6fe98c9a30
build / build (push) Successful in 1m26s
只锁治理库 scope 挡不住 WeKnora 直连和后台写入。把封存链路的 维护机制接到发布路径:持久化 owner/目标身份/原服务状态,关入口、 停写入者、验证排空与入口不可达,再写目标;写完先恢复原运行状态 与入口才释放占用。内容风险一旦落盘,重启恢复不再自动启动写入者。 新增 000071 迁移记录 level/指纹/服务/入口状态;未接线的目标直接 拒绝写,不用库级锁冒充系统维护。
276 lines
9.2 KiB
Go
276 lines
9.2 KiB
Go
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
|
|
ExitCode int
|
|
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"
|
|
// 退出码只在"已经停下"时才有意义:它证明服务是自己收尾退出的(0),
|
|
// 还是被信号切断的(143/137)。运行中的服务不提供这项证据。
|
|
var exit *int
|
|
if !data.State.Running {
|
|
code := data.State.ExitCode
|
|
exit = &code
|
|
}
|
|
return Service{ID: id, Running: data.State.Running, Healthy: healthy, ExitCode: exit}, 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)
|
|
}
|