Files
pangolin/server/internal/agentd/agent.go
T
wangjia f03d2dc8a6 feat(agent): node agent — enroll/mTLS, heartbeat, command stream, sing-box 用户表 (tsk__R8M4jEw43JR)
与控制面同仓同 go.mod,新增节点 agent 实现:

- proto/agent/v1/agent.proto + internal/pb/agentv1:冻结的控制面↔agent gRPC 契约
  (Enroll/Register/Heartbeat/Subscribe/Ack/ReportUsage)。仓库尚无 protoc 流水线,
  暂以手写 Go 类型 + JSON gRPC codec 实现,与 proto 1:1 对应,待 protoc 接入即可替换。
- internal/agentd:
  - enroll.go:首启生成 EC 密钥+CSR,持 bootstrap token 调 Enroll 换 90d 节点证书
    (CN=node_uuid),落 /etc/pangolin-agent/,此后 mTLS。
  - conn.go(agent.go)+creds.go:mTLS 主动拨号 + 指数退避重连;重连携带 last_command_id;
    Register 取 ConfigSnapshot 全量配置覆盖本地。
  - heartbeat.go:30s 上报 peer/带宽/CPU + config_version;need_full_resync→全量同步。
  - command.go:消费 Subscribe,Upsert/Revoke/Rotate/ApplyConfig/Lifecycle 幂等处理后
    Ack(at-least-once,按 command_id 去重)。
  - singbox.go+render.go:内存用户表 + 落盘 state.json(仅 dp_uuid+expires_at);任何变更
    渲染完整 sing-box 配置(REALITY users[uuid,flow] + Hy2 users[派生口令])→ 500ms 去抖
    合并 → systemd 重启。
  - ttl.go:凭证 TTL 定时移除并上报。
  - usage.go:按 dp_uuid 聚合上报,绝无 user_id/email/目的地址。
  - derive.go:Hy2 口令 = HMAC-SHA256(key, dp_uuid),与控制面同源派生。
- cmd/agent:入口(flag/env 配置)。
- infra/cloud-init/{node.yaml.tmpl,install-node.sh,README.md}:一段式安装,下载锁定版本
  二进制并校验 SHA-256,systemd 拉管,首启即 Enroll/Register。shellcheck -S warning 通过。

测试(bufconn mock 控制面,无需 docker):Enroll→Register→Heartbeat 全流转;Upsert/Revoke
渲染正确;Rotate 宽限期新旧并存到点移除;TTL 自动移除并上报;断流重连 last_command_id
续发不丢不重;need_full_resync 触发重注册;state.json 恢复;去抖合并;扫描确认无身份字段。
go test -race ./internal/agentd/... ./internal/pb/... 通过;go vet ./... 通过。

落实 doc/04 §2 节点无状态化与 doc/06 §3 数据面红线(节点仅见 dp_uuid)。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-13 12:26:58 +08:00

203 lines
5.3 KiB
Go

