From fb0f0ba2f78caad643365db24115493007247a62 Mon Sep 17 00:00:00 2001 From: Tomer Karniol Date: Fri, 9 Oct 2026 16:29:20 +0300 Subject: [PATCH 1/8] feat(server): serve Memory, Processors, Storage and EthernetInterfaces ComputerSystem advertised Storage and EthernetInterfaces links, but requests to them fell through to the system handler and returned the parent resource. Memory had the same problem. Add collection and member resources for Memory, Processors, Storage (with drives) and EthernetInterfaces, built from the VM spec. Compute ProcessorSummary from sockets x cores x threads instead of cores only, and stop reporting made-up defaults when the VM does not declare memory. Note: ComputerSystem.Memory is now a link and the memory total moves to MemorySummary, matching the Redfish schema. Signed-off-by: Tomer Karniol --- pkg/kubevirt/client.go | 97 +++++----- pkg/kubevirt/client_test.go | 6 +- pkg/kubevirt/devices.go | 185 +++++++++++++++++++ pkg/kubevirt/devices_test.go | 248 +++++++++++++++++++++++++ pkg/redfish/types.go | 126 ++++++++++++- pkg/redfish/types_test.go | 6 +- pkg/server/server.go | 38 ++-- pkg/server/system_devices.go | 297 ++++++++++++++++++++++++++++++ pkg/server/system_devices_test.go | 185 +++++++++++++++++++ 9 files changed, 1122 insertions(+), 66 deletions(-) create mode 100644 pkg/kubevirt/devices.go create mode 100644 pkg/kubevirt/devices_test.go create mode 100644 pkg/server/system_devices.go create mode 100644 pkg/server/system_devices_test.go diff --git a/pkg/kubevirt/client.go b/pkg/kubevirt/client.go index 329dcfc..5b1805c 100644 --- a/pkg/kubevirt/client.go +++ b/pkg/kubevirt/client.go @@ -2551,66 +2551,79 @@ func (c *Client) GetNamespaceInfo(namespace string) (*corev1.Namespace, error) { return c.kubernetesClient.CoreV1().Namespaces().Get(context.Background(), namespace, metav1.GetOptions{}) } -// GetVMMemory gets memory information of a VirtualMachine +// GetVMMemory gets the memory of a VirtualMachine in GiB. +// It reads domain.memory.guest, then resources.requests.memory, then +// resources.limits.memory. It returns 0 when the spec declares none, so +// callers can tell "unknown" apart from a real size. func (c *Client) GetVMMemory(namespace, name string) (float64, error) { vm, err := c.getVMForRead(namespace, name) if err != nil { - logger.Warning("Failed to get VM %s/%s for memory lookup: %v", namespace, name, err) - return 2.0, nil // Low default fallback + return 0, fmt.Errorf("failed to get VM %s/%s for memory lookup: %w", namespace, name, err) } - // Get memory from VM spec using typed API - if vm.Spec.Template == nil || vm.Spec.Template.Spec.Domain.Memory == nil || - vm.Spec.Template.Spec.Domain.Memory.Guest == nil { - logger.Warning("Memory not found in VM spec for %s/%s, using default 2.0 GB", namespace, name) - return 2.0, nil // Low default fallback + bytes := vmMemoryBytes(vm) + if bytes == 0 { + logger.Warning("Memory not declared in VM spec for %s/%s", namespace, name) } + return float64(bytes) / (1 << 30), nil +} - memory := vm.Spec.Template.Spec.Domain.Memory.Guest.String() - logger.Debug("Found memory spec for %s/%s: %s", namespace, name, memory) - - // Parse memory string (e.g., "48Gi" -> 48.0) - if strings.HasSuffix(memory, "Gi") { - memoryStr := strings.TrimSuffix(memory, "Gi") - if memoryGB, err := strconv.ParseFloat(memoryStr, 64); err == nil { - logger.Debug("Successfully parsed memory for %s/%s: %.1f GB", namespace, name, memoryGB) - return memoryGB, nil - } - } else if strings.HasSuffix(memory, "Mi") { - memoryStr := strings.TrimSuffix(memory, "Mi") - if memoryMB, err := strconv.ParseFloat(memoryStr, 64); err == nil { - memoryGB := memoryMB / 1024.0 - logger.Debug("Successfully parsed memory for %s/%s: %.1f GB (from %s Mi)", namespace, name, memoryGB, memoryStr) - return memoryGB, nil - } +// vmMemoryBytes returns the VM memory in bytes, or 0 when the spec declares none. +func vmMemoryBytes(vm *kubevirtv1.VirtualMachine) int64 { + if vm.Spec.Template == nil { + return 0 } + domain := vm.Spec.Template.Spec.Domain + if domain.Memory != nil && domain.Memory.Guest != nil { + return domain.Memory.Guest.Value() + } + if q, ok := domain.Resources.Requests[corev1.ResourceMemory]; ok { + return q.Value() + } + if q, ok := domain.Resources.Limits[corev1.ResourceMemory]; ok { + return q.Value() + } + return 0 +} - logger.Warning("Failed to parse memory for %s/%s: %s, using default 2.0 GB", namespace, name, memory) - return 2.0, nil // Low default fallback +// CPUTopology is the vCPU layout of a VM. Unset fields count as 1. +type CPUTopology struct { + Sockets, Cores, Threads int + // Model is domain.cpu.model as configured (e.g. "host-model", "Skylake-Client"); + // empty when the VM leaves it to the cluster default. + Model string } -// GetVMCPU gets CPU information of a VirtualMachine -func (c *Client) GetVMCPU(namespace, name string) (int, error) { +// VCPUs returns the total number of vCPUs (sockets x cores x threads). +func (t CPUTopology) VCPUs() int { return t.Sockets * t.Cores * t.Threads } + +// GetVMCPUTopology returns the sockets, cores per socket and threads per core of a VM. +func (c *Client) GetVMCPUTopology(namespace, name string) (CPUTopology, error) { vm, err := c.getVMForRead(namespace, name) if err != nil { - logger.Warning("Failed to get VM %s/%s for CPU lookup: %v", namespace, name, err) - return 1, nil // Low default fallback + return CPUTopology{Sockets: 1, Cores: 1, Threads: 1}, fmt.Errorf("failed to get VM %s/%s for CPU lookup: %w", namespace, name, err) } - - // Get CPU cores from VM spec using typed API if vm.Spec.Template == nil || vm.Spec.Template.Spec.Domain.CPU == nil { - logger.Warning("CPU cores not found in VM spec for %s/%s, using default 1 core", namespace, name) - return 1, nil // Low default fallback - } + logger.Warning("CPU not found in VM spec for %s/%s, using 1 vCPU", namespace, name) + return CPUTopology{Sockets: 1, Cores: 1, Threads: 1}, nil + } + cpu := vm.Spec.Template.Spec.Domain.CPU + return CPUTopology{ + Sockets: int(max(cpu.Sockets, 1)), + Cores: int(max(cpu.Cores, 1)), + Threads: int(max(cpu.Threads, 1)), + Model: cpu.Model, + }, nil +} - cpuCores := vm.Spec.Template.Spec.Domain.CPU.Cores - if cpuCores == 0 { - logger.Warning("CPU cores is 0 in VM spec for %s/%s, using default 1 core", namespace, name) +// GetVMCPU gets the total vCPU count of a VirtualMachine (sockets x cores x threads). +func (c *Client) GetVMCPU(namespace, name string) (int, error) { + t, err := c.GetVMCPUTopology(namespace, name) + if err != nil { + logger.Warning("%v", err) return 1, nil // Low default fallback } - - logger.Debug("Successfully found CPU cores for %s/%s: %d", namespace, name, cpuCores) - return int(cpuCores), nil + return t.VCPUs(), nil } // GetVMStorageDetails gets detailed storage information of a VirtualMachine diff --git a/pkg/kubevirt/client_test.go b/pkg/kubevirt/client_test.go index 1edebc6..58c91ff 100644 --- a/pkg/kubevirt/client_test.go +++ b/pkg/kubevirt/client_test.go @@ -1605,7 +1605,7 @@ func TestGetVMMemory(t *testing.T) { } mockClient.AddVM(vm) }, - expected: 2.0, // Default fallback + expected: 0, // Unknown: no invented default }, } @@ -1688,7 +1688,7 @@ func TestGetVMCPU(t *testing.T) { } mockClient.AddVM(vm) }, - expected: 8, + expected: 16, // sockets x cores }, { name: "VM without CPU spec", @@ -1731,7 +1731,7 @@ func TestGetVMCPU(t *testing.T) { } if result != tc.expected { - t.Errorf("Expected %d CPU cores, got %d", tc.expected, result) + t.Errorf("Expected %d vCPUs, got %d", tc.expected, result) } }) } diff --git a/pkg/kubevirt/devices.go b/pkg/kubevirt/devices.go new file mode 100644 index 0000000..fb7ce5e --- /dev/null +++ b/pkg/kubevirt/devices.go @@ -0,0 +1,185 @@ +/* + * This file is part of the KubeVirt Redfish project + * + * 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. + * + * Copyright 2025 KubeVirt Redfish project and its authors. + * + */ + +package kubevirt + +import ( + "context" + "math" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + kubevirtv1 "kubevirt.io/api/core/v1" +) + +// VMDisk describes one disk attached to a VM. +type VMDisk struct { + Name string + Bus string + // CapacityBytes is nil when the spec does not declare a size + // (containerDisk, cloudInit, ...). + CapacityBytes *int64 +} + +// VMNIC describes one network interface of a VM. +type VMNIC struct { + Name string + // MAC is empty until KubeVirt reports it (VM never started and no macAddress in the spec). + MAC string + IPs []string + // Running is true when the VMI exists and reports this interface. + Running bool +} + +// VMMemoryMiB returns the VM memory in MiB (see GetVMMemory for the source order). +func (c *Client) VMMemoryMiB(namespace, name string) (int64, error) { + gib, err := c.GetVMMemory(namespace, name) + if err != nil { + return 0, err + } + return int64(math.Round(gib * 1024)), nil +} + +// GetVMDisks returns every disk of a VM in spec order. CD-ROM devices are +// excluded because they are exposed as VirtualMedia. +func (c *Client) GetVMDisks(namespace, name string) ([]VMDisk, error) { + vm, err := c.getVMForRead(namespace, name) + if err != nil { + return nil, err + } + if vm.Spec.Template == nil { + return nil, nil + } + + volumes := map[string]kubevirtv1.Volume{} + for _, v := range vm.Spec.Template.Spec.Volumes { + volumes[v.Name] = v + } + + var disks []VMDisk + for _, d := range vm.Spec.Template.Spec.Domain.Devices.Disks { + if d.CDRom != nil { + continue + } + disk := VMDisk{Name: d.Name} + switch { + case d.Disk != nil: + disk.Bus = string(d.Disk.Bus) + case d.LUN != nil: + disk.Bus = string(d.LUN.Bus) + } + if vol, ok := volumes[d.Name]; ok { + disk.CapacityBytes = c.volumeCapacityBytes(namespace, vm, vol) + } + disks = append(disks, disk) + } + return disks, nil +} + +// volumeCapacityBytes resolves the declared size of a volume, or nil if unknown. +func (c *Client) volumeCapacityBytes(namespace string, vm *kubevirtv1.VirtualMachine, vol kubevirtv1.Volume) *int64 { + var claim string + switch { + case vol.PersistentVolumeClaim != nil: + claim = vol.PersistentVolumeClaim.ClaimName + case vol.DataVolume != nil: + claim = vol.DataVolume.Name + case vol.Ephemeral != nil && vol.Ephemeral.PersistentVolumeClaim != nil: + claim = vol.Ephemeral.PersistentVolumeClaim.ClaimName + case vol.EmptyDisk != nil: + b := vol.EmptyDisk.Capacity.Value() + return &b + case vol.HostDisk != nil: + if vol.HostDisk.Capacity.IsZero() { + return nil + } + b := vol.HostDisk.Capacity.Value() + return &b + default: + return nil + } + + // Prefer the real PVC (actual provisioned size), fall back to the DataVolume template. + if c.kubernetesClient != nil { + ctx, cancel := context.WithTimeout(context.Background(), c.timeout) + defer cancel() + pvc, err := c.kubernetesClient.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, claim, metav1.GetOptions{}) + if err == nil { + if q, ok := pvc.Status.Capacity[corev1.ResourceStorage]; ok { + b := q.Value() + return &b + } + if q, ok := pvc.Spec.Resources.Requests[corev1.ResourceStorage]; ok { + b := q.Value() + return &b + } + } + } + for _, dv := range vm.Spec.DataVolumeTemplates { + if dv.Name != claim { + continue + } + if dv.Spec.Storage != nil { + if q, ok := dv.Spec.Storage.Resources.Requests[corev1.ResourceStorage]; ok { + b := q.Value() + return &b + } + } + if dv.Spec.PVC != nil { + if q, ok := dv.Spec.PVC.Resources.Requests[corev1.ResourceStorage]; ok { + b := q.Value() + return &b + } + } + } + return nil +} + +// GetVMNICs returns every network interface of a VM. The MAC and IPs come +// from the running VMI when available, otherwise from the VM spec. +func (c *Client) GetVMNICs(namespace, name string) ([]VMNIC, error) { + vm, err := c.getVMForRead(namespace, name) + if err != nil { + return nil, err + } + if vm.Spec.Template == nil { + return nil, nil + } + + status := map[string]kubevirtv1.VirtualMachineInstanceNetworkInterface{} + if vmi, err := c.getVMIForRead(namespace, name); err == nil { + for _, s := range vmi.Status.Interfaces { + status[s.Name] = s + } + } + + var nics []VMNIC + for _, i := range vm.Spec.Template.Spec.Domain.Devices.Interfaces { + nic := VMNIC{Name: i.Name, MAC: i.MacAddress} + if s, ok := status[i.Name]; ok { + nic.Running = true + if s.MAC != "" { + nic.MAC = s.MAC + } + nic.IPs = s.IPs + } + nics = append(nics, nic) + } + return nics, nil +} diff --git a/pkg/kubevirt/devices_test.go b/pkg/kubevirt/devices_test.go new file mode 100644 index 0000000..3aa50bf --- /dev/null +++ b/pkg/kubevirt/devices_test.go @@ -0,0 +1,248 @@ +/* + * This file is part of the KubeVirt Redfish project + * + * 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. + * + * Copyright 2025 KubeVirt Redfish project and its authors. + * + */ + +package kubevirt + +import ( + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes/fake" + kubevirtv1 "kubevirt.io/api/core/v1" + cdiv1beta1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" +) + +func deviceTestVM(spec kubevirtv1.VirtualMachineInstanceSpec) *kubevirtv1.VirtualMachine { + return &kubevirtv1.VirtualMachine{ + ObjectMeta: metav1.ObjectMeta{Name: "vm", Namespace: "ns"}, + Spec: kubevirtv1.VirtualMachineSpec{ + Template: &kubevirtv1.VirtualMachineInstanceTemplateSpec{Spec: spec}, + }, + } +} + +func TestGetVMCPU_Topology(t *testing.T) { + cases := []struct { + name string + cpu kubevirtv1.CPU + want int + }{ + {"cores only", kubevirtv1.CPU{Cores: 2}, 2}, + {"cores and sockets", kubevirtv1.CPU{Cores: 2, Sockets: 2}, 4}, + {"cores sockets threads", kubevirtv1.CPU{Cores: 2, Sockets: 2, Threads: 2}, 8}, + {"threads only", kubevirtv1.CPU{Threads: 2}, 2}, + {"empty cpu block", kubevirtv1.CPU{}, 1}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + mock := NewMockDynamicClient() + cpu := tc.cpu + if err := mock.AddVM(deviceTestVM(kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{CPU: &cpu}})); err != nil { + t.Fatal(err) + } + c := NewClientWithClients(fake.NewSimpleClientset(), mock, 30*time.Second, nil) + got, err := c.GetVMCPU("ns", "vm") + if err != nil || got != tc.want { + t.Errorf("GetVMCPU = %d, %v; want %d", got, err, tc.want) + } + }) + } +} + +func TestGetVMCPUTopology(t *testing.T) { + mock := NewMockDynamicClient() + cpu := kubevirtv1.CPU{Cores: 4, Sockets: 2, Threads: 2, Model: "host-model"} + if err := mock.AddVM(deviceTestVM(kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{CPU: &cpu}})); err != nil { + t.Fatal(err) + } + c := NewClientWithClients(fake.NewSimpleClientset(), mock, 30*time.Second, nil) + got, err := c.GetVMCPUTopology("ns", "vm") + if err != nil || got != (CPUTopology{Sockets: 2, Cores: 4, Threads: 2, Model: "host-model"}) || got.VCPUs() != 16 { + t.Errorf("topology = %+v, %v", got, err) + } + if _, err := c.GetVMCPUTopology("ns", "nope"); err == nil { + t.Error("expected an error for a missing VM") + } +} + +func TestGetVMMemory_Sources(t *testing.T) { + guest := resource.MustParse("4Gi") + cases := []struct { + name string + domain kubevirtv1.DomainSpec + want float64 + }{ + {"guest memory wins", kubevirtv1.DomainSpec{ + Memory: &kubevirtv1.Memory{Guest: &guest}, + Resources: kubevirtv1.ResourceRequirements{Requests: corev1.ResourceList{corev1.ResourceMemory: resource.MustParse("1Gi")}}, + }, 4}, + {"resources.requests", kubevirtv1.DomainSpec{ + Resources: kubevirtv1.ResourceRequirements{Requests: corev1.ResourceList{corev1.ResourceMemory: resource.MustParse("128Mi")}}, + }, 0.125}, + {"resources.limits", kubevirtv1.DomainSpec{ + Resources: kubevirtv1.ResourceRequirements{Limits: corev1.ResourceList{corev1.ResourceMemory: resource.MustParse("2Gi")}}, + }, 2}, + {"nothing declared reports 0, not a guess", kubevirtv1.DomainSpec{}, 0}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + mock := NewMockDynamicClient() + if err := mock.AddVM(deviceTestVM(kubevirtv1.VirtualMachineInstanceSpec{Domain: tc.domain})); err != nil { + t.Fatal(err) + } + c := NewClientWithClients(fake.NewSimpleClientset(), mock, 30*time.Second, nil) + got, err := c.GetVMMemory("ns", "vm") + if err != nil || got != tc.want { + t.Errorf("GetVMMemory = %v, %v; want %v", got, err, tc.want) + } + }) + } +} + +func TestGetVMMemory_MissingVMIsAnError(t *testing.T) { + c := NewClientWithClients(fake.NewSimpleClientset(), NewMockDynamicClient(), 30*time.Second, nil) + if _, err := c.GetVMMemory("ns", "nope"); err == nil { + t.Error("expected an error for a missing VM") + } +} + +func TestGetVMDisks(t *testing.T) { + dvSize := resource.MustParse("20Gi") + spec := kubevirtv1.VirtualMachineInstanceSpec{ + Domain: kubevirtv1.DomainSpec{Devices: kubevirtv1.Devices{Disks: []kubevirtv1.Disk{ + {Name: "root", DiskDevice: kubevirtv1.DiskDevice{Disk: &kubevirtv1.DiskTarget{Bus: "virtio"}}}, + {Name: "data", DiskDevice: kubevirtv1.DiskDevice{Disk: &kubevirtv1.DiskTarget{Bus: "sata"}}}, + {Name: "tpl", DiskDevice: kubevirtv1.DiskDevice{Disk: &kubevirtv1.DiskTarget{Bus: "virtio"}}}, + {Name: "scratch", DiskDevice: kubevirtv1.DiskDevice{Disk: &kubevirtv1.DiskTarget{Bus: "virtio"}}}, + {Name: "cloud", DiskDevice: kubevirtv1.DiskDevice{Disk: &kubevirtv1.DiskTarget{Bus: "virtio"}}}, + {Name: "cdrom0", DiskDevice: kubevirtv1.DiskDevice{CDRom: &kubevirtv1.CDRomTarget{}}}, + }}}, + Volumes: []kubevirtv1.Volume{ + {Name: "root", VolumeSource: kubevirtv1.VolumeSource{ContainerDisk: &kubevirtv1.ContainerDiskSource{Image: "img"}}}, + {Name: "data", VolumeSource: kubevirtv1.VolumeSource{PersistentVolumeClaim: &kubevirtv1.PersistentVolumeClaimVolumeSource{ + PersistentVolumeClaimVolumeSource: corev1.PersistentVolumeClaimVolumeSource{ClaimName: "data-pvc"}}}}, + {Name: "tpl", VolumeSource: kubevirtv1.VolumeSource{DataVolume: &kubevirtv1.DataVolumeSource{Name: "tpl-dv"}}}, + {Name: "scratch", VolumeSource: kubevirtv1.VolumeSource{EmptyDisk: &kubevirtv1.EmptyDiskSource{Capacity: resource.MustParse("1Gi")}}}, + {Name: "cloud", VolumeSource: kubevirtv1.VolumeSource{CloudInitNoCloud: &kubevirtv1.CloudInitNoCloudSource{UserData: "x"}}}, + }, + } + vm := deviceTestVM(spec) + vm.Spec.DataVolumeTemplates = []kubevirtv1.DataVolumeTemplateSpec{{ + ObjectMeta: metav1.ObjectMeta{Name: "tpl-dv"}, + Spec: cdiv1beta1.DataVolumeSpec{Storage: &cdiv1beta1.StorageSpec{ + Resources: corev1.VolumeResourceRequirements{Requests: corev1.ResourceList{corev1.ResourceStorage: dvSize}}, + }}, + }} + + mock := NewMockDynamicClient() + if err := mock.AddVM(vm); err != nil { + t.Fatal(err) + } + k8s := fake.NewSimpleClientset(&corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{Name: "data-pvc", Namespace: "ns"}, + Status: corev1.PersistentVolumeClaimStatus{Capacity: corev1.ResourceList{corev1.ResourceStorage: resource.MustParse("100Gi")}}, + }) + c := NewClientWithClients(k8s, mock, 30*time.Second, nil) + + disks, err := c.GetVMDisks("ns", "vm") + if err != nil { + t.Fatal(err) + } + want := []struct { + name string + bus string + size int64 // -1 = unknown + }{ + {"root", "virtio", -1}, + {"data", "sata", 100 << 30}, + {"tpl", "virtio", 20 << 30}, + {"scratch", "virtio", 1 << 30}, + {"cloud", "virtio", -1}, + } + if len(disks) != len(want) { + t.Fatalf("got %d disks (%+v), want %d (cdrom must be excluded)", len(disks), disks, len(want)) + } + for i, w := range want { + d := disks[i] + if d.Name != w.name || d.Bus != w.bus { + t.Errorf("disk %d = %s/%s, want %s/%s", i, d.Name, d.Bus, w.name, w.bus) + } + switch { + case w.size < 0 && d.CapacityBytes != nil: + t.Errorf("disk %s: capacity %d, want unknown", d.Name, *d.CapacityBytes) + case w.size >= 0 && (d.CapacityBytes == nil || *d.CapacityBytes != w.size): + t.Errorf("disk %s: capacity %v, want %d", d.Name, d.CapacityBytes, w.size) + } + } +} + +func TestGetVMNICs(t *testing.T) { + spec := kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{Devices: kubevirtv1.Devices{Interfaces: []kubevirtv1.Interface{ + {Name: "default", InterfaceBindingMethod: kubevirtv1.InterfaceBindingMethod{Masquerade: &kubevirtv1.InterfaceMasquerade{}}}, + {Name: "fixed", MacAddress: "02:00:00:00:00:01"}, + }}}} + + t.Run("stopped VM uses the spec MAC and reports no link", func(t *testing.T) { + mock := NewMockDynamicClient() + if err := mock.AddVM(deviceTestVM(spec)); err != nil { + t.Fatal(err) + } + c := NewClientWithClients(fake.NewSimpleClientset(), mock, 30*time.Second, nil) + nics, err := c.GetVMNICs("ns", "vm") + if err != nil || len(nics) != 2 { + t.Fatalf("GetVMNICs = %+v, %v", nics, err) + } + if nics[0].MAC != "" || nics[0].Running { + t.Errorf("default: %+v, want empty MAC and not running", nics[0]) + } + if nics[1].MAC != "02:00:00:00:00:01" || nics[1].Running { + t.Errorf("fixed: %+v", nics[1]) + } + }) + + t.Run("running VM reports the VMI MAC and IPs", func(t *testing.T) { + mock := NewMockDynamicClient() + if err := mock.AddVM(deviceTestVM(spec)); err != nil { + t.Fatal(err) + } + vmi := &kubevirtv1.VirtualMachineInstance{ + ObjectMeta: metav1.ObjectMeta{Name: "vm", Namespace: "ns"}, + Status: kubevirtv1.VirtualMachineInstanceStatus{Interfaces: []kubevirtv1.VirtualMachineInstanceNetworkInterface{ + {Name: "default", MAC: "52:54:00:aa:bb:cc", IPs: []string{"10.0.0.5", "fd00::5"}}, + }}, + } + if err := mock.AddVMI(vmi); err != nil { + t.Fatal(err) + } + c := NewClientWithClients(fake.NewSimpleClientset(), mock, 30*time.Second, nil) + nics, err := c.GetVMNICs("ns", "vm") + if err != nil || len(nics) != 2 { + t.Fatalf("GetVMNICs = %+v, %v", nics, err) + } + if nics[0].MAC != "52:54:00:aa:bb:cc" || !nics[0].Running || len(nics[0].IPs) != 2 { + t.Errorf("default: %+v", nics[0]) + } + if nics[1].Running { + t.Errorf("fixed has no status entry, must not be running: %+v", nics[1]) + } + }) +} diff --git a/pkg/redfish/types.go b/pkg/redfish/types.go index 1c2fd16..731a028 100644 --- a/pkg/redfish/types.go +++ b/pkg/redfish/types.go @@ -99,7 +99,9 @@ type ComputerSystem struct { SystemType string `json:"SystemType"` Status Status `json:"Status"` PowerState string `json:"PowerState"` - Memory MemorySummary `json:"Memory"` + MemorySummary MemorySummary `json:"MemorySummary"` + Memory Link `json:"Memory"` + Processors Link `json:"Processors"` ProcessorSummary ProcessorSummary `json:"ProcessorSummary"` Storage Link `json:"Storage"` EthernetInterfaces Link `json:"EthernetInterfaces"` @@ -118,15 +120,32 @@ type Status struct { // MemorySummary represents memory information for a computer system. // It provides details about the total system memory available to the VM. +// TotalSystemMemoryGiB is omitted when the VM spec declares no memory. type MemorySummary struct { - OdataID string `json:"@odata.id"` - TotalSystemMemoryGiB float64 `json:"TotalSystemMemoryGiB"` + TotalSystemMemoryGiB float64 `json:"TotalSystemMemoryGiB,omitempty"` } // ProcessorSummary represents processor information for a computer system. -// It provides details about the CPU configuration of the VM. +// Count is the number of sockets, CoreCount is sockets x cores and +// LogicalProcessorCount is sockets x cores x threads (the vCPU count). +// The per-socket detail is served under Processors. type ProcessorSummary struct { - Count int `json:"Count"` + Count int `json:"Count"` + CoreCount int `json:"CoreCount"` + LogicalProcessorCount int `json:"LogicalProcessorCount"` + ThreadingEnabled bool `json:"ThreadingEnabled"` + // Model is the configured virtual CPU model; omitted when the VM leaves it to the cluster default. + Model string `json:"Model,omitempty"` + Oem *CPUTopologyOem `json:"Oem,omitempty"` +} + +// CPUTopologyOem spells out the vCPU layout the standard counts are derived from. +type CPUTopologyOem struct { + KubeVirt struct { + Sockets int `json:"Sockets"` + CoresPerSocket int `json:"CoresPerSocket"` + ThreadsPerCore int `json:"ThreadsPerCore"` + } `json:"KubeVirt"` } // Boot represents boot configuration for a computer system. @@ -366,3 +385,100 @@ const ( ErrorCodeResourceNotFound = "Base.1.0.ResourceNotFound" ErrorCodePropertyMissing = "Base.1.0.PropertyMissing" ) + +// ResourceCollection is a generic Redfish collection of linked members. +type ResourceCollection struct { + OdataContext string `json:"@odata.context"` + OdataID string `json:"@odata.id"` + OdataType string `json:"@odata.type"` + Name string `json:"Name"` + Members []Link `json:"Members"` + MembersCount int `json:"Members@odata.count"` +} + +// Memory represents the guest memory of a VM as a single memory module. +type Memory struct { + OdataContext string `json:"@odata.context"` + OdataID string `json:"@odata.id"` + OdataType string `json:"@odata.type"` + ID string `json:"Id"` + Name string `json:"Name"` + MemoryType string `json:"MemoryType"` + CapacityMiB int64 `json:"CapacityMiB,omitempty"` + Status Status `json:"Status"` + Oem *OemCapacity `json:"Oem,omitempty"` +} + +// Storage represents the storage controller that holds a VM's disks. +type Storage struct { + OdataContext string `json:"@odata.context"` + OdataID string `json:"@odata.id"` + OdataType string `json:"@odata.type"` + ID string `json:"Id"` + Name string `json:"Name"` + Status Status `json:"Status"` + Drives []Link `json:"Drives"` + DrivesCount int `json:"Drives@odata.count"` +} + +// Drive represents one disk attached to a VM. +// CapacityBytes is omitted when the size is not declared (e.g. containerDisk). +type Drive struct { + OdataContext string `json:"@odata.context"` + OdataID string `json:"@odata.id"` + OdataType string `json:"@odata.type"` + ID string `json:"Id"` + Name string `json:"Name"` + Protocol string `json:"Protocol,omitempty"` + MediaType string `json:"MediaType,omitempty"` + CapacityBytes *int64 `json:"CapacityBytes,omitempty"` + Status Status `json:"Status"` + Oem *OemCapacity `json:"Oem,omitempty"` +} + +// OemCapacity carries a human-readable GiB copy of a capacity. The standard +// Redfish Drive and Memory schemas only define CapacityBytes and CapacityMiB, +// which clients such as Ironic read, so the GiB value lives under Oem.KubeVirt. +type OemCapacity struct { + KubeVirt struct { + CapacityGiB float64 `json:"CapacityGiB"` + } `json:"KubeVirt"` +} + +// EthernetInterface represents one network interface of a VM. +// LinkStatus is LinkUp while the VM runs and NoLink otherwise. +// MACAddress is omitted when KubeVirt has not assigned one yet (VM never started). +// SpeedMbps is always omitted: virtual NICs have no link speed. +type EthernetInterface struct { + OdataContext string `json:"@odata.context"` + OdataID string `json:"@odata.id"` + OdataType string `json:"@odata.type"` + ID string `json:"Id"` + Name string `json:"Name"` + Description string `json:"Description,omitempty"` + MACAddress string `json:"MACAddress,omitempty"` + LinkStatus string `json:"LinkStatus,omitempty"` + IPv4 []IPv4Address `json:"IPv4Addresses,omitempty"` + Status Status `json:"Status"` +} + +// IPv4Address is one IPv4 address of an EthernetInterface. +type IPv4Address struct { + Address string `json:"Address"` +} + +// Processor represents one virtual CPU socket of a VM. +// TotalCores is cores per socket and TotalThreads is cores x threads per socket. +type Processor struct { + OdataContext string `json:"@odata.context"` + OdataID string `json:"@odata.id"` + OdataType string `json:"@odata.type"` + ID string `json:"Id"` + Name string `json:"Name"` + Socket string `json:"Socket"` + ProcessorType string `json:"ProcessorType"` + TotalCores int `json:"TotalCores"` + TotalThreads int `json:"TotalThreads"` + Model string `json:"Model,omitempty"` + Status Status `json:"Status"` +} diff --git a/pkg/redfish/types_test.go b/pkg/redfish/types_test.go index 27f5210..22950be 100644 --- a/pkg/redfish/types_test.go +++ b/pkg/redfish/types_test.go @@ -83,10 +83,12 @@ func TestComputerSystem(t *testing.T) { Health: HealthOK, }, PowerState: PowerStateOn, - Memory: MemorySummary{ - OdataID: "/redfish/v1/Systems/test-system/Memory", + MemorySummary: MemorySummary{ TotalSystemMemoryGiB: 8.0, }, + Memory: Link{ + OdataID: "/redfish/v1/Systems/test-system/Memory", + }, Storage: Link{ OdataID: "/redfish/v1/Systems/test-system/Storage", }, diff --git a/pkg/server/server.go b/pkg/server/server.go index fa2b8ef..747fb69 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -692,6 +692,12 @@ func (s *Server) handleSystem(w http.ResponseWriter, r *http.Request) { return } + // Hardware sub-resources: Memory, Processors, Storage, EthernetInterfaces + if len(pathParts) >= 6 && (pathParts[5] == "Memory" || pathParts[5] == "Processors" || pathParts[5] == "Storage" || pathParts[5] == "EthernetInterfaces") { + s.handleSystemDevices(w, r, systemName, pathParts) + return + } + // For GET requests to the system resource, validate method if !s.validateMethod(w, r, []string{"GET"}) { return @@ -724,14 +730,13 @@ func (s *Server) handleSystem(w http.ResponseWriter, r *http.Request) { memoryGB, err := s.kubevirtClient.GetVMMemory(namespace, vmName) if err != nil { logger.Warning("Failed to get memory for VM %s: %v", vmName, err) - memoryGB = 2.0 // Low default fallback + memoryGB = 0 // Unknown: omitted from the response } // Get real CPU information - cpuCount, err := s.kubevirtClient.GetVMCPU(namespace, vmName) + cpu, err := s.kubevirtClient.GetVMCPUTopology(namespace, vmName) if err != nil { logger.Warning("Failed to get CPU for VM %s: %v", vmName, err) - cpuCount = 1 // Low default fallback } // Generate the correct System ID for the response @@ -751,13 +756,16 @@ func (s *Server) handleSystem(w http.ResponseWriter, r *http.Request) { Health: "OK", }, PowerState: powerState, - Memory: redfish.MemorySummary{ - OdataID: fmt.Sprintf("/redfish/v1/Systems/%s/Memory", responseSystemID), + MemorySummary: redfish.MemorySummary{ TotalSystemMemoryGiB: memoryGB, }, - ProcessorSummary: redfish.ProcessorSummary{ - Count: cpuCount, + Memory: redfish.Link{ + OdataID: fmt.Sprintf("/redfish/v1/Systems/%s/Memory", responseSystemID), }, + Processors: redfish.Link{ + OdataID: fmt.Sprintf("/redfish/v1/Systems/%s/Processors", responseSystemID), + }, + ProcessorSummary: processorSummary(cpu), Storage: redfish.Link{ OdataID: fmt.Sprintf("/redfish/v1/Systems/%s/Storage", responseSystemID), }, @@ -1247,14 +1255,13 @@ func (s *Server) handleBootUpdate(w http.ResponseWriter, r *http.Request, system memoryGB, err := s.kubevirtClient.GetVMMemory(namespace, vmName) if err != nil { logger.Warning("Failed to get memory for VM %s: %v", vmName, err) - memoryGB = 2.0 // Low default fallback + memoryGB = 0 // Unknown: omitted from the response } // Get real CPU information - cpuCount, err := s.kubevirtClient.GetVMCPU(namespace, vmName) + cpu, err := s.kubevirtClient.GetVMCPUTopology(namespace, vmName) if err != nil { logger.Warning("Failed to get CPU for VM %s: %v", vmName, err) - cpuCount = 1 // Low default fallback } // Return the updated ComputerSystem resource (Redfish spec requirement) @@ -1273,13 +1280,16 @@ func (s *Server) handleBootUpdate(w http.ResponseWriter, r *http.Request, system Health: "OK", }, PowerState: powerState, - Memory: redfish.MemorySummary{ - OdataID: fmt.Sprintf("/redfish/v1/Systems/%s/Memory", responseSystemID), + MemorySummary: redfish.MemorySummary{ TotalSystemMemoryGiB: memoryGB, }, - ProcessorSummary: redfish.ProcessorSummary{ - Count: cpuCount, + Memory: redfish.Link{ + OdataID: fmt.Sprintf("/redfish/v1/Systems/%s/Memory", responseSystemID), + }, + Processors: redfish.Link{ + OdataID: fmt.Sprintf("/redfish/v1/Systems/%s/Processors", responseSystemID), }, + ProcessorSummary: processorSummary(cpu), Storage: redfish.Link{ OdataID: fmt.Sprintf("/redfish/v1/Systems/%s/Storage", responseSystemID), }, diff --git a/pkg/server/system_devices.go b/pkg/server/system_devices.go new file mode 100644 index 0000000..45f2627 --- /dev/null +++ b/pkg/server/system_devices.go @@ -0,0 +1,297 @@ +/* + * This file is part of the KubeVirt Redfish project + * + * 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. + * + * Copyright 2025 KubeVirt Redfish project and its authors. + * + */ + +package server + +import ( + "fmt" + "net" + "net/http" + "strconv" + "strings" + + "github.com/kubevirt/redfish-controller/pkg/config" + "github.com/kubevirt/redfish-controller/pkg/kubevirt" + "github.com/kubevirt/redfish-controller/pkg/logger" + "github.com/kubevirt/redfish-controller/pkg/redfish" +) + +// memoryID and storageID are the fixed member IDs: a VM exposes one logical +// memory module and one storage controller that holds all of its disks. +const ( + memoryID = "1" + storageID = "1" +) + +var okStatus = redfish.Status{State: "Enabled", Health: "OK"} + +// handleSystemDevices serves the read-only hardware sub-resources of a system: +// Memory, Processors, Storage (with Drives) and EthernetInterfaces. pathParts is the split +// request path, so pathParts[5] is the sub-resource name. +func (s *Server) handleSystemDevices(w http.ResponseWriter, r *http.Request, systemName string, pathParts []string) { + if !s.validateMethod(w, r, []string{"GET"}) { + return + } + namespace, vmName, _, ok := s.resolveSystemVMandCheckAccess(w, r, systemName) + if !ok { + return + } + + // Drop a trailing empty element ("/Storage/" -> "/Storage"). + rest := pathParts[5:] + if rest[len(rest)-1] == "" { + rest = rest[:len(rest)-1] + } + base := "/redfish/v1/Systems/" + config.GenerateSystemID(s.currentConfig().SystemIDConvention, namespace, vmName) + + switch rest[0] { + case "Memory": + s.serveMemory(w, namespace, vmName, base, rest) + case "Processors": + s.serveProcessors(w, namespace, vmName, base, rest) + case "Storage": + s.serveStorage(w, namespace, vmName, base, rest) + case "EthernetInterfaces": + s.serveEthernetInterfaces(w, namespace, vmName, base, rest) + } +} + +func (s *Server) serveMemory(w http.ResponseWriter, namespace, vmName, base string, rest []string) { + self := base + "/Memory" + switch { + case len(rest) == 1: + s.writeCollection(w, self, "#MemoryCollection.MemoryCollection", "Memory Collection", []string{self + "/" + memoryID}) + case len(rest) == 2 && rest[1] == memoryID: + mib, err := s.kubevirtClient.VMMemoryMiB(namespace, vmName) + if err != nil { + logger.Error("Failed to get memory for VM %s/%s: %v", namespace, vmName, err) + s.sendInternalError(w, "Failed to get memory information") + return + } + mem := redfish.Memory{ + OdataContext: "/redfish/v1/$metadata#Memory.Memory", + OdataID: self + "/" + memoryID, + OdataType: "#Memory.v1_0_0.Memory", + ID: memoryID, + Name: "System Memory", + MemoryType: "DRAM", + CapacityMiB: mib, + Status: okStatus, + } + if mib > 0 { + mem.Oem = oemCapacity(float64(mib) / 1024) + } + s.writeResource(w, mem) + default: + s.sendNotFound(w, "Memory resource not found") + } +} + +func (s *Server) serveProcessors(w http.ResponseWriter, namespace, vmName, base string, rest []string) { + self := base + "/Processors" + cpu, err := s.kubevirtClient.GetVMCPUTopology(namespace, vmName) + if err != nil { + logger.Error("Failed to get CPU topology for VM %s/%s: %v", namespace, vmName, err) + s.sendInternalError(w, "Failed to get processor information") + return + } + + if len(rest) == 1 { + members := make([]string, 0, cpu.Sockets) + for i := 0; i < cpu.Sockets; i++ { + members = append(members, fmt.Sprintf("%s/CPU%d", self, i)) + } + s.writeCollection(w, self, "#ProcessorCollection.ProcessorCollection", "Processor Collection", members) + return + } + socket, err := strconv.Atoi(strings.TrimPrefix(rest[1], "CPU")) + if len(rest) != 2 || !strings.HasPrefix(rest[1], "CPU") || err != nil || socket < 0 || socket >= cpu.Sockets || rest[1] != fmt.Sprintf("CPU%d", socket) { + s.sendNotFound(w, "Processor not found") + return + } + s.writeResource(w, redfish.Processor{ + OdataContext: "/redfish/v1/$metadata#Processor.Processor", + OdataID: fmt.Sprintf("%s/CPU%d", self, socket), + OdataType: "#Processor.v1_0_0.Processor", + ID: rest[1], + Name: fmt.Sprintf("vCPU Socket %d", socket), + Socket: fmt.Sprint(socket), + ProcessorType: "CPU", + TotalCores: cpu.Cores, + TotalThreads: cpu.Cores * cpu.Threads, + Model: cpu.Model, + Status: okStatus, + }) +} + +func (s *Server) serveStorage(w http.ResponseWriter, namespace, vmName, base string, rest []string) { + self := base + "/Storage" + if len(rest) == 1 { + s.writeCollection(w, self, "#StorageCollection.StorageCollection", "Storage Collection", []string{self + "/" + storageID}) + return + } + if rest[1] != storageID { + s.sendNotFound(w, "Storage resource not found") + return + } + + disks, err := s.kubevirtClient.GetVMDisks(namespace, vmName) + if err != nil { + logger.Error("Failed to get disks for VM %s/%s: %v", namespace, vmName, err) + s.sendInternalError(w, "Failed to get storage information") + return + } + member := self + "/" + storageID + + switch { + case len(rest) == 2: + storage := redfish.Storage{ + OdataContext: "/redfish/v1/$metadata#Storage.Storage", + OdataID: member, + OdataType: "#Storage.v1_0_0.Storage", + ID: storageID, + Name: "VM Disks", + Status: okStatus, + Drives: []redfish.Link{}, + DrivesCount: len(disks), + } + for _, d := range disks { + storage.Drives = append(storage.Drives, redfish.Link{OdataID: member + "/Drives/" + d.Name}) + } + s.writeResource(w, storage) + case len(rest) == 4 && rest[2] == "Drives": + for _, d := range disks { + if d.Name != rest[3] { + continue + } + drive := redfish.Drive{ + OdataContext: "/redfish/v1/$metadata#Drive.Drive", + OdataID: member + "/Drives/" + d.Name, + OdataType: "#Drive.v1_0_0.Drive", + ID: d.Name, + Name: d.Name, + CapacityBytes: d.CapacityBytes, + Status: okStatus, + } + if d.CapacityBytes != nil { + drive.Oem = oemCapacity(float64(*d.CapacityBytes) / (1 << 30)) + } + if d.Bus == "sata" { + drive.Protocol = "SATA" + } + s.writeResource(w, drive) + return + } + s.sendNotFound(w, "Drive not found") + default: + s.sendNotFound(w, "Storage resource not found") + } +} + +func (s *Server) serveEthernetInterfaces(w http.ResponseWriter, namespace, vmName, base string, rest []string) { + self := base + "/EthernetInterfaces" + nics, err := s.kubevirtClient.GetVMNICs(namespace, vmName) + if err != nil { + logger.Error("Failed to get network interfaces for VM %s/%s: %v", namespace, vmName, err) + s.sendInternalError(w, "Failed to get network interface information") + return + } + + if len(rest) == 1 { + members := make([]string, 0, len(nics)) + for _, n := range nics { + members = append(members, self+"/"+n.Name) + } + s.writeCollection(w, self, "#EthernetInterfaceCollection.EthernetInterfaceCollection", "Ethernet Interface Collection", members) + return + } + if len(rest) != 2 { + s.sendNotFound(w, "Ethernet interface not found") + return + } + for _, n := range nics { + if n.Name != rest[1] { + continue + } + eth := redfish.EthernetInterface{ + OdataContext: "/redfish/v1/$metadata#EthernetInterface.EthernetInterface", + OdataID: self + "/" + n.Name, + OdataType: "#EthernetInterface.v1_0_0.EthernetInterface", + ID: n.Name, + Name: n.Name, + MACAddress: n.MAC, + LinkStatus: "NoLink", + Status: okStatus, + } + if n.Running { + eth.LinkStatus = "LinkUp" + } + for _, ip := range n.IPs { + if p := net.ParseIP(ip); p != nil && p.To4() != nil { + eth.IPv4 = append(eth.IPv4, redfish.IPv4Address{Address: ip}) + } + } + s.writeResource(w, eth) + return + } + s.sendNotFound(w, "Ethernet interface not found") +} + +// processorSummary maps a VM's vCPU topology to the Redfish ProcessorSummary. +func processorSummary(cpu kubevirt.CPUTopology) redfish.ProcessorSummary { + oem := &redfish.CPUTopologyOem{} + oem.KubeVirt.Sockets = cpu.Sockets + oem.KubeVirt.CoresPerSocket = cpu.Cores + oem.KubeVirt.ThreadsPerCore = cpu.Threads + return redfish.ProcessorSummary{ + Count: cpu.Sockets, + CoreCount: cpu.Sockets * cpu.Cores, + LogicalProcessorCount: cpu.VCPUs(), + ThreadingEnabled: cpu.Threads > 1, + Model: cpu.Model, + Oem: oem, + } +} + +func oemCapacity(gib float64) *redfish.OemCapacity { + o := &redfish.OemCapacity{} + o.KubeVirt.CapacityGiB = gib + return o +} + +func (s *Server) writeCollection(w http.ResponseWriter, id, odataType, name string, members []string) { + links := make([]redfish.Link, 0, len(members)) + for _, m := range members { + links = append(links, redfish.Link{OdataID: m}) + } + s.writeResource(w, redfish.ResourceCollection{ + OdataContext: fmt.Sprintf("/redfish/v1/$metadata#%s", odataType[1:]), + OdataID: id, + OdataType: odataType, + Name: name, + Members: links, + MembersCount: len(links), + }) +} + +func (s *Server) writeResource(w http.ResponseWriter, v interface{}) { + w.Header().Set("Content-Type", "application/json") + s.setNoCacheHeaders(w) + s.encodeJSONResponse(w, v) +} diff --git a/pkg/server/system_devices_test.go b/pkg/server/system_devices_test.go new file mode 100644 index 0000000..8a8680e --- /dev/null +++ b/pkg/server/system_devices_test.go @@ -0,0 +1,185 @@ +/* + * This file is part of the KubeVirt Redfish project + * + * 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. + * + * Copyright 2025 KubeVirt Redfish project and its authors. + * + */ + +package server + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/kubevirt/redfish-controller/pkg/auth" + "github.com/kubevirt/redfish-controller/pkg/config" + "github.com/kubevirt/redfish-controller/pkg/kubevirt" + "github.com/kubevirt/redfish-controller/pkg/logger" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes/fake" + kubevirtv1 "kubevirt.io/api/core/v1" +) + +func newDevicesTestServer(t *testing.T) *Server { + t.Helper() + mock := kubevirt.NewMockDynamicClient() + vm := &kubevirtv1.VirtualMachine{ + ObjectMeta: metav1.ObjectMeta{Name: "vm-1", Namespace: "ns"}, + Spec: kubevirtv1.VirtualMachineSpec{Template: &kubevirtv1.VirtualMachineInstanceTemplateSpec{ + Spec: kubevirtv1.VirtualMachineInstanceSpec{ + Domain: kubevirtv1.DomainSpec{ + CPU: &kubevirtv1.CPU{Cores: 2, Sockets: 2, Threads: 2, Model: "Skylake-Client"}, + Resources: kubevirtv1.ResourceRequirements{ + Requests: corev1.ResourceList{corev1.ResourceMemory: resource.MustParse("512Mi")}, + }, + Devices: kubevirtv1.Devices{ + Disks: []kubevirtv1.Disk{ + {Name: "root", DiskDevice: kubevirtv1.DiskDevice{Disk: &kubevirtv1.DiskTarget{Bus: "virtio"}}}, + {Name: "data", DiskDevice: kubevirtv1.DiskDevice{Disk: &kubevirtv1.DiskTarget{Bus: "sata"}}}, + }, + Interfaces: []kubevirtv1.Interface{ + {Name: "default", MacAddress: "02:00:00:00:00:01", InterfaceBindingMethod: kubevirtv1.InterfaceBindingMethod{Masquerade: &kubevirtv1.InterfaceMasquerade{}}}, + }, + }, + }, + Volumes: []kubevirtv1.Volume{ + {Name: "root", VolumeSource: kubevirtv1.VolumeSource{ContainerDisk: &kubevirtv1.ContainerDiskSource{Image: "img"}}}, + {Name: "data", VolumeSource: kubevirtv1.VolumeSource{EmptyDisk: &kubevirtv1.EmptyDiskSource{Capacity: resource.MustParse("10Gi")}}}, + }, + }, + }}, + } + require.NoError(t, mock.AddVM(vm)) + + cfg := &config.Config{ + Server: config.ServerConfig{Host: "localhost", Port: 8080, TestMode: true}, + Auth: config.AuthConfig{Users: []config.UserConfig{ + {Username: "u", Password: config.PasswordConfig{Plain: "p"}, Chassis: []string{"c"}}, + }}, + Chassis: []config.ChassisConfig{{Name: "c", Namespace: "ns"}}, + } + client := kubevirt.NewClientWithClients(fake.NewSimpleClientset(), mock, 30*time.Second, nil) + return NewServer(cfg, client) +} + +func getSystemPath(srv *Server, path string) *httptest.ResponseRecorder { + req := httptest.NewRequest("GET", path, nil) + authCtx := &auth.AuthContext{User: &auth.User{Username: "u", Chassis: []string{"c"}}} + req = req.WithContext(logger.WithAuth(req.Context(), authCtx)) + w := httptest.NewRecorder() + srv.handleSystem(w, req) + return w +} + +func TestSystemDevices(t *testing.T) { + srv := newDevicesTestServer(t) + + get := func(t *testing.T, path string) map[string]interface{} { + t.Helper() + w := getSystemPath(srv, path) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + var body map[string]interface{} + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body)) + return body + } + + t.Run("system links the sub-resources and summarises hardware", func(t *testing.T) { + b := get(t, "/redfish/v1/Systems/vm-1") + assert.Equal(t, "/redfish/v1/Systems/vm-1/Memory", b["Memory"].(map[string]interface{})["@odata.id"]) + assert.Equal(t, "/redfish/v1/Systems/vm-1/Processors", b["Processors"].(map[string]interface{})["@odata.id"]) + assert.Equal(t, 0.5, b["MemorySummary"].(map[string]interface{})["TotalSystemMemoryGiB"]) + ps := b["ProcessorSummary"].(map[string]interface{}) + assert.EqualValues(t, 2, ps["Count"], "Count is the socket count") + assert.EqualValues(t, 4, ps["CoreCount"]) + assert.EqualValues(t, 8, ps["LogicalProcessorCount"]) + assert.Equal(t, true, ps["ThreadingEnabled"]) + assert.Equal(t, "Skylake-Client", ps["Model"]) + topo := ps["Oem"].(map[string]interface{})["KubeVirt"].(map[string]interface{}) + assert.EqualValues(t, 2, topo["Sockets"]) + assert.EqualValues(t, 2, topo["CoresPerSocket"]) + assert.EqualValues(t, 2, topo["ThreadsPerCore"]) + }) + + t.Run("memory", func(t *testing.T) { + c := get(t, "/redfish/v1/Systems/vm-1/Memory") + assert.EqualValues(t, 1, c["Members@odata.count"]) + m := get(t, "/redfish/v1/Systems/vm-1/Memory/1") + assert.EqualValues(t, 512, m["CapacityMiB"]) + assert.EqualValues(t, 0.5, m["Oem"].(map[string]interface{})["KubeVirt"].(map[string]interface{})["CapacityGiB"]) + }) + + t.Run("processors report cores and threads per socket", func(t *testing.T) { + c := get(t, "/redfish/v1/Systems/vm-1/Processors") + assert.EqualValues(t, 2, c["Members@odata.count"]) + p := get(t, "/redfish/v1/Systems/vm-1/Processors/CPU1") + assert.Equal(t, "1", p["Socket"]) + assert.Equal(t, "CPU", p["ProcessorType"]) + assert.EqualValues(t, 2, p["TotalCores"]) + assert.EqualValues(t, 4, p["TotalThreads"]) + assert.Equal(t, "Skylake-Client", p["Model"]) + }) + + t.Run("storage lists every disk with its capacity", func(t *testing.T) { + get(t, "/redfish/v1/Systems/vm-1/Storage/") + s := get(t, "/redfish/v1/Systems/vm-1/Storage/1") + assert.EqualValues(t, 2, s["Drives@odata.count"]) + root := get(t, "/redfish/v1/Systems/vm-1/Storage/1/Drives/root") + assert.NotContains(t, root, "CapacityBytes", "containerDisk has no declared size") + data := get(t, "/redfish/v1/Systems/vm-1/Storage/1/Drives/data") + assert.EqualValues(t, 10<<30, data["CapacityBytes"]) + assert.EqualValues(t, 10, data["Oem"].(map[string]interface{})["KubeVirt"].(map[string]interface{})["CapacityGiB"]) + assert.NotContains(t, root, "Oem") + assert.Equal(t, "SATA", data["Protocol"]) + }) + + t.Run("ethernet interfaces expose the MAC", func(t *testing.T) { + c := get(t, "/redfish/v1/Systems/vm-1/EthernetInterfaces") + assert.EqualValues(t, 1, c["Members@odata.count"]) + e := get(t, "/redfish/v1/Systems/vm-1/EthernetInterfaces/default") + assert.Equal(t, "02:00:00:00:00:01", e["MACAddress"]) + assert.Equal(t, "NoLink", e["LinkStatus"], "VM is not running") + assert.NotContains(t, e, "SpeedMbps") + }) + + t.Run("unknown members are 404, not the system body", func(t *testing.T) { + for _, p := range []string{ + "/redfish/v1/Systems/vm-1/Memory/2", + "/redfish/v1/Systems/vm-1/Processors/CPU2", + "/redfish/v1/Systems/vm-1/Processors/CPUx", + "/redfish/v1/Systems/vm-1/Processors/CPU01", + "/redfish/v1/Systems/vm-1/Storage/2", + "/redfish/v1/Systems/vm-1/Storage/1/Drives/nope", + "/redfish/v1/Systems/vm-1/EthernetInterfaces/nope", + "/redfish/v1/Systems/vm-1/EthernetInterfaces/default/extra", + } { + assert.Equal(t, http.StatusNotFound, getSystemPath(srv, p).Code, p) + } + }) + + t.Run("non-GET is rejected", func(t *testing.T) { + req := httptest.NewRequest("POST", "/redfish/v1/Systems/vm-1/Storage", nil) + req = req.WithContext(logger.WithAuth(req.Context(), &auth.AuthContext{User: &auth.User{Username: "u", Chassis: []string{"c"}}})) + w := httptest.NewRecorder() + srv.handleSystem(w, req) + assert.Equal(t, http.StatusMethodNotAllowed, w.Code) + }) +} From fcead6b553ad7ae4e72654e6fc02b50c3044b870 Mon Sep 17 00:00:00 2001 From: Tomer Karniol Date: Fri, 9 Oct 2026 17:12:23 +0300 Subject: [PATCH 2/8] feat(server): report processor architecture and instruction set Processors had no architecture, so clients such as sushy/Ironic reported the architecture as unknown. Map spec.architecture (unset means amd64, the KubeVirt default) to ProcessorArchitecture and InstructionSet: amd64 -> x86 / x86-64 and arm64 -> ARM / ARM-A64. Other architectures are omitted rather than guessed. Signed-off-by: Tomer Karniol --- pkg/kubevirt/client.go | 29 +++++++++++++++--------- pkg/kubevirt/devices_test.go | 17 +++++++++++++- pkg/redfish/types.go | 13 +++++++---- pkg/server/system_devices.go | 37 ++++++++++++++++++++++--------- pkg/server/system_devices_test.go | 14 ++++++++++++ 5 files changed, 84 insertions(+), 26 deletions(-) diff --git a/pkg/kubevirt/client.go b/pkg/kubevirt/client.go index 5b1805c..32b4144 100644 --- a/pkg/kubevirt/client.go +++ b/pkg/kubevirt/client.go @@ -2592,6 +2592,9 @@ type CPUTopology struct { // Model is domain.cpu.model as configured (e.g. "host-model", "Skylake-Client"); // empty when the VM leaves it to the cluster default. Model string + // Architecture is spec.architecture ("amd64", "arm64"); an unset value is + // reported as "amd64", the KubeVirt default. + Architecture string } // VCPUs returns the total number of vCPUs (sockets x cores x threads). @@ -2601,19 +2604,25 @@ func (t CPUTopology) VCPUs() int { return t.Sockets * t.Cores * t.Threads } func (c *Client) GetVMCPUTopology(namespace, name string) (CPUTopology, error) { vm, err := c.getVMForRead(namespace, name) if err != nil { - return CPUTopology{Sockets: 1, Cores: 1, Threads: 1}, fmt.Errorf("failed to get VM %s/%s for CPU lookup: %w", namespace, name, err) + return CPUTopology{Sockets: 1, Cores: 1, Threads: 1, Architecture: "amd64"}, fmt.Errorf("failed to get VM %s/%s for CPU lookup: %w", namespace, name, err) } - if vm.Spec.Template == nil || vm.Spec.Template.Spec.Domain.CPU == nil { - logger.Warning("CPU not found in VM spec for %s/%s, using 1 vCPU", namespace, name) - return CPUTopology{Sockets: 1, Cores: 1, Threads: 1}, nil + topo := CPUTopology{Sockets: 1, Cores: 1, Threads: 1, Architecture: "amd64"} + if vm.Spec.Template == nil { + return topo, nil + } + if arch := vm.Spec.Template.Spec.Architecture; arch != "" { + topo.Architecture = arch } cpu := vm.Spec.Template.Spec.Domain.CPU - return CPUTopology{ - Sockets: int(max(cpu.Sockets, 1)), - Cores: int(max(cpu.Cores, 1)), - Threads: int(max(cpu.Threads, 1)), - Model: cpu.Model, - }, nil + if cpu == nil { + logger.Warning("CPU not found in VM spec for %s/%s, using 1 vCPU", namespace, name) + return topo, nil + } + topo.Sockets = int(max(cpu.Sockets, 1)) + topo.Cores = int(max(cpu.Cores, 1)) + topo.Threads = int(max(cpu.Threads, 1)) + topo.Model = cpu.Model + return topo, nil } // GetVMCPU gets the total vCPU count of a VirtualMachine (sockets x cores x threads). diff --git a/pkg/kubevirt/devices_test.go b/pkg/kubevirt/devices_test.go index 3aa50bf..8c9f5fb 100644 --- a/pkg/kubevirt/devices_test.go +++ b/pkg/kubevirt/devices_test.go @@ -76,9 +76,12 @@ func TestGetVMCPUTopology(t *testing.T) { } c := NewClientWithClients(fake.NewSimpleClientset(), mock, 30*time.Second, nil) got, err := c.GetVMCPUTopology("ns", "vm") - if err != nil || got != (CPUTopology{Sockets: 2, Cores: 4, Threads: 2, Model: "host-model"}) || got.VCPUs() != 16 { + if err != nil || got != (CPUTopology{Sockets: 2, Cores: 4, Threads: 2, Model: "host-model", Architecture: "amd64"}) || got.VCPUs() != 16 { t.Errorf("topology = %+v, %v", got, err) } + if got.Architecture != "amd64" { + t.Errorf("unset architecture = %q, want the amd64 default", got.Architecture) + } if _, err := c.GetVMCPUTopology("ns", "nope"); err == nil { t.Error("expected an error for a missing VM") } @@ -246,3 +249,15 @@ func TestGetVMNICs(t *testing.T) { } }) } + +func TestGetVMCPUTopology_Architecture(t *testing.T) { + mock := NewMockDynamicClient() + if err := mock.AddVM(deviceTestVM(kubevirtv1.VirtualMachineInstanceSpec{Architecture: "arm64"})); err != nil { + t.Fatal(err) + } + c := NewClientWithClients(fake.NewSimpleClientset(), mock, 30*time.Second, nil) + got, err := c.GetVMCPUTopology("ns", "vm") + if err != nil || got.Architecture != "arm64" { + t.Errorf("architecture = %q, %v; want arm64", got.Architecture, err) + } +} diff --git a/pkg/redfish/types.go b/pkg/redfish/types.go index 731a028..8e0bf5d 100644 --- a/pkg/redfish/types.go +++ b/pkg/redfish/types.go @@ -477,8 +477,13 @@ type Processor struct { Name string `json:"Name"` Socket string `json:"Socket"` ProcessorType string `json:"ProcessorType"` - TotalCores int `json:"TotalCores"` - TotalThreads int `json:"TotalThreads"` - Model string `json:"Model,omitempty"` - Status Status `json:"Status"` + // ProcessorArchitecture is the Redfish family ("x86", "ARM") and + // InstructionSet the specific set ("x86-64", "ARM-A64"); both are omitted + // for architectures without a mapping. + ProcessorArchitecture string `json:"ProcessorArchitecture,omitempty"` + InstructionSet string `json:"InstructionSet,omitempty"` + TotalCores int `json:"TotalCores"` + TotalThreads int `json:"TotalThreads"` + Model string `json:"Model,omitempty"` + Status Status `json:"Status"` } diff --git a/pkg/server/system_devices.go b/pkg/server/system_devices.go index 45f2627..3b367c5 100644 --- a/pkg/server/system_devices.go +++ b/pkg/server/system_devices.go @@ -125,18 +125,21 @@ func (s *Server) serveProcessors(w http.ResponseWriter, namespace, vmName, base s.sendNotFound(w, "Processor not found") return } + arch, isa := redfishArchitecture(cpu.Architecture) s.writeResource(w, redfish.Processor{ - OdataContext: "/redfish/v1/$metadata#Processor.Processor", - OdataID: fmt.Sprintf("%s/CPU%d", self, socket), - OdataType: "#Processor.v1_0_0.Processor", - ID: rest[1], - Name: fmt.Sprintf("vCPU Socket %d", socket), - Socket: fmt.Sprint(socket), - ProcessorType: "CPU", - TotalCores: cpu.Cores, - TotalThreads: cpu.Cores * cpu.Threads, - Model: cpu.Model, - Status: okStatus, + OdataContext: "/redfish/v1/$metadata#Processor.Processor", + OdataID: fmt.Sprintf("%s/CPU%d", self, socket), + OdataType: "#Processor.v1_0_0.Processor", + ID: rest[1], + Name: fmt.Sprintf("vCPU Socket %d", socket), + Socket: fmt.Sprint(socket), + ProcessorType: "CPU", + ProcessorArchitecture: arch, + InstructionSet: isa, + TotalCores: cpu.Cores, + TotalThreads: cpu.Cores * cpu.Threads, + Model: cpu.Model, + Status: okStatus, }) } @@ -253,6 +256,18 @@ func (s *Server) serveEthernetInterfaces(w http.ResponseWriter, namespace, vmNam s.sendNotFound(w, "Ethernet interface not found") } +// redfishArchitecture maps a KubeVirt architecture to the Redfish +// ProcessorArchitecture and InstructionSet values. Unknown architectures map to "". +func redfishArchitecture(kubevirtArch string) (arch, instructionSet string) { + switch kubevirtArch { + case "amd64": + return "x86", "x86-64" + case "arm64": + return "ARM", "ARM-A64" + } + return "", "" +} + // processorSummary maps a VM's vCPU topology to the Redfish ProcessorSummary. func processorSummary(cpu kubevirt.CPUTopology) redfish.ProcessorSummary { oem := &redfish.CPUTopologyOem{} diff --git a/pkg/server/system_devices_test.go b/pkg/server/system_devices_test.go index 8a8680e..b2e5bed 100644 --- a/pkg/server/system_devices_test.go +++ b/pkg/server/system_devices_test.go @@ -136,6 +136,8 @@ func TestSystemDevices(t *testing.T) { assert.EqualValues(t, 2, p["TotalCores"]) assert.EqualValues(t, 4, p["TotalThreads"]) assert.Equal(t, "Skylake-Client", p["Model"]) + assert.Equal(t, "x86", p["ProcessorArchitecture"], "unset architecture defaults to amd64") + assert.Equal(t, "x86-64", p["InstructionSet"]) }) t.Run("storage lists every disk with its capacity", func(t *testing.T) { @@ -183,3 +185,15 @@ func TestSystemDevices(t *testing.T) { assert.Equal(t, http.StatusMethodNotAllowed, w.Code) }) } + +func TestRedfishArchitecture(t *testing.T) { + for in, want := range map[string][2]string{ + "amd64": {"x86", "x86-64"}, + "arm64": {"ARM", "ARM-A64"}, + "s390x": {"", ""}, + "ppc64le": {"", ""}, + } { + arch, isa := redfishArchitecture(in) + assert.Equal(t, want, [2]string{arch, isa}, in) + } +} From 383b7ef79b4af8740db6a245a4fb07d9fcbb4b2b Mon Sep 17 00:00:00 2001 From: Tomer Karniol Date: Fri, 9 Oct 2026 17:18:07 +0300 Subject: [PATCH 3/8] fix(server): do not guess the processor architecture When a VM declares no spec.architecture, leave ProcessorArchitecture and InstructionSet out instead of assuming amd64. KubeVirt's real default is the cluster's configured architecture, so a hardcoded amd64 would be wrong on an arm64 cluster. KubeVirt normally fills the field in on creation, so the common case is unchanged. Signed-off-by: Tomer Karniol --- pkg/kubevirt/client.go | 12 +++++------- pkg/kubevirt/devices_test.go | 6 +++--- pkg/server/system_devices_test.go | 32 +++++++++++++++++++++++++++---- 3 files changed, 36 insertions(+), 14 deletions(-) diff --git a/pkg/kubevirt/client.go b/pkg/kubevirt/client.go index 32b4144..bb42f69 100644 --- a/pkg/kubevirt/client.go +++ b/pkg/kubevirt/client.go @@ -2592,8 +2592,8 @@ type CPUTopology struct { // Model is domain.cpu.model as configured (e.g. "host-model", "Skylake-Client"); // empty when the VM leaves it to the cluster default. Model string - // Architecture is spec.architecture ("amd64", "arm64"); an unset value is - // reported as "amd64", the KubeVirt default. + // Architecture is spec.architecture ("amd64", "arm64"). It is empty when the + // VM does not declare one (KubeVirt normally fills it in on creation). Architecture string } @@ -2604,15 +2604,13 @@ func (t CPUTopology) VCPUs() int { return t.Sockets * t.Cores * t.Threads } func (c *Client) GetVMCPUTopology(namespace, name string) (CPUTopology, error) { vm, err := c.getVMForRead(namespace, name) if err != nil { - return CPUTopology{Sockets: 1, Cores: 1, Threads: 1, Architecture: "amd64"}, fmt.Errorf("failed to get VM %s/%s for CPU lookup: %w", namespace, name, err) + return CPUTopology{Sockets: 1, Cores: 1, Threads: 1}, fmt.Errorf("failed to get VM %s/%s for CPU lookup: %w", namespace, name, err) } - topo := CPUTopology{Sockets: 1, Cores: 1, Threads: 1, Architecture: "amd64"} + topo := CPUTopology{Sockets: 1, Cores: 1, Threads: 1} if vm.Spec.Template == nil { return topo, nil } - if arch := vm.Spec.Template.Spec.Architecture; arch != "" { - topo.Architecture = arch - } + topo.Architecture = vm.Spec.Template.Spec.Architecture cpu := vm.Spec.Template.Spec.Domain.CPU if cpu == nil { logger.Warning("CPU not found in VM spec for %s/%s, using 1 vCPU", namespace, name) diff --git a/pkg/kubevirt/devices_test.go b/pkg/kubevirt/devices_test.go index 8c9f5fb..69de7fd 100644 --- a/pkg/kubevirt/devices_test.go +++ b/pkg/kubevirt/devices_test.go @@ -76,11 +76,11 @@ func TestGetVMCPUTopology(t *testing.T) { } c := NewClientWithClients(fake.NewSimpleClientset(), mock, 30*time.Second, nil) got, err := c.GetVMCPUTopology("ns", "vm") - if err != nil || got != (CPUTopology{Sockets: 2, Cores: 4, Threads: 2, Model: "host-model", Architecture: "amd64"}) || got.VCPUs() != 16 { + if err != nil || got != (CPUTopology{Sockets: 2, Cores: 4, Threads: 2, Model: "host-model"}) || got.VCPUs() != 16 { t.Errorf("topology = %+v, %v", got, err) } - if got.Architecture != "amd64" { - t.Errorf("unset architecture = %q, want the amd64 default", got.Architecture) + if got.Architecture != "" { + t.Errorf("unset architecture = %q, want it left empty, not guessed", got.Architecture) } if _, err := c.GetVMCPUTopology("ns", "nope"); err == nil { t.Error("expected an error for a missing VM") diff --git a/pkg/server/system_devices_test.go b/pkg/server/system_devices_test.go index b2e5bed..7b90fb4 100644 --- a/pkg/server/system_devices_test.go +++ b/pkg/server/system_devices_test.go @@ -39,13 +39,14 @@ import ( kubevirtv1 "kubevirt.io/api/core/v1" ) -func newDevicesTestServer(t *testing.T) *Server { +func newDevicesTestServer(t *testing.T, arch string) *Server { t.Helper() mock := kubevirt.NewMockDynamicClient() vm := &kubevirtv1.VirtualMachine{ ObjectMeta: metav1.ObjectMeta{Name: "vm-1", Namespace: "ns"}, Spec: kubevirtv1.VirtualMachineSpec{Template: &kubevirtv1.VirtualMachineInstanceTemplateSpec{ Spec: kubevirtv1.VirtualMachineInstanceSpec{ + Architecture: arch, Domain: kubevirtv1.DomainSpec{ CPU: &kubevirtv1.CPU{Cores: 2, Sockets: 2, Threads: 2, Model: "Skylake-Client"}, Resources: kubevirtv1.ResourceRequirements{ @@ -91,7 +92,7 @@ func getSystemPath(srv *Server, path string) *httptest.ResponseRecorder { } func TestSystemDevices(t *testing.T) { - srv := newDevicesTestServer(t) + srv := newDevicesTestServer(t, "") get := func(t *testing.T, path string) map[string]interface{} { t.Helper() @@ -136,8 +137,8 @@ func TestSystemDevices(t *testing.T) { assert.EqualValues(t, 2, p["TotalCores"]) assert.EqualValues(t, 4, p["TotalThreads"]) assert.Equal(t, "Skylake-Client", p["Model"]) - assert.Equal(t, "x86", p["ProcessorArchitecture"], "unset architecture defaults to amd64") - assert.Equal(t, "x86-64", p["InstructionSet"]) + assert.NotContains(t, p, "ProcessorArchitecture", "VM declares no architecture, so none is guessed") + assert.NotContains(t, p, "InstructionSet") }) t.Run("storage lists every disk with its capacity", func(t *testing.T) { @@ -197,3 +198,26 @@ func TestRedfishArchitecture(t *testing.T) { assert.Equal(t, want, [2]string{arch, isa}, in) } } + +func TestProcessorArchitecture(t *testing.T) { + for _, tc := range []struct{ arch, wantArch, wantISA string }{ + {"amd64", "x86", "x86-64"}, + {"arm64", "ARM", "ARM-A64"}, + {"s390x", "", ""}, + } { + t.Run(tc.arch, func(t *testing.T) { + srv := newDevicesTestServer(t, tc.arch) + w := getSystemPath(srv, "/redfish/v1/Systems/vm-1/Processors/CPU0") + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + var p map[string]interface{} + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &p)) + if tc.wantArch == "" { + assert.NotContains(t, p, "ProcessorArchitecture") + assert.NotContains(t, p, "InstructionSet") + return + } + assert.Equal(t, tc.wantArch, p["ProcessorArchitecture"]) + assert.Equal(t, tc.wantISA, p["InstructionSet"]) + }) + } +} From 65848160a09b38d77feb54706a205edf885495dc Mon Sep 17 00:00:00 2001 From: Tomer Karniol Date: Fri, 9 Oct 2026 19:00:12 +0300 Subject: [PATCH 4/8] fix(server): report real errors and valid schema versions for system hardware Follow-up fixes found while testing the Memory, Processors, Storage and EthernetInterfaces resources on OpenShift Virtualization and reviewing the change. Cost: - Read the size of one drive per request instead of one PVC per disk. GetVMDisks now returns names and bus only; GetVMDisk resolves a single size. A 24-disk VM went from about 4.7s to about 0.5s per request. Errors that were hidden: - A PVC that cannot be read for a reason other than NotFound (forbidden, timeout) is now an error (HTTP 500) instead of a size taken from the DataVolume template. - A VMI that cannot be read for a reason other than NotFound is now an error instead of reporting NoLink for a VM that may be running. The test mock returns a typed NotFound like the real API. - If the CPU topology cannot be read, ProcessorSummary and Oem are left out instead of showing a guessed 1/1/1. GetVMCPUTopology returns the zero value on error, and the now unused GetVMCPU is removed. Schema: - Declare versions that define what is emitted, checked with the DMTF Redfish Service Validator: ComputerSystem v1_15_0, Memory v1_1_0, EthernetInterface v1_1_0 and VirtualMedia v1_2_0. - ProcessorSummary has no Oem property in any schema version, so the vCPU layout moves to the system-level Oem. - Add IPv6Addresses next to IPv4Addresses. - A zero-sized emptyDisk reports no capacity. Remove the unused Drive.MediaType and EthernetInterface.Description fields. Tests cover forbidden/timeout/not-found for PVC and VMI reads, the PVC lookup count for a 24-disk VM, users without access to the chassis, a running NIC with IPv4 and IPv6, empty VMs, and the schema versions. Signed-off-by: Tomer Karniol --- pkg/kubevirt/client.go | 13 +- pkg/kubevirt/client_test.go | 7 +- pkg/kubevirt/devices.go | 106 +++++++++---- pkg/kubevirt/devices_test.go | 254 ++++++++++++++++++++++++++++-- pkg/redfish/types.go | 62 ++++---- pkg/server/server.go | 22 ++- pkg/server/system_devices.go | 96 +++++++---- pkg/server/system_devices_test.go | 233 ++++++++++++++++++++++++--- 8 files changed, 640 insertions(+), 153 deletions(-) diff --git a/pkg/kubevirt/client.go b/pkg/kubevirt/client.go index bb42f69..ab81d80 100644 --- a/pkg/kubevirt/client.go +++ b/pkg/kubevirt/client.go @@ -2601,10 +2601,11 @@ type CPUTopology struct { func (t CPUTopology) VCPUs() int { return t.Sockets * t.Cores * t.Threads } // GetVMCPUTopology returns the sockets, cores per socket and threads per core of a VM. +// On error it returns the zero value, never a guessed topology. func (c *Client) GetVMCPUTopology(namespace, name string) (CPUTopology, error) { vm, err := c.getVMForRead(namespace, name) if err != nil { - return CPUTopology{Sockets: 1, Cores: 1, Threads: 1}, fmt.Errorf("failed to get VM %s/%s for CPU lookup: %w", namespace, name, err) + return CPUTopology{}, fmt.Errorf("failed to get VM %s/%s for CPU lookup: %w", namespace, name, err) } topo := CPUTopology{Sockets: 1, Cores: 1, Threads: 1} if vm.Spec.Template == nil { @@ -2623,16 +2624,6 @@ func (c *Client) GetVMCPUTopology(namespace, name string) (CPUTopology, error) { return topo, nil } -// GetVMCPU gets the total vCPU count of a VirtualMachine (sockets x cores x threads). -func (c *Client) GetVMCPU(namespace, name string) (int, error) { - t, err := c.GetVMCPUTopology(namespace, name) - if err != nil { - logger.Warning("%v", err) - return 1, nil // Low default fallback - } - return t.VCPUs(), nil -} - // GetVMStorageDetails gets detailed storage information of a VirtualMachine func (c *Client) GetVMStorageDetails(namespace, name string) (map[string]interface{}, error) { vm, err := c.getVMForRead(namespace, name) diff --git a/pkg/kubevirt/client_test.go b/pkg/kubevirt/client_test.go index 58c91ff..4d27bf1 100644 --- a/pkg/kubevirt/client_test.go +++ b/pkg/kubevirt/client_test.go @@ -1634,7 +1634,7 @@ func TestGetVMMemory(t *testing.T) { } } -// TestGetVMCPU tests the GetVMCPU function using MockDynamicClient +// TestGetVMCPU tests the vCPU count derived from GetVMCPUTopology using MockDynamicClient func TestGetVMCPU(t *testing.T) { testCases := []struct { name string @@ -1724,8 +1724,9 @@ func TestGetVMCPU(t *testing.T) { // Create client with mock clients client := NewClientWithClients(fakeK8sClient, mockDynamicClient, 30*time.Second, nil) - // Call the actual GetVMCPU function - result, err := client.GetVMCPU("test-namespace", "test-vm") + // Total vCPUs come from the topology (sockets x cores x threads) + topology, err := client.GetVMCPUTopology("test-namespace", "test-vm") + result := topology.VCPUs() if err != nil { t.Fatalf("Unexpected error: %v", err) } diff --git a/pkg/kubevirt/devices.go b/pkg/kubevirt/devices.go index fb7ce5e..539d61d 100644 --- a/pkg/kubevirt/devices.go +++ b/pkg/kubevirt/devices.go @@ -21,9 +21,11 @@ package kubevirt import ( "context" + "fmt" "math" corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kubevirtv1 "kubevirt.io/api/core/v1" ) @@ -33,7 +35,7 @@ type VMDisk struct { Name string Bus string // CapacityBytes is nil when the spec does not declare a size - // (containerDisk, cloudInit, ...). + // (containerDisk, cloudInit, ...) and always nil from GetVMDisks. CapacityBytes *int64 } @@ -56,23 +58,18 @@ func (c *Client) VMMemoryMiB(namespace, name string) (int64, error) { return int64(math.Round(gib * 1024)), nil } -// GetVMDisks returns every disk of a VM in spec order. CD-ROM devices are -// excluded because they are exposed as VirtualMedia. -func (c *Client) GetVMDisks(namespace, name string) ([]VMDisk, error) { - vm, err := c.getVMForRead(namespace, name) - if err != nil { - return nil, err - } +// vmDisks lists the disks of a VM in spec order together with their backing +// volume (nil when the spec has none). CD-ROM devices are excluded because +// they are exposed as VirtualMedia. It makes no API calls. +func vmDisks(vm *kubevirtv1.VirtualMachine) (disks []VMDisk, volumes []*kubevirtv1.Volume) { if vm.Spec.Template == nil { return nil, nil } - - volumes := map[string]kubevirtv1.Volume{} - for _, v := range vm.Spec.Template.Spec.Volumes { - volumes[v.Name] = v + byName := map[string]*kubevirtv1.Volume{} + for i := range vm.Spec.Template.Spec.Volumes { + v := &vm.Spec.Template.Spec.Volumes[i] + byName[v.Name] = v } - - var disks []VMDisk for _, d := range vm.Spec.Template.Spec.Domain.Devices.Disks { if d.CDRom != nil { continue @@ -84,16 +81,53 @@ func (c *Client) GetVMDisks(namespace, name string) ([]VMDisk, error) { case d.LUN != nil: disk.Bus = string(d.LUN.Bus) } - if vol, ok := volumes[d.Name]; ok { - disk.CapacityBytes = c.volumeCapacityBytes(namespace, vm, vol) - } disks = append(disks, disk) + volumes = append(volumes, byName[d.Name]) } + return disks, volumes +} + +// GetVMDisks returns the disks of a VM in spec order with name and bus only. +// CapacityBytes is left unset on purpose: resolving a size can cost an API +// call per disk, so use GetVMDisk when the size of one disk is needed. +func (c *Client) GetVMDisks(namespace, name string) ([]VMDisk, error) { + vm, err := c.getVMForRead(namespace, name) + if err != nil { + return nil, err + } + disks, _ := vmDisks(vm) return disks, nil } -// volumeCapacityBytes resolves the declared size of a volume, or nil if unknown. -func (c *Client) volumeCapacityBytes(namespace string, vm *kubevirtv1.VirtualMachine, vol kubevirtv1.Volume) *int64 { +// GetVMDisk returns one disk of a VM including its capacity, or nil if the VM +// has no such disk. Only that disk's size is looked up. +func (c *Client) GetVMDisk(namespace, name, disk string) (*VMDisk, error) { + vm, err := c.getVMForRead(namespace, name) + if err != nil { + return nil, err + } + disks, volumes := vmDisks(vm) + for i := range disks { + if disks[i].Name != disk { + continue + } + if volumes[i] != nil { + capacity, err := c.volumeCapacityBytes(namespace, vm, *volumes[i]) + if err != nil { + return nil, err + } + disks[i].CapacityBytes = capacity + } + return &disks[i], nil + } + return nil, nil +} + +// volumeCapacityBytes resolves the declared size of a volume, or nil if it has +// none. A PVC that does not exist yet falls back to the DataVolume template; +// any other failure to read the PVC (forbidden, timeout, ...) is returned so +// the caller does not report a size that may be wrong. +func (c *Client) volumeCapacityBytes(namespace string, vm *kubevirtv1.VirtualMachine, vol kubevirtv1.Volume) (*int64, error) { var claim string switch { case vol.PersistentVolumeClaim != nil: @@ -103,16 +137,19 @@ func (c *Client) volumeCapacityBytes(namespace string, vm *kubevirtv1.VirtualMac case vol.Ephemeral != nil && vol.Ephemeral.PersistentVolumeClaim != nil: claim = vol.Ephemeral.PersistentVolumeClaim.ClaimName case vol.EmptyDisk != nil: + if vol.EmptyDisk.Capacity.IsZero() { + return nil, nil + } b := vol.EmptyDisk.Capacity.Value() - return &b + return &b, nil case vol.HostDisk != nil: if vol.HostDisk.Capacity.IsZero() { - return nil + return nil, nil } b := vol.HostDisk.Capacity.Value() - return &b + return &b, nil default: - return nil + return nil, nil } // Prefer the real PVC (actual provisioned size), fall back to the DataVolume template. @@ -120,15 +157,18 @@ func (c *Client) volumeCapacityBytes(namespace string, vm *kubevirtv1.VirtualMac ctx, cancel := context.WithTimeout(context.Background(), c.timeout) defer cancel() pvc, err := c.kubernetesClient.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, claim, metav1.GetOptions{}) - if err == nil { + switch { + case err == nil: if q, ok := pvc.Status.Capacity[corev1.ResourceStorage]; ok { b := q.Value() - return &b + return &b, nil } if q, ok := pvc.Spec.Resources.Requests[corev1.ResourceStorage]; ok { b := q.Value() - return &b + return &b, nil } + case !apierrors.IsNotFound(err): + return nil, fmt.Errorf("failed to get PVC %s/%s: %w", namespace, claim, err) } } for _, dv := range vm.Spec.DataVolumeTemplates { @@ -138,17 +178,17 @@ func (c *Client) volumeCapacityBytes(namespace string, vm *kubevirtv1.VirtualMac if dv.Spec.Storage != nil { if q, ok := dv.Spec.Storage.Resources.Requests[corev1.ResourceStorage]; ok { b := q.Value() - return &b + return &b, nil } } if dv.Spec.PVC != nil { if q, ok := dv.Spec.PVC.Resources.Requests[corev1.ResourceStorage]; ok { b := q.Value() - return &b + return &b, nil } } } - return nil + return nil, nil } // GetVMNICs returns every network interface of a VM. The MAC and IPs come @@ -162,11 +202,17 @@ func (c *Client) GetVMNICs(namespace, name string) ([]VMNIC, error) { return nil, nil } + // No VMI means the VM is not running. Any other failure is returned: reporting + // NoLink for a running VM whose VMI could not be read would be wrong. status := map[string]kubevirtv1.VirtualMachineInstanceNetworkInterface{} - if vmi, err := c.getVMIForRead(namespace, name); err == nil { + vmi, err := c.getVMIForRead(namespace, name) + switch { + case err == nil: for _, s := range vmi.Status.Interfaces { status[s.Name] = s } + case !apierrors.IsNotFound(err): + return nil, err } var nics []VMNIC diff --git a/pkg/kubevirt/devices_test.go b/pkg/kubevirt/devices_test.go index 69de7fd..184a2c1 100644 --- a/pkg/kubevirt/devices_test.go +++ b/pkg/kubevirt/devices_test.go @@ -20,13 +20,22 @@ package kubevirt import ( + "context" + "errors" + "fmt" "testing" "time" corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/dynamic" "k8s.io/client-go/kubernetes/fake" + k8stesting "k8s.io/client-go/testing" kubevirtv1 "kubevirt.io/api/core/v1" cdiv1beta1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" ) @@ -40,7 +49,7 @@ func deviceTestVM(spec kubevirtv1.VirtualMachineInstanceSpec) *kubevirtv1.Virtua } } -func TestGetVMCPU_Topology(t *testing.T) { +func TestGetVMCPUTopology_VCPUs(t *testing.T) { cases := []struct { name string cpu kubevirtv1.CPU @@ -60,9 +69,9 @@ func TestGetVMCPU_Topology(t *testing.T) { t.Fatal(err) } c := NewClientWithClients(fake.NewSimpleClientset(), mock, 30*time.Second, nil) - got, err := c.GetVMCPU("ns", "vm") - if err != nil || got != tc.want { - t.Errorf("GetVMCPU = %d, %v; want %d", got, err, tc.want) + topo, err := c.GetVMCPUTopology("ns", "vm") + if got := topo.VCPUs(); err != nil || got != tc.want { + t.Errorf("vCPUs = %d, %v; want %d", got, err, tc.want) } }) } @@ -82,8 +91,8 @@ func TestGetVMCPUTopology(t *testing.T) { if got.Architecture != "" { t.Errorf("unset architecture = %q, want it left empty, not guessed", got.Architecture) } - if _, err := c.GetVMCPUTopology("ns", "nope"); err == nil { - t.Error("expected an error for a missing VM") + if zero, err := c.GetVMCPUTopology("ns", "nope"); err == nil || zero != (CPUTopology{}) { + t.Errorf("missing VM: got %+v, %v; want the zero topology and an error, never a guess", zero, err) } } @@ -164,12 +173,13 @@ func TestGetVMDisks(t *testing.T) { ObjectMeta: metav1.ObjectMeta{Name: "data-pvc", Namespace: "ns"}, Status: corev1.PersistentVolumeClaimStatus{Capacity: corev1.ResourceList{corev1.ResourceStorage: resource.MustParse("100Gi")}}, }) + pvcGets := 0 + k8s.PrependReactor("get", "persistentvolumeclaims", func(k8stesting.Action) (bool, runtime.Object, error) { + pvcGets++ + return false, nil, nil // count only, let the fake answer + }) c := NewClientWithClients(k8s, mock, 30*time.Second, nil) - disks, err := c.GetVMDisks("ns", "vm") - if err != nil { - t.Fatal(err) - } want := []struct { name string bus string @@ -181,21 +191,97 @@ func TestGetVMDisks(t *testing.T) { {"scratch", "virtio", 1 << 30}, {"cloud", "virtio", -1}, } + + // The list carries names and bus only and must not touch any PVC. + disks, err := c.GetVMDisks("ns", "vm") + if err != nil { + t.Fatal(err) + } if len(disks) != len(want) { t.Fatalf("got %d disks (%+v), want %d (cdrom must be excluded)", len(disks), disks, len(want)) } for i, w := range want { - d := disks[i] - if d.Name != w.name || d.Bus != w.bus { - t.Errorf("disk %d = %s/%s, want %s/%s", i, d.Name, d.Bus, w.name, w.bus) + if disks[i].Name != w.name || disks[i].Bus != w.bus || disks[i].CapacityBytes != nil { + t.Errorf("disk %d = %+v, want %s/%s and no capacity", i, disks[i], w.name, w.bus) + } + } + if pvcGets != 0 { + t.Errorf("GetVMDisks made %d PVC lookups, want 0", pvcGets) + } + + // A single disk resolves its own size, with at most one PVC lookup. + for _, w := range want { + pvcGets = 0 + d, err := c.GetVMDisk("ns", "vm", w.name) + if err != nil || d == nil { + t.Fatalf("GetVMDisk(%s) = %v, %v", w.name, d, err) + } + if d.Bus != w.bus { + t.Errorf("disk %s bus = %s, want %s", w.name, d.Bus, w.bus) } switch { case w.size < 0 && d.CapacityBytes != nil: - t.Errorf("disk %s: capacity %d, want unknown", d.Name, *d.CapacityBytes) + t.Errorf("disk %s: capacity %d, want unknown", w.name, *d.CapacityBytes) case w.size >= 0 && (d.CapacityBytes == nil || *d.CapacityBytes != w.size): - t.Errorf("disk %s: capacity %v, want %d", d.Name, d.CapacityBytes, w.size) + t.Errorf("disk %s: capacity %v, want %d", w.name, d.CapacityBytes, w.size) + } + if pvcGets > 1 { + t.Errorf("GetVMDisk(%s) made %d PVC lookups, want at most 1", w.name, pvcGets) } } + + // Unknown disks and CD-ROMs (exposed as VirtualMedia) are not drives. + for _, name := range []string{"nope", "cdrom0"} { + if d, err := c.GetVMDisk("ns", "vm", name); err != nil || d != nil { + t.Errorf("GetVMDisk(%s) = %v, %v; want nil, nil", name, d, err) + } + } + if _, err := c.GetVMDisk("ns", "missing-vm", "root"); err == nil { + t.Error("expected an error for a missing VM") + } +} + +// The cost of reading one drive must not depend on how many disks the VM has. +func TestGetVMDisk_LookupsDoNotGrowWithDiskCount(t *testing.T) { + const n = 24 + spec := kubevirtv1.VirtualMachineInstanceSpec{} + var pvcs []runtime.Object + for i := 0; i < n; i++ { + name := fmt.Sprintf("d%d", i) + claim := fmt.Sprintf("claim-%d", i) + spec.Domain.Devices.Disks = append(spec.Domain.Devices.Disks, + kubevirtv1.Disk{Name: name, DiskDevice: kubevirtv1.DiskDevice{Disk: &kubevirtv1.DiskTarget{Bus: "virtio"}}}) + spec.Volumes = append(spec.Volumes, kubevirtv1.Volume{Name: name, VolumeSource: kubevirtv1.VolumeSource{ + PersistentVolumeClaim: &kubevirtv1.PersistentVolumeClaimVolumeSource{ + PersistentVolumeClaimVolumeSource: corev1.PersistentVolumeClaimVolumeSource{ClaimName: claim}}}}) + pvcs = append(pvcs, &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{Name: claim, Namespace: "ns"}, + Spec: corev1.PersistentVolumeClaimSpec{Resources: corev1.VolumeResourceRequirements{ + Requests: corev1.ResourceList{corev1.ResourceStorage: *resource.NewQuantity(int64(i+1)<<30, resource.BinarySI)}}}, + }) + } + mock := NewMockDynamicClient() + if err := mock.AddVM(deviceTestVM(spec)); err != nil { + t.Fatal(err) + } + k8s := fake.NewSimpleClientset(pvcs...) + pvcGets := 0 + k8s.PrependReactor("get", "persistentvolumeclaims", func(k8stesting.Action) (bool, runtime.Object, error) { + pvcGets++ + return false, nil, nil + }) + c := NewClientWithClients(k8s, mock, 30*time.Second, nil) + + if disks, err := c.GetVMDisks("ns", "vm"); err != nil || len(disks) != n || pvcGets != 0 { + t.Fatalf("GetVMDisks: %d disks, %d PVC lookups, err %v; want %d, 0", len(disks), pvcGets, err, n) + } + d, err := c.GetVMDisk("ns", "vm", "d23") + if err != nil || d == nil || d.CapacityBytes == nil || *d.CapacityBytes != 24<<30 { + t.Fatalf("GetVMDisk(d23) = %+v, %v", d, err) + } + if pvcGets != 1 { + t.Errorf("reading one of %d drives made %d PVC lookups, want 1", n, pvcGets) + } } func TestGetVMNICs(t *testing.T) { @@ -261,3 +347,141 @@ func TestGetVMCPUTopology_Architecture(t *testing.T) { t.Errorf("architecture = %q, %v; want arm64", got.Architecture, err) } } + +// failingVMIs makes every VMI Get fail with err; everything else passes through. +type failingVMIs struct { + dynamic.Interface + err error +} + +func (f failingVMIs) Resource(gvr schema.GroupVersionResource) dynamic.NamespaceableResourceInterface { + r := f.Interface.Resource(gvr) + if gvr.Resource == "virtualmachineinstances" { + return failingVMIResource{NamespaceableResourceInterface: r, err: f.err} + } + return r +} + +type failingVMIResource struct { + dynamic.NamespaceableResourceInterface + err error +} + +func (r failingVMIResource) Namespace(ns string) dynamic.ResourceInterface { + return failingVMIGet{ResourceInterface: r.NamespaceableResourceInterface.Namespace(ns), err: r.err} +} + +type failingVMIGet struct { + dynamic.ResourceInterface + err error +} + +func (r failingVMIGet) Get(context.Context, string, metav1.GetOptions, ...string) (*unstructured.Unstructured, error) { + return nil, r.err +} + +// A PVC that cannot be read for any reason other than "not found" must surface +// as an error instead of a size taken from somewhere else. +func TestGetVMDisk_PVCReadErrorsAreNotHidden(t *testing.T) { + templateSize := resource.MustParse("20Gi") + vm := deviceTestVM(kubevirtv1.VirtualMachineInstanceSpec{ + Domain: kubevirtv1.DomainSpec{Devices: kubevirtv1.Devices{Disks: []kubevirtv1.Disk{ + {Name: "data", DiskDevice: kubevirtv1.DiskDevice{Disk: &kubevirtv1.DiskTarget{Bus: "virtio"}}}, + }}}, + Volumes: []kubevirtv1.Volume{{Name: "data", VolumeSource: kubevirtv1.VolumeSource{ + DataVolume: &kubevirtv1.DataVolumeSource{Name: "data-dv"}}}}, + }) + vm.Spec.DataVolumeTemplates = []kubevirtv1.DataVolumeTemplateSpec{{ + ObjectMeta: metav1.ObjectMeta{Name: "data-dv"}, + Spec: cdiv1beta1.DataVolumeSpec{Storage: &cdiv1beta1.StorageSpec{ + Resources: corev1.VolumeResourceRequirements{Requests: corev1.ResourceList{corev1.ResourceStorage: templateSize}}, + }}, + }} + gr := schema.GroupResource{Resource: "persistentvolumeclaims"} + + for name, tc := range map[string]struct { + err error + wantErr bool + wantSize int64 + }{ + "not found falls back to the template": {apierrors.NewNotFound(gr, "data-dv"), false, 20 << 30}, + "forbidden is returned": {apierrors.NewForbidden(gr, "data-dv", errors.New("no access")), true, 0}, + "timeout is returned": {apierrors.NewTimeoutError("slow", 1), true, 0}, + "server error is returned": {apierrors.NewInternalError(errors.New("boom")), true, 0}, + } { + t.Run(name, func(t *testing.T) { + mock := NewMockDynamicClient() + if err := mock.AddVM(vm.DeepCopy()); err != nil { + t.Fatal(err) + } + k8s := fake.NewSimpleClientset() + k8s.PrependReactor("get", "persistentvolumeclaims", func(k8stesting.Action) (bool, runtime.Object, error) { + return true, nil, tc.err + }) + c := NewClientWithClients(k8s, mock, 30*time.Second, nil) + d, err := c.GetVMDisk("ns", "vm", "data") + if tc.wantErr { + if err == nil || d != nil { + t.Fatalf("got %+v, %v; want an error and no disk", d, err) + } + return + } + if err != nil || d == nil || d.CapacityBytes == nil || *d.CapacityBytes != tc.wantSize { + t.Fatalf("got %+v, %v; want %d bytes from the template", d, err, tc.wantSize) + } + }) + } +} + +func TestGetVMDisk_ZeroSizedEmptyDiskHasNoCapacity(t *testing.T) { + mock := NewMockDynamicClient() + if err := mock.AddVM(deviceTestVM(kubevirtv1.VirtualMachineInstanceSpec{ + Domain: kubevirtv1.DomainSpec{Devices: kubevirtv1.Devices{Disks: []kubevirtv1.Disk{ + {Name: "scratch", DiskDevice: kubevirtv1.DiskDevice{Disk: &kubevirtv1.DiskTarget{Bus: "virtio"}}}, + }}}, + Volumes: []kubevirtv1.Volume{{Name: "scratch", VolumeSource: kubevirtv1.VolumeSource{EmptyDisk: &kubevirtv1.EmptyDiskSource{}}}}, + })); err != nil { + t.Fatal(err) + } + c := NewClientWithClients(fake.NewSimpleClientset(), mock, 30*time.Second, nil) + d, err := c.GetVMDisk("ns", "vm", "scratch") + if err != nil || d == nil || d.CapacityBytes != nil { + t.Errorf("got %+v, %v; want the drive without a capacity, not 0 bytes", d, err) + } +} + +// Only "no VMI" means the VM is stopped. Failing to read the VMI of a VM that may +// be running must be an error, not a NoLink answer. +func TestGetVMNICs_VMIReadErrorsAreNotHidden(t *testing.T) { + spec := kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{Devices: kubevirtv1.Devices{Interfaces: []kubevirtv1.Interface{ + {Name: "default", MacAddress: "02:00:00:00:00:01"}, + }}}} + gr := schema.GroupResource{Group: "kubevirt.io", Resource: "virtualmachineinstances"} + + for name, tc := range map[string]struct { + err error + wantErr bool + }{ + "not found means stopped": {apierrors.NewNotFound(gr, "vm"), false}, + "forbidden is returned": {apierrors.NewForbidden(gr, "vm", errors.New("no access")), true}, + "timeout is returned": {apierrors.NewTimeoutError("slow", 1), true}, + } { + t.Run(name, func(t *testing.T) { + mock := NewMockDynamicClient() + if err := mock.AddVM(deviceTestVM(spec)); err != nil { + t.Fatal(err) + } + c := NewClientWithClients(fake.NewSimpleClientset(), failingVMIs{Interface: mock, err: tc.err}, 30*time.Second, nil) + nics, err := c.GetVMNICs("ns", "vm") + if tc.wantErr { + if err == nil || nics != nil { + t.Fatalf("got %+v, %v; want an error and no NICs", nics, err) + } + return + } + if err != nil || len(nics) != 1 || nics[0].Running || nics[0].MAC != "02:00:00:00:00:01" { + t.Fatalf("got %+v, %v; want one stopped NIC with the spec MAC", nics, err) + } + }) + } +} diff --git a/pkg/redfish/types.go b/pkg/redfish/types.go index 8e0bf5d..0d63fcc 100644 --- a/pkg/redfish/types.go +++ b/pkg/redfish/types.go @@ -90,25 +90,26 @@ type ComputerSystemCollection struct { // This is the main resource type for representing KubeVirt VMs in the Redfish API. // It includes power state, status, memory information, CPU details, and available actions. type ComputerSystem struct { - OdataContext string `json:"@odata.context"` - OdataID string `json:"@odata.id"` - OdataType string `json:"@odata.type"` - OdataEtag string `json:"@odata.etag,omitempty"` - ID string `json:"Id"` - Name string `json:"Name"` - SystemType string `json:"SystemType"` - Status Status `json:"Status"` - PowerState string `json:"PowerState"` - MemorySummary MemorySummary `json:"MemorySummary"` - Memory Link `json:"Memory"` - Processors Link `json:"Processors"` - ProcessorSummary ProcessorSummary `json:"ProcessorSummary"` - Storage Link `json:"Storage"` - EthernetInterfaces Link `json:"EthernetInterfaces"` - VirtualMedia Link `json:"VirtualMedia"` - Boot Boot `json:"Boot"` - Actions Actions `json:"Actions"` - Links SystemLinks `json:"Links"` + OdataContext string `json:"@odata.context"` + OdataID string `json:"@odata.id"` + OdataType string `json:"@odata.type"` + OdataEtag string `json:"@odata.etag,omitempty"` + ID string `json:"Id"` + Name string `json:"Name"` + SystemType string `json:"SystemType"` + Status Status `json:"Status"` + PowerState string `json:"PowerState"` + MemorySummary MemorySummary `json:"MemorySummary"` + Memory Link `json:"Memory"` + Processors Link `json:"Processors"` + ProcessorSummary *ProcessorSummary `json:"ProcessorSummary,omitempty"` + Storage Link `json:"Storage"` + EthernetInterfaces Link `json:"EthernetInterfaces"` + VirtualMedia Link `json:"VirtualMedia"` + Boot Boot `json:"Boot"` + Actions Actions `json:"Actions"` + Links SystemLinks `json:"Links"` + Oem *SystemOem `json:"Oem,omitempty"` } // Status represents the status of a Redfish resource. @@ -135,16 +136,17 @@ type ProcessorSummary struct { LogicalProcessorCount int `json:"LogicalProcessorCount"` ThreadingEnabled bool `json:"ThreadingEnabled"` // Model is the configured virtual CPU model; omitted when the VM leaves it to the cluster default. - Model string `json:"Model,omitempty"` - Oem *CPUTopologyOem `json:"Oem,omitempty"` + Model string `json:"Model,omitempty"` } -// CPUTopologyOem spells out the vCPU layout the standard counts are derived from. -type CPUTopologyOem struct { +// SystemOem carries vendor extensions of a ComputerSystem. +type SystemOem struct { KubeVirt struct { - Sockets int `json:"Sockets"` - CoresPerSocket int `json:"CoresPerSocket"` - ThreadsPerCore int `json:"ThreadsPerCore"` + Processors struct { + Sockets int `json:"Sockets"` + CoresPerSocket int `json:"CoresPerSocket"` + ThreadsPerCore int `json:"ThreadsPerCore"` + } `json:"Processors"` } `json:"KubeVirt"` } @@ -430,7 +432,6 @@ type Drive struct { ID string `json:"Id"` Name string `json:"Name"` Protocol string `json:"Protocol,omitempty"` - MediaType string `json:"MediaType,omitempty"` CapacityBytes *int64 `json:"CapacityBytes,omitempty"` Status Status `json:"Status"` Oem *OemCapacity `json:"Oem,omitempty"` @@ -455,13 +456,18 @@ type EthernetInterface struct { OdataType string `json:"@odata.type"` ID string `json:"Id"` Name string `json:"Name"` - Description string `json:"Description,omitempty"` MACAddress string `json:"MACAddress,omitempty"` LinkStatus string `json:"LinkStatus,omitempty"` IPv4 []IPv4Address `json:"IPv4Addresses,omitempty"` + IPv6 []IPv6Address `json:"IPv6Addresses,omitempty"` Status Status `json:"Status"` } +// IPv6Address is one IPv6 address of an EthernetInterface. +type IPv6Address struct { + Address string `json:"Address"` +} + // IPv4Address is one IPv4 address of an EthernetInterface. type IPv4Address struct { Address string `json:"Address"` diff --git a/pkg/server/server.go b/pkg/server/server.go index 747fb69..e1b6d55 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -734,10 +734,7 @@ func (s *Server) handleSystem(w http.ResponseWriter, r *http.Request) { } // Get real CPU information - cpu, err := s.kubevirtClient.GetVMCPUTopology(namespace, vmName) - if err != nil { - logger.Warning("Failed to get CPU for VM %s: %v", vmName, err) - } + procSummary, sysOem := s.processorFields(namespace, vmName) // Generate the correct System ID for the response responseSystemID := config.GenerateSystemID(s.currentConfig().SystemIDConvention, namespace, vmName) @@ -746,7 +743,7 @@ func (s *Server) handleSystem(w http.ResponseWriter, r *http.Request) { system := redfish.ComputerSystem{ OdataContext: "/redfish/v1/$metadata#ComputerSystem.ComputerSystem", OdataID: fmt.Sprintf("/redfish/v1/Systems/%s", responseSystemID), - OdataType: "#ComputerSystem.v1_0_0.ComputerSystem", + OdataType: "#ComputerSystem.v1_15_0.ComputerSystem", OdataEtag: fmt.Sprintf("W/\"%d\"", time.Now().Unix()), // Simple ETag for versioning ID: responseSystemID, Name: vmName, // Name remains vmName @@ -765,7 +762,8 @@ func (s *Server) handleSystem(w http.ResponseWriter, r *http.Request) { Processors: redfish.Link{ OdataID: fmt.Sprintf("/redfish/v1/Systems/%s/Processors", responseSystemID), }, - ProcessorSummary: processorSummary(cpu), + ProcessorSummary: procSummary, + Oem: sysOem, Storage: redfish.Link{ OdataID: fmt.Sprintf("/redfish/v1/Systems/%s/Storage", responseSystemID), }, @@ -956,7 +954,7 @@ func (s *Server) handleGetVirtualMedia(w http.ResponseWriter, r *http.Request, s virtualMedia := redfish.VirtualMedia{ OdataContext: "/redfish/v1/$metadata#VirtualMedia.VirtualMedia", OdataID: fmt.Sprintf("/redfish/v1/Systems/%s/VirtualMedia/%s", responseSystemID, mediaID), - OdataType: "#VirtualMedia.v1_0_0.VirtualMedia", + OdataType: "#VirtualMedia.v1_2_0.VirtualMedia", OdataEtag: fmt.Sprintf("W/\"%d\"", time.Now().Unix()), ID: mediaID, Name: fmt.Sprintf("Virtual Media %s", mediaID), @@ -1259,10 +1257,7 @@ func (s *Server) handleBootUpdate(w http.ResponseWriter, r *http.Request, system } // Get real CPU information - cpu, err := s.kubevirtClient.GetVMCPUTopology(namespace, vmName) - if err != nil { - logger.Warning("Failed to get CPU for VM %s: %v", vmName, err) - } + procSummary, sysOem := s.processorFields(namespace, vmName) // Return the updated ComputerSystem resource (Redfish spec requirement) responseSystemID := config.GenerateSystemID(s.currentConfig().SystemIDConvention, namespace, vmName) @@ -1270,7 +1265,7 @@ func (s *Server) handleBootUpdate(w http.ResponseWriter, r *http.Request, system system := redfish.ComputerSystem{ OdataContext: "/redfish/v1/$metadata#ComputerSystem.ComputerSystem", OdataID: fmt.Sprintf("/redfish/v1/Systems/%s", responseSystemID), - OdataType: "#ComputerSystem.v1_0_0.ComputerSystem", + OdataType: "#ComputerSystem.v1_15_0.ComputerSystem", OdataEtag: fmt.Sprintf("W/\"%d\"", time.Now().Unix()), ID: responseSystemID, Name: vmName, @@ -1289,7 +1284,8 @@ func (s *Server) handleBootUpdate(w http.ResponseWriter, r *http.Request, system Processors: redfish.Link{ OdataID: fmt.Sprintf("/redfish/v1/Systems/%s/Processors", responseSystemID), }, - ProcessorSummary: processorSummary(cpu), + ProcessorSummary: procSummary, + Oem: sysOem, Storage: redfish.Link{ OdataID: fmt.Sprintf("/redfish/v1/Systems/%s/Storage", responseSystemID), }, diff --git a/pkg/server/system_devices.go b/pkg/server/system_devices.go index 3b367c5..47531ff 100644 --- a/pkg/server/system_devices.go +++ b/pkg/server/system_devices.go @@ -87,7 +87,7 @@ func (s *Server) serveMemory(w http.ResponseWriter, namespace, vmName, base stri mem := redfish.Memory{ OdataContext: "/redfish/v1/$metadata#Memory.Memory", OdataID: self + "/" + memoryID, - OdataType: "#Memory.v1_0_0.Memory", + OdataType: "#Memory.v1_1_0.Memory", ID: memoryID, Name: "System Memory", MemoryType: "DRAM", @@ -154,16 +154,16 @@ func (s *Server) serveStorage(w http.ResponseWriter, namespace, vmName, base str return } - disks, err := s.kubevirtClient.GetVMDisks(namespace, vmName) - if err != nil { - logger.Error("Failed to get disks for VM %s/%s: %v", namespace, vmName, err) - s.sendInternalError(w, "Failed to get storage information") - return - } member := self + "/" + storageID switch { case len(rest) == 2: + disks, err := s.kubevirtClient.GetVMDisks(namespace, vmName) + if err != nil { + logger.Error("Failed to get disks for VM %s/%s: %v", namespace, vmName, err) + s.sendInternalError(w, "Failed to get storage information") + return + } storage := redfish.Storage{ OdataContext: "/redfish/v1/$metadata#Storage.Storage", OdataID: member, @@ -179,29 +179,32 @@ func (s *Server) serveStorage(w http.ResponseWriter, namespace, vmName, base str } s.writeResource(w, storage) case len(rest) == 4 && rest[2] == "Drives": - for _, d := range disks { - if d.Name != rest[3] { - continue - } - drive := redfish.Drive{ - OdataContext: "/redfish/v1/$metadata#Drive.Drive", - OdataID: member + "/Drives/" + d.Name, - OdataType: "#Drive.v1_0_0.Drive", - ID: d.Name, - Name: d.Name, - CapacityBytes: d.CapacityBytes, - Status: okStatus, - } - if d.CapacityBytes != nil { - drive.Oem = oemCapacity(float64(*d.CapacityBytes) / (1 << 30)) - } - if d.Bus == "sata" { - drive.Protocol = "SATA" - } - s.writeResource(w, drive) + d, err := s.kubevirtClient.GetVMDisk(namespace, vmName, rest[3]) + if err != nil { + logger.Error("Failed to get disk %s of VM %s/%s: %v", rest[3], namespace, vmName, err) + s.sendInternalError(w, "Failed to get storage information") return } - s.sendNotFound(w, "Drive not found") + if d == nil { + s.sendNotFound(w, "Drive not found") + return + } + drive := redfish.Drive{ + OdataContext: "/redfish/v1/$metadata#Drive.Drive", + OdataID: member + "/Drives/" + d.Name, + OdataType: "#Drive.v1_0_0.Drive", + ID: d.Name, + Name: d.Name, + CapacityBytes: d.CapacityBytes, + Status: okStatus, + } + if d.CapacityBytes != nil { + drive.Oem = oemCapacity(float64(*d.CapacityBytes) / (1 << 30)) + } + if d.Bus == "sata" { + drive.Protocol = "SATA" + } + s.writeResource(w, drive) default: s.sendNotFound(w, "Storage resource not found") } @@ -235,7 +238,7 @@ func (s *Server) serveEthernetInterfaces(w http.ResponseWriter, namespace, vmNam eth := redfish.EthernetInterface{ OdataContext: "/redfish/v1/$metadata#EthernetInterface.EthernetInterface", OdataID: self + "/" + n.Name, - OdataType: "#EthernetInterface.v1_0_0.EthernetInterface", + OdataType: "#EthernetInterface.v1_1_0.EthernetInterface", ID: n.Name, Name: n.Name, MACAddress: n.MAC, @@ -246,8 +249,12 @@ func (s *Server) serveEthernetInterfaces(w http.ResponseWriter, namespace, vmNam eth.LinkStatus = "LinkUp" } for _, ip := range n.IPs { - if p := net.ParseIP(ip); p != nil && p.To4() != nil { + switch p := net.ParseIP(ip); { + case p == nil: + case p.To4() != nil: eth.IPv4 = append(eth.IPv4, redfish.IPv4Address{Address: ip}) + default: + eth.IPv6 = append(eth.IPv6, redfish.IPv6Address{Address: ip}) } } s.writeResource(w, eth) @@ -268,22 +275,41 @@ func redfishArchitecture(kubevirtArch string) (arch, instructionSet string) { return "", "" } +// processorFields reads the vCPU topology of a VM and returns the ProcessorSummary +// and Oem for the ComputerSystem. If the topology cannot be read both are nil, so +// they are left out of the response instead of showing a guessed topology. +func (s *Server) processorFields(namespace, vmName string) (*redfish.ProcessorSummary, *redfish.SystemOem) { + cpu, err := s.kubevirtClient.GetVMCPUTopology(namespace, vmName) + if err != nil { + logger.Error("Failed to get CPU topology for VM %s/%s, leaving it out of the response: %v", namespace, vmName, err) + return nil, nil + } + summary := processorSummary(cpu) + return &summary, systemOem(cpu) +} + // processorSummary maps a VM's vCPU topology to the Redfish ProcessorSummary. func processorSummary(cpu kubevirt.CPUTopology) redfish.ProcessorSummary { - oem := &redfish.CPUTopologyOem{} - oem.KubeVirt.Sockets = cpu.Sockets - oem.KubeVirt.CoresPerSocket = cpu.Cores - oem.KubeVirt.ThreadsPerCore = cpu.Threads return redfish.ProcessorSummary{ Count: cpu.Sockets, CoreCount: cpu.Sockets * cpu.Cores, LogicalProcessorCount: cpu.VCPUs(), ThreadingEnabled: cpu.Threads > 1, Model: cpu.Model, - Oem: oem, } } +// systemOem spells out the vCPU layout that the standard counts are derived +// from. ProcessorSummary has no Oem property in any schema version, so it +// lives in the system-level Oem. +func systemOem(cpu kubevirt.CPUTopology) *redfish.SystemOem { + oem := &redfish.SystemOem{} + oem.KubeVirt.Processors.Sockets = cpu.Sockets + oem.KubeVirt.Processors.CoresPerSocket = cpu.Cores + oem.KubeVirt.Processors.ThreadsPerCore = cpu.Threads + return oem +} + func oemCapacity(gib float64) *redfish.OemCapacity { o := &redfish.OemCapacity{} o.KubeVirt.CapacityGiB = gib diff --git a/pkg/server/system_devices_test.go b/pkg/server/system_devices_test.go index 7b90fb4..1ef2fdb 100644 --- a/pkg/server/system_devices_test.go +++ b/pkg/server/system_devices_test.go @@ -21,6 +21,7 @@ package server import ( "encoding/json" + "errors" "net/http" "net/http/httptest" "testing" @@ -33,13 +34,23 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/kubernetes/fake" + k8stesting "k8s.io/client-go/testing" kubevirtv1 "kubevirt.io/api/core/v1" ) func newDevicesTestServer(t *testing.T, arch string) *Server { + t.Helper() + return newDevicesTestServerWith(t, arch, nil, nil) +} + +// newDevicesTestServerWith adds an optional running VMI and a custom fake Kubernetes client. +func newDevicesTestServerWith(t *testing.T, arch string, vmi *kubevirtv1.VirtualMachineInstance, k8s *fake.Clientset) *Server { t.Helper() mock := kubevirt.NewMockDynamicClient() vm := &kubevirtv1.VirtualMachine{ @@ -70,22 +81,35 @@ func newDevicesTestServer(t *testing.T, arch string) *Server { }}, } require.NoError(t, mock.AddVM(vm)) + if vmi != nil { + require.NoError(t, mock.AddVMI(vmi)) + } + if k8s == nil { + k8s = fake.NewSimpleClientset() + } cfg := &config.Config{ Server: config.ServerConfig{Host: "localhost", Port: 8080, TestMode: true}, Auth: config.AuthConfig{Users: []config.UserConfig{ {Username: "u", Password: config.PasswordConfig{Plain: "p"}, Chassis: []string{"c"}}, + {Username: "outsider", Password: config.PasswordConfig{Plain: "p"}, Chassis: []string{"other"}}, }}, - Chassis: []config.ChassisConfig{{Name: "c", Namespace: "ns"}}, + Chassis: []config.ChassisConfig{{Name: "c", Namespace: "ns"}, {Name: "other", Namespace: "other-ns"}}, } - client := kubevirt.NewClientWithClients(fake.NewSimpleClientset(), mock, 30*time.Second, nil) + client := kubevirt.NewClientWithClients(k8s, mock, 30*time.Second, nil) return NewServer(cfg, client) } func getSystemPath(srv *Server, path string) *httptest.ResponseRecorder { + return getSystemPathAs(srv, path, &auth.User{Username: "u", Chassis: []string{"c"}}) +} + +// getSystemPathAs sends a GET as the given user; a nil user sends no authentication context. +func getSystemPathAs(srv *Server, path string, user *auth.User) *httptest.ResponseRecorder { req := httptest.NewRequest("GET", path, nil) - authCtx := &auth.AuthContext{User: &auth.User{Username: "u", Chassis: []string{"c"}}} - req = req.WithContext(logger.WithAuth(req.Context(), authCtx)) + if user != nil { + req = req.WithContext(logger.WithAuth(req.Context(), &auth.AuthContext{User: user})) + } w := httptest.NewRecorder() srv.handleSystem(w, req) return w @@ -114,12 +138,26 @@ func TestSystemDevices(t *testing.T) { assert.EqualValues(t, 8, ps["LogicalProcessorCount"]) assert.Equal(t, true, ps["ThreadingEnabled"]) assert.Equal(t, "Skylake-Client", ps["Model"]) - topo := ps["Oem"].(map[string]interface{})["KubeVirt"].(map[string]interface{}) + assert.NotContains(t, ps, "Oem", "ProcessorSummary has no Oem property in any schema version") + topo := b["Oem"].(map[string]interface{})["KubeVirt"].(map[string]interface{})["Processors"].(map[string]interface{}) assert.EqualValues(t, 2, topo["Sockets"]) assert.EqualValues(t, 2, topo["CoresPerSocket"]) assert.EqualValues(t, 2, topo["ThreadsPerCore"]) }) + t.Run("resources declare a schema version that defines what they emit", func(t *testing.T) { + for path, want := range map[string]string{ + "/redfish/v1/Systems/vm-1": "#ComputerSystem.v1_15_0.ComputerSystem", + "/redfish/v1/Systems/vm-1/Memory/1": "#Memory.v1_1_0.Memory", + "/redfish/v1/Systems/vm-1/Processors/CPU0": "#Processor.v1_0_0.Processor", + "/redfish/v1/Systems/vm-1/Storage/1": "#Storage.v1_0_0.Storage", + "/redfish/v1/Systems/vm-1/Storage/1/Drives/root": "#Drive.v1_0_0.Drive", + "/redfish/v1/Systems/vm-1/EthernetInterfaces/default": "#EthernetInterface.v1_1_0.EthernetInterface", + } { + assert.Equal(t, want, get(t, path)["@odata.type"], path) + } + }) + t.Run("memory", func(t *testing.T) { c := get(t, "/redfish/v1/Systems/vm-1/Memory") assert.EqualValues(t, 1, c["Members@odata.count"]) @@ -142,7 +180,7 @@ func TestSystemDevices(t *testing.T) { }) t.Run("storage lists every disk with its capacity", func(t *testing.T) { - get(t, "/redfish/v1/Systems/vm-1/Storage/") + assert.EqualValues(t, 1, get(t, "/redfish/v1/Systems/vm-1/Storage/")["Members@odata.count"], "trailing slash lists the one controller") s := get(t, "/redfish/v1/Systems/vm-1/Storage/1") assert.EqualValues(t, 2, s["Drives@odata.count"]) root := get(t, "/redfish/v1/Systems/vm-1/Storage/1/Drives/root") @@ -187,23 +225,12 @@ func TestSystemDevices(t *testing.T) { }) } -func TestRedfishArchitecture(t *testing.T) { - for in, want := range map[string][2]string{ - "amd64": {"x86", "x86-64"}, - "arm64": {"ARM", "ARM-A64"}, - "s390x": {"", ""}, - "ppc64le": {"", ""}, - } { - arch, isa := redfishArchitecture(in) - assert.Equal(t, want, [2]string{arch, isa}, in) - } -} - func TestProcessorArchitecture(t *testing.T) { for _, tc := range []struct{ arch, wantArch, wantISA string }{ {"amd64", "x86", "x86-64"}, {"arm64", "ARM", "ARM-A64"}, {"s390x", "", ""}, + {"ppc64le", "", ""}, } { t.Run(tc.arch, func(t *testing.T) { srv := newDevicesTestServer(t, tc.arch) @@ -221,3 +248,173 @@ func TestProcessorArchitecture(t *testing.T) { }) } } + +// A VM that declares nothing (no disks, NICs, CPU or memory) must still give +// well-formed resources: empty collections as [] (not null), no invented +// values, and 404 for members that do not exist. +func TestSystemDevices_EmptyVM(t *testing.T) { + for name, spec := range map[string]*kubevirtv1.VirtualMachineInstanceTemplateSpec{ + "empty spec": {}, + "no template": nil, + } { + t.Run(name, func(t *testing.T) { + mock := kubevirt.NewMockDynamicClient() + require.NoError(t, mock.AddVM(&kubevirtv1.VirtualMachine{ + ObjectMeta: metav1.ObjectMeta{Name: "vm-empty", Namespace: "ns"}, + Spec: kubevirtv1.VirtualMachineSpec{Template: spec}, + })) + cfg := &config.Config{ + Server: config.ServerConfig{Host: "localhost", Port: 8080, TestMode: true}, + Auth: config.AuthConfig{Users: []config.UserConfig{ + {Username: "u", Password: config.PasswordConfig{Plain: "p"}, Chassis: []string{"c"}}, + }}, + Chassis: []config.ChassisConfig{{Name: "c", Namespace: "ns"}}, + } + srv := NewServer(cfg, kubevirt.NewClientWithClients(fake.NewSimpleClientset(), mock, 30*time.Second, nil)) + + raw := func(path string) (int, string) { + w := getSystemPath(srv, path) + return w.Code, w.Body.String() + } + get := func(path string) map[string]interface{} { + code, body := raw(path) + require.Equal(t, http.StatusOK, code, "%s: %s", path, body) + var m map[string]interface{} + require.NoError(t, json.Unmarshal([]byte(body), &m)) + return m + } + const base = "/redfish/v1/Systems/vm-empty" + + sys := get(base) + assert.Empty(t, sys["MemorySummary"], "no memory declared, so no total is invented") + assert.EqualValues(t, 1, sys["ProcessorSummary"].(map[string]interface{})["Count"]) + + storage := get(base + "/Storage/1") + assert.EqualValues(t, 0, storage["Drives@odata.count"]) + assert.Equal(t, []interface{}{}, storage["Drives"], "Drives must be [] and not null") + assert.Equal(t, http.StatusNotFound, getSystemPath(srv, base+"/Storage/1/Drives/root").Code) + + nics := get(base + "/EthernetInterfaces") + assert.EqualValues(t, 0, nics["Members@odata.count"]) + assert.Equal(t, []interface{}{}, nics["Members"], "Members must be [] and not null") + assert.Equal(t, http.StatusNotFound, getSystemPath(srv, base+"/EthernetInterfaces/default").Code) + + mem := get(base + "/Memory/1") + assert.NotContains(t, mem, "CapacityMiB") + assert.NotContains(t, mem, "Oem") + + assert.EqualValues(t, 1, get(base + "/Processors")["Members@odata.count"]) + cpu := get(base + "/Processors/CPU0") + assert.EqualValues(t, 1, cpu["TotalCores"]) + assert.EqualValues(t, 1, cpu["TotalThreads"]) + assert.NotContains(t, cpu, "Model") + assert.NotContains(t, cpu, "InstructionSet") + }) + } +} + +// Users without access to the VM's chassis, or without any authentication +// context, must get nothing from any of the new endpoints. +func TestSystemDevices_Unauthorized(t *testing.T) { + srv := newDevicesTestServer(t, "amd64") + leaks := []string{"CapacityMiB", "CapacityBytes", "MACAddress", "TotalCores", "KubeVirt", "LinkStatus"} + + for _, path := range []string{ + "/redfish/v1/Systems/vm-1/Memory", + "/redfish/v1/Systems/vm-1/Memory/1", + "/redfish/v1/Systems/vm-1/Processors", + "/redfish/v1/Systems/vm-1/Processors/CPU0", + "/redfish/v1/Systems/vm-1/Storage", + "/redfish/v1/Systems/vm-1/Storage/1", + "/redfish/v1/Systems/vm-1/Storage/1/Drives/root", + "/redfish/v1/Systems/vm-1/EthernetInterfaces", + "/redfish/v1/Systems/vm-1/EthernetInterfaces/default", + "/redfish/v1/Systems/ns.vm-1/Storage/1/Drives/data", + } { + t.Run(path, func(t *testing.T) { + outsider := getSystemPathAs(srv, path, &auth.User{Username: "outsider", Chassis: []string{"other"}}) + assert.Equal(t, http.StatusNotFound, outsider.Code, "a user of another chassis") + anonymous := getSystemPathAs(srv, path, nil) + assert.Equal(t, http.StatusForbidden, anonymous.Code, "no authentication context") + for _, body := range []string{outsider.Body.String(), anonymous.Body.String()} { + for _, leak := range leaks { + assert.NotContains(t, body, leak) + } + } + }) + } +} + +// A running VM reports LinkUp, the MAC KubeVirt assigned and its addresses, split +// into IPv4 and IPv6. Anything that is not an IP address is dropped. +func TestSystemDevices_RunningNIC(t *testing.T) { + vmi := &kubevirtv1.VirtualMachineInstance{ + ObjectMeta: metav1.ObjectMeta{Name: "vm-1", Namespace: "ns"}, + Status: kubevirtv1.VirtualMachineInstanceStatus{Interfaces: []kubevirtv1.VirtualMachineInstanceNetworkInterface{ + {Name: "default", MAC: "52:54:00:aa:bb:cc", IPs: []string{"10.0.0.5", "fd00::5", "not-an-ip", "10.0.0.6"}}, + }}, + } + srv := newDevicesTestServerWith(t, "", vmi, nil) + w := getSystemPath(srv, "/redfish/v1/Systems/vm-1/EthernetInterfaces/default") + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + var nic map[string]interface{} + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &nic)) + + assert.Equal(t, "LinkUp", nic["LinkStatus"]) + assert.Equal(t, "52:54:00:aa:bb:cc", nic["MACAddress"], "the running MAC wins over the spec MAC") + assert.Equal(t, []interface{}{ + map[string]interface{}{"Address": "10.0.0.5"}, + map[string]interface{}{"Address": "10.0.0.6"}, + }, nic["IPv4Addresses"]) + assert.Equal(t, []interface{}{map[string]interface{}{"Address": "fd00::5"}}, nic["IPv6Addresses"]) +} + +// When the cluster cannot be read for a reason other than "not found", the +// endpoints answer 500 instead of a plausible but wrong 200. +func TestSystemDevices_ClusterReadErrors(t *testing.T) { + t.Run("PVC lookup forbidden gives 500 for the drive, names still list", func(t *testing.T) { + mock := kubevirt.NewMockDynamicClient() + require.NoError(t, mock.AddVM(&kubevirtv1.VirtualMachine{ + ObjectMeta: metav1.ObjectMeta{Name: "vm-pvc", Namespace: "ns"}, + Spec: kubevirtv1.VirtualMachineSpec{Template: &kubevirtv1.VirtualMachineInstanceTemplateSpec{ + Spec: kubevirtv1.VirtualMachineInstanceSpec{ + Domain: kubevirtv1.DomainSpec{Devices: kubevirtv1.Devices{Disks: []kubevirtv1.Disk{ + {Name: "data", DiskDevice: kubevirtv1.DiskDevice{Disk: &kubevirtv1.DiskTarget{Bus: "virtio"}}}, + }}}, + Volumes: []kubevirtv1.Volume{{Name: "data", VolumeSource: kubevirtv1.VolumeSource{ + PersistentVolumeClaim: &kubevirtv1.PersistentVolumeClaimVolumeSource{ + PersistentVolumeClaimVolumeSource: corev1.PersistentVolumeClaimVolumeSource{ClaimName: "claim"}}}}}, + }, + }}, + })) + k8s := fake.NewSimpleClientset() + k8s.PrependReactor("get", "persistentvolumeclaims", func(k8stesting.Action) (bool, runtime.Object, error) { + return true, nil, apierrors.NewForbidden(schema.GroupResource{Resource: "persistentvolumeclaims"}, "claim", errors.New("no access")) + }) + cfg := &config.Config{ + Server: config.ServerConfig{Host: "localhost", Port: 8080, TestMode: true}, + Auth: config.AuthConfig{Users: []config.UserConfig{ + {Username: "u", Password: config.PasswordConfig{Plain: "p"}, Chassis: []string{"c"}}, + }}, + Chassis: []config.ChassisConfig{{Name: "c", Namespace: "ns"}}, + } + srv := NewServer(cfg, kubevirt.NewClientWithClients(k8s, mock, 30*time.Second, nil)) + + w := getSystemPath(srv, "/redfish/v1/Systems/vm-pvc/Storage/1/Drives/data") + assert.Equal(t, http.StatusInternalServerError, w.Code, "a size that cannot be read is an error, not a guess") + assert.NotContains(t, w.Body.String(), "CapacityBytes") + assert.Equal(t, http.StatusOK, getSystemPath(srv, "/redfish/v1/Systems/vm-pvc/Storage/1").Code, + "the controller listing needs no PVC lookup") + }) + + t.Run("CPU topology unreadable leaves the CPU fields out", func(t *testing.T) { + srv := newDevicesTestServer(t, "") + summary, oem := srv.processorFields("ns", "does-not-exist") + assert.Nil(t, summary, "no guessed ProcessorSummary") + assert.Nil(t, oem, "no guessed Oem topology") + summary, oem = srv.processorFields("ns", "vm-1") + require.NotNil(t, summary) + assert.Equal(t, 2, summary.Count) + assert.NotNil(t, oem) + }) +} From 6fee9c36a77661a095af8f7f0c5a00d001deb0fd Mon Sep 17 00:00:00 2001 From: Tomer Karniol Date: Fri, 9 Oct 2026 19:00:12 +0300 Subject: [PATCH 5/8] docs: describe the system hardware resources Update the single-system example to the current ComputerSystem shape (MemorySummary and Memory link, Processors link, ProcessorSummary counts, system-level Oem) and add a section with real responses for Processors, Memory, a Drive and an EthernetInterface. Signed-off-by: Tomer Karniol --- docs/README.md | 127 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 123 insertions(+), 4 deletions(-) diff --git a/docs/README.md b/docs/README.md index aada8ec..e00fd44 100644 --- a/docs/README.md +++ b/docs/README.md @@ -181,7 +181,7 @@ While your deployment is starting to deploy in the background, you can explore t { "@odata.context": "/redfish/v1/$metadata#ComputerSystem.ComputerSystem", "@odata.id": "/redfish/v1/Systems/ztp-jinkit-kvm-00", - "@odata.type": "#ComputerSystem.v1_0_0.ComputerSystem", + "@odata.type": "#ComputerSystem.v1_15_0.ComputerSystem", "@odata.etag": "W/\"1756160934\"", "Id": "ztp-jinkit-kvm-00", "Name": "ztp-jinkit-kvm-00", @@ -191,12 +191,20 @@ While your deployment is starting to deploy in the background, you can explore t "Health": "OK" }, "PowerState": "On", - "Memory": { - "@odata.id": "/redfish/v1/Systems/ztp-jinkit-kvm-00/Memory", + "MemorySummary": { "TotalSystemMemoryGiB": 48 }, + "Memory": { + "@odata.id": "/redfish/v1/Systems/ztp-jinkit-kvm-00/Memory" + }, + "Processors": { + "@odata.id": "/redfish/v1/Systems/ztp-jinkit-kvm-00/Processors" + }, "ProcessorSummary": { - "Count": 20 + "Count": 1, + "CoreCount": 20, + "LogicalProcessorCount": 20, + "ThreadingEnabled": false }, "Storage": { "@odata.id": "/redfish/v1/Systems/ztp-jinkit-kvm-00/Storage" @@ -237,10 +245,121 @@ While your deployment is starting to deploy in the background, you can explore t "@odata.id": "/redfish/v1/Managers/1" } ] + }, + "Oem": { + "KubeVirt": { + "Processors": { + "Sockets": 1, + "CoresPerSocket": 20, + "ThreadsPerCore": 1 + } + } + } + } + ``` + +3. **Review the Hardware of a Managed System** + + A system also exposes its processors, memory, disks and network interfaces. The examples below come from a virtual machine named `my-vm` with 2 sockets, 2 cores per socket, 2 threads per core, 512 MiB of memory, a root disk from a container image and a 3 GiB SATA disk. All of them are read-only and follow the links in the system response. + + **Processors** (one entry per socket, `/Processors/CPU0`, `/Processors/CPU1`): + + ```bash + curl -sk -u admin:admin123 https:///redfish/v1/Systems/my-vm/Processors/CPU0 | jq + ``` + + ```json + { + "@odata.context": "/redfish/v1/$metadata#Processor.Processor", + "@odata.id": "/redfish/v1/Systems/my-vm/Processors/CPU0", + "@odata.type": "#Processor.v1_0_0.Processor", + "Id": "CPU0", + "Name": "vCPU Socket 0", + "Socket": "0", + "ProcessorType": "CPU", + "ProcessorArchitecture": "x86", + "InstructionSet": "x86-64", + "TotalCores": 2, + "TotalThreads": 4, + "Model": "host-model", + "Status": { + "State": "Enabled", + "Health": "OK" + } + } + ``` + + **Memory** (a single module, `/Memory/1`). `CapacityMiB` is the standard field and `Oem.KubeVirt.CapacityGiB` repeats it in GiB: + + ```json + { + "@odata.context": "/redfish/v1/$metadata#Memory.Memory", + "@odata.id": "/redfish/v1/Systems/my-vm/Memory/1", + "@odata.type": "#Memory.v1_1_0.Memory", + "Id": "1", + "Name": "System Memory", + "MemoryType": "DRAM", + "CapacityMiB": 512, + "Status": { + "State": "Enabled", + "Health": "OK" + }, + "Oem": { + "KubeVirt": { + "CapacityGiB": 0.5 + } + } + } + ``` + + **Disks** (`/Storage/1` lists every disk of the VM, CD-ROMs excluded because they are VirtualMedia; each drive is under `/Storage/1/Drives/{name}`). A disk whose size is not declared in the VM, such as a container image or a cloud-init disk, has no `CapacityBytes`: + + ```json + { + "@odata.context": "/redfish/v1/$metadata#Drive.Drive", + "@odata.id": "/redfish/v1/Systems/my-vm/Storage/1/Drives/scratch", + "@odata.type": "#Drive.v1_0_0.Drive", + "Id": "scratch", + "Name": "scratch", + "Protocol": "SATA", + "CapacityBytes": 3221225472, + "Status": { + "State": "Enabled", + "Health": "OK" + }, + "Oem": { + "KubeVirt": { + "CapacityGiB": 3 + } } } ``` + **Network interfaces** (`/EthernetInterfaces` lists every NIC). `LinkStatus` is `LinkUp` while the VM is running and `NoLink` otherwise. The MAC address comes from the running VM, or from the VM definition when it is stopped, and is omitted if neither has one. Virtual NICs have no link speed, so `SpeedMbps` is not reported: + + ```json + { + "@odata.context": "/redfish/v1/$metadata#EthernetInterface.EthernetInterface", + "@odata.id": "/redfish/v1/Systems/my-vm/EthernetInterfaces/default", + "@odata.type": "#EthernetInterface.v1_1_0.EthernetInterface", + "Id": "default", + "Name": "default", + "MACAddress": "02:11:22:33:44:55", + "LinkStatus": "LinkUp", + "IPv4Addresses": [ + { + "Address": "10.128.2.164" + } + ], + "Status": { + "State": "Enabled", + "Health": "OK" + } + } + ``` + + `ProcessorSummary` follows the Redfish definitions: `Count` is the number of sockets, `CoreCount` is sockets x cores and `LogicalProcessorCount` is sockets x cores x threads. The processor `Model` is the CPU model configured on the VM (for example `host-model`) and is omitted when the VM does not set one. + ## Environment Cleanup To clean up your environment, you can run the following series of commands. From afae03364230084fa799bc29ad5f7eca144da4bb Mon Sep 17 00:00:00 2001 From: Tomer Karniol Date: Tue, 13 Oct 2026 01:39:27 +0300 Subject: [PATCH 6/8] feat(kubevirt): read CPU, memory, disks and NICs from the running VMI The VM spec holds the staged values; the VMI is what the guest is running. Reviewing the Processors and Memory resources raised the question whether hotplug and not-yet-applied edits are accounted for. They were not: every value came from the VM spec. A running VM now reports its VMI, a stopped VM its VM spec: - CPU: status.currentCPUTopology, then the VMI spec, then the VM spec. - Memory: status.memory.guestCurrent, then the VMI spec, then the VM spec. - Architecture: the VMI spec, then the VM spec. - Disks and NICs: the VMI spec, then the VM spec. A volume hot-plugged without --persist is listed, one only staged in the VM is not. - NICs report the operational linkState (up/down) the VMI gives. Only "VMI not found" and a VMI in a final phase (Succeeded/Failed, which KubeVirt can leave behind after a shutdown) count as stopped. Any other failure to read the VMI is returned, so a running VM is never shown with its staged values. GetVMNICs shares the same helper. Tests cover VMI over VM for each value, hotplug status, nil status fields, final-phase VMIs, hot-plugged disks, link state and VMI read errors. Signed-off-by: Tomer Karniol --- pkg/kubevirt/client.go | 79 ++++++--- pkg/kubevirt/devices.go | 90 +++++++--- pkg/kubevirt/devices_test.go | 269 +++++++++++++++++++++++++++++- pkg/server/system_devices_test.go | 2 + 4 files changed, 396 insertions(+), 44 deletions(-) diff --git a/pkg/kubevirt/client.go b/pkg/kubevirt/client.go index ab81d80..75f281b 100644 --- a/pkg/kubevirt/client.go +++ b/pkg/kubevirt/client.go @@ -2552,28 +2552,40 @@ func (c *Client) GetNamespaceInfo(namespace string) (*corev1.Namespace, error) { } // GetVMMemory gets the memory of a VirtualMachine in GiB. -// It reads domain.memory.guest, then resources.requests.memory, then -// resources.limits.memory. It returns 0 when the spec declares none, so -// callers can tell "unknown" apart from a real size. +// A running VM reports what its VMI has now (status.memory.guestCurrent, then +// the VMI spec), so memory hotplug and staged-but-not-applied VM edits do not +// show up early. A stopped VM (no VMI) reports its VM spec. +// Within a spec it reads domain.memory.guest, then resources.requests.memory, +// then resources.limits.memory. It returns 0 when none is declared, so callers +// can tell "unknown" apart from a real size. func (c *Client) GetVMMemory(namespace, name string) (float64, error) { vm, err := c.getVMForRead(namespace, name) if err != nil { return 0, fmt.Errorf("failed to get VM %s/%s for memory lookup: %w", namespace, name, err) } + vmi, err := c.getRunningVMI(namespace, name) + if err != nil { + return 0, fmt.Errorf("failed to get VMI %s/%s for memory lookup: %w", namespace, name, err) + } - bytes := vmMemoryBytes(vm) + var bytes int64 + switch { + case vmi != nil && vmi.Status.Memory != nil && vmi.Status.Memory.GuestCurrent != nil: + bytes = vmi.Status.Memory.GuestCurrent.Value() + case vmi != nil: + bytes = specMemoryBytes(&vmi.Spec) + case vm.Spec.Template != nil: + bytes = specMemoryBytes(&vm.Spec.Template.Spec) + } if bytes == 0 { - logger.Warning("Memory not declared in VM spec for %s/%s", namespace, name) + logger.Warning("Memory not declared for %s/%s", namespace, name) } return float64(bytes) / (1 << 30), nil } -// vmMemoryBytes returns the VM memory in bytes, or 0 when the spec declares none. -func vmMemoryBytes(vm *kubevirtv1.VirtualMachine) int64 { - if vm.Spec.Template == nil { - return 0 - } - domain := vm.Spec.Template.Spec.Domain +// specMemoryBytes returns the memory a spec declares in bytes, or 0 when it declares none. +func specMemoryBytes(spec *kubevirtv1.VirtualMachineInstanceSpec) int64 { + domain := spec.Domain if domain.Memory != nil && domain.Memory.Guest != nil { return domain.Memory.Guest.Value() } @@ -2592,8 +2604,8 @@ type CPUTopology struct { // Model is domain.cpu.model as configured (e.g. "host-model", "Skylake-Client"); // empty when the VM leaves it to the cluster default. Model string - // Architecture is spec.architecture ("amd64", "arm64"). It is empty when the - // VM does not declare one (KubeVirt normally fills it in on creation). + // Architecture is spec.architecture ("amd64", "arm64"). It is empty when + // neither the VMI nor the VM declares one. Architecture string } @@ -2601,26 +2613,49 @@ type CPUTopology struct { func (t CPUTopology) VCPUs() int { return t.Sockets * t.Cores * t.Threads } // GetVMCPUTopology returns the sockets, cores per socket and threads per core of a VM. +// A running VM reports what its VMI has now (status.currentCPUTopology, then the +// VMI spec); a stopped VM (no VMI) reports its VM spec. // On error it returns the zero value, never a guessed topology. func (c *Client) GetVMCPUTopology(namespace, name string) (CPUTopology, error) { vm, err := c.getVMForRead(namespace, name) if err != nil { return CPUTopology{}, fmt.Errorf("failed to get VM %s/%s for CPU lookup: %w", namespace, name, err) } + vmi, err := c.getRunningVMI(namespace, name) + if err != nil { + return CPUTopology{}, fmt.Errorf("failed to get VMI %s/%s for CPU lookup: %w", namespace, name, err) + } + topo := CPUTopology{Sockets: 1, Cores: 1, Threads: 1} - if vm.Spec.Template == nil { + var spec *kubevirtv1.VirtualMachineInstanceSpec + switch { + case vmi != nil: + spec = &vmi.Spec + case vm.Spec.Template != nil: + spec = &vm.Spec.Template.Spec + default: return topo, nil } - topo.Architecture = vm.Spec.Template.Spec.Architecture - cpu := vm.Spec.Template.Spec.Domain.CPU + + topo.Architecture = spec.Architecture + if topo.Architecture == "" && vm.Spec.Template != nil { + topo.Architecture = vm.Spec.Template.Spec.Architecture + } + cpu := spec.Domain.CPU if cpu == nil { - logger.Warning("CPU not found in VM spec for %s/%s, using 1 vCPU", namespace, name) - return topo, nil + logger.Warning("CPU not found in spec for %s/%s, using 1 vCPU", namespace, name) + } else { + topo.Sockets = int(max(cpu.Sockets, 1)) + topo.Cores = int(max(cpu.Cores, 1)) + topo.Threads = int(max(cpu.Threads, 1)) + topo.Model = cpu.Model + } + if vmi != nil && vmi.Status.CurrentCPUTopology != nil { + cur := vmi.Status.CurrentCPUTopology + topo.Sockets = int(max(cur.Sockets, 1)) + topo.Cores = int(max(cur.Cores, 1)) + topo.Threads = int(max(cur.Threads, 1)) } - topo.Sockets = int(max(cpu.Sockets, 1)) - topo.Cores = int(max(cpu.Cores, 1)) - topo.Threads = int(max(cpu.Threads, 1)) - topo.Model = cpu.Model return topo, nil } diff --git a/pkg/kubevirt/devices.go b/pkg/kubevirt/devices.go index 539d61d..5cfc40a 100644 --- a/pkg/kubevirt/devices.go +++ b/pkg/kubevirt/devices.go @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * Copyright 2025 KubeVirt Redfish project and its authors. + * Copyright 2026 KubeVirt Redfish project and its authors. * */ @@ -47,6 +47,9 @@ type VMNIC struct { IPs []string // Running is true when the VMI exists and reports this interface. Running bool + // LinkState is the operational link state the VMI reports ("up" or "down"). + // It is empty when the VMI does not report one (older KubeVirt, or not running). + LinkState string } // VMMemoryMiB returns the VM memory in MiB (see GetVMMemory for the source order). @@ -58,19 +61,49 @@ func (c *Client) VMMemoryMiB(namespace, name string) (int64, error) { return int64(math.Round(gib * 1024)), nil } -// vmDisks lists the disks of a VM in spec order together with their backing +// getRunningVMI returns the VMI of a VM, or nil when the VM is not running: either +// there is no VMI, or it is in a final phase (Succeeded/Failed), which KubeVirt +// can leave behind after a shutdown. Any other failure is returned: treating it +// as "stopped" would show the staged VM spec for a VM that is running. +func (c *Client) getRunningVMI(namespace, name string) (*kubevirtv1.VirtualMachineInstance, error) { + vmi, err := c.getVMIForRead(namespace, name) + if apierrors.IsNotFound(err) { + return nil, nil + } + if err != nil { + return nil, err + } + if vmi.IsFinal() { + return nil, nil + } + return vmi, nil +} + +// effectiveSpec returns the spec that describes what the VM is now: the running +// VMI's when there is one, otherwise the VM template's (nil if it has none). +func effectiveSpec(vm *kubevirtv1.VirtualMachine, vmi *kubevirtv1.VirtualMachineInstance) *kubevirtv1.VirtualMachineInstanceSpec { + if vmi != nil { + return &vmi.Spec + } + if vm.Spec.Template != nil { + return &vm.Spec.Template.Spec + } + return nil +} + +// vmDisks lists the disks of a spec in order together with their backing // volume (nil when the spec has none). CD-ROM devices are excluded because // they are exposed as VirtualMedia. It makes no API calls. -func vmDisks(vm *kubevirtv1.VirtualMachine) (disks []VMDisk, volumes []*kubevirtv1.Volume) { - if vm.Spec.Template == nil { +func vmDisks(spec *kubevirtv1.VirtualMachineInstanceSpec) (disks []VMDisk, volumes []*kubevirtv1.Volume) { + if spec == nil { return nil, nil } byName := map[string]*kubevirtv1.Volume{} - for i := range vm.Spec.Template.Spec.Volumes { - v := &vm.Spec.Template.Spec.Volumes[i] + for i := range spec.Volumes { + v := &spec.Volumes[i] byName[v.Name] = v } - for _, d := range vm.Spec.Template.Spec.Domain.Devices.Disks { + for _, d := range spec.Domain.Devices.Disks { if d.CDRom != nil { continue } @@ -88,6 +121,9 @@ func vmDisks(vm *kubevirtv1.VirtualMachine) (disks []VMDisk, volumes []*kubevirt } // GetVMDisks returns the disks of a VM in spec order with name and bus only. +// A running VM reports the disks its VMI has (so a volume hot-plugged without +// --persist is listed and one only staged in the VM spec is not); a stopped VM +// reports its VM spec. // CapacityBytes is left unset on purpose: resolving a size can cost an API // call per disk, so use GetVMDisk when the size of one disk is needed. func (c *Client) GetVMDisks(namespace, name string) ([]VMDisk, error) { @@ -95,18 +131,27 @@ func (c *Client) GetVMDisks(namespace, name string) ([]VMDisk, error) { if err != nil { return nil, err } - disks, _ := vmDisks(vm) + vmi, err := c.getRunningVMI(namespace, name) + if err != nil { + return nil, err + } + disks, _ := vmDisks(effectiveSpec(vm, vmi)) return disks, nil } // GetVMDisk returns one disk of a VM including its capacity, or nil if the VM -// has no such disk. Only that disk's size is looked up. +// has no such disk. Only that disk's size is looked up. The disk list follows +// the same VMI-first rule as GetVMDisks. func (c *Client) GetVMDisk(namespace, name, disk string) (*VMDisk, error) { vm, err := c.getVMForRead(namespace, name) if err != nil { return nil, err } - disks, volumes := vmDisks(vm) + vmi, err := c.getRunningVMI(namespace, name) + if err != nil { + return nil, err + } + disks, volumes := vmDisks(effectiveSpec(vm, vmi)) for i := range disks { if disks[i].Name != disk { continue @@ -191,32 +236,34 @@ func (c *Client) volumeCapacityBytes(namespace string, vm *kubevirtv1.VirtualMac return nil, nil } -// GetVMNICs returns every network interface of a VM. The MAC and IPs come -// from the running VMI when available, otherwise from the VM spec. +// GetVMNICs returns every network interface of a VM. A running VM reports the +// interfaces its VMI has, with the MAC, IPs and link state the VMI reports; a +// stopped VM (no VMI, or a finished one) reports its VM spec. func (c *Client) GetVMNICs(namespace, name string) ([]VMNIC, error) { vm, err := c.getVMForRead(namespace, name) if err != nil { return nil, err } - if vm.Spec.Template == nil { + // Only "no VMI" means the VM is not running. Any other failure is returned: + // reporting NoLink for a running VM whose VMI could not be read would be wrong. + vmi, err := c.getRunningVMI(namespace, name) + if err != nil { + return nil, err + } + spec := effectiveSpec(vm, vmi) + if spec == nil { return nil, nil } - // No VMI means the VM is not running. Any other failure is returned: reporting - // NoLink for a running VM whose VMI could not be read would be wrong. status := map[string]kubevirtv1.VirtualMachineInstanceNetworkInterface{} - vmi, err := c.getVMIForRead(namespace, name) - switch { - case err == nil: + if vmi != nil { for _, s := range vmi.Status.Interfaces { status[s.Name] = s } - case !apierrors.IsNotFound(err): - return nil, err } var nics []VMNIC - for _, i := range vm.Spec.Template.Spec.Domain.Devices.Interfaces { + for _, i := range spec.Domain.Devices.Interfaces { nic := VMNIC{Name: i.Name, MAC: i.MacAddress} if s, ok := status[i.Name]; ok { nic.Running = true @@ -224,6 +271,7 @@ func (c *Client) GetVMNICs(namespace, name string) ([]VMNIC, error) { nic.MAC = s.MAC } nic.IPs = s.IPs + nic.LinkState = s.LinkState } nics = append(nics, nic) } diff --git a/pkg/kubevirt/devices_test.go b/pkg/kubevirt/devices_test.go index 184a2c1..ddc1300 100644 --- a/pkg/kubevirt/devices_test.go +++ b/pkg/kubevirt/devices_test.go @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * Copyright 2025 KubeVirt Redfish project and its authors. + * Copyright 2026 KubeVirt Redfish project and its authors. * */ @@ -315,6 +315,7 @@ func TestGetVMNICs(t *testing.T) { } vmi := &kubevirtv1.VirtualMachineInstance{ ObjectMeta: metav1.ObjectMeta{Name: "vm", Namespace: "ns"}, + Spec: spec, Status: kubevirtv1.VirtualMachineInstanceStatus{Interfaces: []kubevirtv1.VirtualMachineInstanceNetworkInterface{ {Name: "default", MAC: "52:54:00:aa:bb:cc", IPs: []string{"10.0.0.5", "fd00::5"}}, }}, @@ -348,6 +349,272 @@ func TestGetVMCPUTopology_Architecture(t *testing.T) { } } +// deviceTestVMI is a running VMI named like deviceTestVM. +func deviceTestVMI(spec kubevirtv1.VirtualMachineInstanceSpec, status kubevirtv1.VirtualMachineInstanceStatus) *kubevirtv1.VirtualMachineInstance { + return &kubevirtv1.VirtualMachineInstance{ + ObjectMeta: metav1.ObjectMeta{Name: "vm", Namespace: "ns"}, + Spec: spec, + Status: status, + } +} + +// The VM spec holds the staged values; a running VM must report its VMI instead, +// and a stopped VM (no VMI) must report the VM spec. +func TestGetVMCPUTopology_VMIWinsOverVM(t *testing.T) { + vmSpec := kubevirtv1.VirtualMachineInstanceSpec{ + Architecture: "amd64", + Domain: kubevirtv1.DomainSpec{CPU: &kubevirtv1.CPU{Sockets: 8, Cores: 8, Threads: 2, Model: "staged-model"}}, + } + vmiSpec := kubevirtv1.VirtualMachineInstanceSpec{ + Architecture: "arm64", + Domain: kubevirtv1.DomainSpec{CPU: &kubevirtv1.CPU{Sockets: 2, Cores: 2, Threads: 1, Model: "running-model"}}, + } + cases := []struct { + name string + vmi *kubevirtv1.VirtualMachineInstance + want CPUTopology + }{ + {"stopped VM uses the VM spec", nil, + CPUTopology{Sockets: 8, Cores: 8, Threads: 2, Model: "staged-model", Architecture: "amd64"}}, + {"running VM uses the VMI spec", deviceTestVMI(vmiSpec, kubevirtv1.VirtualMachineInstanceStatus{}), + CPUTopology{Sockets: 2, Cores: 2, Threads: 1, Model: "running-model", Architecture: "arm64"}}, + {"hotplug in progress uses status.currentCPUTopology", + deviceTestVMI(vmiSpec, kubevirtv1.VirtualMachineInstanceStatus{ + CurrentCPUTopology: &kubevirtv1.CPUTopology{Sockets: 1, Cores: 2, Threads: 1}}), + CPUTopology{Sockets: 1, Cores: 2, Threads: 1, Model: "running-model", Architecture: "arm64"}}, + {"VMI without architecture falls back to the VM's", + deviceTestVMI(kubevirtv1.VirtualMachineInstanceSpec{Domain: vmiSpec.Domain}, kubevirtv1.VirtualMachineInstanceStatus{}), + CPUTopology{Sockets: 2, Cores: 2, Threads: 1, Model: "running-model", Architecture: "amd64"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + mock := NewMockDynamicClient() + if err := mock.AddVM(deviceTestVM(vmSpec)); err != nil { + t.Fatal(err) + } + if tc.vmi != nil { + if err := mock.AddVMI(tc.vmi); err != nil { + t.Fatal(err) + } + } + c := NewClientWithClients(fake.NewSimpleClientset(), mock, 30*time.Second, nil) + got, err := c.GetVMCPUTopology("ns", "vm") + if err != nil || got != tc.want { + t.Errorf("topology = %+v, %v; want %+v", got, err, tc.want) + } + }) + } +} + +func TestGetVMMemory_VMIWinsOverVM(t *testing.T) { + staged := resource.MustParse("8Gi") + running := resource.MustParse("2Gi") + current := resource.MustParse("3Gi") + vmSpec := kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{Memory: &kubevirtv1.Memory{Guest: &staged}}} + vmiSpec := kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{Memory: &kubevirtv1.Memory{Guest: &running}}} + cases := []struct { + name string + vmi *kubevirtv1.VirtualMachineInstance + want float64 + }{ + {"stopped VM uses the VM spec", nil, 8}, + {"running VM uses the VMI spec", deviceTestVMI(vmiSpec, kubevirtv1.VirtualMachineInstanceStatus{}), 2}, + {"hotplug in progress uses status.memory.guestCurrent", + deviceTestVMI(vmiSpec, kubevirtv1.VirtualMachineInstanceStatus{Memory: &kubevirtv1.MemoryStatus{GuestCurrent: ¤t}}), 3}, + {"status.memory without guestCurrent falls back to the VMI spec", + deviceTestVMI(vmiSpec, kubevirtv1.VirtualMachineInstanceStatus{Memory: &kubevirtv1.MemoryStatus{}}), 2}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + mock := NewMockDynamicClient() + if err := mock.AddVM(deviceTestVM(vmSpec)); err != nil { + t.Fatal(err) + } + if tc.vmi != nil { + if err := mock.AddVMI(tc.vmi); err != nil { + t.Fatal(err) + } + } + c := NewClientWithClients(fake.NewSimpleClientset(), mock, 30*time.Second, nil) + got, err := c.GetVMMemory("ns", "vm") + if err != nil || got != tc.want { + t.Errorf("memory = %v, %v; want %v", got, err, tc.want) + } + }) + } +} + +// A VMI that cannot be read (not "not found") must fail the lookup, not fall +// back to the staged VM spec. +func TestGetVMCPUAndMemory_VMIReadErrorsAreNotHidden(t *testing.T) { + mock := NewMockDynamicClient() + if err := mock.AddVM(deviceTestVM(kubevirtv1.VirtualMachineInstanceSpec{})); err != nil { + t.Fatal(err) + } + forbidden := apierrors.NewForbidden(schema.GroupResource{Resource: "virtualmachineinstances"}, "vm", errors.New("no access")) + c := NewClientWithClients(fake.NewSimpleClientset(), failingVMIs{Interface: mock, err: forbidden}, 30*time.Second, nil) + if topo, err := c.GetVMCPUTopology("ns", "vm"); err == nil || topo != (CPUTopology{}) { + t.Errorf("CPU: got %+v, %v; want the zero topology and an error", topo, err) + } + if _, err := c.GetVMMemory("ns", "vm"); err == nil { + t.Error("memory: expected an error") + } + if _, err := c.GetVMDisks("ns", "vm"); err == nil { + t.Error("disks: expected an error") + } + if _, err := c.GetVMDisk("ns", "vm", "root"); err == nil { + t.Error("disk: expected an error") + } + if _, err := c.GetVMNICs("ns", "vm"); err == nil { + t.Error("NICs: expected an error") + } +} + +func newDeviceClient(t *testing.T, vm *kubevirtv1.VirtualMachine, vmi *kubevirtv1.VirtualMachineInstance) *Client { + t.Helper() + mock := NewMockDynamicClient() + if err := mock.AddVM(vm); err != nil { + t.Fatal(err) + } + if vmi != nil { + if err := mock.AddVMI(vmi); err != nil { + t.Fatal(err) + } + } + return NewClientWithClients(fake.NewSimpleClientset(), mock, 30*time.Second, nil) +} + +// status.currentCPUTopology wins field by field, not only for sockets. +func TestGetVMCPUTopology_StatusTopologyWinsOverSpec(t *testing.T) { + spec := kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{CPU: &kubevirtv1.CPU{Sockets: 1, Cores: 1, Threads: 1}}} + vmi := deviceTestVMI(spec, kubevirtv1.VirtualMachineInstanceStatus{ + CurrentCPUTopology: &kubevirtv1.CPUTopology{Sockets: 2, Cores: 3, Threads: 2}}) + got, err := newDeviceClient(t, deviceTestVM(spec), vmi).GetVMCPUTopology("ns", "vm") + if err != nil || got.Sockets != 2 || got.Cores != 3 || got.Threads != 2 || got.VCPUs() != 12 { + t.Errorf("topology = %+v, %v; want 2x3x2", got, err) + } + + // An unset field in the status counts as 1, like in the spec. + vmi = deviceTestVMI(spec, kubevirtv1.VirtualMachineInstanceStatus{ + CurrentCPUTopology: &kubevirtv1.CPUTopology{Sockets: 2}}) + got, err = newDeviceClient(t, deviceTestVM(spec), vmi).GetVMCPUTopology("ns", "vm") + if err != nil || got.Sockets != 2 || got.Cores != 1 || got.Threads != 1 { + t.Errorf("topology = %+v, %v; want 2x1x1", got, err) + } +} + +// A VMI in a final phase can outlive the guest. The VM is stopped then, so every +// lookup must read the VM spec, not the dead VMI. +func TestFinishedVMIReadsTheVMSpec(t *testing.T) { + vmMem, vmiMem := resource.MustParse("8Gi"), resource.MustParse("1Gi") + vmSpec := kubevirtv1.VirtualMachineInstanceSpec{ + Architecture: "amd64", + Domain: kubevirtv1.DomainSpec{ + CPU: &kubevirtv1.CPU{Sockets: 4, Cores: 2, Threads: 1}, + Memory: &kubevirtv1.Memory{Guest: &vmMem}, + Devices: kubevirtv1.Devices{ + Disks: []kubevirtv1.Disk{{Name: "staged", DiskDevice: kubevirtv1.DiskDevice{Disk: &kubevirtv1.DiskTarget{Bus: "virtio"}}}}, + Interfaces: []kubevirtv1.Interface{{Name: "staged-nic", MacAddress: "02:00:00:00:00:99"}}, + }, + }, + } + vmiSpec := kubevirtv1.VirtualMachineInstanceSpec{ + Architecture: "arm64", + Domain: kubevirtv1.DomainSpec{ + CPU: &kubevirtv1.CPU{Sockets: 1, Cores: 1, Threads: 1}, + Memory: &kubevirtv1.Memory{Guest: &vmiMem}, + Devices: kubevirtv1.Devices{ + Disks: []kubevirtv1.Disk{{Name: "old", DiskDevice: kubevirtv1.DiskDevice{Disk: &kubevirtv1.DiskTarget{Bus: "virtio"}}}}, + Interfaces: []kubevirtv1.Interface{{Name: "old-nic"}}, + }, + }, + } + for _, phase := range []kubevirtv1.VirtualMachineInstancePhase{kubevirtv1.Succeeded, kubevirtv1.Failed} { + t.Run(string(phase), func(t *testing.T) { + vmi := deviceTestVMI(vmiSpec, kubevirtv1.VirtualMachineInstanceStatus{ + Phase: phase, + CurrentCPUTopology: &kubevirtv1.CPUTopology{Sockets: 1, Cores: 1, Threads: 1}, + Interfaces: []kubevirtv1.VirtualMachineInstanceNetworkInterface{{Name: "old-nic", MAC: "52:54:00:00:00:01", IPs: []string{"10.0.0.9"}}}, + }) + c := newDeviceClient(t, deviceTestVM(vmSpec), vmi) + + if topo, err := c.GetVMCPUTopology("ns", "vm"); err != nil || topo.Sockets != 4 || topo.Cores != 2 || topo.Architecture != "amd64" { + t.Errorf("CPU = %+v, %v; want the VM spec", topo, err) + } + if gib, err := c.GetVMMemory("ns", "vm"); err != nil || gib != 8 { + t.Errorf("memory = %v, %v; want 8", gib, err) + } + if disks, err := c.GetVMDisks("ns", "vm"); err != nil || len(disks) != 1 || disks[0].Name != "staged" { + t.Errorf("disks = %+v, %v; want the VM's", disks, err) + } + nics, err := c.GetVMNICs("ns", "vm") + if err != nil || len(nics) != 1 || nics[0].Name != "staged-nic" || nics[0].Running || len(nics[0].IPs) != 0 || nics[0].MAC != "02:00:00:00:00:99" { + t.Errorf("NICs = %+v, %v; want the VM's, not running", nics, err) + } + }) + } +} + +// A running VM lists the disks and NICs of its VMI, not the staged VM spec. +func TestGetVMDisksAndNICs_VMIWinsOverVM(t *testing.T) { + disk := func(n string) kubevirtv1.Disk { + return kubevirtv1.Disk{Name: n, DiskDevice: kubevirtv1.DiskDevice{Disk: &kubevirtv1.DiskTarget{Bus: "virtio"}}} + } + vmSpec := kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{Devices: kubevirtv1.Devices{ + Disks: []kubevirtv1.Disk{disk("root"), disk("staged-only")}, + Interfaces: []kubevirtv1.Interface{{Name: "default"}, {Name: "staged-nic"}}, + }}} + vmiSpec := kubevirtv1.VirtualMachineInstanceSpec{ + Domain: kubevirtv1.DomainSpec{Devices: kubevirtv1.Devices{ + Disks: []kubevirtv1.Disk{disk("root"), disk("hotplugged")}, + Interfaces: []kubevirtv1.Interface{{Name: "default"}}, + }}, + Volumes: []kubevirtv1.Volume{{Name: "hotplugged", VolumeSource: kubevirtv1.VolumeSource{ + EmptyDisk: &kubevirtv1.EmptyDiskSource{Capacity: resource.MustParse("1Gi")}}}}, + } + c := newDeviceClient(t, deviceTestVM(vmSpec), deviceTestVMI(vmiSpec, kubevirtv1.VirtualMachineInstanceStatus{Phase: kubevirtv1.Running})) + + disks, err := c.GetVMDisks("ns", "vm") + if err != nil || len(disks) != 2 || disks[0].Name != "root" || disks[1].Name != "hotplugged" { + t.Errorf("disks = %+v, %v; want root and hotplugged (the VMI's)", disks, err) + } + if d, err := c.GetVMDisk("ns", "vm", "hotplugged"); err != nil || d == nil || d.CapacityBytes == nil || *d.CapacityBytes != 1<<30 { + t.Errorf("hotplugged disk = %+v, %v; want 1Gi", d, err) + } + if d, err := c.GetVMDisk("ns", "vm", "staged-only"); err != nil || d != nil { + t.Errorf("staged-only disk = %+v, %v; want nil (not attached yet)", d, err) + } + if nics, err := c.GetVMNICs("ns", "vm"); err != nil || len(nics) != 1 || nics[0].Name != "default" { + t.Errorf("NICs = %+v, %v; want only default", nics, err) + } +} + +func TestGetVMNICs_LinkState(t *testing.T) { + spec := kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{Devices: kubevirtv1.Devices{ + Interfaces: []kubevirtv1.Interface{{Name: "up"}, {Name: "down"}, {Name: "unreported"}}, + }}} + vmi := deviceTestVMI(spec, kubevirtv1.VirtualMachineInstanceStatus{Interfaces: []kubevirtv1.VirtualMachineInstanceNetworkInterface{ + {Name: "up", LinkState: "up"}, {Name: "down", LinkState: "down"}, {Name: "unreported"}, + }}) + nics, err := newDeviceClient(t, deviceTestVM(spec), vmi).GetVMNICs("ns", "vm") + if err != nil || len(nics) != 3 { + t.Fatalf("NICs = %+v, %v", nics, err) + } + for i, want := range []string{"up", "down", ""} { + if !nics[i].Running || nics[i].LinkState != want { + t.Errorf("%s: %+v; want running with link state %q", nics[i].Name, nics[i], want) + } + } +} + +func TestVMMemoryMiB_Rounds(t *testing.T) { + q := resource.MustParse("1000000000") // 953.67 MiB + spec := kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{Memory: &kubevirtv1.Memory{Guest: &q}}} + if mib, err := newDeviceClient(t, deviceTestVM(spec), nil).VMMemoryMiB("ns", "vm"); err != nil || mib != 954 { + t.Errorf("VMMemoryMiB = %d, %v; want 954", mib, err) + } +} + // failingVMIs makes every VMI Get fail with err; everything else passes through. type failingVMIs struct { dynamic.Interface diff --git a/pkg/server/system_devices_test.go b/pkg/server/system_devices_test.go index 1ef2fdb..89b3115 100644 --- a/pkg/server/system_devices_test.go +++ b/pkg/server/system_devices_test.go @@ -350,6 +350,8 @@ func TestSystemDevices_Unauthorized(t *testing.T) { func TestSystemDevices_RunningNIC(t *testing.T) { vmi := &kubevirtv1.VirtualMachineInstance{ ObjectMeta: metav1.ObjectMeta{Name: "vm-1", Namespace: "ns"}, + Spec: kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{Devices: kubevirtv1.Devices{ + Interfaces: []kubevirtv1.Interface{{Name: "default"}}}}}, Status: kubevirtv1.VirtualMachineInstanceStatus{Interfaces: []kubevirtv1.VirtualMachineInstanceNetworkInterface{ {Name: "default", MAC: "52:54:00:aa:bb:cc", IPs: []string{"10.0.0.5", "fd00::5", "not-an-ip", "10.0.0.6"}}, }}, From 2c14c61004e77242466a2906acc7542e720bb866 Mon Sep 17 00:00:00 2001 From: Tomer Karniol Date: Tue, 13 Oct 2026 01:39:40 +0300 Subject: [PATCH 7/8] fix(server): answer 405 on hardware resources and report NIC link state Routing: - handleSystem sent every PATCH under /Systems/{id}/... to the boot update handler before looking at the path, so PATCH /Systems/vm-1/Memory/1 was treated as a boot update and answered 200 instead of 405. The hardware resources (Memory, Processors, Storage, EthernetInterfaces) are now routed first. - The Reset action was matched with strings.Contains, so POST /Systems/vm-1/Memory/1/Actions/ComputerSystem.Reset reached the power handler. Only /Systems/{id}/Actions/ComputerSystem.Reset matches now. NICs: - A NIC the VMI reports as linkState "down" is NoLink. A running NIC with no reported state is still LinkUp. Tests and review follow-ups: - 405 with Allow: GET for POST/PATCH/PUT/DELETE (with a boot body) on every hardware path, and the Reset action under them. - A VMI that cannot be read gives 500 on every hardware endpoint. - Asymmetric topologies (3x2x1, 1x3x4), hotplug status over the VMI spec, VMI over VM for storage and NICs, final-phase VMIs, odd member paths. - Test helper comments explain that the VMI is not derived from the VM and why a controller RBAC failure is a 500 and not a 403. - Document the VMI-first rule and the link state. Signed-off-by: Tomer Karniol --- docs/README.md | 4 +- pkg/server/server.go | 30 ++- pkg/server/system_devices.go | 13 +- pkg/server/system_devices_test.go | 369 ++++++++++++++++++++++++++++-- 4 files changed, 388 insertions(+), 28 deletions(-) diff --git a/docs/README.md b/docs/README.md index e00fd44..9c600e9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -262,6 +262,8 @@ While your deployment is starting to deploy in the background, you can explore t A system also exposes its processors, memory, disks and network interfaces. The examples below come from a virtual machine named `my-vm` with 2 sockets, 2 cores per socket, 2 threads per core, 512 MiB of memory, a root disk from a container image and a 3 GiB SATA disk. All of them are read-only and follow the links in the system response. + While the VM is running, the values describe what the running VM has now (its VirtualMachineInstance), so a CPU or memory change that is not applied yet, or a disk or network interface that is not attached yet, does not show up early. While the VM is stopped, or when its last run has finished, they come from the VM definition. + **Processors** (one entry per socket, `/Processors/CPU0`, `/Processors/CPU1`): ```bash @@ -335,7 +337,7 @@ While your deployment is starting to deploy in the background, you can explore t } ``` - **Network interfaces** (`/EthernetInterfaces` lists every NIC). `LinkStatus` is `LinkUp` while the VM is running and `NoLink` otherwise. The MAC address comes from the running VM, or from the VM definition when it is stopped, and is omitted if neither has one. Virtual NICs have no link speed, so `SpeedMbps` is not reported: + **Network interfaces** (`/EthernetInterfaces` lists every NIC). `LinkStatus` is `LinkUp` while the VM is running and `NoLink` when it is stopped or when KubeVirt reports the interface link as down. The MAC address comes from the running VM, or from the VM definition when it is stopped, and is omitted if neither has one. Virtual NICs have no link speed, so `SpeedMbps` is not reported: ```json { diff --git a/pkg/server/server.go b/pkg/server/server.go index e1b6d55..a168ea6 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -650,6 +650,16 @@ func (s *Server) handleSystemsCollection(w http.ResponseWriter, r *http.Request) s.encodeJSONResponse(w, collection) } +// isResetActionPath reports whether pathParts (the split request path) is +// exactly /redfish/v1/Systems/{id}/Actions/ComputerSystem.Reset, with an +// optional trailing slash. +func isResetActionPath(pathParts []string) bool { + if len(pathParts) == 8 && pathParts[7] == "" { + pathParts = pathParts[:7] + } + return len(pathParts) == 7 && pathParts[5] == "Actions" && pathParts[6] == "ComputerSystem.Reset" +} + // handleSystem handles individual system (VM) endpoints. // It returns detailed information about a specific virtual machine. // @@ -675,11 +685,23 @@ func (s *Server) handleSystem(w http.ResponseWriter, r *http.Request) { logger.LogSafeHeaders("System request headers", r.Header, logger.GetCorrelationID(r.Context())) // Handle power management actions - if r.Method == "POST" && strings.Contains(r.URL.Path, "/Actions/ComputerSystem.Reset") { + // Only the system's own action path counts: a Contains check would also match + // "/Systems/{id}/Memory/1/Actions/ComputerSystem.Reset" and power-cycle the VM + // from a read-only resource instead of answering 405. + if r.Method == "POST" && isResetActionPath(pathParts) { s.handlePowerAction(w, r, systemName) return } + // Hardware sub-resources: Memory, Processors, Storage, EthernetInterfaces. + // This must come before the PATCH branch below, which takes every PATCH + // whatever its path: otherwise a PATCH to a read-only resource is treated as + // a boot update instead of being answered with 405. + if len(pathParts) >= 6 && (pathParts[5] == "Memory" || pathParts[5] == "Processors" || pathParts[5] == "Storage" || pathParts[5] == "EthernetInterfaces") { + s.handleSystemDevices(w, r, systemName, pathParts) + return + } + // Handle boot configuration updates if r.Method == "PATCH" { s.handleBootUpdate(w, r, systemName) @@ -692,12 +714,6 @@ func (s *Server) handleSystem(w http.ResponseWriter, r *http.Request) { return } - // Hardware sub-resources: Memory, Processors, Storage, EthernetInterfaces - if len(pathParts) >= 6 && (pathParts[5] == "Memory" || pathParts[5] == "Processors" || pathParts[5] == "Storage" || pathParts[5] == "EthernetInterfaces") { - s.handleSystemDevices(w, r, systemName, pathParts) - return - } - // For GET requests to the system resource, validate method if !s.validateMethod(w, r, []string{"GET"}) { return diff --git a/pkg/server/system_devices.go b/pkg/server/system_devices.go index 47531ff..a8eed93 100644 --- a/pkg/server/system_devices.go +++ b/pkg/server/system_devices.go @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * Copyright 2025 KubeVirt Redfish project and its authors. + * Copyright 2026 KubeVirt Redfish project and its authors. * */ @@ -43,7 +43,9 @@ var okStatus = redfish.Status{State: "Enabled", Health: "OK"} // handleSystemDevices serves the read-only hardware sub-resources of a system: // Memory, Processors, Storage (with Drives) and EthernetInterfaces. pathParts is the split -// request path, so pathParts[5] is the sub-resource name. +// request path. For "/redfish/v1/Systems/vm-1/Storage/1/Drives/root" that is +// ["", "redfish", "v1", "Systems", "vm-1", "Storage", "1", "Drives", "root"], so +// pathParts[5:] starts at the sub-resource name ("Storage"). func (s *Server) handleSystemDevices(w http.ResponseWriter, r *http.Request, systemName string, pathParts []string) { if !s.validateMethod(w, r, []string{"GET"}) { return @@ -53,7 +55,8 @@ func (s *Server) handleSystemDevices(w http.ResponseWriter, r *http.Request, sys return } - // Drop a trailing empty element ("/Storage/" -> "/Storage"). + // Drop a trailing empty element: "/redfish/v1/Systems/vm-1/Storage/" splits + // into [... "Storage", ""], which must be handled like "/Storage". rest := pathParts[5:] if rest[len(rest)-1] == "" { rest = rest[:len(rest)-1] @@ -245,7 +248,9 @@ func (s *Server) serveEthernetInterfaces(w http.ResponseWriter, namespace, vmNam LinkStatus: "NoLink", Status: okStatus, } - if n.Running { + // A reported "down" is a disconnected virtual NIC on a running VM; an empty + // state (not reported) on a running NIC is treated as up. + if n.Running && n.LinkState != "down" { eth.LinkStatus = "LinkUp" } for _, ip := range n.IPs { diff --git a/pkg/server/system_devices_test.go b/pkg/server/system_devices_test.go index 89b3115..e610955 100644 --- a/pkg/server/system_devices_test.go +++ b/pkg/server/system_devices_test.go @@ -13,17 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * Copyright 2025 KubeVirt Redfish project and its authors. + * Copyright 2026 KubeVirt Redfish project and its authors. * */ package server import ( + "context" "encoding/json" "errors" "net/http" "net/http/httptest" + "strconv" + "strings" "testing" "time" @@ -37,8 +40,10 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/dynamic" "k8s.io/client-go/kubernetes/fake" k8stesting "k8s.io/client-go/testing" kubevirtv1 "kubevirt.io/api/core/v1" @@ -49,8 +54,12 @@ func newDevicesTestServer(t *testing.T, arch string) *Server { return newDevicesTestServerWith(t, arch, nil, nil) } -// newDevicesTestServerWith adds an optional running VMI and a custom fake Kubernetes client. -func newDevicesTestServerWith(t *testing.T, arch string, vmi *kubevirtv1.VirtualMachineInstance, k8s *fake.Clientset) *Server { +// newDevicesTestServerWith builds the fixed VM "vm-1" (2x2x2 CPU, 512Mi, one NIC +// with MAC 02:00:00:00:00:01, two disks) and optionally a running VMI and a custom +// fake Kubernetes client. The VMI is NOT derived from the VM: a test that passes +// one decides which values it shares with the VM and which deliberately differ. +// Name and namespace must match ("vm-1"/"ns"), which is how the pair is tied together. +func newDevicesTestServerWith(t *testing.T, arch string, vmi *kubevirtv1.VirtualMachineInstance, k8s *fake.Clientset, wrap ...func(dynamic.Interface) dynamic.Interface) *Server { t.Helper() mock := kubevirt.NewMockDynamicClient() vm := &kubevirtv1.VirtualMachine{ @@ -82,6 +91,8 @@ func newDevicesTestServerWith(t *testing.T, arch string, vmi *kubevirtv1.Virtual } require.NoError(t, mock.AddVM(vm)) if vmi != nil { + require.Equal(t, vm.Name, vmi.Name, "the VMI must belong to the VM") + require.Equal(t, vm.Namespace, vmi.Namespace, "the VMI must belong to the VM") require.NoError(t, mock.AddVMI(vmi)) } if k8s == nil { @@ -96,10 +107,64 @@ func newDevicesTestServerWith(t *testing.T, arch string, vmi *kubevirtv1.Virtual }}, Chassis: []config.ChassisConfig{{Name: "c", Namespace: "ns"}, {Name: "other", Namespace: "other-ns"}}, } - client := kubevirt.NewClientWithClients(k8s, mock, 30*time.Second, nil) + var dyn dynamic.Interface = mock + for _, w := range wrap { + dyn = w(dyn) + } + client := kubevirt.NewClientWithClients(k8s, dyn, 30*time.Second, nil) return NewServer(cfg, client) } +// failVMIReads makes every VMI Get fail with err; everything else passes through. +func failVMIReads(err error) func(dynamic.Interface) dynamic.Interface { + return func(d dynamic.Interface) dynamic.Interface { return failingVMIs{Interface: d, err: err} } +} + +type failingVMIs struct { + dynamic.Interface + err error +} + +func (f failingVMIs) Resource(gvr schema.GroupVersionResource) dynamic.NamespaceableResourceInterface { + r := f.Interface.Resource(gvr) + if gvr.Resource == "virtualmachineinstances" { + return failingVMIResource{NamespaceableResourceInterface: r, err: f.err} + } + return r +} + +type failingVMIResource struct { + dynamic.NamespaceableResourceInterface + err error +} + +func (r failingVMIResource) Namespace(ns string) dynamic.ResourceInterface { + return failingVMIGet{ResourceInterface: r.NamespaceableResourceInterface.Namespace(ns), err: r.err} +} + +type failingVMIGet struct { + dynamic.ResourceInterface + err error +} + +func (g failingVMIGet) Get(context.Context, string, metav1.GetOptions, ...string) (*unstructured.Unstructured, error) { + return nil, g.err +} + +// vmiOf builds a VMI that belongs to the fixed VM "vm-1". +func vmiOf(spec kubevirtv1.VirtualMachineInstanceSpec, status kubevirtv1.VirtualMachineInstanceStatus) *kubevirtv1.VirtualMachineInstance { + return &kubevirtv1.VirtualMachineInstance{ObjectMeta: metav1.ObjectMeta{Name: "vm-1", Namespace: "ns"}, Spec: spec, Status: status} +} + +func getJSON(t *testing.T, srv *Server, path string) map[string]interface{} { + t.Helper() + w := getSystemPath(srv, path) + require.Equal(t, http.StatusOK, w.Code, path+": "+w.Body.String()) + var m map[string]interface{} + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &m)) + return m +} + func getSystemPath(srv *Server, path string) *httptest.ResponseRecorder { return getSystemPathAs(srv, path, &auth.User{Username: "u", Chassis: []string{"c"}}) } @@ -216,12 +281,26 @@ func TestSystemDevices(t *testing.T) { } }) + // A PATCH under /Systems/{id}/ is a boot update on the system itself. On these + // read-only resources it must be answered with 405, not treated as a boot update. t.Run("non-GET is rejected", func(t *testing.T) { - req := httptest.NewRequest("POST", "/redfish/v1/Systems/vm-1/Storage", nil) - req = req.WithContext(logger.WithAuth(req.Context(), &auth.AuthContext{User: &auth.User{Username: "u", Chassis: []string{"c"}}})) - w := httptest.NewRecorder() - srv.handleSystem(w, req) - assert.Equal(t, http.StatusMethodNotAllowed, w.Code) + bootBody := `{"Boot": {"BootSourceOverrideTarget": "Cd", "BootSourceOverrideEnabled": "Once"}}` + for _, method := range []string{"POST", "PATCH", "PUT", "DELETE"} { + for _, p := range []string{ + "/redfish/v1/Systems/vm-1/Memory/1", + "/redfish/v1/Systems/vm-1/Processors", + "/redfish/v1/Systems/vm-1/Storage", + "/redfish/v1/Systems/vm-1/Storage/1/Drives/root", + "/redfish/v1/Systems/vm-1/EthernetInterfaces/default", + } { + req := httptest.NewRequest(method, p, strings.NewReader(bootBody)) + req = req.WithContext(logger.WithAuth(req.Context(), &auth.AuthContext{User: &auth.User{Username: "u", Chassis: []string{"c"}}})) + w := httptest.NewRecorder() + srv.handleSystem(w, req) + assert.Equal(t, http.StatusMethodNotAllowed, w.Code, method+" "+p) + assert.Equal(t, "GET", w.Header().Get("Allow"), method+" "+p) + } + } }) } @@ -348,14 +427,12 @@ func TestSystemDevices_Unauthorized(t *testing.T) { // A running VM reports LinkUp, the MAC KubeVirt assigned and its addresses, split // into IPv4 and IPv6. Anything that is not an IP address is dropped. func TestSystemDevices_RunningNIC(t *testing.T) { - vmi := &kubevirtv1.VirtualMachineInstance{ - ObjectMeta: metav1.ObjectMeta{Name: "vm-1", Namespace: "ns"}, - Spec: kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{Devices: kubevirtv1.Devices{ + vmi := vmiOf( + kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{Devices: kubevirtv1.Devices{ Interfaces: []kubevirtv1.Interface{{Name: "default"}}}}}, - Status: kubevirtv1.VirtualMachineInstanceStatus{Interfaces: []kubevirtv1.VirtualMachineInstanceNetworkInterface{ + kubevirtv1.VirtualMachineInstanceStatus{Interfaces: []kubevirtv1.VirtualMachineInstanceNetworkInterface{ {Name: "default", MAC: "52:54:00:aa:bb:cc", IPs: []string{"10.0.0.5", "fd00::5", "not-an-ip", "10.0.0.6"}}, - }}, - } + }}) srv := newDevicesTestServerWith(t, "", vmi, nil) w := getSystemPath(srv, "/redfish/v1/Systems/vm-1/EthernetInterfaces/default") require.Equal(t, http.StatusOK, w.Code, w.Body.String()) @@ -371,8 +448,48 @@ func TestSystemDevices_RunningNIC(t *testing.T) { assert.Equal(t, []interface{}{map[string]interface{}{"Address": "fd00::5"}}, nic["IPv6Addresses"]) } +// The running VMI is what the VM is doing now; the VM spec is only what is staged +// for the next start. Every value the VMI sets must win over the VM's. +func TestSystemDevices_RunningVMIWinsOverVMSpec(t *testing.T) { + running := resource.MustParse("1Gi") + vmi := &kubevirtv1.VirtualMachineInstance{ + ObjectMeta: metav1.ObjectMeta{Name: "vm-1", Namespace: "ns"}, + Spec: kubevirtv1.VirtualMachineInstanceSpec{ + Architecture: "arm64", + Domain: kubevirtv1.DomainSpec{ + CPU: &kubevirtv1.CPU{Sockets: 1, Cores: 3, Threads: 1, Model: "running-model"}, + Memory: &kubevirtv1.Memory{Guest: &running}, + }, + }, + } + // The VM spec says amd64, 2 sockets x 2 cores x 2 threads, Skylake-Client, 512Mi. + srv := newDevicesTestServerWith(t, "amd64", vmi, nil) + get := func(path string) map[string]interface{} { + w := getSystemPath(srv, path) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + var m map[string]interface{} + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &m)) + return m + } + + cpu := get("/redfish/v1/Systems/vm-1/Processors/CPU0") + assert.Equal(t, "running-model", cpu["Model"]) + assert.EqualValues(t, 3, cpu["TotalCores"]) + assert.Equal(t, "ARM", cpu["ProcessorArchitecture"]) + assert.Equal(t, http.StatusNotFound, getSystemPath(srv, "/redfish/v1/Systems/vm-1/Processors/CPU1").Code, + "the VMI has 1 socket, the staged VM spec has 2") + + assert.EqualValues(t, 1024, get("/redfish/v1/Systems/vm-1/Memory/1")["CapacityMiB"]) + + summary := get("/redfish/v1/Systems/vm-1")["ProcessorSummary"].(map[string]interface{}) + assert.EqualValues(t, 3, summary["LogicalProcessorCount"]) +} + // When the cluster cannot be read for a reason other than "not found", the -// endpoints answer 500 instead of a plausible but wrong 200. +// endpoints answer 500 instead of a plausible but wrong 200. The 500 (not 403) +// is deliberate: the caller already passed the access check, and it is the +// controller's own service account that lacks the permission. That is a server +// fault the client cannot fix, so it must not look like the caller was denied. func TestSystemDevices_ClusterReadErrors(t *testing.T) { t.Run("PVC lookup forbidden gives 500 for the drive, names still list", func(t *testing.T) { mock := kubevirt.NewMockDynamicClient() @@ -420,3 +537,223 @@ func TestSystemDevices_ClusterReadErrors(t *testing.T) { assert.NotNil(t, oem) }) } + +// A POST to the Reset action of the system itself reaches the power handler. The +// same action path below a read-only resource must not: it answers 405 instead +// of power-cycling the VM from /Memory/1. +func TestSystemDevices_ResetActionOnlyOnTheSystem(t *testing.T) { + srv := newDevicesTestServer(t, "") + post := func(path, body string) *httptest.ResponseRecorder { + req := httptest.NewRequest("POST", path, strings.NewReader(body)) + req = req.WithContext(logger.WithAuth(req.Context(), &auth.AuthContext{User: &auth.User{Username: "u", Chassis: []string{"c"}}})) + w := httptest.NewRecorder() + srv.handleSystem(w, req) + return w + } + + for _, p := range []string{ + "/redfish/v1/Systems/vm-1/Memory/1/Actions/ComputerSystem.Reset", + "/redfish/v1/Systems/vm-1/Processors/Actions/ComputerSystem.Reset", + "/redfish/v1/Systems/vm-1/Storage/1/Actions/ComputerSystem.Reset", + "/redfish/v1/Systems/vm-1/EthernetInterfaces/default/Actions/ComputerSystem.Reset", + } { + w := post(p, `{"ResetType":"ForceOff"}`) + assert.Equal(t, http.StatusMethodNotAllowed, w.Code, p) + assert.Equal(t, "GET", w.Header().Get("Allow"), p) + } + + // The real action still goes to handlePowerAction, which rejects a bad body + // with 400 (a 405 or a 200 would mean it was routed somewhere else). + for _, p := range []string{ + "/redfish/v1/Systems/vm-1/Actions/ComputerSystem.Reset", + "/redfish/v1/Systems/vm-1/Actions/ComputerSystem.Reset/", + } { + assert.Equal(t, http.StatusBadRequest, post(p, "not json").Code, p) + } +} + +func TestIsResetActionPath(t *testing.T) { + for path, want := range map[string]bool{ + "/redfish/v1/Systems/vm-1/Actions/ComputerSystem.Reset": true, + "/redfish/v1/Systems/vm-1/Actions/ComputerSystem.Reset/": true, + "/redfish/v1/Systems/vm-1/Memory/1/Actions/ComputerSystem.Reset": false, + "/redfish/v1/Systems/vm-1/Actions/ComputerSystem.Reset/extra": false, + "/redfish/v1/Systems/vm-1/Actions": false, + "/redfish/v1/Systems/vm-1": false, + "/redfish/v1/Systems/vm-1/Actions/ComputerSystem.Reset/Actions/x/y/z/w": false, + } { + assert.Equal(t, want, isResetActionPath(strings.Split(path, "/")), path) + } +} + +// Whatever the endpoint, a VMI that cannot be read (not "not found") is a 500 +// with no data, never the staged VM spec or an empty list. +func TestSystemDevices_VMIReadErrorsAre500(t *testing.T) { + forbidden := apierrors.NewForbidden(schema.GroupResource{Resource: "virtualmachineinstances"}, "vm-1", errors.New("no access")) + srv := newDevicesTestServerWith(t, "", nil, nil, failVMIReads(forbidden)) + for _, p := range []string{ + "/redfish/v1/Systems/vm-1/Memory/1", + "/redfish/v1/Systems/vm-1/Processors", + "/redfish/v1/Systems/vm-1/Processors/CPU0", + "/redfish/v1/Systems/vm-1/Storage/1", + "/redfish/v1/Systems/vm-1/Storage/1/Drives/data", + "/redfish/v1/Systems/vm-1/EthernetInterfaces", + "/redfish/v1/Systems/vm-1/EthernetInterfaces/default", + } { + w := getSystemPath(srv, p) + assert.Equal(t, http.StatusInternalServerError, w.Code, p) + for _, leak := range []string{"CapacityMiB", "TotalCores", "MACAddress", "CapacityBytes", "Drives\":[{", "Members\":[{"} { + assert.NotContains(t, w.Body.String(), leak, p) + } + } +} + +// 3 sockets x 2 cores x 1 thread: no threading, three processors, and every +// number comes from the right field (the sockets, cores and threads all differ). +func TestSystemDevices_AsymmetricTopology(t *testing.T) { + for _, tc := range []struct { + name string + sockets, cores, threads uint32 + wantThreading bool + wantTotalThreads, wantLogicals int + }{ + {"no threading", 3, 2, 1, false, 2, 6}, + {"threading", 1, 3, 4, true, 12, 12}, + } { + t.Run(tc.name, func(t *testing.T) { + vmi := vmiOf(kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{ + CPU: &kubevirtv1.CPU{Sockets: tc.sockets, Cores: tc.cores, Threads: tc.threads}}}, kubevirtv1.VirtualMachineInstanceStatus{}) + srv := newDevicesTestServerWith(t, "", vmi, nil) + + coll := getJSON(t, srv, "/redfish/v1/Systems/vm-1/Processors") + assert.EqualValues(t, tc.sockets, coll["Members@odata.count"]) + last := int(tc.sockets) - 1 + cpu := getJSON(t, srv, "/redfish/v1/Systems/vm-1/Processors/CPU"+strconv.Itoa(last)) + assert.Equal(t, "vCPU Socket "+strconv.Itoa(last), cpu["Name"]) + assert.Equal(t, "CPU"+strconv.Itoa(last), cpu["Id"]) + assert.EqualValues(t, tc.cores, cpu["TotalCores"]) + assert.EqualValues(t, tc.wantTotalThreads, cpu["TotalThreads"]) + assert.Equal(t, http.StatusNotFound, getSystemPath(srv, "/redfish/v1/Systems/vm-1/Processors/CPU"+strconv.Itoa(int(tc.sockets))).Code) + + sys := getJSON(t, srv, "/redfish/v1/Systems/vm-1") + sum := sys["ProcessorSummary"].(map[string]interface{}) + assert.EqualValues(t, tc.sockets, sum["Count"]) + assert.EqualValues(t, tc.sockets*tc.cores, sum["CoreCount"]) + assert.EqualValues(t, tc.wantLogicals, sum["LogicalProcessorCount"]) + assert.Equal(t, tc.wantThreading, sum["ThreadingEnabled"]) + oem := sys["Oem"].(map[string]interface{})["KubeVirt"].(map[string]interface{})["Processors"].(map[string]interface{}) + assert.EqualValues(t, tc.sockets, oem["Sockets"]) + assert.EqualValues(t, tc.cores, oem["CoresPerSocket"]) + assert.EqualValues(t, tc.threads, oem["ThreadsPerCore"]) + }) + } +} + +// During a hotplug the status says what the guest has; it wins over the VMI spec +// for cores and threads as well as sockets, and for memory. +func TestSystemDevices_HotplugStatusWins(t *testing.T) { + spec := kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{CPU: &kubevirtv1.CPU{Sockets: 1, Cores: 1, Threads: 1}}} + guest := resource.MustParse("2Gi") + vmi := vmiOf(spec, kubevirtv1.VirtualMachineInstanceStatus{ + CurrentCPUTopology: &kubevirtv1.CPUTopology{Sockets: 2, Cores: 3, Threads: 2}, + Memory: &kubevirtv1.MemoryStatus{GuestCurrent: &guest}, + }) + srv := newDevicesTestServerWith(t, "", vmi, nil) + + cpu := getJSON(t, srv, "/redfish/v1/Systems/vm-1/Processors/CPU1") + assert.EqualValues(t, 3, cpu["TotalCores"]) + assert.EqualValues(t, 6, cpu["TotalThreads"]) + assert.EqualValues(t, 2048, getJSON(t, srv, "/redfish/v1/Systems/vm-1/Memory/1")["CapacityMiB"]) + sys := getJSON(t, srv, "/redfish/v1/Systems/vm-1") + assert.EqualValues(t, 12, sys["ProcessorSummary"].(map[string]interface{})["LogicalProcessorCount"]) + assert.EqualValues(t, 2, sys["MemorySummary"].(map[string]interface{})["TotalSystemMemoryGiB"]) +} + +// Odd member paths are 404 and a trailing slash on a member is tolerated. +func TestSystemDevices_OddPaths(t *testing.T) { + srv := newDevicesTestServer(t, "") + for _, p := range []string{ + "/redfish/v1/Systems/vm-1/Processors/CPU-1", + "/redfish/v1/Systems/vm-1/Processors/CPU0/extra", + "/redfish/v1/Systems/vm-1/Storage/1/foo", + "/redfish/v1/Systems/vm-1/Storage/1/Drives", + "/redfish/v1/Systems/vm-1/Storage/1/Drives/root/x", + "/redfish/v1/Systems/vm-1/Memory/1/x", + "/redfish/v1/Systems/vm-1/EthernetInterfaces/default/x", + } { + assert.Equal(t, http.StatusNotFound, getSystemPath(srv, p).Code, p) + } + for _, p := range []string{ + "/redfish/v1/Systems/vm-1/Memory/1/", + "/redfish/v1/Systems/vm-1/Processors/CPU0/", + "/redfish/v1/Systems/vm-1/EthernetInterfaces/", + "/redfish/v1/Systems/vm-1/Storage/1/", + } { + assert.Equal(t, http.StatusOK, getSystemPath(srv, p).Code, p) + } +} + +// A VMI that is Succeeded or Failed is a stopped VM: everything is read from the +// VM spec and the NIC has no link. +func TestSystemDevices_FinishedVMIReadsTheVM(t *testing.T) { + for _, phase := range []kubevirtv1.VirtualMachineInstancePhase{kubevirtv1.Succeeded, kubevirtv1.Failed} { + t.Run(string(phase), func(t *testing.T) { + guest := resource.MustParse("8Gi") + vmi := vmiOf(kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{ + CPU: &kubevirtv1.CPU{Sockets: 1, Cores: 1, Threads: 1, Model: "dead-vmi"}, + Memory: &kubevirtv1.Memory{Guest: &guest}, + Devices: kubevirtv1.Devices{Interfaces: []kubevirtv1.Interface{{Name: "default"}}}, + }}, kubevirtv1.VirtualMachineInstanceStatus{ + Phase: phase, + Interfaces: []kubevirtv1.VirtualMachineInstanceNetworkInterface{ + {Name: "default", MAC: "52:54:00:de:ad:00", IPs: []string{"10.9.9.9"}}}, + }) + srv := newDevicesTestServerWith(t, "", vmi, nil) + + // The VM spec has 2x2x2, Skylake-Client, 512Mi and MAC 02:00:00:00:00:01. + assert.Equal(t, "Skylake-Client", getJSON(t, srv, "/redfish/v1/Systems/vm-1/Processors/CPU1")["Model"]) + assert.EqualValues(t, 512, getJSON(t, srv, "/redfish/v1/Systems/vm-1/Memory/1")["CapacityMiB"]) + nic := getJSON(t, srv, "/redfish/v1/Systems/vm-1/EthernetInterfaces/default") + assert.Equal(t, "NoLink", nic["LinkStatus"]) + assert.Equal(t, "02:00:00:00:00:01", nic["MACAddress"]) + assert.Nil(t, nic["IPv4Addresses"]) + }) + } +} + +// A virtual NIC the VMI reports as down is NoLink, an up or unreported state on a +// running NIC is LinkUp. +func TestSystemDevices_NICLinkState(t *testing.T) { + spec := kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{Devices: kubevirtv1.Devices{ + Interfaces: []kubevirtv1.Interface{{Name: "up"}, {Name: "down"}, {Name: "unreported"}, {Name: "booting"}}}}} + vmi := vmiOf(spec, kubevirtv1.VirtualMachineInstanceStatus{Interfaces: []kubevirtv1.VirtualMachineInstanceNetworkInterface{ + {Name: "up", LinkState: "up"}, {Name: "down", LinkState: "down"}, {Name: "unreported"}, + }}) + srv := newDevicesTestServerWith(t, "", vmi, nil) + for name, want := range map[string]string{"up": "LinkUp", "down": "NoLink", "unreported": "LinkUp", "booting": "NoLink"} { + assert.Equal(t, want, getJSON(t, srv, "/redfish/v1/Systems/vm-1/EthernetInterfaces/"+name)["LinkStatus"], name) + } +} + +// Disks and NICs of a running VM are the VMI's: a volume added to the running VM +// only is listed, one staged in the VM spec is not. +func TestSystemDevices_StorageAndNICsFollowTheVMI(t *testing.T) { + vmi := vmiOf(kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{Devices: kubevirtv1.Devices{ + Disks: []kubevirtv1.Disk{ + {Name: "root", DiskDevice: kubevirtv1.DiskDevice{Disk: &kubevirtv1.DiskTarget{Bus: "virtio"}}}, + {Name: "hotplugged", DiskDevice: kubevirtv1.DiskDevice{Disk: &kubevirtv1.DiskTarget{Bus: "scsi"}}}, + }, + Interfaces: []kubevirtv1.Interface{{Name: "default"}, {Name: "hot-nic"}}, + }}}, kubevirtv1.VirtualMachineInstanceStatus{}) + srv := newDevicesTestServerWith(t, "", vmi, nil) + + // The VM spec has the disks root and data and the NIC default. + st := getJSON(t, srv, "/redfish/v1/Systems/vm-1/Storage/1") + assert.Equal(t, []interface{}{ + map[string]interface{}{"@odata.id": "/redfish/v1/Systems/vm-1/Storage/1/Drives/root"}, + map[string]interface{}{"@odata.id": "/redfish/v1/Systems/vm-1/Storage/1/Drives/hotplugged"}, + }, st["Drives"]) + assert.Equal(t, http.StatusNotFound, getSystemPath(srv, "/redfish/v1/Systems/vm-1/Storage/1/Drives/data").Code, "staged in the VM only") + assert.Equal(t, http.StatusOK, getSystemPath(srv, "/redfish/v1/Systems/vm-1/Storage/1/Drives/hotplugged").Code) + assert.EqualValues(t, 2, getJSON(t, srv, "/redfish/v1/Systems/vm-1/EthernetInterfaces")["Members@odata.count"]) +} From 078cde4e1cf3f1732711555bbb8be483c74a7e81 Mon Sep 17 00:00:00 2001 From: Tomer Karniol Date: Wed, 21 Oct 2026 00:27:57 +0300 Subject: [PATCH 8/8] refactor(server): check access once for the hardware resources handleSystem now validates the method and resolves the VM with its access check for Memory, Processors, Storage and EthernetInterfaces, then hands the resolved namespace and VM name to handleSystemDevices. The handler no longer repeats the check itself. The method check still comes first, so non-GET requests keep answering 405 with Allow: GET. The power, boot and virtual media handlers are unchanged. Signed-off-by: Tomer Karniol --- pkg/server/server.go | 9 ++++++++- pkg/server/system_devices.go | 13 +++---------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/pkg/server/server.go b/pkg/server/server.go index a168ea6..1585029 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -698,7 +698,14 @@ func (s *Server) handleSystem(w http.ResponseWriter, r *http.Request) { // whatever its path: otherwise a PATCH to a read-only resource is treated as // a boot update instead of being answered with 405. if len(pathParts) >= 6 && (pathParts[5] == "Memory" || pathParts[5] == "Processors" || pathParts[5] == "Storage" || pathParts[5] == "EthernetInterfaces") { - s.handleSystemDevices(w, r, systemName, pathParts) + if !s.validateMethod(w, r, []string{"GET"}) { + return + } + namespace, vmName, _, ok := s.resolveSystemVMandCheckAccess(w, r, systemName) + if !ok { + return + } + s.handleSystemDevices(w, r, namespace, vmName, pathParts) return } diff --git a/pkg/server/system_devices.go b/pkg/server/system_devices.go index a8eed93..e799cd8 100644 --- a/pkg/server/system_devices.go +++ b/pkg/server/system_devices.go @@ -42,19 +42,12 @@ const ( var okStatus = redfish.Status{State: "Enabled", Health: "OK"} // handleSystemDevices serves the read-only hardware sub-resources of a system: -// Memory, Processors, Storage (with Drives) and EthernetInterfaces. pathParts is the split +// Memory, Processors, Storage (with Drives) and EthernetInterfaces. The caller has +// already validated the method and resolved the VM with its access check. pathParts is the split // request path. For "/redfish/v1/Systems/vm-1/Storage/1/Drives/root" that is // ["", "redfish", "v1", "Systems", "vm-1", "Storage", "1", "Drives", "root"], so // pathParts[5:] starts at the sub-resource name ("Storage"). -func (s *Server) handleSystemDevices(w http.ResponseWriter, r *http.Request, systemName string, pathParts []string) { - if !s.validateMethod(w, r, []string{"GET"}) { - return - } - namespace, vmName, _, ok := s.resolveSystemVMandCheckAccess(w, r, systemName) - if !ok { - return - } - +func (s *Server) handleSystemDevices(w http.ResponseWriter, r *http.Request, namespace, vmName string, pathParts []string) { // Drop a trailing empty element: "/redfish/v1/Systems/vm-1/Storage/" splits // into [... "Storage", ""], which must be handled like "/Storage". rest := pathParts[5:]