Files
Reims-Go/internal/host/stats.go
T
NwflowerandClaude Opus 5.5 c639682a88 refactor: remove unused functions and keep the codebase free of them
Delete functions that no product code calls, and fold "simple plus
WithOptions" pairs into the one signature callers actually use. Rename
the live macOS lifecycle functions that were labelled Legacy.

The architecture tests now share one source loader and reject functions
without a product caller and catalog messages nobody reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 20:55:03 -07:00

278 lines
7.6 KiB
Go

package host
import (
"encoding/binary"
"errors"
"io"
"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"`
ExtendedL2 bool `json:"extended_l2,omitempty"`
SnapshotCount uint32 `json:"snapshot_count,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",
}
f, err := os.Open(path)
if err != nil {
return usage, nil
}
defer f.Close()
if vSize, extendedL2, snapshotCount, ok := decodeQCOW2HeaderMeta(f); ok {
usage.VirtualBytes = vSize
usage.ExtendedL2 = extendedL2
usage.SnapshotCount = snapshotCount
usage.Format = "qcow2"
usage.BackingDepth, usage.BackingBroken = inspectQCOW2BackingDepth(path, f)
}
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) {
return inspectQCOW2BackingDepth(path, nil)
}
func inspectQCOW2BackingDepth(path string, first io.ReaderAt) (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{}{}
var backing string
var hasBacking bool
var err error
if i == 0 && first != nil {
backing, hasBacking, err = readQCOW2BackingPath(first, cur)
} else {
backing, hasBacking, err = ReadQCOW2BackingPath(cur)
}
if err != nil {
if depth > 0 {
return depth, true
}
return 0, false
}
if !hasBacking {
return depth, false
}
depth++
if _, err := os.Stat(backing); err != nil {
return depth, true
}
cur = backing
}
return depth, true
}
// ReadQCOW2BackingPath reads the immediate backing file from a qcow2 header.
// Relative backing paths are resolved from the directory containing the image.
func ReadQCOW2BackingPath(path string) (string, bool, error) {
f, err := os.Open(path)
if err != nil {
return "", false, err
}
defer f.Close()
return readQCOW2BackingPath(f, path)
}
func readQCOW2BackingPath(f io.ReaderAt, path string) (string, bool, error) {
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 {
return "", false, nil
}
if size == 0 || size > 4096 {
return "", true, os.ErrInvalid
}
buf := make([]byte, size)
if _, err := f.ReadAt(buf, int64(off)); err != nil {
return "", true, err
}
backing := strings.TrimSpace(string(buf))
if !filepath.IsAbs(backing) {
backing = filepath.Join(filepath.Dir(path), backing)
}
return backing, 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")
}
func decodeQCOW2HeaderMeta(f io.ReaderAt) (virtualSize uint64, extendedL2 bool, snapshotCount uint32, ok bool) {
var hdr [104]byte
n, err := f.ReadAt(hdr[:], 0)
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
return 0, false, 0, false
}
if n < 72 || string(hdr[:4]) != "QFI\xfb" {
return 0, false, 0, false
}
ver := binary.BigEndian.Uint32(hdr[4:8])
switch ver {
case 2:
// qcow2 v2 header is 72 bytes.
case 3:
if n < 104 {
return 0, false, 0, false
}
extendedL2 = binary.BigEndian.Uint64(hdr[72:80])&0x10 != 0
default:
return 0, false, 0, false
}
snapshotCount = binary.BigEndian.Uint32(hdr[60:64])
return binary.BigEndian.Uint64(hdr[24:32]), extendedL2, snapshotCount, true
}