package agentd
import (
"context"
"errors"
"math/rand"
"sync/atomic"
"time"
agentv1 "github.com/wangjia/pangolin/server/internal/pb/agentv1"
)
// errResync is returned within a session to force a reconnect + full Register.
var errResync = errors.New("agentd: full resync required")
// Agent is the top-level node daemon. Construct with New and drive with Run.
type Agent struct {
cfg Config
sb *SingBox
nodeUUID atomic.Value // string; written once by Run, read by all loops + tests
dial Dialer
enrollDial EnrollDialer
load LoadSource
usage UsageSource
clock func() time.Time
lastCommandID atomic.Int64
shutdown context.CancelFunc
restarter Restarter
}
// Option customises an Agent (primarily for tests / dependency injection).
type Option func(*Agent)
func WithRestarter(r Restarter) Option { return func(a *Agent) { a.restarter = r } }
func WithDialer(d Dialer) Option { return func(a *Agent) { a.dial = d } }
func WithEnrollDialer(d EnrollDialer) Option { return func(a *Agent) { a.enrollDial = d } }
func WithLoadSource(l LoadSource) Option { return func(a *Agent) { a.load = l } }
func WithUsageSource(u UsageSource) Option { return func(a *Agent) { a.usage = u } }
func WithClock(f func() time.Time) Option { return func(a *Agent) { a.clock = f } }
// New builds an Agent. Production callers pass nothing extra and get mTLS dialers;
// tests inject bufconn dialers, fake restarters, etc.
func New(cfg Config, opts ...Option) *Agent {
cfg = cfg.withDefaults()
a := &Agent{cfg: cfg, clock: time.Now}
for _, o := range opts {
o(a)
}
if a.dial == nil {
if cfg.Insecure {
a.dial = insecureDialer(cfg.ControlPlaneAddr)
} else {
a.dial = NewMTLSDialer(cfg)
}
}
if a.enrollDial == nil {
if cfg.Insecure {
a.enrollDial = EnrollDialer(insecureDialer(cfg.ControlPlaneAddr))
} else {
a.enrollDial = NewEnrollDialer(cfg)
}
}
a.sb = NewSingBox(cfg, a.restarter)
a.sb.clock = a.clock
if a.load == nil {
a.load = defaultLoadSource{sb: a.sb}
}
if a.usage == nil {
a.usage = nopUsageSource{}
}
return a
}
// SingBox exposes the underlying manager (tests / introspection).
func (a *Agent) SingBox() *SingBox { return a.sb }
// NodeUUID returns the enrolled node UUID (empty until Run enrolls).
func (a *Agent) NodeUUID() string {
v, _ := a.nodeUUID.Load().(string)
return v
}
// Run enrolls (if needed), restores state, then maintains the control-plane
// connection with exponential-backoff reconnect until ctx is cancelled.
func (a *Agent) Run(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
a.shutdown = cancel
uuid, err := EnsureEnrolled(ctx, a.cfg, a.enrollDial)
if err != nil {
return err
}
a.nodeUUID.Store(uuid)
if err := a.sb.LoadState(); err != nil {
return err
}
go a.sb.Run(ctx)
go a.runTTL(ctx)
a.sb.markDirty() // render whatever we restored before the first connect
backoff := a.cfg.BackoffMin
for {
if ctx.Err() != nil {
return nil
}
registered, err := a.runSession(ctx)
if ctx.Err() != nil {
return nil
}
if registered {
backoff = a.cfg.BackoffMin // healthy session → reset backoff
}
if err != nil && !errors.Is(err, errResync) {
logf("session ended: %v; reconnecting in %s", err, backoff)
}
if !sleepCtx(ctx, jitter(backoff)) {
return nil
}
backoff = nextBackoff(backoff, a.cfg.BackoffMax)
}
}
// runSession establishes one connection: Register (full snapshot), then runs
// heartbeat/subscribe/usage until the first of them fails. Returns whether
// Register succeeded (used to reset backoff).
func (a *Agent) runSession(ctx context.Context) (registered bool, err error) {
conn, err := a.dial(ctx)
if err != nil {
return false, err
}
defer conn.Close()
client := agentv1.NewAgentServiceClient(conn)
snap, err := client.Register(ctx, &agentv1.RegisterRequest{
NodeUUID: a.NodeUUID(),
AgentVersion: a.cfg.AgentVersion,
LocalConfigVersion: a.sb.ConfigVersion(),
})
if err != nil {
return false, err
}
// Full snapshot is authoritative: overwrite local credential table + inbounds.
a.sb.ApplyConfig(snap, true)
if snap.LastCommandID > a.lastCommandID.Load() {
a.lastCommandID.Store(snap.LastCommandID)
}
sctx, cancel := context.WithCancel(ctx)
defer cancel()
errc := make(chan error, 3)
go func() { errc <- a.runHeartbeat(sctx, client) }()
go func() { errc <- a.runSubscribe(sctx, client) }()
go func() { errc <- a.runUsage(sctx, client) }()
first := <-errc
cancel()
<-errc
<-errc
return true, first
}
// ─── backoff helpers ─────────────────────────────────────────────────────────
func nextBackoff(cur, max time.Duration) time.Duration {
next := cur * 2
if next > max {
next = max
}
return next
}
// jitter applies ±20% randomisation to avoid thundering-herd reconnects.
func jitter(d time.Duration) time.Duration {
if d <= 0 {
return 0
}
delta := float64(d) * 0.2
return d + time.Duration((rand.Float64()*2-1)*delta)
}
// sleepCtx sleeps for d unless ctx is cancelled first. Returns false if cancelled.
func sleepCtx(ctx context.Context, d time.Duration) bool {
if d <= 0 {
return ctx.Err() == nil
}
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return false
case <-t.C:
return true
}
}