96 lines
2.5 KiB
Go
96 lines
2.5 KiB
Go
package host
|
|
|
|
import (
|
|
"encoding/binary"
|
|
"os"
|
|
"time"
|
|
)
|
|
|
|
// ProcessSample is a point-in-time CPU time + memory snapshot for a running process.
|
|
type ProcessSample struct {
|
|
PID int
|
|
CPUDuration time.Duration // kernel + user CPU time accumulated
|
|
SampledAt time.Time
|
|
WorkingSet uint64 // RSS / working set bytes
|
|
PrivateBytes uint64 // private committed bytes
|
|
CreatedAt time.Time
|
|
}
|
|
|
|
// DiskUsage reports host-allocated vs virtual logical capacity of a VM disk image.
|
|
type DiskUsage struct {
|
|
Path string `json:"path,omitempty"`
|
|
ActualBytes uint64 `json:"actual_bytes"`
|
|
VirtualBytes uint64 `json:"virtual_bytes"`
|
|
Format string `json:"format,omitempty"`
|
|
}
|
|
|
|
// ComputeCPUPercent computes host CPU utilization percentage between two samples.
|
|
// Returns a value normalized to 0..100 across logicalCPUs (matching Windows Task Manager).
|
|
func ComputeCPUPercent(prev, cur ProcessSample, logicalCPUs int) float64 {
|
|
if prev.PID == 0 || prev.PID != cur.PID {
|
|
return 0
|
|
}
|
|
wall := cur.SampledAt.Sub(prev.SampledAt)
|
|
if wall <= 0 {
|
|
return 0
|
|
}
|
|
cpuDelta := cur.CPUDuration - prev.CPUDuration
|
|
if cpuDelta <= 0 {
|
|
return 0
|
|
}
|
|
if logicalCPUs <= 0 {
|
|
logicalCPUs = 1
|
|
}
|
|
pct := (float64(cpuDelta) / float64(wall)) * 100.0 / float64(logicalCPUs)
|
|
if pct < 0 {
|
|
return 0
|
|
}
|
|
if pct > 100 {
|
|
return 100
|
|
}
|
|
return pct
|
|
}
|
|
|
|
// InspectDiskUsage returns actual host bytes consumed and virtual logical capacity
|
|
// for a .qcow2 or raw disk image without spawning qemu-img.
|
|
func InspectDiskUsage(path string) (DiskUsage, error) {
|
|
info, err := os.Stat(path)
|
|
if err != nil {
|
|
return DiskUsage{}, err
|
|
}
|
|
actual := fileActualSize(path, uint64(info.Size()))
|
|
usage := DiskUsage{
|
|
Path: path,
|
|
ActualBytes: actual,
|
|
VirtualBytes: uint64(info.Size()),
|
|
Format: "raw",
|
|
}
|
|
if vSize, ok := readQCOW2VirtualSize(path); ok {
|
|
usage.VirtualBytes = vSize
|
|
usage.Format = "qcow2"
|
|
}
|
|
return usage, nil
|
|
}
|
|
|
|
// readQCOW2VirtualSize reads the 8-byte big-endian virtual size from a QCOW2
|
|
// header (magic "QFI\xfb", version 2 or 3, size at byte offset 24).
|
|
func readQCOW2VirtualSize(path string) (uint64, bool) {
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return 0, false
|
|
}
|
|
defer f.Close()
|
|
var hdr [32]byte
|
|
if _, err := f.ReadAt(hdr[:], 0); err != nil {
|
|
return 0, false
|
|
}
|
|
if hdr[0] != 'Q' || hdr[1] != 'F' || hdr[2] != 'I' || hdr[3] != 0xfb {
|
|
return 0, false
|
|
}
|
|
ver := binary.BigEndian.Uint32(hdr[4:8])
|
|
if ver < 2 || ver > 3 {
|
|
return 0, false
|
|
}
|
|
return binary.BigEndian.Uint64(hdr[24:32]), true
|
|
}
|