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:
@@ -26,13 +26,6 @@ type libraryCaptureRequest struct {
|
||||
}
|
||||
|
||||
func libraryCaptureEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if config.LibraryAgentSocket == "" {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{
|
||||
"code": "library_capture_unwired",
|
||||
"reason": "未接线:主机侧封存 agent 没有挂载,页面无法发起封存",
|
||||
})
|
||||
return
|
||||
}
|
||||
var request libraryCaptureRequest
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&request); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
|
||||
@@ -52,6 +45,17 @@ func libraryCaptureEnqueue(w http.ResponseWriter, r *http.Request, config Config
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid job id"})
|
||||
return
|
||||
}
|
||||
// 请求形状先校验(400),再看执行器(503):不只看"配了 socket"——执行器可能
|
||||
// 不可达、可能指向别的实例、可能降级。页面与接口必须用同一份判定,否则又会出现
|
||||
// "点了才失败"或"封错库"。
|
||||
if available, reason, executor := libraryExecutorAvailability(r.Context(), config); !available {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{
|
||||
"code": "library_capture_unavailable",
|
||||
"reason": reason,
|
||||
"executor": executor,
|
||||
})
|
||||
return
|
||||
}
|
||||
requestedBy := ""
|
||||
if identity, ok := sessionFrom(r.Context()); ok {
|
||||
requestedBy = identity.Username
|
||||
|
||||
@@ -17,31 +17,11 @@ func captureRequest(body string) *http.Request {
|
||||
return request
|
||||
}
|
||||
|
||||
// An unwired agent must refuse clearly instead of queueing a job nobody can run.
|
||||
func TestLibraryCaptureRefusedWhenAgentUnwired(t *testing.T) {
|
||||
store := &fakeJobStore{}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryCaptureEnqueue(recorder, captureRequest(`{"scope":"internal"}`), Config{Store: store})
|
||||
if recorder.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body["code"] != "library_capture_unwired" || body["reason"] == "" {
|
||||
t.Fatalf("unexpected body %v", body)
|
||||
}
|
||||
if store.enqueued.Type != "" {
|
||||
t.Fatal("unwired agent still enqueued a job")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureEnqueuesFixedJobShape(t *testing.T) {
|
||||
store := &fakeJobStore{enqueueEchoRequestedID: true}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryCaptureEnqueue(recorder, captureRequest(`{"scope":"external","job":"lib-external-review"}`),
|
||||
Config{Store: store, LibraryAgentSocket: "/run/library-agent/agent.sock"})
|
||||
captureReadyConfig(store))
|
||||
if recorder.Code != http.StatusAccepted {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
@@ -76,7 +56,7 @@ func TestLibraryCaptureRejectsInvalidRequest(t *testing.T) {
|
||||
} {
|
||||
store := &fakeJobStore{}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryCaptureEnqueue(recorder, captureRequest(body), Config{Store: store, LibraryAgentSocket: "/tmp/agent.sock"})
|
||||
libraryCaptureEnqueue(recorder, captureRequest(body), captureReadyConfig(store))
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Fatalf("body %q status=%d", body, recorder.Code)
|
||||
}
|
||||
@@ -92,8 +72,7 @@ func TestLibraryCaptureQueueIDFitsTheColumn(t *testing.T) {
|
||||
for _, scope := range []string{"internal", "external"} {
|
||||
store := &fakeJobStore{enqueueEchoRequestedID: true}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryCaptureEnqueue(recorder, captureRequest(`{"scope":"`+scope+`"}`),
|
||||
Config{Store: store, LibraryAgentSocket: "/tmp/agent.sock"})
|
||||
libraryCaptureEnqueue(recorder, captureRequest(`{"scope":"`+scope+`"}`), captureReadyConfig(store))
|
||||
if recorder.Code != http.StatusAccepted {
|
||||
t.Fatalf("%s status=%d body=%s", scope, recorder.Code, recorder.Body.String())
|
||||
}
|
||||
@@ -146,7 +125,7 @@ func TestLibraryCaptureRejectsScopeConflictForReusedJob(t *testing.T) {
|
||||
Payload: json.RawMessage(`{"scope":"internal","capture_job":"lib-shared","requested_by":"yaozhanghao"}`)}}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryCaptureEnqueue(recorder, captureRequest(`{"scope":"external","job":"lib-shared"}`),
|
||||
Config{Store: store, LibraryAgentSocket: "/run/library-agent/agent.sock"})
|
||||
captureReadyConfig(store))
|
||||
if recorder.Code != http.StatusConflict {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
@@ -166,7 +145,7 @@ func TestLibraryCaptureReplayReportsStoredJob(t *testing.T) {
|
||||
Payload: json.RawMessage(`{"scope":"internal","capture_job":"lib-shared","requested_by":"yaozhanghao"}`)}}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryCaptureEnqueue(recorder, captureRequest(`{"scope":"internal","job":"lib-shared"}`),
|
||||
Config{Store: store, LibraryAgentSocket: "/run/library-agent/agent.sock"})
|
||||
captureReadyConfig(store))
|
||||
if recorder.Code != http.StatusAccepted {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/libraryexecutor"
|
||||
)
|
||||
|
||||
// libraryExecutorView 是"封存执行器到底能不能用"的页面口径。
|
||||
//
|
||||
// 为什么不是 `LIBRARY_AGENT_SOCKET != ""`:正式栈里 API 根本没有挂载那个 socket,
|
||||
// 配置非空并不代表链路通;更危险的是 agent 可能顶着正式单元名却在冻结另一个实例。
|
||||
// 这里只认 worker 写入的真实观测,并把观测时间与执行器自报的身份一起给出来。
|
||||
type libraryExecutorView struct {
|
||||
Available bool `json:"available"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Instance string `json:"instance,omitempty"`
|
||||
Project string `json:"project,omitempty"`
|
||||
SourceApp string `json:"source_app,omitempty"`
|
||||
ArchiveRoot string `json:"archive_root,omitempty"`
|
||||
Busy bool `json:"busy"`
|
||||
Degraded string `json:"degraded,omitempty"`
|
||||
ObservedAt *time.Time `json:"observed_at,omitempty"`
|
||||
}
|
||||
|
||||
type libraryExecutorStore interface {
|
||||
LibraryExecutorStatus(ctx context.Context, instance string) (*libraryexecutor.Observation, error)
|
||||
}
|
||||
|
||||
// libraryExecutorAvailability 把"配置里的期望"与"worker 观测到的真实身份"合起来判定:
|
||||
// 观测不存在、过期、不可达、实例不符、降级、正忙,任何一条都不可用,并给出原因。
|
||||
func libraryExecutorAvailability(ctx context.Context, config Config) (bool, string, libraryExecutorView) {
|
||||
// 期望身份是**封存源**:agent 冻结的是源库写入者,与同步目标(LIBRARY_TARGET_*)
|
||||
// 本来就是两套名字(本机候选栈:源 kgmaint、目标 kgseal)。
|
||||
instance := config.LibrarySourceInstance
|
||||
view := libraryExecutorView{Instance: instance}
|
||||
if instance == "" {
|
||||
return false, "未配置封存来源实例身份(LIBRARY_SOURCE_INSTANCE),无法确认执行器归属", view
|
||||
}
|
||||
store, ok := config.Store.(libraryExecutorStore)
|
||||
if !ok {
|
||||
return false, "执行器状态存储不可用", view
|
||||
}
|
||||
observation, err := store.LibraryExecutorStatus(ctx, instance)
|
||||
if err != nil {
|
||||
return false, "读取执行器状态失败:" + err.Error(), view
|
||||
}
|
||||
if observation == nil {
|
||||
return false, "封存执行器还没有上报状态(worker 未运行,或实例身份与 worker 不一致)", view
|
||||
}
|
||||
available, reason := libraryexecutor.Evaluate(*observation,
|
||||
libraryexecutor.Expectation{Instance: instance, Project: config.LibrarySourceProject,
|
||||
ArchiveRoot: config.LibraryArchiveRoot},
|
||||
executorStatusMaxAge(config), time.Now().UTC())
|
||||
observedAt := observation.ObservedAt
|
||||
view.Available = available
|
||||
view.Reason = reason
|
||||
view.Project = observation.Identity.Project
|
||||
view.SourceApp = observation.Identity.SourceApp
|
||||
view.ArchiveRoot = observation.Identity.ArchiveRoot
|
||||
view.Busy = observation.Busy
|
||||
view.Degraded = observation.Degraded
|
||||
view.ObservedAt = &observedAt
|
||||
return available, reason, view
|
||||
}
|
||||
|
||||
// defaultLibraryExecutorStatusMaxAge 与 worker 的探测间隔(30s)配套:
|
||||
// 没配上限绝不等于"永不过期"——那会把一次陈旧的"可用"永久留在页面上。
|
||||
const defaultLibraryExecutorStatusMaxAge = 2 * time.Minute
|
||||
|
||||
func executorStatusMaxAge(config Config) time.Duration {
|
||||
if config.LibraryExecutorStatusMaxAge > 0 {
|
||||
return config.LibraryExecutorStatusMaxAge
|
||||
}
|
||||
return defaultLibraryExecutorStatusMaxAge
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/libraryexecutor"
|
||||
)
|
||||
|
||||
// fakeJobStore 只是"存储"替身;执行器状态同样是它的一条记录。
|
||||
func (s *fakeJobStore) LibraryExecutorStatus(_ context.Context, instance string) (*libraryexecutor.Observation, error) {
|
||||
if s.executorStatus == nil || s.executorStatus.Instance != instance {
|
||||
return nil, nil
|
||||
}
|
||||
return s.executorStatus, nil
|
||||
}
|
||||
|
||||
// healthyExecutor 返回一份"worker 刚观测到、指向本实例"的记录。
|
||||
func healthyExecutor(now time.Time) *libraryexecutor.Observation {
|
||||
return &libraryexecutor.Observation{
|
||||
Instance: "kgmaint-weknora", Reachable: true, ObservedAt: now,
|
||||
Identity: libraryexecutor.Identity{Project: "kgmaint-weknora", SourceApp: "kgmaint-app",
|
||||
ArchiveRoot: "/tmp/kg-e2e/archive", Writers: "app"},
|
||||
}
|
||||
}
|
||||
|
||||
// captureReadyConfig 是"执行器真的可用"时的配置:实例、期望项目与观测三者一致。
|
||||
func captureReadyConfig(store *fakeJobStore) Config {
|
||||
store.executorStatus = healthyExecutor(time.Now().UTC())
|
||||
return Config{
|
||||
Store: store,
|
||||
LibraryAgentSocket: "/run/library-agent/agent.sock",
|
||||
LibrarySourceInstance: "kgmaint-weknora",
|
||||
LibrarySourceProject: "kgmaint-weknora",
|
||||
LibraryArchiveRoot: "/var/lib/knowledge-governance/library",
|
||||
}
|
||||
}
|
||||
|
||||
func decodeCaptureRefusal(t *testing.T, recorder *httptest.ResponseRecorder) (string, string) {
|
||||
t.Helper()
|
||||
var body struct {
|
||||
Code string `json:"code"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("body %s: %v", recorder.Body.String(), err)
|
||||
}
|
||||
return body.Code, body.Reason
|
||||
}
|
||||
|
||||
// 页面上的"可发起"必须等于接口真的会接受:配置了 socket 但执行器不可达、
|
||||
// 指向别的实例、降级或过期时,都必须带着原因拒绝,而不是先排队再失败。
|
||||
func TestLibraryCaptureRefusesWhenExecutorIsNotVerified(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
tests := []struct {
|
||||
name string
|
||||
config func(*Config)
|
||||
text string
|
||||
}{
|
||||
{name: "no instance identity", config: func(c *Config) {
|
||||
c.LibrarySourceInstance = ""
|
||||
}, text: "LIBRARY_SOURCE_INSTANCE"},
|
||||
{name: "nothing reported yet", config: func(c *Config) {
|
||||
c.Store.(*fakeJobStore).executorStatus = nil
|
||||
}, text: "还没有上报状态"},
|
||||
{name: "unreachable", config: func(c *Config) {
|
||||
c.Store.(*fakeJobStore).executorStatus.Reachable = false
|
||||
c.Store.(*fakeJobStore).executorStatus.Error = "library agent is unreachable"
|
||||
}, text: "不可达"},
|
||||
{name: "stale observation", config: func(c *Config) {
|
||||
c.Store.(*fakeJobStore).executorStatus.ObservedAt = now.Add(-10 * time.Minute)
|
||||
}, text: "已过期"},
|
||||
{name: "points at another instance", config: func(c *Config) {
|
||||
c.Store.(*fakeJobStore).executorStatus.Identity.Project = "weknora071full"
|
||||
}, text: "指向的实例不匹配"},
|
||||
{name: "degraded", config: func(c *Config) {
|
||||
c.Store.(*fakeJobStore).executorStatus.Degraded = "写入者恢复失败"
|
||||
}, text: "降级"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
store := &fakeJobStore{}
|
||||
config := captureReadyConfig(store)
|
||||
test.config(&config)
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryCaptureEnqueue(recorder, captureRequest(`{"scope":"internal"}`), config)
|
||||
if recorder.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
code, reason := decodeCaptureRefusal(t, recorder)
|
||||
if code != "library_capture_unavailable" {
|
||||
t.Fatalf("code=%q body=%s", code, recorder.Body.String())
|
||||
}
|
||||
if reason == "" || !strings.Contains(reason, test.text) {
|
||||
t.Fatalf("reason=%q want it to mention %q", reason, test.text)
|
||||
}
|
||||
if store.enqueued.Type != "" {
|
||||
t.Fatal("refused capture still enqueued a job")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The overview must report the same reason the capture endpoint would use.
|
||||
func TestLibraryOverviewReportsExecutorIdentityAndReason(t *testing.T) {
|
||||
store := &fakeLibraryStore{}
|
||||
config := captureReadyConfig(&store.fakeJobStore)
|
||||
// libraryJobStore 的方法在 fakeLibraryStore 上,执行器状态在嵌入的 fakeJobStore 上。
|
||||
config.Store = store
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryOverviewHandler(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/library/overview?scope=internal", nil), config)
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
CaptureAvailable bool `json:"capture_available"`
|
||||
Executor struct {
|
||||
Available bool `json:"available"`
|
||||
Instance string `json:"instance"`
|
||||
Project string `json:"project"`
|
||||
SourceApp string `json:"source_app"`
|
||||
ArchiveRoot string `json:"archive_root"`
|
||||
} `json:"executor"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !body.CaptureAvailable || !body.Executor.Available {
|
||||
t.Fatalf("overview did not report an available executor: %s", recorder.Body.String())
|
||||
}
|
||||
if body.Executor.Project != "kgmaint-weknora" || body.Executor.SourceApp != "kgmaint-app" ||
|
||||
body.Executor.ArchiveRoot != "/tmp/kg-e2e/archive" || body.Executor.Instance != "kgmaint-weknora" {
|
||||
t.Fatalf("executor view = %+v", body.Executor)
|
||||
}
|
||||
|
||||
store.fakeJobStore.executorStatus.Identity.Project = "weknora071full"
|
||||
recorder = httptest.NewRecorder()
|
||||
libraryOverviewHandler(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/library/overview?scope=internal", nil), config)
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body.CaptureAvailable {
|
||||
t.Fatalf("overview still says available after the executor moved to another instance: %s", recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// "恢复至该版本"必须由真实条件决定:没有 restore 授权就明确说出来。
|
||||
func TestLibraryRestoreAvailabilityExplainsMissingAuthorization(t *testing.T) {
|
||||
store := &fakeJobStore{}
|
||||
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryRestoreAvailability(recorder, httptest.NewRequest(http.MethodGet,
|
||||
"/api/v1/library/restore-availability?scope=internal&snapshot_id=snap-1", nil), config)
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
Allowed bool `json:"allowed"`
|
||||
Reasons []string `json:"reasons"`
|
||||
Authorization struct {
|
||||
State string `json:"state"`
|
||||
} `json:"authorization"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body.Allowed || body.Authorization.State != "none" || len(body.Reasons) == 0 {
|
||||
t.Fatalf("body=%s", recorder.Body.String())
|
||||
}
|
||||
found := false
|
||||
for _, reason := range body.Reasons {
|
||||
if strings.Contains(reason, "恢复授权") {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("reasons = %v", body.Reasons)
|
||||
}
|
||||
}
|
||||
@@ -307,6 +307,7 @@ type libraryOverview struct {
|
||||
Authorization libraryAuthorizationView `json:"authorization"`
|
||||
CaptureAvailable bool `json:"capture_available"`
|
||||
CaptureReason string `json:"capture_reason,omitempty"`
|
||||
Executor libraryExecutorView `json:"executor"`
|
||||
Now time.Time `json:"now"`
|
||||
}
|
||||
|
||||
@@ -563,12 +564,10 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
overview := libraryOverview{Scope: scope, Jobs: []governance.LibraryJob{}, Now: now,
|
||||
CaptureAvailable: strings.TrimSpace(config.LibraryAgentSocket) != "",
|
||||
Gate: libraryGateView{Reasons: []string{}},
|
||||
Diff: libraryDiffView{State: "unknown", Reason: "生产与测试的文档级差异读取未接线", Added: []any{}, Updated: []any{}, Removed: []any{}}}
|
||||
if !overview.CaptureAvailable {
|
||||
overview.CaptureReason = "主机侧封存 agent 未接线"
|
||||
}
|
||||
Gate: libraryGateView{Reasons: []string{}},
|
||||
Diff: libraryDiffView{State: "unknown", Reason: "生产与测试的文档级差异读取未接线", Added: []any{}, Updated: []any{}, Removed: []any{}}}
|
||||
// 可发起封存 = worker 真实探测到执行器可用且指向本实例;原因逐条给全。
|
||||
overview.CaptureAvailable, overview.CaptureReason, overview.Executor = libraryExecutorAvailability(r.Context(), config)
|
||||
|
||||
// 测试封存来自归档:它只是测试侧事实。
|
||||
snapshots, snapErr := readLibrarySnapshots(r.Context(), config.LibraryArchiveRoot)
|
||||
|
||||
@@ -146,6 +146,64 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": false})
|
||||
}
|
||||
|
||||
// libraryRestoreAvailability 回答"现在能不能把生产恢复到这份快照"。
|
||||
//
|
||||
// 为什么需要它:页面原来把"恢复至该版本"按钮写死为 disabled,理由是"未接线"——
|
||||
// 但接口、授权、恢复作业其实都已经在跑。按钮该由真实条件决定:双闸打开、
|
||||
// 有这份快照的恢复授权、目标实例没有在维护。
|
||||
type libraryRestoreAvailabilityView struct {
|
||||
Allowed bool `json:"allowed"`
|
||||
Reasons []string `json:"reasons"`
|
||||
Scope string `json:"scope"`
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
Authorization libraryAuthorizationView `json:"authorization"`
|
||||
}
|
||||
|
||||
func libraryRestoreAvailability(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
scope, err := scopeFromQuery(r)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
snapshotID := strings.TrimSpace(r.URL.Query().Get("snapshot_id"))
|
||||
if snapshotID == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "snapshot_id required"})
|
||||
return
|
||||
}
|
||||
view := libraryRestoreAvailabilityView{Scope: scope, SnapshotID: snapshotID, Reasons: []string{}}
|
||||
if !config.ProductionReleaseRequestsEnabled {
|
||||
view.Reasons = append(view.Reasons, "生产写入闸口关闭(PRODUCTION_RELEASE_REQUESTS_ENABLED=false)")
|
||||
}
|
||||
if !config.ProductionBackupRestoreVerified {
|
||||
view.Reasons = append(view.Reasons, "没有已核验的生产恢复演练证据(PRODUCTION_BACKUP_RESTORE_VERIFIED=false)")
|
||||
}
|
||||
digest, err := libraryRestoreParamsDigest(scope, snapshotID)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot digest params"})
|
||||
return
|
||||
}
|
||||
grant, found := governance.LibraryReleaseAuthorization{}, false
|
||||
if storeWithAuth, ok := config.Store.(interface {
|
||||
ActiveLibraryAuthorization(ctx context.Context, scope, snapshotID, digest string, now time.Time) (governance.LibraryReleaseAuthorization, bool, error)
|
||||
}); ok {
|
||||
grant, found, err = storeWithAuth.ActiveLibraryAuthorization(r.Context(), scope, snapshotID, digest, time.Now().UTC())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"allowed": false,
|
||||
"reasons": []string{"读取恢复授权失败:" + err.Error()}})
|
||||
return
|
||||
}
|
||||
}
|
||||
view.Authorization = authorizationViewOf(grant, found)
|
||||
if !found {
|
||||
view.Reasons = append(view.Reasons, "没有针对该快照的恢复授权:先签发 restore 授权(绑定同一快照)")
|
||||
}
|
||||
if _, held := instanceMaintenanceGuard(r.Context(), config, scope); held {
|
||||
view.Reasons = append(view.Reasons, "目标实例正在维护中,等当前作业释放后再恢复")
|
||||
}
|
||||
view.Allowed = len(view.Reasons) == 0
|
||||
writeJSON(w, http.StatusOK, view)
|
||||
}
|
||||
|
||||
// 崩溃续作:失败作业可以按原参数重新排队,生成新作业(旧作业保留为审计记录)。
|
||||
func libraryJobResume(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
identity, ok := sessionFrom(r.Context())
|
||||
|
||||
@@ -85,15 +85,14 @@ const libraryCaptureNote = "封存由运维命令 scripts/library-capture.sh cap
|
||||
|
||||
func librarySnapshotsList(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
view, err := readLibrarySnapshots(r.Context(), config.LibraryArchiveRoot)
|
||||
view.CaptureAvailable = config.LibraryAgentSocket != ""
|
||||
if !view.CaptureAvailable {
|
||||
view.CaptureReason = "未接线:主机侧封存 agent 没有挂载,页面只能查看已封存版本"
|
||||
}
|
||||
// 能不能发起封存只认 worker 的真实观测,不认"配置里写了 socket 路径"。
|
||||
view.CaptureAvailable, view.CaptureReason, _ = libraryExecutorAvailability(r.Context(), config)
|
||||
if err != nil {
|
||||
status, reason := libraryArchiveErrorStatus(err, "归档不可读")
|
||||
writeJSON(w, status, librarySnapshotList{Available: false, Reason: reason,
|
||||
Snapshots: []librarySnapshotView{}, Verification: libraryVerificationManifest,
|
||||
VerificationNote: libraryVerificationNote, CaptureNote: libraryCaptureNote})
|
||||
VerificationNote: libraryVerificationNote, CaptureNote: libraryCaptureNote,
|
||||
CaptureAvailable: view.CaptureAvailable, CaptureReason: view.CaptureReason})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, view)
|
||||
|
||||
@@ -152,6 +152,11 @@ type Config struct {
|
||||
LibrarySourceInstance string
|
||||
// LibraryAgentSocket 是主机侧封存 agent 的 unix socket;留空即页面不能发起封存。
|
||||
LibraryAgentSocket string
|
||||
// LibrarySourceProject 是执行器应指向的实例名(agent -project,封存源)。
|
||||
// 与它不一致时按"封错库"处理:不可发起,并说明差在哪。
|
||||
LibrarySourceProject string
|
||||
// LibraryExecutorStatusMaxAge 是执行器观测的有效期;超过即"无法确认"。
|
||||
LibraryExecutorStatusMaxAge time.Duration
|
||||
// LibraryCapacityBudgetBytes 是整库归档容量预算;0 = 未设置(容量门禁不放行)。
|
||||
LibraryCapacityBudgetBytes int64
|
||||
// 整库生产目标的只读探测配置:首次发布要能证明"生产可读且为空"。
|
||||
@@ -510,6 +515,10 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("POST /api/v1/library/restores", func(w http.ResponseWriter, r *http.Request) {
|
||||
libraryRestoreEnqueue(w, r, config)
|
||||
})
|
||||
// 页面问"这份快照现在能不能恢复":条件来自双闸、授权与实例维护,而不是写死的按钮。
|
||||
mux.HandleFunc("GET /api/v1/library/restore-availability", func(w http.ResponseWriter, r *http.Request) {
|
||||
libraryRestoreAvailability(w, r, config)
|
||||
})
|
||||
// 失败/取消作业续作:按原参数重新排队,旧作业保留审计。
|
||||
mux.HandleFunc("POST /api/v1/library/jobs/{id}/resume", func(w http.ResponseWriter, r *http.Request) {
|
||||
libraryJobResume(w, r, config)
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/libraryexecutor"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
@@ -1501,30 +1502,32 @@ type fakeJobStore struct {
|
||||
activateSettingsErr error
|
||||
// enqueueEchoRequestedID:幂等"首次入队"语义 —— 返回调用方请求的那个 id
|
||||
// (默认 false 时返回 enqueueResult,即"复用已有任务"的路径)。
|
||||
enqueueEchoRequestedID bool
|
||||
listSettingsConnectionID string
|
||||
listSettingsErr error
|
||||
settingsRevisions []governance.SourceConnectionRevision
|
||||
jobFailureFilter governance.JobFailureFilter
|
||||
jobFailurePage governance.JobFailurePage
|
||||
jobFailureErr error
|
||||
retryBatchRequest *governance.RetryPublicationsBatchRequest
|
||||
retryBatchOperation string
|
||||
retryBatchResult governance.RetryPublicationsBatchResult
|
||||
cancelBatchRequest *governance.CancelPublicationsBatchRequest
|
||||
cancelBatchOperation string
|
||||
cancelBatchResult governance.RetryPublicationsBatchResult
|
||||
cancelBatchReplayed bool
|
||||
cancelBatchErr error
|
||||
retryBatchReplayed bool
|
||||
retryBatchErr error
|
||||
requeueFailureRequest *governance.RequeueArtifactFetchRequest
|
||||
requeueFailureOperation string
|
||||
requeueFailureResult governance.RequeueArtifactFetchResult
|
||||
requeueFailureReplayed bool
|
||||
requeueFailureErr error
|
||||
enqueued jobs.EnqueueRequest
|
||||
enqueueResult *jobs.Job
|
||||
enqueueEchoRequestedID bool
|
||||
listSettingsConnectionID string
|
||||
listSettingsErr error
|
||||
settingsRevisions []governance.SourceConnectionRevision
|
||||
jobFailureFilter governance.JobFailureFilter
|
||||
jobFailurePage governance.JobFailurePage
|
||||
jobFailureErr error
|
||||
retryBatchRequest *governance.RetryPublicationsBatchRequest
|
||||
retryBatchOperation string
|
||||
retryBatchResult governance.RetryPublicationsBatchResult
|
||||
cancelBatchRequest *governance.CancelPublicationsBatchRequest
|
||||
cancelBatchOperation string
|
||||
cancelBatchResult governance.RetryPublicationsBatchResult
|
||||
cancelBatchReplayed bool
|
||||
cancelBatchErr error
|
||||
retryBatchReplayed bool
|
||||
retryBatchErr error
|
||||
requeueFailureRequest *governance.RequeueArtifactFetchRequest
|
||||
requeueFailureOperation string
|
||||
requeueFailureResult governance.RequeueArtifactFetchResult
|
||||
requeueFailureReplayed bool
|
||||
requeueFailureErr error
|
||||
enqueued jobs.EnqueueRequest
|
||||
enqueueResult *jobs.Job
|
||||
// executorStatus 是封存执行器的"最近一次观测";nil 表示还没有任何上报。
|
||||
executorStatus *libraryexecutor.Observation
|
||||
listResult []jobs.Job
|
||||
listType string
|
||||
listByTypeResult []jobs.Job
|
||||
|
||||
Reference in New Issue
Block a user