package host import ( "encoding/binary" "os" "path/filepath" "sort" "strings" "time" ) // BackingChainWarnDepth is the CoW backing chain depth threshold at which // read-through across multiple qcow2 layers warrants a host/UI/CLI advisory. const BackingChainWarnDepth = 2 // BackingChainIssue summarizes one VM disk whose qcow2 CoW backing chain // exceeds BackingChainWarnDepth or references a missing parent image. type BackingChainIssue struct { VMName string `json:"vm_name"` Path string `json:"path"` Depth int `json:"depth"` Broken bool `json:"broken,omitempty"` } // 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"` BackingDepth int `json:"backing_depth,omitempty"` BackingBroken bool `json:"backing_broken,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" usage.BackingDepth, usage.BackingBroken = InspectQCOW2BackingDepth(path) } return usage, nil } // InspectQCOW2BackingDepth walks a qcow2 image's header backing_file chain // without invoking qemu-img or requiring elevation. Returns depth (0 for a // standalone image, 1 for a direct CoW overlay, >=2 for nested overlays) and // whether any parent image in the chain is missing or unreadable. func InspectQCOW2BackingDepth(path string) (depth int, broken bool) { const maxChainWalk = 32 visited := make(map[string]struct{}) cur := path for i := 0; i < maxChainWalk; i++ { norm := strings.ToLower(filepath.Clean(cur)) if _, seen := visited[norm]; seen { return depth, true } visited[norm] = struct{}{} backing, hasBacking, err := readQCOW2BackingPath(cur) if err != nil { if depth > 0 { return depth, true } return 0, false } if !hasBacking { return depth, false } depth++ next := backing if !filepath.IsAbs(next) { next = filepath.Join(filepath.Dir(cur), next) } if _, err := os.Stat(next); err != nil { return depth, true } cur = next } return depth, true } func readQCOW2BackingPath(path string) (string, bool, error) { f, err := os.Open(path) if err != nil { return "", false, err } defer f.Close() var hdr [24]byte if _, err := f.ReadAt(hdr[:], 0); err != nil { return "", false, err } if hdr[0] != 'Q' || hdr[1] != 'F' || hdr[2] != 'I' || hdr[3] != 0xfb { return "", false, nil } ver := binary.BigEndian.Uint32(hdr[4:8]) if ver < 2 || ver > 3 { return "", false, nil } off := binary.BigEndian.Uint64(hdr[8:16]) size := binary.BigEndian.Uint32(hdr[16:20]) if off == 0 || size == 0 { return "", false, nil } if size > 4096 { return "", true, os.ErrInvalid } buf := make([]byte, size) if _, err := f.ReadAt(buf, int64(off)); err != nil { return "", true, err } return strings.TrimSpace(string(buf)), true, nil } // InspectVMDiskChains scans VM directories under dataRoot and reports any // qcow2 system disk whose backing chain depth is >= BackingChainWarnDepth or // has a missing backing file. func InspectVMDiskChains(dataRoot string) []BackingChainIssue { if strings.TrimSpace(dataRoot) == "" { return nil } vmsDir := filepath.Join(dataRoot, "data", "reims-ctl", "vms") entries, err := os.ReadDir(vmsDir) if err != nil { return nil } var issues []BackingChainIssue for _, e := range entries { if !e.IsDir() { continue } vmDir := filepath.Join(vmsDir, e.Name()) diskPath := resolveDiskPathFromVMToml(vmDir) if diskPath == "" { continue } if _, err := os.Stat(diskPath); err != nil { continue } depth, broken := InspectQCOW2BackingDepth(diskPath) if depth >= BackingChainWarnDepth || broken { issues = append(issues, BackingChainIssue{ VMName: e.Name(), Path: diskPath, Depth: depth, Broken: broken, }) } } sort.Slice(issues, func(i, j int) bool { return issues[i].VMName < issues[j].VMName }) return issues } func resolveDiskPathFromVMToml(vmDir string) string { raw, err := os.ReadFile(filepath.Join(vmDir, "vm.toml")) if err == nil { for _, line := range strings.Split(string(raw), "\n") { t := strings.TrimSpace(line) if strings.HasPrefix(t, "disk") && strings.Contains(t, "=") { parts := strings.SplitN(t, "=", 2) if strings.TrimSpace(parts[0]) == "disk" { val := strings.TrimSpace(parts[1]) val = strings.Trim(val, `"'`) if val != "" { if filepath.IsAbs(val) { return val } return filepath.Join(vmDir, val) } } } } } return filepath.Join(vmDir, "disk.qcow2") } // 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 }