- libraryctl:status/preflight/capture/list/verify/recover,只读来源会话、
结清检查、契约推导、维护窗口内停写者、导出十表+索引+对象+Wiki、封存候选后恢复
- libraryfreeze.ProjectController:按 Compose 项目逐服务声明固定身份,
未声明服务/容器重建即拒绝,仅 SIGTERM,恢复后必须 healthy
- httpapi:GET /api/v1/library/snapshots[/{id}] 只读列出封存产物
- web:「整库版本」页(只读、未接线显示原因、无假按钮)
- api:LIBRARY_ARCHIVE_ROOT + 归档根只读挂载
- docs/library-capture.md:运维手册与 2026-10-28 两次真实封存实测
不代表整库业务验收通过:内容/问答/性能验收、跨系统切点、Wiki 删除语义重算、
生产预备份/恢复演练/双闸/同步协调仍未完成。
This commit is contained in:
@@ -69,6 +69,9 @@ type Config struct {
|
||||
VersionHistoryAllowedOrigins []string
|
||||
// VersionHistoryLinkOrigin 是**页面链接**用的 origin(给内网外的浏览器点开),
|
||||
// 留空即与抓取 origin 相同。只用于拼展示链接,不参与任何请求。
|
||||
// LibraryArchiveRoot 是整库封存产物的只读归档根(主机私有 0700 目录的只读挂载)。
|
||||
// 留空即"未接线":页面只显示原因,不显示空表冒充没有快照。
|
||||
LibraryArchiveRoot string
|
||||
VersionHistoryLinkOrigin string
|
||||
VersionHistoryHTTPTimeout time.Duration
|
||||
VersionHistoryMaxPages int
|
||||
@@ -116,6 +119,7 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")),
|
||||
VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"),
|
||||
VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")),
|
||||
LibraryArchiveRoot: strings.TrimSpace(getenv("LIBRARY_ARCHIVE_ROOT")),
|
||||
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
|
||||
VersionHistoryHTTPTimeout: 15 * time.Second,
|
||||
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
|
||||
@@ -226,6 +230,9 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if config.LibraryArchiveRoot != "" && !filepath.IsAbs(config.LibraryArchiveRoot) {
|
||||
return Config{}, errors.New("LIBRARY_ARCHIVE_ROOT 必须是绝对路径(归档根按只读目录挂载)")
|
||||
}
|
||||
if config.TestWeKnoraHTTPTimeout, err = durationOrDefault(getenv("TEST_WEKNORA_HTTP_TIMEOUT"), config.TestWeKnoraHTTPTimeout); err != nil {
|
||||
return Config{}, fmt.Errorf("TEST_WEKNORA_HTTP_TIMEOUT: %w", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// 「整库版本」只读视图:把已经封存的候选产物(artifact-acceptance-v1)如实列出来。
|
||||
//
|
||||
// 边界(刻意不做的事):
|
||||
// - 不触发封存、不停/起写入者:封存需要维护窗口与来源凭据,只能由运维命令
|
||||
// scripts/library-capture.sh 在目标主机执行;
|
||||
// - 不把候选当版本:候选只证明"这一份内容被完整、可核验地封存了",内容/问答/
|
||||
// 性能验收与生产发布是另外的、需要独立授权的事;
|
||||
// - 归档根没接线时返回可用性=false 与原因,不返回空表冒充"没有快照"。
|
||||
type librarySnapshotPart struct {
|
||||
Kind string `json:"kind"`
|
||||
Name string `json:"name"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Count int64 `json:"count"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
}
|
||||
|
||||
type librarySnapshotView struct {
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
Scope string `json:"scope"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ValidationPolicy string `json:"validation_policy"`
|
||||
Format string `json:"format"`
|
||||
Compatibility librarysnapshot.Compatibility `json:"compatibility"`
|
||||
Parts []librarySnapshotPart `json:"parts"`
|
||||
LogicalBytes int64 `json:"logical_bytes"`
|
||||
UniqueBytes int64 `json:"unique_bytes"`
|
||||
SharedBytes int64 `json:"shared_bytes"`
|
||||
Totals map[string]int64 `json:"totals"`
|
||||
}
|
||||
|
||||
type librarySnapshotList struct {
|
||||
Available bool `json:"available"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
ArchiveRoot string `json:"archive_root,omitempty"`
|
||||
Snapshots []librarySnapshotView `json:"snapshots"`
|
||||
StoredBytes int64 `json:"stored_bytes"`
|
||||
// 页面必须能说清"封存由谁执行",不能让人以为页面上有个没实现的按钮。
|
||||
CaptureNote string `json:"capture_note"`
|
||||
}
|
||||
|
||||
const libraryCaptureNote = "封存由运维命令 scripts/library-capture.sh capture -scope internal|external 在目标主机执行(停写入者→导出→恢复)。页面只读展示已封存的候选;候选不等于验收通过或可发布。"
|
||||
|
||||
func librarySnapshotsList(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
view, err := readLibrarySnapshots(config.LibraryArchiveRoot)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, librarySnapshotList{Available: false,
|
||||
Reason: "归档不可读:" + err.Error(), Snapshots: []librarySnapshotView{}, CaptureNote: libraryCaptureNote})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, view)
|
||||
}
|
||||
|
||||
func librarySnapshotDetail(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
id := strings.TrimSpace(r.PathValue("id"))
|
||||
if id == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "snapshot id required"})
|
||||
return
|
||||
}
|
||||
if config.LibraryArchiveRoot == "" {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"available": false,
|
||||
"reason": "未接线:LIBRARY_ARCHIVE_ROOT 未配置,本平台没有整库归档可读"})
|
||||
return
|
||||
}
|
||||
archive, err := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false, "reason": "归档不可读"})
|
||||
return
|
||||
}
|
||||
defer archive.Close()
|
||||
manifest, err := archive.Load(id)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusNotFound, map[string]any{"available": false, "reason": "快照不存在或校验失败"})
|
||||
return
|
||||
}
|
||||
usage, err := archive.Usage()
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false, "reason": "归档用量不可读"})
|
||||
return
|
||||
}
|
||||
view, ok := librarySnapshotViewOf(id, manifest, usage)
|
||||
if !ok {
|
||||
view = librarySnapshotViewOfNoUsage(id, manifest)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"available": true, "snapshot": view, "capture_note": libraryCaptureNote})
|
||||
}
|
||||
|
||||
func readLibrarySnapshots(root string) (librarySnapshotList, error) {
|
||||
view := librarySnapshotList{Snapshots: []librarySnapshotView{}, CaptureNote: libraryCaptureNote}
|
||||
if root == "" {
|
||||
view.Reason = "未接线:LIBRARY_ARCHIVE_ROOT 未配置,本平台没有整库归档可读"
|
||||
return view, nil
|
||||
}
|
||||
view.ArchiveRoot = root
|
||||
archive, err := librarysnapshot.Open(root, 256*1024*1024)
|
||||
if err != nil {
|
||||
return view, errors.New("归档根不可用")
|
||||
}
|
||||
defer archive.Close()
|
||||
usage, err := archive.Usage()
|
||||
if err != nil {
|
||||
return view, errors.New("归档用量不可读")
|
||||
}
|
||||
byID := map[string]librarysnapshot.Usage{}
|
||||
for _, item := range usage {
|
||||
byID[item.VersionID] = item
|
||||
view.StoredBytes += item.UniqueBytes
|
||||
}
|
||||
for id, item := range byID {
|
||||
manifest, loadErr := archive.Load(id)
|
||||
if loadErr != nil {
|
||||
return view, errors.New("归档快照校验失败")
|
||||
}
|
||||
snapshot, ok := librarySnapshotViewOf(id, manifest, []librarysnapshot.Usage{item})
|
||||
if !ok {
|
||||
snapshot = librarySnapshotViewOfNoUsage(id, manifest)
|
||||
}
|
||||
view.Snapshots = append(view.Snapshots, snapshot)
|
||||
}
|
||||
sort.Slice(view.Snapshots, func(i, j int) bool {
|
||||
if view.Snapshots[i].CreatedAt.Equal(view.Snapshots[j].CreatedAt) {
|
||||
return view.Snapshots[i].SnapshotID > view.Snapshots[j].SnapshotID
|
||||
}
|
||||
return view.Snapshots[i].CreatedAt.After(view.Snapshots[j].CreatedAt)
|
||||
})
|
||||
view.Available = true
|
||||
return view, nil
|
||||
}
|
||||
|
||||
func librarySnapshotViewOf(id string, manifest librarysnapshot.Manifest, usage []librarysnapshot.Usage) (librarySnapshotView, bool) {
|
||||
snapshot := librarySnapshotViewOfNoUsage(id, manifest)
|
||||
for _, item := range usage {
|
||||
if item.VersionID == id {
|
||||
snapshot.LogicalBytes = item.LogicalBytes
|
||||
snapshot.UniqueBytes = item.UniqueBytes
|
||||
snapshot.SharedBytes = item.SharedBytes
|
||||
return snapshot, true
|
||||
}
|
||||
}
|
||||
return snapshot, false
|
||||
}
|
||||
|
||||
func librarySnapshotViewOfNoUsage(id string, manifest librarysnapshot.Manifest) librarySnapshotView {
|
||||
snapshot := librarySnapshotView{SnapshotID: id, Scope: manifest.Scope, KnowledgeBaseID: manifest.KnowledgeBaseID,
|
||||
TenantID: manifest.TenantID, CreatedAt: manifest.CreatedAt, ValidationPolicy: manifest.ValidationPolicy,
|
||||
Format: manifest.Format, Compatibility: manifest.Compatibility, Parts: make([]librarySnapshotPart, 0, len(manifest.Parts)),
|
||||
Totals: map[string]int64{}}
|
||||
for _, part := range manifest.Parts {
|
||||
snapshot.Parts = append(snapshot.Parts, librarySnapshotPart{Kind: part.Kind, Name: part.Name,
|
||||
SHA256: part.SHA256, Count: part.Count, Bytes: part.Bytes})
|
||||
snapshot.LogicalBytes += part.Bytes
|
||||
// 汇总按"数量字段"给出人看得懂的四个数字:文档/分块/索引/资源/Wiki 页。
|
||||
switch part.Name {
|
||||
case "knowledges":
|
||||
snapshot.Totals["documents"] = part.Count
|
||||
case "chunks":
|
||||
if part.Kind == "database" {
|
||||
snapshot.Totals["chunks"] = part.Count
|
||||
} else {
|
||||
snapshot.Totals["index_documents"] = part.Count
|
||||
}
|
||||
case "resources":
|
||||
snapshot.Totals["resources"] = part.Count
|
||||
case "wiki_pages":
|
||||
snapshot.Totals["wiki_pages"] = part.Count
|
||||
case "wiki_folders":
|
||||
snapshot.Totals["wiki_folders"] = part.Count
|
||||
}
|
||||
}
|
||||
sort.Slice(snapshot.Parts, func(i, j int) bool {
|
||||
if snapshot.Parts[i].Kind == snapshot.Parts[j].Kind {
|
||||
return snapshot.Parts[i].Name < snapshot.Parts[j].Name
|
||||
}
|
||||
return snapshot.Parts[i].Kind < snapshot.Parts[j].Kind
|
||||
})
|
||||
return snapshot
|
||||
}
|
||||
@@ -127,8 +127,10 @@ type Config struct {
|
||||
// 所在主机上读回/下发计划并触发一次整库备份(未接线时页面降级展示)。
|
||||
// VersionHistory 是「版本记录」页的只读查询面;VersionHistoryRepo 是固定的仓库标识
|
||||
// (owner/name)。两者都给才接线,否则页面降级为"未接线"(不报 500)。
|
||||
VersionHistory VersionHistoryStore
|
||||
VersionHistoryRepo string
|
||||
VersionHistory VersionHistoryStore
|
||||
VersionHistoryRepo string
|
||||
// LibraryArchiveRoot 是整库封存产物的只读归档根;留空即未接线(页面降级)。
|
||||
LibraryArchiveRoot string
|
||||
BackupSchedule BackupScheduleStore
|
||||
BackupHost BackupHost
|
||||
BackupRuns *BackupRunTracker
|
||||
@@ -387,6 +389,13 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("GET /api/v1/build-info", func(w http.ResponseWriter, r *http.Request) {
|
||||
buildInfo(w, r)
|
||||
})
|
||||
// 整库版本(只读):列出已封存的整库候选产物与其分项数量/字节/摘要。
|
||||
mux.HandleFunc("GET /api/v1/library/snapshots", func(w http.ResponseWriter, r *http.Request) {
|
||||
librarySnapshotsList(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/library/snapshots/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
librarySnapshotDetail(w, r, config)
|
||||
})
|
||||
// 全部 main 提交时间线(读本库缓存,不直接打 Gitea)
|
||||
mux.HandleFunc("GET /api/v1/version-history", func(w http.ResponseWriter, r *http.Request) {
|
||||
versionHistoryList(w, r, config)
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
package libraryfreeze
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A deployed test stack owns its containers: it cannot be relabelled without
|
||||
// recreating it, which would be a change to that stack rather than to this
|
||||
// platform. ProjectController therefore pins the writer group by the identity
|
||||
// the stack already carries: the Compose project and the exact service names.
|
||||
//
|
||||
// Safety properties (the reason this is not a name filter):
|
||||
// - the whole Compose project is enumerated, not just the running subset;
|
||||
// - every service in the project must be declared, either as a writer or as
|
||||
// explicitly non-writing with a reason, so a new sibling container cannot
|
||||
// be silently omitted from the maintenance window;
|
||||
// - container IDs are pinned on first inventory, so a recreated container is
|
||||
// refused instead of being stopped by a stale identity;
|
||||
// - only SIGTERM is sent and start waits for health, exactly like the
|
||||
// label-scoped controller.
|
||||
type ProjectController struct {
|
||||
project string
|
||||
writers map[string]bool
|
||||
nonWriter map[string]string
|
||||
timeout time.Duration
|
||||
client *http.Client
|
||||
transport *http.Transport
|
||||
pinned map[string]string
|
||||
}
|
||||
|
||||
const composeProjectLabel = "com.docker.compose.project"
|
||||
const composeServiceLabel = "com.docker.compose.service"
|
||||
|
||||
// NewProjectController validates the declaration. nonWriter must explain every
|
||||
// service in the project which is not a writer; an empty reason is rejected.
|
||||
func NewProjectController(socket, project string, writers []string, nonWriter map[string]string, timeout time.Duration) (*ProjectController, error) {
|
||||
if !filepath.IsAbs(socket) || !validID(project) || timeout <= 0 || timeout > 5*time.Minute || len(writers) == 0 || len(writers) > 32 {
|
||||
return nil, errors.New("invalid project Docker controller configuration")
|
||||
}
|
||||
set := map[string]bool{}
|
||||
for _, name := range writers {
|
||||
if !validID(name) || set[name] {
|
||||
return nil, errors.New("invalid project writer declaration")
|
||||
}
|
||||
if _, both := nonWriter[name]; both {
|
||||
return nil, errors.New("project service declared as both writer and non-writer")
|
||||
}
|
||||
set[name] = true
|
||||
}
|
||||
for name, reason := range nonWriter {
|
||||
if !validID(name) || strings.TrimSpace(reason) == "" {
|
||||
return nil, errors.New("invalid non-writer declaration")
|
||||
}
|
||||
}
|
||||
info, err := os.Stat(socket)
|
||||
if err != nil || info.Mode()&os.ModeSocket == 0 {
|
||||
return nil, errors.New("local Docker socket unavailable")
|
||||
}
|
||||
transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{}).DialContext(ctx, "unix", socket)
|
||||
}}
|
||||
client := &http.Client{Transport: transport, Timeout: timeout, CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return errors.New("Docker redirects prohibited")
|
||||
}}
|
||||
return &ProjectController{project: project, writers: set, nonWriter: nonWriter, timeout: timeout,
|
||||
client: client, transport: transport, pinned: map[string]string{}}, nil
|
||||
}
|
||||
|
||||
func (p *ProjectController) Close() { p.transport.CloseIdleConnections() }
|
||||
|
||||
func (p *ProjectController) request(ctx context.Context, method, path string, out any) error {
|
||||
req, err := http.NewRequestWithContext(ctx, method, "http://docker"+path, nil)
|
||||
if err != nil {
|
||||
return errors.New("invalid Docker request")
|
||||
}
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return errors.New("project Docker request failed")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return errors.New("project Docker request rejected")
|
||||
}
|
||||
if out != nil {
|
||||
data, readErr := io.ReadAll(io.LimitReader(resp.Body, 1024*1024+1))
|
||||
if readErr != nil || len(data) > 1024*1024 || json.Unmarshal(data, out) != nil {
|
||||
return errors.New("invalid Docker response")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type projectInspection struct {
|
||||
ID string `json:"Id"`
|
||||
Config struct {
|
||||
Labels map[string]string `json:"Labels"`
|
||||
Image string `json:"Image"`
|
||||
} `json:"Config"`
|
||||
State struct {
|
||||
Running bool
|
||||
Paused bool
|
||||
Restarting bool
|
||||
Dead bool
|
||||
Status string
|
||||
Health *struct{ Status string }
|
||||
} `json:"State"`
|
||||
}
|
||||
|
||||
// service resolves one container to its declared service name, refusing any
|
||||
// container which does not belong to the declared project.
|
||||
func (p *ProjectController) service(data projectInspection) (string, error) {
|
||||
if data.Config.Labels[composeProjectLabel] != p.project {
|
||||
return "", errors.New("container is not part of the declared project")
|
||||
}
|
||||
name := data.Config.Labels[composeServiceLabel]
|
||||
if !p.writers[name] {
|
||||
return "", errors.New("container service is not a declared writer")
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
func (p *ProjectController) inspect(ctx context.Context, id string) (Service, error) {
|
||||
if !dockerID(id) {
|
||||
return Service{}, errors.New("immutable Docker ID required")
|
||||
}
|
||||
var data projectInspection
|
||||
if err := p.request(ctx, "GET", "/containers/"+id+"/json", &data); err != nil {
|
||||
return Service{}, err
|
||||
}
|
||||
if data.ID != id {
|
||||
return Service{}, errors.New("container identity mismatch")
|
||||
}
|
||||
name, err := p.service(data)
|
||||
if err != nil {
|
||||
return Service{}, err
|
||||
}
|
||||
if pinned, ok := p.pinned[name]; ok && pinned != id {
|
||||
return Service{}, errors.New("declared project writer identity changed")
|
||||
}
|
||||
if data.State.Paused || data.State.Restarting || data.State.Dead {
|
||||
return Service{}, errors.New("project writer has unstable runtime state")
|
||||
}
|
||||
if data.State.Status != "running" && data.State.Status != "exited" && data.State.Status != "created" {
|
||||
return Service{}, errors.New("unknown project writer runtime state")
|
||||
}
|
||||
if data.State.Running != (data.State.Status == "running") {
|
||||
return Service{}, errors.New("contradictory project writer state")
|
||||
}
|
||||
healthy := data.State.Running && data.State.Health != nil && data.State.Health.Status == "healthy"
|
||||
return Service{ID: id, Running: data.State.Running, Healthy: healthy}, nil
|
||||
}
|
||||
|
||||
// Inventory enumerates the complete project writer group and rejects an
|
||||
// incomplete or extended declaration.
|
||||
func (p *ProjectController) Inventory(ctx context.Context) ([]Service, error) {
|
||||
filters, _ := json.Marshal(map[string][]string{"label": {composeProjectLabel + "=" + p.project}})
|
||||
var containers []struct {
|
||||
ID string `json:"Id"`
|
||||
Labels map[string]string `json:"Labels"`
|
||||
}
|
||||
if err := p.request(ctx, "GET", "/containers/json?all=1&filters="+url.QueryEscape(string(filters)), &containers); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(containers) == 0 || len(containers) > 256 {
|
||||
return nil, errors.New("empty or oversized project container group")
|
||||
}
|
||||
byService := map[string]string{}
|
||||
for _, container := range containers {
|
||||
service := container.Labels[composeServiceLabel]
|
||||
if service == "" {
|
||||
return nil, errors.New("project container without a compose service label")
|
||||
}
|
||||
if _, duplicate := byService[service]; duplicate {
|
||||
return nil, errors.New("duplicate project service instance")
|
||||
}
|
||||
if !p.writers[service] {
|
||||
if _, declared := p.nonWriter[service]; declared {
|
||||
continue
|
||||
}
|
||||
return nil, errors.New("undeclared project service " + service)
|
||||
}
|
||||
byService[service] = container.ID
|
||||
}
|
||||
for name := range p.writers {
|
||||
if byService[name] == "" {
|
||||
return nil, errors.New("declared project writer is missing")
|
||||
}
|
||||
}
|
||||
items := make([]Service, 0, len(byService))
|
||||
for _, id := range byService {
|
||||
s, err := p.inspect(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, s)
|
||||
}
|
||||
// Pin after every successful inventory so a later recreation is visible even
|
||||
// when the coordinator journal is inspected outside a run.
|
||||
for name, id := range byService {
|
||||
p.pinned[name] = id
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool { return items[i].ID < items[j].ID })
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (p *ProjectController) wait(ctx context.Context, id string, running bool) error {
|
||||
ticker := time.NewTicker(100 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
s, err := p.inspect(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.Running == running && (!running || s.Healthy) {
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return errors.New("project writer state did not settle before deadline")
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Stop sends SIGTERM only; there is no delayed SIGKILL which could fire after
|
||||
// recovery starts the container again.
|
||||
func (p *ProjectController) Stop(ctx context.Context, id string) error {
|
||||
bounded, cancel := context.WithTimeout(ctx, p.timeout)
|
||||
defer cancel()
|
||||
s, err := p.inspect(bounded, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !s.Running {
|
||||
return nil
|
||||
}
|
||||
if err = p.request(bounded, "POST", "/containers/"+id+"/kill?signal=SIGTERM", nil); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.wait(bounded, id, false)
|
||||
}
|
||||
|
||||
func (p *ProjectController) Start(ctx context.Context, id string) error {
|
||||
bounded, cancel := context.WithTimeout(ctx, p.timeout)
|
||||
defer cancel()
|
||||
s, err := p.inspect(bounded, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !s.Running {
|
||||
if err = p.request(bounded, "POST", "/containers/"+id+"/start", nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return p.wait(bounded, id, true)
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package libraryfreeze
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type projectFixture struct {
|
||||
appID string
|
||||
frontID string
|
||||
appRunning bool
|
||||
appHealthy bool
|
||||
signals []string
|
||||
services []string
|
||||
}
|
||||
|
||||
func newProjectFixture(t *testing.T) (*projectFixture, string) {
|
||||
t.Helper()
|
||||
f := &projectFixture{
|
||||
appID: strings.Repeat("a", 64),
|
||||
frontID: strings.Repeat("b", 64),
|
||||
appRunning: true,
|
||||
appHealthy: true,
|
||||
services: []string{"app", "frontend"},
|
||||
}
|
||||
// A short path: unix socket addresses are length-limited and t.TempDir()
|
||||
// embeds the (long) test name.
|
||||
root, err := os.MkdirTemp(os.TempDir(), "kgp-")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(root) })
|
||||
socket := filepath.Join(root, "engine.sock")
|
||||
listener, err := net.Listen("unix", socket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
labels := func(service string) map[string]string {
|
||||
return map[string]string{composeProjectLabel: "weknora", composeServiceLabel: service}
|
||||
}
|
||||
server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/containers/json"):
|
||||
if !strings.Contains(r.URL.Query().Get("filters"), "weknora") {
|
||||
t.Error("missing project filter")
|
||||
}
|
||||
items := []map[string]any{}
|
||||
for _, service := range f.services {
|
||||
id := f.appID
|
||||
if service == "frontend" {
|
||||
id = f.frontID
|
||||
}
|
||||
items = append(items, map[string]any{"Id": id, "Labels": labels(service)})
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(items)
|
||||
case r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/json"):
|
||||
id := strings.TrimPrefix(strings.TrimSuffix(r.URL.Path, "/json"), "/containers/")
|
||||
service := "app"
|
||||
if id == f.frontID {
|
||||
service = "frontend"
|
||||
}
|
||||
status := "exited"
|
||||
health := any(nil)
|
||||
if id == f.appID && f.appRunning {
|
||||
status = "running"
|
||||
if f.appHealthy {
|
||||
health = map[string]string{"Status": "healthy"}
|
||||
} else {
|
||||
health = map[string]string{"Status": "starting"}
|
||||
}
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"Id": id, "Config": map[string]any{"Labels": labels(service)},
|
||||
"State": map[string]any{"Running": id == f.appID && f.appRunning, "Status": status, "Health": health}})
|
||||
case r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/kill"):
|
||||
if r.URL.Query().Get("signal") != "SIGTERM" {
|
||||
t.Error("unsafe stop signal")
|
||||
}
|
||||
if !strings.Contains(r.URL.Path, f.appID) {
|
||||
t.Error("stopped an undeclared container")
|
||||
}
|
||||
f.signals = append(f.signals, "stop")
|
||||
f.appRunning = false
|
||||
w.WriteHeader(204)
|
||||
case r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/start"):
|
||||
f.signals = append(f.signals, "start")
|
||||
f.appRunning = true
|
||||
w.WriteHeader(204)
|
||||
default:
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
})}
|
||||
go server.Serve(listener)
|
||||
t.Cleanup(func() { server.Close() })
|
||||
return f, socket
|
||||
}
|
||||
|
||||
func TestProjectControllerStopsOnlyDeclaredWritersByPinnedIdentity(t *testing.T) {
|
||||
fixture, socket := newProjectFixture(t)
|
||||
control, err := NewProjectController(socket, "weknora", []string{"app"},
|
||||
map[string]string{"frontend": "serves the UI only; never writes knowledge"}, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer control.Close()
|
||||
items, err := control.Inventory(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(items) != 1 || items[0].ID != fixture.appID || !items[0].Running || !items[0].Healthy {
|
||||
t.Fatalf("unexpected writer inventory %+v", items)
|
||||
}
|
||||
if err = control.Stop(context.Background(), fixture.appID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fixture.appRunning {
|
||||
t.Fatal("writer still running after stop")
|
||||
}
|
||||
if err = control.Start(context.Background(), fixture.appID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fixture.signals) != 2 || fixture.signals[0] != "stop" || fixture.signals[1] != "start" {
|
||||
t.Fatalf("unexpected signal order %v", fixture.signals)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectControllerRefusesUndeclaredSibling(t *testing.T) {
|
||||
fixture, socket := newProjectFixture(t)
|
||||
control, err := NewProjectController(socket, "weknora", []string{"app"}, map[string]string{}, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer control.Close()
|
||||
if _, err = control.Inventory(context.Background()); err == nil {
|
||||
t.Fatal("undeclared sibling service was accepted")
|
||||
}
|
||||
if len(fixture.signals) != 0 {
|
||||
t.Fatal("refused inventory still signalled a container")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectControllerRefusesReplacedContainerIdentity(t *testing.T) {
|
||||
fixture, socket := newProjectFixture(t)
|
||||
control, err := NewProjectController(socket, "weknora", []string{"app"},
|
||||
map[string]string{"frontend": "serves the UI only; never writes knowledge"}, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer control.Close()
|
||||
if _, err = control.Inventory(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A recreated container keeps the service name but is a different instance:
|
||||
// stopping it would hit a container the maintenance window never declared.
|
||||
fixture.appID = strings.Repeat("c", 64)
|
||||
if _, err = control.Inventory(context.Background()); err == nil {
|
||||
t.Fatal("recreated writer identity was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectControllerWaitsForHealthOnStart(t *testing.T) {
|
||||
fixture, socket := newProjectFixture(t)
|
||||
control, err := NewProjectController(socket, "weknora", []string{"app"},
|
||||
map[string]string{"frontend": "serves the UI only; never writes knowledge"}, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer control.Close()
|
||||
if _, err = control.Inventory(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fixture.appRunning = false
|
||||
fixture.appHealthy = false
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
|
||||
defer cancel()
|
||||
if err = control.Start(ctx, fixture.appID); err == nil {
|
||||
t.Fatal("start succeeded without health")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// Operator preflight surface. These wrappers expose the *same* checks used by
|
||||
// the capture path so an operator command can inspect a real source without
|
||||
// sealing an artifact, stopping a writer, or writing anything. They add no new
|
||||
// acceptance rule: a preflight which passes here is still only a candidate.
|
||||
//
|
||||
// Nothing here authorizes publication: artifact-acceptance-v1 still requires
|
||||
// snapshot-bound content, question/answer and performance acceptance, and
|
||||
// production release remains a separate, double-gated decision.
|
||||
|
||||
// LibrarySourceSettled reports whether the whole source database has finished
|
||||
// recorded processing. It is the identical query CaptureLibrary enforces before
|
||||
// and inside the maintenance window.
|
||||
func LibrarySourceSettled(ctx context.Context, db *pgxpool.Pool) error {
|
||||
return checkLibrarySourceSettlement(ctx, db)
|
||||
}
|
||||
|
||||
// ValidateLibraryCandidateForPreflight runs the candidate validator used by
|
||||
// ArchiveLibraryCandidate (identity, bidirectional content coverage, generated
|
||||
// question coverage, resources and digests) without archiving anything.
|
||||
func ValidateLibraryCandidateForPreflight(identity PostgresIdentity, pg PostgresSnapshot, es SearchSnapshot) error {
|
||||
return validateLibraryCandidate(identity, pg, es)
|
||||
}
|
||||
|
||||
// LibraryContentTables is the stable list of PostgreSQL tables a library
|
||||
// snapshot must contain, so an operator view does not hard-code table names.
|
||||
func LibraryContentTables() []string {
|
||||
names := make([]string, 0, len(libraryContentQueries)+1)
|
||||
names = append(names, "resources")
|
||||
for _, entry := range libraryContentQueries {
|
||||
names = append(names, entry.name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// LibrarySnapshotCompatibility is the archive-level compatibility contract.
|
||||
type LibrarySnapshotCompatibility = librarysnapshot.Compatibility
|
||||
Reference in New Issue
Block a user