Compare commits

..

4 Commits

Author SHA1 Message Date
zhi
e136f1b290 fix: correct telemetry identifier and visibility when containerized
Three related fixes for running Monitor inside a container with
/:/host:ro bind-mounted and network_mode: host.

* config: when HF_MONITER_ROOTFS is set, read the default identifier
  from <rootFS>/etc/hostname instead of os.Hostname(). Under
  network_mode: host the UTS namespace is not shared, so os.Hostname()
  returns a random docker-assigned string that changes across
  recreations, causing the backend to treat each restart as a new
  server.

* telemetry: log gopsutil errors from BuildPayload instead of silently
  swallowing them. Previously a missing /host mount would send a
  payload full of zeroed fields with no indication of failure.

* docker-compose: drop the 'ports:' block. It is silently ignored
  under network_mode: host (the bridge server binds directly on the
  host's 127.0.0.1:MONITOR_PORT).
2026-04-15 23:02:44 +00:00
758d3d1c59 refactor: use heartbeat endpoint consistently 2026-04-04 08:05:49 +00:00
65f521dce0 feat: support monitor cli override flags 2026-04-04 07:53:34 +00:00
6e60fae559 Merge pull request 'Merge dev-2026-03-21 into main' (#1) from dev-2026-03-21 into main
Reviewed-on: #1
2026-03-22 14:16:01 +00:00
5 changed files with 118 additions and 26 deletions

View File

@@ -19,7 +19,7 @@
客户端调用:
- `POST /monitor/server/heartbeat-v2`
- `POST /monitor/server/heartbeat`
- Header: `X-API-Key`
## 项目结构
@@ -66,7 +66,7 @@ HarborForge.Monitor/
### MONITOR_PORT — 插件桥接端口
`MONITOR_PORT` (或 `monitorPort`) 设置为大于 0 的值时Monitor 会在 `127.0.0.1:<MONITOR_PORT>` 上启动一个本地 HTTP 服务,供 HarborForge OpenClaw 插件查询遥测数据。
`MONITOR_PORT` 设置为大于 0 的值时Monitor 会在 `127.0.0.1:<MONITOR_PORT>` 上启动一个本地 HTTP 服务,供 HarborForge OpenClaw 插件查询遥测数据。
支持的端点:

View File

@@ -24,12 +24,26 @@ func main() {
printPayload bool
dryRun bool
showVersion bool
backendURL string
identifier string
apiKey string
reportInt int
logLevel string
rootFS string
monitorPort int
)
flag.StringVar(&configPath, "config", "/etc/harborforge-monitor/config.json", "Path to config file")
flag.BoolVar(&runOnce, "once", false, "Collect and send telemetry once, then exit")
flag.BoolVar(&printPayload, "print-payload", false, "Print payload JSON before sending")
flag.BoolVar(&dryRun, "dry-run", false, "Collect telemetry but do not send it")
flag.BoolVar(&showVersion, "version", false, "Print version and exit")
flag.StringVar(&backendURL, "backend-url", "", "Override backend URL")
flag.StringVar(&identifier, "identifier", "", "Override identifier")
flag.StringVar(&apiKey, "api-key", "", "Override API key")
flag.IntVar(&reportInt, "report-interval", 0, "Override report interval in seconds")
flag.StringVar(&logLevel, "log-level", "", "Override log level")
flag.StringVar(&rootFS, "rootfs", "", "Override root filesystem path")
flag.IntVar(&monitorPort, "monitor-port", 0, "Override monitor bridge port")
flag.Parse()
if showVersion {
@@ -37,7 +51,15 @@ func main() {
return
}
cfg, err := config.Load(configPath)
cfg, err := config.LoadWithOverrides(configPath, config.Overrides{
BackendURL: backendURL,
Identifier: identifier,
APIKey: apiKey,
ReportIntervalSec: reportInt,
LogLevel: logLevel,
RootFS: rootFS,
MonitorPort: monitorPort,
})
if err != nil {
log.Fatalf("load config: %v", err)
}

View File

@@ -15,8 +15,8 @@ services:
- MONITOR_PORT=${MONITOR_PORT:-0}
volumes:
- /:/host:ro
ports:
# Expose MONITOR_PORT on 127.0.0.1 only for plugin communication.
# Only active when MONITOR_PORT > 0.
- "127.0.0.1:${MONITOR_PORT:-9100}:${MONITOR_PORT:-9100}"
# network_mode: host shares the host network namespace, so the bridge
# server (if MONITOR_PORT > 0) listens directly on the host's
# 127.0.0.1:<MONITOR_PORT>. `ports:` is ignored under network_mode:
# host, so it is intentionally omitted.
network_mode: host

View File

@@ -5,6 +5,7 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
)
type Config struct {
@@ -17,10 +18,34 @@ type Config struct {
MonitorPort int `json:"monitorPort"`
}
type Overrides struct {
BackendURL string
Identifier string
APIKey string
ReportIntervalSec int
LogLevel string
RootFS string
MonitorPort int
}
func Load(path string) (Config, error) {
return LoadWithOverrides(path, Overrides{})
}
func LoadWithOverrides(path string, overrides Overrides) (Config, error) {
// If running inside a container with the host FS bind-mounted, prefer
// the host's /etc/hostname for the default identifier. The container's
// own os.Hostname() is a docker-assigned random string under
// network_mode: host (UTS namespace is not shared).
rootFSEarly := getenvAny([]string{"HF_MONITER_ROOTFS", "HF_MONITOR_ROOTFS"}, "")
defaultIdentifier := hostHostname(rootFSEarly)
if defaultIdentifier == "" {
defaultIdentifier = hostnameOr("unknown-host")
}
cfg := Config{
BackendURL: getenvAny([]string{"HF_MONITER_BACKEND_URL", "HF_MONITOR_BACKEND_URL"}, "https://monitor.hangman-lab.top"),
Identifier: getenvAny([]string{"HF_MONITER_IDENTIFIER", "HF_MONITOR_IDENTIFIER"}, hostnameOr("unknown-host")),
Identifier: getenvAny([]string{"HF_MONITER_IDENTIFIER", "HF_MONITOR_IDENTIFIER"}, defaultIdentifier),
APIKey: getenvAny([]string{"HF_MONITER_API_KEY", "HF_MONITOR_API_KEY"}, ""),
ReportIntervalSec: getenvIntAny([]string{"HF_MONITER_REPORT_INTERVAL", "HF_MONITOR_REPORT_INTERVAL"}, 30),
LogLevel: getenvAny([]string{"HF_MONITER_LOG_LEVEL", "HF_MONITOR_LOG_LEVEL"}, "info"),
@@ -46,6 +71,28 @@ func Load(path string) (Config, error) {
cfg.RootFS = getenvAny([]string{"HF_MONITER_ROOTFS", "HF_MONITOR_ROOTFS"}, cfg.RootFS)
cfg.MonitorPort = getenvIntAny([]string{"MONITOR_PORT", "HF_MONITOR_PORT"}, cfg.MonitorPort)
if overrides.BackendURL != "" {
cfg.BackendURL = overrides.BackendURL
}
if overrides.Identifier != "" {
cfg.Identifier = overrides.Identifier
}
if overrides.APIKey != "" {
cfg.APIKey = overrides.APIKey
}
if overrides.ReportIntervalSec > 0 {
cfg.ReportIntervalSec = overrides.ReportIntervalSec
}
if overrides.LogLevel != "" {
cfg.LogLevel = overrides.LogLevel
}
if overrides.RootFS != "" {
cfg.RootFS = overrides.RootFS
}
if overrides.MonitorPort > 0 {
cfg.MonitorPort = overrides.MonitorPort
}
if cfg.BackendURL == "" {
return cfg, fmt.Errorf("backendUrl is required")
}
@@ -117,11 +164,25 @@ func getenvIntAny(keys []string, fallback int) int {
}
func hostnameOr(fallback string) string {
name, err := os.Hostname()
if err != nil || name == "" {
return fallback
if name, err := os.Hostname(); err == nil && name != "" {
return name
}
return name
return fallback
}
// hostHostname reads the hostname from <rootFS>/etc/hostname. Used when
// Monitor runs inside a container and wants the host's hostname rather
// than the container's UTS namespace hostname (which docker randomizes
// unless hostname: is set).
func hostHostname(rootFS string) string {
if rootFS == "" {
return ""
}
buf, err := os.ReadFile(filepath.Join(rootFS, "etc", "hostname"))
if err != nil {
return ""
}
return strings.TrimSpace(string(buf))
}
func applyHostFSEnv(rootFS string) {

View File

@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"os/exec"
@@ -50,12 +51,15 @@ func BuildPayload(ctx context.Context, cfg config.Config) (Payload, error) {
}
cpuPct, err := cpu.PercentWithContext(ctx, time.Second, false)
if err == nil && len(cpuPct) > 0 {
if err != nil {
log.Printf("telemetry: cpu.Percent failed: %v", err)
} else if len(cpuPct) > 0 {
payload.CPUPct = round1(cpuPct[0])
}
vm, err := mem.VirtualMemoryWithContext(ctx)
if err == nil {
if vm, err := mem.VirtualMemoryWithContext(ctx); err != nil {
log.Printf("telemetry: mem.VirtualMemory failed: %v", err)
} else {
payload.MemPct = round1(vm.UsedPercent)
}
@@ -63,28 +67,33 @@ func BuildPayload(ctx context.Context, cfg config.Config) (Payload, error) {
if diskPath == "" {
diskPath = "/"
}
diskUsage, err := disk.UsageWithContext(ctx, diskPath)
if err == nil {
if diskUsage, err := disk.UsageWithContext(ctx, diskPath); err != nil {
log.Printf("telemetry: disk.Usage(%s) failed: %v", diskPath, err)
} else {
payload.DiskPct = round1(diskUsage.UsedPercent)
}
swapUsage, err := mem.SwapMemoryWithContext(ctx)
if err == nil {
if swapUsage, err := mem.SwapMemoryWithContext(ctx); err != nil {
log.Printf("telemetry: mem.SwapMemory failed: %v", err)
} else {
payload.SwapPct = round1(swapUsage.UsedPercent)
}
avg, err := gopsload.AvgWithContext(ctx)
if err == nil {
if avg, err := gopsload.AvgWithContext(ctx); err != nil {
log.Printf("telemetry: load.Avg failed: %v", err)
} else {
payload.LoadAvg = []float64{round2(avg.Load1), round2(avg.Load5), round2(avg.Load15)}
}
hostInfo, err := host.InfoWithContext(ctx)
if err == nil {
if hostInfo, err := host.InfoWithContext(ctx); err != nil {
log.Printf("telemetry: host.Info failed: %v", err)
} else {
payload.UptimeSeconds = hostInfo.Uptime
}
nginxInstalled, nginxSites, err := detectNginx(cfg.RootFS)
if err == nil {
if nginxInstalled, nginxSites, err := detectNginx(cfg.RootFS); err != nil {
log.Printf("telemetry: detectNginx failed: %v", err)
} else {
payload.NginxInstalled = nginxInstalled
payload.NginxSites = nginxSites
}
@@ -98,7 +107,7 @@ func Send(ctx context.Context, client *http.Client, cfg config.Config, payload P
return fmt.Errorf("marshal payload: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(cfg.BackendURL, "/")+"/monitor/server/heartbeat-v2", strings.NewReader(string(body)))
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(cfg.BackendURL, "/")+"/monitor/server/heartbeat", strings.NewReader(string(body)))
if err != nil {
return fmt.Errorf("build request: %w", err)
}