Files
Reims-Go/internal/host/stats_windows.go
T

93 lines
2.5 KiB
Go

//go:build windows
package host
import (
"fmt"
"syscall"
"time"
"unsafe"
)
var (
procK32GetProcessMemoryInfo = kernel32.NewProc("K32GetProcessMemoryInfo")
procGetCompressedFileSizeW = kernel32.NewProc("GetCompressedFileSizeW")
)
const (
invalidFileSize = 0xFFFFFFFF
)
type processMemoryCountersEx struct {
CB uint32
PageFaultCount uint32
PeakWorkingSetSize uintptr
WorkingSetSize uintptr
QuotaPeakPagedPoolUsage uintptr
QuotaPagedPoolUsage uintptr
QuotaPeakNonPagedPoolUsage uintptr
QuotaNonPagedPoolUsage uintptr
PagefileUsage uintptr
PeakPagefileUsage uintptr
PrivateUsage uintptr
}
// SampleProcessStats queries CPU time and memory usage for pid using native Win32 APIs.
func SampleProcessStats(pid int) (ProcessSample, error) {
if pid <= 0 {
return ProcessSample{}, fmt.Errorf("invalid pid %d", pid)
}
h, _, err := procOpenProcess.Call(uintptr(processQueryLimitedInfo), 0, uintptr(pid))
if h == 0 {
return ProcessSample{}, fmt.Errorf("OpenProcess(%d): %w", pid, err)
}
defer procCloseHandle.Call(h)
now := time.Now()
sample := ProcessSample{
PID: pid,
SampledAt: now,
}
var createFT, exitFT, kernelFT, userFT syscall.Filetime
if r, _, _ := procGetProcessTimes.Call(
h,
uintptr(unsafe.Pointer(&createFT)),
uintptr(unsafe.Pointer(&exitFT)),
uintptr(unsafe.Pointer(&kernelFT)),
uintptr(unsafe.Pointer(&userFT)),
); r != 0 {
k100ns := int64(kernelFT.HighDateTime)<<32 | int64(kernelFT.LowDateTime)
u100ns := int64(userFT.HighDateTime)<<32 | int64(userFT.LowDateTime)
sample.CPUDuration = time.Duration(k100ns+u100ns) * 100 * time.Nanosecond
if createFT.HighDateTime != 0 || createFT.LowDateTime != 0 {
sample.CreatedAt = time.Unix(0, createFT.Nanoseconds())
}
}
var pmc processMemoryCountersEx
pmc.CB = uint32(unsafe.Sizeof(pmc))
if r, _, _ := procK32GetProcessMemoryInfo.Call(
h,
uintptr(unsafe.Pointer(&pmc)),
uintptr(pmc.CB),
); r != 0 {
sample.WorkingSet = uint64(pmc.WorkingSetSize)
sample.PrivateBytes = uint64(pmc.PrivateUsage)
}
return sample, nil
}
func fileActualSize(path string, fallback uint64) uint64 {
p, err := syscall.UTF16PtrFromString(path)
if err != nil {
return fallback
}
var high uint32
low, _, err := procGetCompressedFileSizeW.Call(uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(&high)))
if low == invalidFileSize && err != syscall.Errno(0) {
return fallback
}
return (uint64(high) << 32) | uint64(low)
}