Files
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

106 lines
2.9 KiB
Go

package agentd
import (
"context"
agentv1 "github.com/wangjia/pangolin/server/internal/pb/agentv1"
)
// runSubscribe opens the Command stream (resuming from the last durably processed
// command id) and applies each command idempotently, Ack'ing after apply
// (at-least-once). It returns when ctx is cancelled or the stream errors, so the
// session can reconnect and resume.
func (a *Agent) runSubscribe(ctx context.Context, client agentv1.AgentServiceClient) error {
nodeUUID := a.NodeUUID()
stream, err := client.Subscribe(ctx, &agentv1.SubscribeRequest{
NodeUUID: nodeUUID,
LastCommandID: a.lastCommandID.Load(),
})
if err != nil {
return err
}
for {
cmd, err := stream.Recv()
if err != nil {
return err
}
a.handleCommand(cmd)
// Ack after apply. A failed Ack just causes redelivery, which the
// dedup-by-command-id + idempotent apply below tolerates.
if _, err := client.Ack(ctx, &agentv1.AckRequest{
NodeUUID: nodeUUID,
CommandID: cmd.CommandID,
}); err != nil {
return err
}
}
}
// handleCommand applies one command. Commands at or below the high-water mark are
// skipped (already applied) — this makes redelivery after a dropped Ack safe.
func (a *Agent) handleCommand(cmd *agentv1.Command) {
if cmd.CommandID != 0 && cmd.CommandID <= a.lastCommandID.Load() {
return
}
switch cmd.Type {
case agentv1.CommandTypeUpsert:
if cmd.Upsert != nil && cmd.Upsert.Credential != nil {
a.sb.Upsert(credFromPB(cmd.Upsert.Credential))
}
case agentv1.CommandTypeRevoke:
if cmd.Revoke != nil {
a.sb.Revoke(cmd.Revoke.DpUUID)
}
case agentv1.CommandTypeRotateCredential:
if cmd.Rotate != nil && cmd.Rotate.NewCredential != nil {
a.sb.Rotate(cmd.Rotate.OldDpUUID, credFromPB(cmd.Rotate.NewCredential), cmd.Rotate.GraceUntilUnix)
}
case agentv1.CommandTypeApplyConfig:
if cmd.ApplyConfig != nil {
a.sb.ApplyConfig(cmd.ApplyConfig, cmd.ApplyConfig.Credentials != nil)
}
case agentv1.CommandTypeLifecycle:
a.handleLifecycle(cmd.Lifecycle)
default:
logf("ignoring command id=%d with unknown type=%d", cmd.CommandID, cmd.Type)
}
if cmd.CommandID > a.lastCommandID.Load() {
a.lastCommandID.Store(cmd.CommandID)
}
}
func (a *Agent) handleLifecycle(p *agentv1.LifecyclePayload) {
if p == nil {
return
}
switch p.Action {
case agentv1.LifecycleActionDrain:
// Draining is steered by control-plane node weight; the data plane keeps
// serving existing sessions. Nothing to mutate locally.
logf("lifecycle: drain")
case agentv1.LifecycleActionResume:
logf("lifecycle: resume")
case agentv1.LifecycleActionShutdown:
logf("lifecycle: shutdown requested")
if a.shutdown != nil {
a.shutdown()
}
default:
logf("lifecycle: unknown action %d", p.Action)
}
}
func credFromPB(c *agentv1.Credential) *Cred {
flow := c.Flow
if flow == "" {
flow = DefaultFlow
}
return &Cred{
DpUUID: c.DpUUID,
Protocol: c.Protocol,
Flow: flow,
ExpiresAt: c.ExpiresAtUnix,
}
}