Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 128 additions & 4 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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"
Expand Down Expand Up @@ -237,10 +245,126 @@ 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
},
"NodeName": "worker-3"
}
}
}
```

`Oem.KubeVirt.NodeName` is the node the running VMI is scheduled on (`status.nodeName`); it is omitted while the VM is stopped and changes when the VM is live-migrated.

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-route>/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.
Expand Down
130 changes: 88 additions & 42 deletions pkg/kubevirt/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 7 additions & 6 deletions pkg/kubevirt/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1605,7 +1605,7 @@ func TestGetVMMemory(t *testing.T) {
}
mockClient.AddVM(vm)
},
expected: 2.0, // Default fallback
expected: 0, // Unknown: no invented default
},
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -1688,7 +1688,7 @@ func TestGetVMCPU(t *testing.T) {
}
mockClient.AddVM(vm)
},
expected: 8,
expected: 16, // sockets x cores
},
{
name: "VM without CPU spec",
Expand Down Expand Up @@ -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)
}
})
}
Expand Down
Loading