Compare commits
7 Commits
739b8fcd74
...
docs/readm
| Author | SHA1 | Date | |
|---|---|---|---|
| e5df1eba0d | |||
| 758d3d1c59 | |||
| 65f521dce0 | |||
| 6e60fae559 | |||
| dc05fa01d1 | |||
| 360743ba6b | |||
| ccfa49bc7d |
@@ -15,6 +15,7 @@ ENV HF_MONITER_BACKEND_URL=https://monitor.hangman-lab.top \
|
|||||||
HF_MONITER_API_KEY= \
|
HF_MONITER_API_KEY= \
|
||||||
HF_MONITER_REPORT_INTERVAL=30 \
|
HF_MONITER_REPORT_INTERVAL=30 \
|
||||||
HF_MONITER_LOG_LEVEL=info \
|
HF_MONITER_LOG_LEVEL=info \
|
||||||
HF_MONITER_ROOTFS=/host
|
HF_MONITER_ROOTFS=/host \
|
||||||
|
MONITOR_PORT=0
|
||||||
|
|
||||||
ENTRYPOINT ["/usr/local/bin/harborforge-monitor"]
|
ENTRYPOINT ["/usr/local/bin/harborforge-monitor"]
|
||||||
|
|||||||
170
README.md
170
README.md
@@ -1,44 +1,54 @@
|
|||||||
# HarborForge.Monitor
|
# HarborForge.Monitor
|
||||||
|
|
||||||
轻量级 Go 遥测客户端,用于把服务器硬件状态上报到 HarborForge Monitor。
|
Lightweight Go telemetry client that reports server hardware status to the HarborForge backend.
|
||||||
|
|
||||||
它**不依赖 OpenClaw**,适合普通 Linux 主机、VPS、Nginx 机器等。
|
Part of the [HarborForge](../README.md) platform.
|
||||||
|
|
||||||
## 采集内容
|
- Role: standalone telemetry agent; **does not depend on OpenClaw**, suitable for plain Linux hosts, VPS, Nginx boxes, etc.
|
||||||
|
- Reports to the HarborForge backend (`POST /monitor/server/heartbeat`).
|
||||||
|
- Optional local bridge HTTP server on `127.0.0.1:<MONITOR_PORT>` (default port `9100`) for the HarborForge OpenClaw plugin.
|
||||||
|
|
||||||
- CPU 使用率
|
## Collected Metrics
|
||||||
- 内存使用率
|
|
||||||
- 磁盘使用率
|
|
||||||
- Swap 使用率
|
|
||||||
- Load Average
|
|
||||||
- Uptime
|
|
||||||
- Nginx 是否安装
|
|
||||||
- `/etc/nginx/sites-enabled` 列表
|
|
||||||
|
|
||||||
## 上报接口
|
- CPU usage (`cpu_pct`)
|
||||||
|
- Memory usage (`mem_pct`)
|
||||||
|
- Disk usage (`disk_pct`, for the root / `rootFs` filesystem)
|
||||||
|
- Swap usage (`swap_pct`)
|
||||||
|
- Load average (`load_avg` — 1/5/15 min)
|
||||||
|
- Uptime (`uptime_seconds`)
|
||||||
|
- Nginx installed (`nginx_installed`)
|
||||||
|
- `/etc/nginx/sites-enabled` listing (`nginx_sites`)
|
||||||
|
|
||||||
客户端调用:
|
When OpenClaw metadata has been pushed to the bridge, heartbeats are additionally enriched with `openclaw_version`, `plugin_version`, and `agents`.
|
||||||
|
|
||||||
- `POST /monitor/server/heartbeat-v2`
|
## Reporting Endpoint
|
||||||
- Header: `X-API-Key`
|
|
||||||
|
|
||||||
## 项目结构
|
The client sends:
|
||||||
|
|
||||||
|
- `POST <backendUrl>/monitor/server/heartbeat`
|
||||||
|
- Header: `X-API-Key: <apiKey>`
|
||||||
|
- JSON body: the telemetry payload described above
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
```text
|
```text
|
||||||
HarborForge.Monitor/
|
HarborForge.Monitor/
|
||||||
├── cmd/harborforge-monitor/ # 程序入口
|
├── cmd/harborforge-monitor/ # Program entry point (main.go)
|
||||||
├── internal/config/ # 配置加载
|
├── internal/config/ # Config loading (file + env + flags)
|
||||||
├── internal/telemetry/ # 指标采集与上报
|
├── internal/telemetry/ # Metric collection and reporting
|
||||||
├── Dockerfile # 容器化运行
|
├── internal/bridge/ # Local MONITOR_PORT bridge server
|
||||||
|
├── systemd/ # systemd unit file
|
||||||
|
├── Dockerfile # Container build
|
||||||
|
├── docker-compose.yml # Docker Compose configuration
|
||||||
├── config.example.json
|
├── config.example.json
|
||||||
└── README.md
|
└── README.md
|
||||||
```
|
```
|
||||||
|
|
||||||
## 配置
|
## Configuration
|
||||||
|
|
||||||
先在 HarborForge Monitor 中注册服务器并生成 API Key。
|
First register the server in the HarborForge backend and generate an API Key.
|
||||||
|
|
||||||
然后准备配置文件,例如 `/etc/harborforge-monitor/config.json`:
|
Then prepare a config file, e.g. `/etc/harborforge-monitor/config.json`:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -46,22 +56,62 @@ HarborForge.Monitor/
|
|||||||
"identifier": "vps-nginx-01",
|
"identifier": "vps-nginx-01",
|
||||||
"apiKey": "your-api-key",
|
"apiKey": "your-api-key",
|
||||||
"reportIntervalSec": 30,
|
"reportIntervalSec": 30,
|
||||||
"logLevel": "info"
|
"logLevel": "info",
|
||||||
|
"rootFs": "/host",
|
||||||
|
"monitorPort": 9100
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
也支持环境变量覆盖。为了兼容你的命名,这里优先支持:
|
Resolution order is: defaults → config file → environment variables → command-line flags (later wins). `apiKey` is required; the process exits if it is empty.
|
||||||
|
|
||||||
- `HF_MONITER_BACKEND_URL`
|
### Environment Variables
|
||||||
- `HF_MONITER_IDENTIFIER`
|
|
||||||
- `HF_MONITER_API_KEY`
|
|
||||||
- `HF_MONITER_REPORT_INTERVAL`
|
|
||||||
- `HF_MONITER_LOG_LEVEL`
|
|
||||||
- `HF_MONITER_ROOTFS`
|
|
||||||
|
|
||||||
同时也兼容旧的/正确拼写的 `HF_MONITOR_*` 变量名。
|
Both the (intentionally compatible) `HF_MONITER_*` spelling and the `HF_MONITOR_*` spelling are accepted; `HF_MONITER_*` is checked first.
|
||||||
|
|
||||||
## 本地开发
|
| Variable | Purpose | Default |
|
||||||
|
|----------|---------|---------|
|
||||||
|
| `HF_MONITER_BACKEND_URL` / `HF_MONITOR_BACKEND_URL` | Backend base URL | `https://monitor.hangman-lab.top` |
|
||||||
|
| `HF_MONITER_IDENTIFIER` / `HF_MONITOR_IDENTIFIER` | Server identifier | hostname |
|
||||||
|
| `HF_MONITER_API_KEY` / `HF_MONITOR_API_KEY` | Server API key | (required) |
|
||||||
|
| `HF_MONITER_REPORT_INTERVAL` / `HF_MONITOR_REPORT_INTERVAL` | Report interval (seconds) | `30` |
|
||||||
|
| `HF_MONITER_LOG_LEVEL` / `HF_MONITOR_LOG_LEVEL` | Log level | `info` |
|
||||||
|
| `HF_MONITER_ROOTFS` / `HF_MONITOR_ROOTFS` | Host root filesystem mount (for container use) | (empty) |
|
||||||
|
| `MONITOR_PORT` / `HF_MONITOR_PORT` | Local bridge port (`0` = disabled) | `0` |
|
||||||
|
|
||||||
|
When `rootFs` is set, `HOST_PROC` / `HOST_SYS` / `HOST_ETC` / `HOST_VAR` / `HOST_RUN` are derived from it (if not already set) so that gopsutil reads host metrics instead of the container's.
|
||||||
|
|
||||||
|
### Command-line Flags
|
||||||
|
|
||||||
|
```text
|
||||||
|
-config string Path to config file (default "/etc/harborforge-monitor/config.json")
|
||||||
|
-once Collect and send telemetry once, then exit
|
||||||
|
-print-payload Print the payload JSON before sending
|
||||||
|
-dry-run Collect telemetry but do not send it
|
||||||
|
-version Print version and exit
|
||||||
|
-backend-url string Override backend URL
|
||||||
|
-identifier string Override identifier
|
||||||
|
-api-key string Override API key
|
||||||
|
-report-interval int Override report interval in seconds
|
||||||
|
-log-level string Override log level
|
||||||
|
-rootfs string Override root filesystem path
|
||||||
|
-monitor-port int Override monitor bridge port
|
||||||
|
```
|
||||||
|
|
||||||
|
### MONITOR_PORT — Plugin Bridge
|
||||||
|
|
||||||
|
When `MONITOR_PORT` (or `monitorPort`) is greater than 0, Monitor starts a local HTTP server on `127.0.0.1:<MONITOR_PORT>` for the HarborForge OpenClaw plugin to query telemetry.
|
||||||
|
|
||||||
|
| Endpoint | Method | Description |
|
||||||
|
|----------|--------|-------------|
|
||||||
|
| `/health` | `GET` | Health check; returns status, `monitor_version`, and `identifier` |
|
||||||
|
| `/telemetry` | `GET` | Returns the latest cached telemetry snapshot |
|
||||||
|
| `/openclaw` | `POST` | Receives OpenClaw metadata (version, plugin version, agents) from the plugin |
|
||||||
|
|
||||||
|
After the plugin pushes metadata via `POST /openclaw`, Monitor attaches `openclaw_version`, `plugin_version`, and `agents` to subsequent heartbeats. If the plugin never pushes metadata, these fields are omitted and heartbeats are unaffected.
|
||||||
|
|
||||||
|
**Important:** the bridge is optional. If `MONITOR_PORT` is 0 or unset, the bridge does not start. Even if the bridge fails to start, heartbeat reporting continues normally (bridge errors are logged as non-fatal).
|
||||||
|
|
||||||
|
## Local Development
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
go mod tidy
|
go mod tidy
|
||||||
@@ -69,42 +119,54 @@ go build ./cmd/harborforge-monitor
|
|||||||
./harborforge-monitor -config ./config.example.json -dry-run -once
|
./harborforge-monitor -config ./config.example.json -dry-run -once
|
||||||
```
|
```
|
||||||
|
|
||||||
## Docker 运行
|
## Docker
|
||||||
|
|
||||||
构建镜像:
|
Build the image:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker build -t harborforge-monitor .
|
docker build -t harborforge-monitor .
|
||||||
```
|
```
|
||||||
|
|
||||||
推荐以**宿主机 rootfs 只读挂载**方式运行,这样容器里采集到的是宿主机信息而不是容器自身:
|
### Docker Compose
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export HF_IDENTIFIER=my-server
|
||||||
|
export HF_API_KEY=your-api-key
|
||||||
|
export MONITOR_PORT=9100
|
||||||
|
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
The compose file runs with `network_mode: host` and mounts the host root filesystem read-only at `/host` (the image defaults `HF_MONITER_ROOTFS=/host`).
|
||||||
|
|
||||||
|
### Manual Docker Run
|
||||||
|
|
||||||
|
Run with the **host rootfs mounted read-only** so the container collects host metrics instead of its own:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker run -d \
|
docker run -d \
|
||||||
--name harborforge-monitor \
|
--name harborforge-monitor \
|
||||||
--restart unless-stopped \
|
--restart unless-stopped \
|
||||||
-e HF_MONITER_BACKEND_URL=https://monitor.hangman-lab.top \
|
--network host \
|
||||||
-e HF_MONITER_IDENTIFIER=vps-nginx-01 \
|
|
||||||
-e HF_MONITER_API_KEY=your-api-key \
|
|
||||||
-e HF_MONITER_REPORT_INTERVAL=30 \
|
|
||||||
-e HF_MONITER_ROOTFS=/host \
|
|
||||||
-v /:/host:ro \
|
-v /:/host:ro \
|
||||||
|
-e HF_MONITER_BACKEND_URL=https://monitor.hangman-lab.top \
|
||||||
|
-e HF_MONITER_IDENTIFIER=my-server \
|
||||||
|
-e HF_MONITER_API_KEY=your-api-key \
|
||||||
|
-e HF_MONITER_ROOTFS=/host \
|
||||||
|
-e MONITOR_PORT=9100 \
|
||||||
harborforge-monitor
|
harborforge-monitor
|
||||||
```
|
```
|
||||||
|
|
||||||
`Dockerfile` 里已经预置了这些环境变量:
|
## systemd
|
||||||
|
|
||||||
- `HF_MONITER_BACKEND_URL`
|
You can also run the compiled binary via systemd:
|
||||||
- `HF_MONITER_IDENTIFIER`
|
|
||||||
- `HF_MONITER_API_KEY`
|
|
||||||
- `HF_MONITER_REPORT_INTERVAL`
|
|
||||||
- `HF_MONITER_LOG_LEVEL`
|
|
||||||
- `HF_MONITER_ROOTFS`
|
|
||||||
|
|
||||||
## 注意
|
```bash
|
||||||
|
go build -o /usr/local/bin/harborforge-monitor ./cmd/harborforge-monitor
|
||||||
|
|
||||||
- Docker 模式下,建议挂载 `-v /:/host:ro` 并设置 `HF_MONITER_ROOTFS=/host`
|
cp systemd/harborforge-monitor.service /etc/systemd/system/
|
||||||
- 这样 CPU/MEM/LOAD/UPTIME 会通过 host proc/sys 视角采集,磁盘和 nginx 配置也会走宿主机路径
|
systemctl daemon-reload
|
||||||
- 当前 Nginx site 列表读取的是 `${ROOTFS}/etc/nginx/sites-enabled`
|
systemctl enable --now harborforge-monitor
|
||||||
- 如果机器没有安装 Nginx,会回报 `nginx_installed = false`
|
```
|
||||||
- 该客户端不会尝试读取 OpenClaw 信息,`agents` 默认为空,`openclaw_version` 不上报
|
|
||||||
|
The provided unit runs `harborforge-monitor -config /etc/harborforge-monitor/config.json` as `root` with `Restart=always`.
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.hangman-lab.top/zhi/HarborForge.Monitor/internal/bridge"
|
||||||
"git.hangman-lab.top/zhi/HarborForge.Monitor/internal/config"
|
"git.hangman-lab.top/zhi/HarborForge.Monitor/internal/config"
|
||||||
"git.hangman-lab.top/zhi/HarborForge.Monitor/internal/telemetry"
|
"git.hangman-lab.top/zhi/HarborForge.Monitor/internal/telemetry"
|
||||||
)
|
)
|
||||||
@@ -23,12 +24,26 @@ func main() {
|
|||||||
printPayload bool
|
printPayload bool
|
||||||
dryRun bool
|
dryRun bool
|
||||||
showVersion 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.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(&runOnce, "once", false, "Collect and send telemetry once, then exit")
|
||||||
flag.BoolVar(&printPayload, "print-payload", false, "Print payload JSON before sending")
|
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(&dryRun, "dry-run", false, "Collect telemetry but do not send it")
|
||||||
flag.BoolVar(&showVersion, "version", false, "Print version and exit")
|
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()
|
flag.Parse()
|
||||||
|
|
||||||
if showVersion {
|
if showVersion {
|
||||||
@@ -36,7 +51,15 @@ func main() {
|
|||||||
return
|
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 {
|
if err != nil {
|
||||||
log.Fatalf("load config: %v", err)
|
log.Fatalf("load config: %v", err)
|
||||||
}
|
}
|
||||||
@@ -50,11 +73,43 @@ func main() {
|
|||||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||||
defer stop()
|
defer stop()
|
||||||
|
|
||||||
|
// Start the bridge server if MONITOR_PORT is configured.
|
||||||
|
// The bridge is independent of heartbeat — if it fails to start,
|
||||||
|
// heartbeat continues normally.
|
||||||
|
var bridgeSrv *bridge.Server
|
||||||
|
if cfg.MonitorPort > 0 {
|
||||||
|
bridgeSrv = bridge.New(cfg, logger)
|
||||||
|
go func() {
|
||||||
|
if err := bridgeSrv.Start(ctx); err != nil {
|
||||||
|
logger.Printf("bridge error (non-fatal): %v", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
sendOnce := func() error {
|
sendOnce := func() error {
|
||||||
payload, err := telemetry.BuildPayload(ctx, cfg)
|
payload, err := telemetry.BuildPayload(ctx, cfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Update bridge with latest telemetry
|
||||||
|
if bridgeSrv != nil {
|
||||||
|
bridgeSrv.UpdatePayload(payload)
|
||||||
|
|
||||||
|
// Enrich payload with OpenClaw metadata if available
|
||||||
|
if meta := bridgeSrv.GetOpenClawMeta(); meta != nil {
|
||||||
|
if meta.Version != "" {
|
||||||
|
payload.OpenClawVersion = meta.Version
|
||||||
|
}
|
||||||
|
if meta.PluginVersion != "" {
|
||||||
|
payload.PluginVersion = meta.PluginVersion
|
||||||
|
}
|
||||||
|
if len(meta.Agents) > 0 {
|
||||||
|
payload.Agents = meta.Agents
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if printPayload || dryRun {
|
if printPayload || dryRun {
|
||||||
buf, _ := json.MarshalIndent(payload, "", " ")
|
buf, _ := json.MarshalIndent(payload, "", " ")
|
||||||
fmt.Println(string(buf))
|
fmt.Println(string(buf))
|
||||||
|
|||||||
@@ -4,5 +4,6 @@
|
|||||||
"apiKey": "replace-with-server-api-key",
|
"apiKey": "replace-with-server-api-key",
|
||||||
"reportIntervalSec": 30,
|
"reportIntervalSec": 30,
|
||||||
"logLevel": "info",
|
"logLevel": "info",
|
||||||
"rootFs": "/host"
|
"rootFs": "/host",
|
||||||
|
"monitorPort": 9100
|
||||||
}
|
}
|
||||||
|
|||||||
22
docker-compose.yml
Normal file
22
docker-compose.yml
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
version: "3.8"
|
||||||
|
|
||||||
|
services:
|
||||||
|
harborforge-monitor:
|
||||||
|
build: .
|
||||||
|
container_name: harborforge-monitor
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
- HF_MONITER_BACKEND_URL=https://monitor.hangman-lab.top
|
||||||
|
- HF_MONITER_IDENTIFIER=${HF_IDENTIFIER:-}
|
||||||
|
- HF_MONITER_API_KEY=${HF_API_KEY:-}
|
||||||
|
- HF_MONITER_REPORT_INTERVAL=${HF_REPORT_INTERVAL:-30}
|
||||||
|
- HF_MONITER_LOG_LEVEL=${HF_LOG_LEVEL:-info}
|
||||||
|
- HF_MONITER_ROOTFS=/host
|
||||||
|
- 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
|
||||||
187
internal/bridge/bridge.go
Normal file
187
internal/bridge/bridge.go
Normal file
@@ -0,0 +1,187 @@
|
|||||||
|
// Package bridge provides a local HTTP server on MONITOR_PORT for
|
||||||
|
// communication between the HarborForge OpenClaw plugin and Monitor.
|
||||||
|
//
|
||||||
|
// The bridge serves two purposes:
|
||||||
|
// 1. Expose hardware telemetry to the plugin via GET /telemetry
|
||||||
|
// 2. Receive OpenClaw metadata from the plugin via POST /openclaw
|
||||||
|
//
|
||||||
|
// The bridge is optional: if monitorPort is 0 or not set, the bridge
|
||||||
|
// is not started and Monitor operates normally.
|
||||||
|
package bridge
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.hangman-lab.top/zhi/HarborForge.Monitor/internal/config"
|
||||||
|
"git.hangman-lab.top/zhi/HarborForge.Monitor/internal/telemetry"
|
||||||
|
)
|
||||||
|
|
||||||
|
// OpenClawMeta holds metadata received from the OpenClaw plugin.
|
||||||
|
// This data is optional enrichment for heartbeat uploads.
|
||||||
|
type OpenClawMeta struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
PluginVersion string `json:"plugin_version"`
|
||||||
|
Agents []any `json:"agents,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server is the local bridge HTTP server.
|
||||||
|
type Server struct {
|
||||||
|
cfg config.Config
|
||||||
|
logger *log.Logger
|
||||||
|
srv *http.Server
|
||||||
|
|
||||||
|
mu sync.RWMutex
|
||||||
|
lastPayload *telemetry.Payload
|
||||||
|
lastUpdated time.Time
|
||||||
|
|
||||||
|
openclawMeta *OpenClawMeta
|
||||||
|
openclawUpdated time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// New creates a bridge server. It does not start listening.
|
||||||
|
func New(cfg config.Config, logger *log.Logger) *Server {
|
||||||
|
return &Server{
|
||||||
|
cfg: cfg,
|
||||||
|
logger: logger,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdatePayload stores the latest telemetry payload so the bridge can
|
||||||
|
// serve it to plugin queries without re-collecting.
|
||||||
|
func (s *Server) UpdatePayload(p telemetry.Payload) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
s.lastPayload = &p
|
||||||
|
s.lastUpdated = time.Now()
|
||||||
|
}
|
||||||
|
|
||||||
|
// bridgeResponse is the JSON structure served to the plugin.
|
||||||
|
type bridgeResponse struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
MonitorVer string `json:"monitor_version"`
|
||||||
|
Identifier string `json:"identifier"`
|
||||||
|
Telemetry *telemetry.Payload `json:"telemetry,omitempty"`
|
||||||
|
LastUpdated *time.Time `json:"last_updated,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetOpenClawMeta returns the latest OpenClaw metadata received from
|
||||||
|
// the plugin, or nil if no metadata has been received.
|
||||||
|
func (s *Server) GetOpenClawMeta() *OpenClawMeta {
|
||||||
|
s.mu.RLock()
|
||||||
|
defer s.mu.RUnlock()
|
||||||
|
return s.openclawMeta
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handler() http.Handler {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
|
||||||
|
// Health / discovery endpoint
|
||||||
|
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]string{
|
||||||
|
"status": "ok",
|
||||||
|
"monitor_version": telemetry.Version,
|
||||||
|
"identifier": s.cfg.Identifier,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// Telemetry endpoint — returns the latest cached payload
|
||||||
|
mux.HandleFunc("/telemetry", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
s.mu.RLock()
|
||||||
|
payload := s.lastPayload
|
||||||
|
updated := s.lastUpdated
|
||||||
|
s.mu.RUnlock()
|
||||||
|
|
||||||
|
resp := bridgeResponse{
|
||||||
|
Status: "ok",
|
||||||
|
MonitorVer: telemetry.Version,
|
||||||
|
Identifier: s.cfg.Identifier,
|
||||||
|
}
|
||||||
|
if payload != nil {
|
||||||
|
resp.Telemetry = payload
|
||||||
|
resp.LastUpdated = &updated
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(resp)
|
||||||
|
})
|
||||||
|
|
||||||
|
// OpenClaw metadata endpoint — plugin POSTs its metadata here
|
||||||
|
mux.HandleFunc("/openclaw", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := io.ReadAll(io.LimitReader(r.Body, 64*1024))
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "read error", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
|
|
||||||
|
var meta OpenClawMeta
|
||||||
|
if err := json.Unmarshal(body, &meta); err != nil {
|
||||||
|
http.Error(w, "invalid json", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
s.openclawMeta = &meta
|
||||||
|
s.openclawUpdated = time.Now()
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
s.logger.Printf("received OpenClaw metadata: version=%s plugin=%s agents=%d",
|
||||||
|
meta.Version, meta.PluginVersion, len(meta.Agents))
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]string{
|
||||||
|
"status": "ok",
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
return mux
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start begins listening on 127.0.0.1:<monitorPort>. It blocks until
|
||||||
|
// the context is cancelled or an error occurs.
|
||||||
|
func (s *Server) Start(ctx context.Context) error {
|
||||||
|
if s.cfg.MonitorPort <= 0 {
|
||||||
|
return nil // bridge disabled
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := fmt.Sprintf("127.0.0.1:%d", s.cfg.MonitorPort)
|
||||||
|
listener, err := net.Listen("tcp", addr)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("bridge listen on %s: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
s.srv = &http.Server{
|
||||||
|
Handler: s.handler(),
|
||||||
|
ReadTimeout: 5 * time.Second,
|
||||||
|
WriteTimeout: 5 * time.Second,
|
||||||
|
IdleTimeout: 30 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
s.logger.Printf("bridge listening on %s", addr)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
<-ctx.Done()
|
||||||
|
shutCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
s.srv.Shutdown(shutCtx)
|
||||||
|
}()
|
||||||
|
|
||||||
|
if err := s.srv.Serve(listener); err != nil && err != http.ErrServerClosed {
|
||||||
|
return fmt.Errorf("bridge serve: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -14,9 +14,24 @@ type Config struct {
|
|||||||
ReportIntervalSec int `json:"reportIntervalSec"`
|
ReportIntervalSec int `json:"reportIntervalSec"`
|
||||||
LogLevel string `json:"logLevel"`
|
LogLevel string `json:"logLevel"`
|
||||||
RootFS string `json:"rootFs"`
|
RootFS string `json:"rootFs"`
|
||||||
|
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) {
|
func Load(path string) (Config, error) {
|
||||||
|
return LoadWithOverrides(path, Overrides{})
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadWithOverrides(path string, overrides Overrides) (Config, error) {
|
||||||
cfg := Config{
|
cfg := Config{
|
||||||
BackendURL: getenvAny([]string{"HF_MONITER_BACKEND_URL", "HF_MONITOR_BACKEND_URL"}, "https://monitor.hangman-lab.top"),
|
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"}, hostnameOr("unknown-host")),
|
||||||
@@ -43,6 +58,29 @@ func Load(path string) (Config, error) {
|
|||||||
cfg.ReportIntervalSec = getenvIntAny([]string{"HF_MONITER_REPORT_INTERVAL", "HF_MONITOR_REPORT_INTERVAL"}, cfg.ReportIntervalSec)
|
cfg.ReportIntervalSec = getenvIntAny([]string{"HF_MONITER_REPORT_INTERVAL", "HF_MONITOR_REPORT_INTERVAL"}, cfg.ReportIntervalSec)
|
||||||
cfg.LogLevel = getenvAny([]string{"HF_MONITER_LOG_LEVEL", "HF_MONITOR_LOG_LEVEL"}, cfg.LogLevel)
|
cfg.LogLevel = getenvAny([]string{"HF_MONITER_LOG_LEVEL", "HF_MONITOR_LOG_LEVEL"}, cfg.LogLevel)
|
||||||
cfg.RootFS = getenvAny([]string{"HF_MONITER_ROOTFS", "HF_MONITOR_ROOTFS"}, cfg.RootFS)
|
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 == "" {
|
if cfg.BackendURL == "" {
|
||||||
return cfg, fmt.Errorf("backendUrl is required")
|
return cfg, fmt.Errorf("backendUrl is required")
|
||||||
@@ -88,6 +126,9 @@ func merge(dst *Config, src Config) {
|
|||||||
if src.RootFS != "" {
|
if src.RootFS != "" {
|
||||||
dst.RootFS = src.RootFS
|
dst.RootFS = src.RootFS
|
||||||
}
|
}
|
||||||
|
if src.MonitorPort > 0 {
|
||||||
|
dst.MonitorPort = src.MonitorPort
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getenvAny(keys []string, fallback string) string {
|
func getenvAny(keys []string, fallback string) string {
|
||||||
|
|||||||
@@ -35,6 +35,10 @@ type Payload struct {
|
|||||||
SwapPct float64 `json:"swap_pct,omitempty"`
|
SwapPct float64 `json:"swap_pct,omitempty"`
|
||||||
LoadAvg []float64 `json:"load_avg,omitempty"`
|
LoadAvg []float64 `json:"load_avg,omitempty"`
|
||||||
UptimeSeconds uint64 `json:"uptime_seconds,omitempty"`
|
UptimeSeconds uint64 `json:"uptime_seconds,omitempty"`
|
||||||
|
|
||||||
|
// Optional OpenClaw metadata, enriched from plugin bridge.
|
||||||
|
// These fields are omitted if no plugin data is available.
|
||||||
|
OpenClawVersion string `json:"openclaw_version,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func BuildPayload(ctx context.Context, cfg config.Config) (Payload, error) {
|
func BuildPayload(ctx context.Context, cfg config.Config) (Payload, error) {
|
||||||
@@ -94,7 +98,7 @@ func Send(ctx context.Context, client *http.Client, cfg config.Config, payload P
|
|||||||
return fmt.Errorf("marshal payload: %w", err)
|
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 {
|
if err != nil {
|
||||||
return fmt.Errorf("build request: %w", err)
|
return fmt.Errorf("build request: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user