diff --git a/docs/README.md b/docs/README.md index aada8ec..9c600e9 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,123 @@ 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. + + 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 + 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` 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 + { + "@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. diff --git a/pkg/kubevirt/client.go b/pkg/kubevirt/client.go index 329dcfc..75f281b 100644 --- a/pkg/kubevirt/client.go +++ b/pkg/kubevirt/client.go @@ -2551,66 +2551,112 @@ 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. +// 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 { - 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 + 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) } - memory := vm.Spec.Template.Spec.Domain.Memory.Guest.String() - logger.Debug("Found memory spec for %s/%s: %s", namespace, name, memory) + 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 for %s/%s", namespace, name) + } + return float64(bytes) / (1 << 30), nil +} - // 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 - } +// 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() + } + 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 + // Architecture is spec.architecture ("amd64", "arm64"). It is empty when + // neither the VMI nor the VM declares one. + Architecture 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. +// 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 { - logger.Warning("Failed to get VM %s/%s for CPU lookup: %v", namespace, name, err) - return 1, nil // Low default fallback + return CPUTopology{}, 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 + 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) } - 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) - return 1, nil // Low default fallback + topo := CPUTopology{Sockets: 1, Cores: 1, Threads: 1} + 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 } - logger.Debug("Successfully found CPU cores for %s/%s: %d", namespace, name, cpuCores) - return int(cpuCores), nil + 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 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)) + } + return topo, 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..4d27bf1 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 }, } @@ -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 @@ -1688,7 +1688,7 @@ func TestGetVMCPU(t *testing.T) { } mockClient.AddVM(vm) }, - expected: 8, + expected: 16, // sockets x cores }, { name: "VM without CPU spec", @@ -1724,14 +1724,15 @@ 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) } 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..5cfc40a --- /dev/null +++ b/pkg/kubevirt/devices.go @@ -0,0 +1,279 @@ +/* + * 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 2026 KubeVirt Redfish project and its authors. + * + */ + +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" +) + +// 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, ...) and always nil from GetVMDisks. + 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 + // 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). +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 +} + +// 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(spec *kubevirtv1.VirtualMachineInstanceSpec) (disks []VMDisk, volumes []*kubevirtv1.Volume) { + if spec == nil { + return nil, nil + } + byName := map[string]*kubevirtv1.Volume{} + for i := range spec.Volumes { + v := &spec.Volumes[i] + byName[v.Name] = v + } + for _, d := range 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) + } + 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. +// 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) { + vm, err := c.getVMForRead(namespace, name) + if err != nil { + return nil, err + } + 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. 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 + } + 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 + } + 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: + 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: + if vol.EmptyDisk.Capacity.IsZero() { + return nil, nil + } + b := vol.EmptyDisk.Capacity.Value() + return &b, nil + case vol.HostDisk != nil: + if vol.HostDisk.Capacity.IsZero() { + return nil, nil + } + b := vol.HostDisk.Capacity.Value() + return &b, nil + default: + return nil, 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{}) + switch { + case err == nil: + if q, ok := pvc.Status.Capacity[corev1.ResourceStorage]; ok { + b := q.Value() + return &b, nil + } + if q, ok := pvc.Spec.Resources.Requests[corev1.ResourceStorage]; ok { + b := q.Value() + 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 { + 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, nil + } + } + if dv.Spec.PVC != nil { + if q, ok := dv.Spec.PVC.Resources.Requests[corev1.ResourceStorage]; ok { + b := q.Value() + return &b, nil + } + } + } + return nil, nil +} + +// 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 + } + // 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 + } + + status := map[string]kubevirtv1.VirtualMachineInstanceNetworkInterface{} + if vmi != nil { + for _, s := range vmi.Status.Interfaces { + status[s.Name] = s + } + } + + var nics []VMNIC + 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 + if s.MAC != "" { + nic.MAC = s.MAC + } + nic.IPs = s.IPs + nic.LinkState = s.LinkState + } + 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..ddc1300 --- /dev/null +++ b/pkg/kubevirt/devices_test.go @@ -0,0 +1,754 @@ +/* + * 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 2026 KubeVirt Redfish project and its authors. + * + */ + +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" +) + +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 TestGetVMCPUTopology_VCPUs(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) + 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) + } + }) + } +} + +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 got.Architecture != "" { + t.Errorf("unset architecture = %q, want it left empty, not guessed", got.Architecture) + } + 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) + } +} + +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")}}, + }) + 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) + + 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}, + } + + // 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 { + 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", w.name, *d.CapacityBytes) + case w.size >= 0 && (d.CapacityBytes == nil || *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) { + 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"}, + 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"}}, + }}, + } + 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]) + } + }) +} + +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) + } +} + +// 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 + 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 1c2fd16..0d63fcc 100644 --- a/pkg/redfish/types.go +++ b/pkg/redfish/types.go @@ -90,23 +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"` - Memory MemorySummary `json:"Memory"` - 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. @@ -118,15 +121,33 @@ 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"` +} + +// SystemOem carries vendor extensions of a ComputerSystem. +type SystemOem struct { + KubeVirt struct { + Processors struct { + Sockets int `json:"Sockets"` + CoresPerSocket int `json:"CoresPerSocket"` + ThreadsPerCore int `json:"ThreadsPerCore"` + } `json:"Processors"` + } `json:"KubeVirt"` } // Boot represents boot configuration for a computer system. @@ -366,3 +387,109 @@ 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"` + 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"` + 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"` +} + +// 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"` + // 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/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..1585029 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,30 @@ 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") { + 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 + } + // Handle boot configuration updates if r.Method == "PATCH" { s.handleBootUpdate(w, r, systemName) @@ -724,15 +753,11 @@ 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) - if err != nil { - logger.Warning("Failed to get CPU for VM %s: %v", vmName, err) - cpuCount = 1 // Low default fallback - } + procSummary, sysOem := s.processorFields(namespace, vmName) // Generate the correct System ID for the response responseSystemID := config.GenerateSystemID(s.currentConfig().SystemIDConvention, namespace, vmName) @@ -741,7 +766,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 @@ -751,13 +776,17 @@ 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: procSummary, + Oem: sysOem, Storage: redfish.Link{ OdataID: fmt.Sprintf("/redfish/v1/Systems/%s/Storage", responseSystemID), }, @@ -948,7 +977,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), @@ -1247,15 +1276,11 @@ 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) - if err != nil { - logger.Warning("Failed to get CPU for VM %s: %v", vmName, err) - cpuCount = 1 // Low default fallback - } + procSummary, sysOem := s.processorFields(namespace, vmName) // Return the updated ComputerSystem resource (Redfish spec requirement) responseSystemID := config.GenerateSystemID(s.currentConfig().SystemIDConvention, namespace, vmName) @@ -1263,7 +1288,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, @@ -1273,13 +1298,17 @@ 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: 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 new file mode 100644 index 0000000..e799cd8 --- /dev/null +++ b/pkg/server/system_devices.go @@ -0,0 +1,336 @@ +/* + * 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 2026 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. 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, 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:] + 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_1_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 + } + 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", + ProcessorArchitecture: arch, + InstructionSet: isa, + 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 + } + + 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, + 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": + 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 + } + 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") + } +} + +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_1_0.EthernetInterface", + ID: n.Name, + Name: n.Name, + MACAddress: n.MAC, + LinkStatus: "NoLink", + Status: okStatus, + } + // 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 { + 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) + return + } + 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 "", "" +} + +// 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 { + return redfish.ProcessorSummary{ + Count: cpu.Sockets, + CoreCount: cpu.Sockets * cpu.Cores, + LogicalProcessorCount: cpu.VCPUs(), + ThreadingEnabled: cpu.Threads > 1, + Model: cpu.Model, + } +} + +// 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 + 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..e610955 --- /dev/null +++ b/pkg/server/system_devices_test.go @@ -0,0 +1,759 @@ +/* + * 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 2026 KubeVirt Redfish project and its authors. + * + */ + +package server + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "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" + 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" +) + +func newDevicesTestServer(t *testing.T, arch string) *Server { + t.Helper() + return newDevicesTestServerWith(t, arch, nil, nil) +} + +// 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{ + 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{ + 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)) + 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 { + 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"}, {Name: "other", Namespace: "other-ns"}}, + } + 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"}}) +} + +// 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) + if user != nil { + req = req.WithContext(logger.WithAuth(req.Context(), &auth.AuthContext{User: user})) + } + 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"]) + 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"]) + 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"]) + 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) { + 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") + 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) + } + }) + + // 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) { + 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) + } + } + }) +} + +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) + 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"]) + }) + } +} + +// 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 := vmiOf( + kubevirtv1.VirtualMachineInstanceSpec{Domain: kubevirtv1.DomainSpec{Devices: kubevirtv1.Devices{ + Interfaces: []kubevirtv1.Interface{{Name: "default"}}}}}, + 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"]) +} + +// 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. 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() + 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) + }) +} + +// 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"]) +}