Files
zerorigin-toolbox/internal/platform/windows/heartbeat.go
T
zerorigin2019 0a1c1e82ea chore: 初始化仓库(零源工具箱 0.1.0 基线)
- Go 主进程 cmd/zerorigin(托盘常驻 + 触发器/规则/动作引擎)
- Wails v3 设置进程 cmd/settings(独立 module)
- 监督进程 cmd/watchdog(-supervise 异常重启)
- 构建脚本 build.bat / NSIS 安装包 deploy/、便携版 portable/
- 架构与 MVP 计划文档 docs/、阶段 0-4 验收记录 deploy/acceptance-0-4.md
2026-08-05 00:42:45 +08:00

143 lines
4.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package windows
// heartbeat.go — 进程心跳与内存观测。
//
// 心跳文件(%LOCALAPPDATA%\ZerOriginTool\logs\heartbeat.json)每 30 秒
// 原子更新一次,记录 PID / 时间 / 内存 / 运行时长。进程消失后结合三类
// 证据判定死因:
//
// - heartbeat 停在 T,app.log 无 "bye",crash.log 有记录 → 自身崩溃
// - heartbeat 停在 T,app.log 无 "bye",crash.log 无记录 → 被外部强杀
// - app.log 有 "bye" → 正常退出
//
// 内存看门狗:每次心跳顺带检查 WorkingSet,超过阈值写 WARN 日志,
// 用于提前发现内存泄漏趋势。
import (
"encoding/json"
"log/slog"
"os"
"path/filepath"
"runtime"
"sync"
"syscall"
"time"
"unsafe"
)
var (
heartbeatPsapi = syscall.NewLazyDLL("psapi.dll")
procGetProcessMemoryInfo = heartbeatPsapi.NewProc("GetProcessMemoryInfo")
heartbeatKernel32 = syscall.NewLazyDLL("kernel32.dll")
procGetCurrentProcess = heartbeatKernel32.NewProc("GetCurrentProcess")
)
// processMemoryCounters 对应 PROCESS_MEMORY_COUNTERS(仅取所需字段)。
type processMemoryCounters struct {
cb uint32
pageFaultCount uint32
peakWorkingSetSize uintptr
workingSetSize uintptr
quotaPeakPagedPoolUsage uintptr
quotaPagedPoolUsage uintptr
quotaPeakNonPagedPoolUsage uintptr
quotaNonPagedPoolUsage uintptr
pagefileUsage uintptr
peakPagefileUsage uintptr
}
// SelfWorkingSetMB 返回当前进程 WorkingSet(MB)。失败返回 0。
func SelfWorkingSetMB() int64 {
h, _, _ := procGetCurrentProcess.Call()
if h == 0 {
return 0
}
var mc processMemoryCounters
mc.cb = uint32(unsafe.Sizeof(mc))
r, _, _ := procGetProcessMemoryInfo.Call(h, uintptr(unsafe.Pointer(&mc)), uintptr(mc.cb))
if r == 0 {
return 0
}
return int64(mc.workingSetSize) / (1024 * 1024)
}
// heartbeatEntry 为心跳文件内容(JSON,便于后续脚本分析)。
type heartbeatEntry struct {
PID int `json:"pid"`
TS string `json:"ts"`
UptimeS int64 `json:"uptime_s"`
MemMB int64 `json:"mem_mb"`
}
// StartHeartbeat 启动心跳 goroutine:interval 周期写心跳文件,超过
// memLimitMB 时写 WARN 日志(memLimitMB <= 0 表示不检查)。
// 返回 stop 函数(幂等)。
func StartHeartbeat(logger *slog.Logger, logsDir string, interval time.Duration, memLimitMB int64) (stop func()) {
if logger == nil {
logger = slog.Default()
}
if interval <= 0 {
interval = 30 * time.Second
}
path := filepath.Join(logsDir, "heartbeat.json")
start := time.Now()
done := make(chan struct{})
var once sync.Once
go func() {
defer func() {
if r := recover(); r != nil {
LogGoPanic("heartbeat", r, debugStack())
}
}()
ticker := time.NewTicker(interval)
defer ticker.Stop()
writeHeartbeat(logger, path, start) // 启动即写一次
for {
select {
case <-done:
return
case <-ticker.C:
mem := SelfWorkingSetMB()
if memLimitMB > 0 && mem > memLimitMB {
logger.Warn("memory watchdog", "working_set_mb", mem, "limit_mb", memLimitMB)
}
writeHeartbeat(logger, path, start)
}
}
}()
return func() {
once.Do(func() { close(done) })
}
}
func writeHeartbeat(logger *slog.Logger, path string, start time.Time) {
e := heartbeatEntry{
PID: os.Getpid(),
TS: time.Now().Format("2006-01-02T15:04:05.000-07:00"),
UptimeS: int64(time.Since(start).Seconds()),
MemMB: SelfWorkingSetMB(),
}
b, err := json.Marshal(e)
if err != nil {
return
}
// 原子替换:写临时文件再 rename,避免读端看到半写内容。
tmp := path + ".tmp"
if err := os.WriteFile(tmp, b, 0o644); err != nil {
logger.Debug("heartbeat write failed", "err", err)
return
}
if err := os.Rename(tmp, path); err != nil {
// rename 失败(如杀软锁文件):保留临时文件内容即可,不致命。
_ = os.Remove(tmp)
}
}
// debugStack 返回当前 goroutine 堆栈(心跳/崩溃记录用,避免 import cycle)。
func debugStack() []byte {
buf := make([]byte, 32<<10)
n := runtime.Stack(buf, false)
return buf[:n]
}