feat(library): 封存执行器可用性与还原条件来自真实观测

页面上的"可发起封存"原来只判 LIBRARY_AGENT_SOCKET 非空:正式栈的 API 根本没挂
那个 socket,而 agent 曾顶着正式单元名冻结候选实例——配置非空、页面可点、真发起
却封错库。

现在:agent 新增 health 动作(不占封存操作锁、不跑子进程,只回答身份/降级/忙),
worker 每 30 秒探测并写入迁移 074 的 library_executor_status;overview、快照列表与
POST /library/captures 共用同一份判定(过期、不可达、实例不符、降级、正忙都拒绝并
给原因)。封存结果由 agent 附上自报身份,worker 在停写入者之前再探测一次、执行后
用结果复核,不一致就不登记测试封存——心跳只能证明"刚才"。

期望身份用 LIBRARY_SOURCE_*(封存源),不是 LIBRARY_TARGET_*(同步目标),否则
正确的执行器会被判成不匹配。另加 GET /library/restore-availability:恢复能否执行由
双闸、该快照的恢复授权与实例维护状态决定,页面不再写死 disabled。

真跑(候选隔离栈,两处 socket 隔离不变):overview 返回 executor
{kgmaint-weknora/kgmaint-app};停 agent 后转不可达并 503 带原因;重启后恢复。
This commit is contained in:
姚章浩
2026-10-29 13:01:37 +08:00
parent a06945516f
commit 47eb23cf68
26 changed files with 1351 additions and 113 deletions
+100 -14
View File
@@ -89,13 +89,45 @@ const maxReleasedDeadLetters = 64
type Agent struct {
config Config
mu sync.Mutex
// stateMu 只保护下面两个"给人看"的字段:健康应答不能被一次 15 分钟的封存
// 卡住(否则页面会把"正在封存"读成"执行器不可达")。
stateMu sync.RWMutex
// degraded is non-empty when a failed operation could not be followed by a
// verified recovery. While set, capture requests are refused: leaving the
// source writer stopped is worse than refusing work.
degraded string
busy bool
wg sync.WaitGroup
}
// captureState 是健康应答要暴露的执行器状态:是否在跑、是否降级。
type captureState struct {
Busy bool `json:"busy"`
Degraded string `json:"degraded"`
}
func (a *Agent) snapshotState() captureState {
a.stateMu.RLock()
defer a.stateMu.RUnlock()
return captureState{Busy: a.busy, Degraded: a.degraded}
}
func (a *Agent) setBusy(busy bool) {
a.stateMu.Lock()
defer a.stateMu.Unlock()
a.busy = busy
}
func (a *Agent) setDegraded(reason string) {
a.stateMu.Lock()
defer a.stateMu.Unlock()
a.degraded = reason
}
func (a *Agent) clearDegraded() {
a.setDegraded("")
}
func New(config Config) (*Agent, error) {
if !filepath.IsAbs(config.Socket) || !filepath.IsAbs(config.ArchiveRoot) || !filepath.IsAbs(config.JournalRoot) {
return nil, errors.New("library agent paths must be absolute")
@@ -143,7 +175,7 @@ func (a *Agent) Serve(ctx context.Context) error {
// writer from a previous killed run. Recover before accepting work; if that
// fails, stay degraded and refuse captures instead of pretending to be ready.
if err := a.recoverWriters(ctx); err != nil {
a.degraded = err.Error()
a.setDegraded(err.Error())
log.Printf("library agent: pending freeze recovery failed: %v", err)
}
go func() {
@@ -194,13 +226,18 @@ func (a *Agent) handle(ctx context.Context, conn net.Conn) {
// execute serialises operations and maps a request onto the one fixed command.
func (a *Agent) execute(ctx context.Context, req request) response {
// health 不进操作锁、不跑子进程:调用方要的是"这个执行器指向谁、能不能干活",
// 而一次正在进行的封存不该让这个回答变成"不可达"。
if req.Action == "health" {
return a.health()
}
a.mu.Lock()
defer a.mu.Unlock()
out := response{Action: req.Action, Scope: req.Scope, Job: req.Job}
// Degraded blocks new captures, but recover and status must stay reachable:
// otherwise there is no way back to a verified state.
if a.degraded != "" && req.Action == "capture" {
out.Error = "封存执行边界处于降级状态(上次恢复失败:" + a.degraded + "),先执行 recover"
if state := a.snapshotState(); state.Degraded != "" && req.Action == "capture" {
out.Error = "封存执行边界处于降级状态(上次恢复失败:" + state.Degraded + "),先执行 recover"
return out
}
var args []string
@@ -242,6 +279,10 @@ func (a *Agent) execute(ctx context.Context, req request) response {
args = append(args, a.config.declaration()...)
bounded, cancel := context.WithTimeout(ctx, a.config.MaxDuration)
defer cancel()
if req.Action == "capture" || req.Action == "recover" {
a.setBusy(true)
defer a.setBusy(false)
}
payload, err := a.config.run(bounded, a.config.Binary, args...)
if err != nil {
detail := "operation failed"
@@ -254,7 +295,7 @@ func (a *Agent) execute(ctx context.Context, req request) response {
// verify.
if req.Action == "capture" || req.Action == "recover" {
if recoveryErr := a.recoverWriters(ctx); recoveryErr != nil {
a.degraded = recoveryErr.Error()
a.setDegraded(recoveryErr.Error())
out.Error = detail + ";写入者恢复失败:" + recoveryErr.Error() + "(已阻断后续封存,需人工处理)"
return out
}
@@ -266,7 +307,7 @@ func (a *Agent) execute(ctx context.Context, req request) response {
return out
}
if req.Action == "recover" {
a.degraded = ""
a.clearDegraded()
}
out.OK = true
if json.Valid(payload) {
@@ -274,9 +315,28 @@ func (a *Agent) execute(ctx context.Context, req request) response {
} else {
out.Payload = json.RawMessage(`{}`)
}
// 封存结果必须带上"这次是谁执行的":调用方据此复核,防止心跳与执行之间
// socket 被换成另一个 agent(真正的封错库事故就是这样发生的)。
if req.Action == "capture" {
out.Payload = a.attachIdentity(out.Payload)
}
return out
}
// attachIdentity 把执行器身份并进封存结果(保留 CLI 原有的字段,如 snapshot_id)。
func (a *Agent) attachIdentity(payload json.RawMessage) json.RawMessage {
var document map[string]any
if err := json.Unmarshal(payload, &document); err != nil {
return payload
}
document["agent_identity"] = a.config.identity()
encoded, err := json.Marshal(document)
if err != nil {
return payload
}
return json.RawMessage(encoded)
}
// recoverWriters runs the idempotent recovery command with its own budget, even
// when the triggering context is already cancelled (timeout / shutdown).
func (a *Agent) recoverWriters(ctx context.Context) error {
@@ -285,7 +345,7 @@ func (a *Agent) recoverWriters(ctx context.Context) error {
if _, err := a.config.run(bounded, a.config.Binary, append([]string{"recover"}, a.config.declaration()...)...); err != nil {
return err
}
a.degraded = ""
a.clearDegraded()
return nil
}
@@ -332,12 +392,38 @@ func (c Config) run(ctx context.Context, name string, args ...string) ([]byte, e
// Describe returns a redacted view for logs and health checks.
func (a *Agent) Describe() map[string]any {
return map[string]any{
"socket": a.config.Socket,
"archive_root": a.config.ArchiveRoot,
"journal_root": a.config.JournalRoot,
"project": a.config.Project,
"writers": a.config.Writers,
"scope_choice": "request may select internal or external only",
}
view := a.config.identity()
view["scope_choice"] = "request may select internal or external only"
return view
}
// health 是"这个执行器指向谁、现在能不能干活"的唯一回答。它只暴露容器名、
// 路径与声明,不含任何凭据;调用方据此核对源身份,而不是靠配置猜。
func (a *Agent) health() response {
state := a.snapshotState()
payload := a.config.identity()
payload["busy"] = state.Busy
payload["degraded"] = state.Degraded
encoded, err := json.Marshal(payload)
if err != nil {
return response{Action: "health", Error: "cannot encode health"}
}
return response{OK: true, Action: "health", Payload: json.RawMessage(encoded)}
}
// identity 被日志与健康应答共用一份,避免两处描述漂移。
func (c Config) identity() map[string]any {
identity := map[string]any{
"project": c.Project,
"archive_root": c.ArchiveRoot,
"journal_root": c.JournalRoot,
"source_app": c.SourceApp,
"source_pg": c.SourcePG,
"source_es": c.SourceES,
"writers": c.Writers,
}
if c.SourceS3Endpoint != "" {
identity["source_s3_endpoint"] = c.SourceS3Endpoint
}
return identity
}
+6
View File
@@ -46,6 +46,12 @@ func Status(ctx context.Context, config ClientConfig) (Result, error) {
return call(ctx, config, map[string]any{"action": "status"})
}
// Health 只问三件事:这个执行器指向谁(project/容器/归档)、是否在跑、是否降级。
// 它不跑子进程、不占操作锁,所以可以当心跳用;Status 会去查源库,代价高得多。
func Health(ctx context.Context, config ClientConfig) (Result, error) {
return call(ctx, config, map[string]any{"action": "health"})
}
// Recover restores writers from an interrupted freeze journal.
func Recover(ctx context.Context, config ClientConfig) (Result, error) {
return call(ctx, config, map[string]any{"action": "recover"})
+108
View File
@@ -0,0 +1,108 @@
package libraryagent
import (
"context"
"encoding/json"
"os"
"testing"
"time"
)
func serveAgent(t *testing.T, agent *Agent, socket string) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go func() { _ = agent.Serve(ctx) }()
deadline := time.Now().Add(2 * time.Second)
for {
if _, err := os.Stat(socket); err == nil {
return
}
if time.Now().After(deadline) {
t.Fatal("agent socket never appeared")
}
time.Sleep(10 * time.Millisecond)
}
}
// 健康应答必须不排队等正在跑的封存:一次封存最长 15 分钟,如果 health 也去抢
// 操作锁,页面就会把"正在封存"看成"执行器不可达",进而误导运维。
func TestHealthAnswersWhileACaptureHoldsTheOperationLock(t *testing.T) {
agent, socket, calls := testAgent(t)
serveAgent(t, agent, socket)
// 占住操作锁并置 busy,模拟一次正在进行的封存。
agent.mu.Lock()
defer agent.mu.Unlock()
agent.setBusy(true)
defer agent.setBusy(false)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
result, err := Health(ctx, ClientConfig{Socket: socket, Timeout: 2 * time.Second})
if err != nil {
t.Fatalf("health while busy: %v", err)
}
var payload struct {
Project string `json:"project"`
Busy bool `json:"busy"`
}
if err = json.Unmarshal(result.Payload, &payload); err != nil {
t.Fatalf("health payload: %v", err)
}
if payload.Project != "weknora071full" || !payload.Busy {
t.Fatalf("health payload = %+v", payload)
}
if len(captureCalls(calls())) != 0 {
t.Fatalf("health must not run the capture binary, calls = %v", calls())
}
}
// 降级状态必须能被调用方看见:否则页面只能看到"可发起",而真发起会被拒。
func TestHealthReportsDegradedState(t *testing.T) {
agent, socket, _ := testAgent(t)
serveAgent(t, agent, socket)
// 启动恢复成功会清空降级;这里在它之后模拟"恢复失败"留下的降级状态。
agent.setDegraded("写入者恢复失败")
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
result, err := Health(ctx, ClientConfig{Socket: socket, Timeout: 2 * time.Second})
if err != nil {
t.Fatal(err)
}
var payload struct {
Degraded string `json:"degraded"`
SourceApp string `json:"source_app"`
Writers string `json:"writers"`
}
if err = json.Unmarshal(result.Payload, &payload); err != nil {
t.Fatal(err)
}
if payload.Degraded != "写入者恢复失败" || payload.SourceApp != "WKNFull-app" || payload.Writers != "app" {
t.Fatalf("health payload = %+v", payload)
}
}
// 封存结果必须自带"这次是谁执行的":调用方据此在事后复核,防止心跳与执行之间
// socket 被换成另一个实例。
func TestCaptureResultCarriesTheAgentIdentity(t *testing.T) {
agent, socket, _ := testAgent(t)
serveAgent(t, agent, socket)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
result, err := Capture(ctx, ClientConfig{Socket: socket, Timeout: 5 * time.Second}, "internal", "lib-internal-identity")
if err != nil {
t.Fatal(err)
}
var payload struct {
SnapshotID string `json:"snapshot_id"`
Identity struct {
Project string `json:"project"`
} `json:"agent_identity"`
}
if err = json.Unmarshal(result.Payload, &payload); err != nil {
t.Fatal(err)
}
if payload.SnapshotID != "abc" || payload.Identity.Project != "weknora071full" {
t.Fatalf("payload = %s", result.Payload)
}
}