删掉会自己开入口、只看服务健康的 FinalizeAfterOperatorRecovery。 新的 RecoverWindow 绑定原作业/目标指纹/持久化预备份,在维护关闭下 执行恢复与逐类校验,通过才恢复服务与入口;失败继续维护。 预备份身份与内容风险在第一笔写入前一起落盘;后台任务必须静默后才停写者; 写入者发布端口即拒绝开窗口;维护占用改为按实例互斥(000072)。
This commit is contained in:
@@ -0,0 +1,141 @@
|
||||
package librarymaintenance
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
// dockerAPI 是目标维护用到的 Docker Engine 最小客户端(unix socket)。
|
||||
// 入口闸门与拓扑校验共用同一份实现:两处各自拼一套请求只会长出两套毛病。
|
||||
type dockerAPI struct {
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func newDockerAPI(socket string, timeout time.Duration) (*dockerAPI, error) {
|
||||
if socket == "" || timeout <= 0 {
|
||||
return nil, errors.New("invalid docker api configuration")
|
||||
}
|
||||
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)
|
||||
}}
|
||||
return &dockerAPI{client: &http.Client{Transport: transport, Timeout: timeout,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("docker redirects prohibited") }}}, nil
|
||||
}
|
||||
|
||||
func (d *dockerAPI) Close() { d.client.CloseIdleConnections() }
|
||||
|
||||
func (d *dockerAPI) 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 := d.client.Do(req)
|
||||
if err != nil {
|
||||
return errors.New("docker request failed")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("docker request rejected: %d", resp.StatusCode)
|
||||
}
|
||||
if out != nil {
|
||||
data, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if readErr != nil || json.Unmarshal(data, out) != nil {
|
||||
return errors.New("invalid docker response")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type containerSummary struct {
|
||||
ID string `json:"Id"`
|
||||
Labels map[string]string `json:"Labels"`
|
||||
Ports []struct {
|
||||
PrivatePort int `json:"PrivatePort"`
|
||||
PublicPort int `json:"PublicPort"`
|
||||
Type string `json:"Type"`
|
||||
} `json:"Ports"`
|
||||
}
|
||||
|
||||
func (d *dockerAPI) listProject(ctx context.Context, project string) ([]containerSummary, error) {
|
||||
filters, _ := json.Marshal(map[string][]string{"label": {"com.docker.compose.project=" + project}})
|
||||
var items []containerSummary
|
||||
if err := d.request(ctx, "GET", "/containers/json?all=1&filters="+url.QueryEscape(string(filters)), &items); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
type containerState struct {
|
||||
ID string `json:"Id"`
|
||||
Labels map[string]string `json:"Config"`
|
||||
Config struct {
|
||||
Labels map[string]string `json:"Labels"`
|
||||
} `json:"-"`
|
||||
State struct {
|
||||
Running bool
|
||||
Status string
|
||||
ExitCode int
|
||||
Health *struct{ Status string }
|
||||
} `json:"State"`
|
||||
HostConfig struct {
|
||||
PortBindings map[string][]struct {
|
||||
HostIP string `json:"HostIp"`
|
||||
HostPort string `json:"HostPort"`
|
||||
} `json:"PortBindings"`
|
||||
} `json:"HostConfig"`
|
||||
NetworkSettings struct {
|
||||
Ports map[string][]struct {
|
||||
HostIP string `json:"HostIp"`
|
||||
HostPort string `json:"HostPort"`
|
||||
} `json:"Ports"`
|
||||
} `json:"NetworkSettings"`
|
||||
}
|
||||
|
||||
func (d *dockerAPI) inspect(ctx context.Context, id string) (containerState, error) {
|
||||
var data containerState
|
||||
if err := d.request(ctx, "GET", "/containers/"+id+"/json", &data); err != nil {
|
||||
return containerState{}, err
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// publishedPorts 返回容器对外发布的端口(HostConfig + NetworkSettings 都算)。
|
||||
// 写入者只要发布了一个端口,就存在"绕开入口闸门直连"的通道。
|
||||
func (c containerState) publishedPorts() []string {
|
||||
seen := map[string]bool{}
|
||||
out := make([]string, 0, 2)
|
||||
add := func(hostIP, hostPort, containerPort string) {
|
||||
if hostPort == "" || hostPort == "0" {
|
||||
return
|
||||
}
|
||||
key := hostIP + ":" + hostPort + "->" + containerPort
|
||||
if seen[key] {
|
||||
return
|
||||
}
|
||||
seen[key] = true
|
||||
out = append(out, key)
|
||||
}
|
||||
for port, bindings := range c.HostConfig.PortBindings {
|
||||
for _, binding := range bindings {
|
||||
add(binding.HostIP, binding.HostPort, port)
|
||||
}
|
||||
}
|
||||
for port, bindings := range c.NetworkSettings.Ports {
|
||||
for _, binding := range bindings {
|
||||
add(binding.HostIP, binding.HostPort, port)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -6,11 +6,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/libraryfreeze"
|
||||
@@ -20,8 +16,7 @@ import (
|
||||
// 闸门自己写下的 drain.json(停止接客时还有多少在途连接、最后是否归零)。
|
||||
// 不看 HTTP 探测就宣布"入口关了"——那是猜。
|
||||
type dockerGate struct {
|
||||
client *http.Client
|
||||
socket string
|
||||
api *dockerAPI
|
||||
project string
|
||||
service string
|
||||
drainFile string
|
||||
@@ -29,79 +24,41 @@ type dockerGate struct {
|
||||
}
|
||||
|
||||
func newDockerGate(socket, project, service, drainFile string, timeout time.Duration) (*dockerGate, error) {
|
||||
if !filepath.IsAbs(socket) || project == "" || service == "" || !filepath.IsAbs(drainFile) {
|
||||
if project == "" || service == "" || drainFile == "" || drainFile[0] != '/' {
|
||||
return nil, errors.New("入口闸门配置不完整")
|
||||
}
|
||||
info, err := os.Stat(socket)
|
||||
if err != nil || info.Mode()&os.ModeSocket == 0 {
|
||||
return nil, errors.New("local Docker socket unavailable")
|
||||
api, err := newDockerAPI(socket, timeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{}).DialContext(ctx, "unix", socket)
|
||||
}}
|
||||
return &dockerGate{
|
||||
client: &http.Client{Transport: transport, Timeout: timeout,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("docker redirects prohibited") }},
|
||||
socket: socket, project: project, service: service, drainFile: drainFile, timeout: timeout,
|
||||
}, nil
|
||||
return &dockerGate{api: api, project: project, service: service, drainFile: drainFile, timeout: timeout}, nil
|
||||
}
|
||||
|
||||
func (g *dockerGate) request(ctx context.Context, method, path string, out any) error {
|
||||
req, err := http.NewRequestWithContext(ctx, method, "http://docker"+path, nil)
|
||||
func (g *dockerGate) container(ctx context.Context) (containerState, error) {
|
||||
items, err := g.api.listProject(ctx, g.project)
|
||||
if err != nil {
|
||||
return errors.New("invalid docker request")
|
||||
return containerState{}, err
|
||||
}
|
||||
resp, err := g.client.Do(req)
|
||||
if err != nil {
|
||||
return errors.New("docker request failed")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("docker request rejected: %d", resp.StatusCode)
|
||||
}
|
||||
if out != nil {
|
||||
data, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if readErr != nil || json.Unmarshal(data, out) != nil {
|
||||
return errors.New("invalid docker response")
|
||||
id := ""
|
||||
for _, item := range items {
|
||||
if item.Labels["com.docker.compose.service"] != g.service {
|
||||
continue
|
||||
}
|
||||
if id != "" {
|
||||
return containerState{}, fmt.Errorf("入口闸门实例数异常:多于一个 %s", g.service)
|
||||
}
|
||||
id = item.ID
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type gateInspection struct {
|
||||
ID string `json:"Id"`
|
||||
Config struct {
|
||||
Labels map[string]string `json:"Labels"`
|
||||
} `json:"Config"`
|
||||
State struct {
|
||||
Running bool
|
||||
Status string
|
||||
ExitCode int
|
||||
Health *struct{ Status string }
|
||||
} `json:"State"`
|
||||
}
|
||||
|
||||
func (g *dockerGate) container(ctx context.Context) (gateInspection, error) {
|
||||
filters, _ := json.Marshal(map[string][]string{"label": {
|
||||
"com.docker.compose.project=" + g.project,
|
||||
"com.docker.compose.service=" + g.service,
|
||||
}})
|
||||
var listed []struct {
|
||||
ID string `json:"Id"`
|
||||
if id == "" {
|
||||
return containerState{}, fmt.Errorf("找不到入口闸门服务 %s", g.service)
|
||||
}
|
||||
if err := g.request(ctx, "GET", "/containers/json?all=1&filters="+url.QueryEscape(string(filters)), &listed); err != nil {
|
||||
return gateInspection{}, err
|
||||
}
|
||||
if len(listed) != 1 {
|
||||
return gateInspection{}, fmt.Errorf("入口闸门实例数异常:%d", len(listed))
|
||||
}
|
||||
var data gateInspection
|
||||
if err := g.request(ctx, "GET", "/containers/"+listed[0].ID+"/json", &data); err != nil {
|
||||
return gateInspection{}, err
|
||||
data, err := g.api.inspect(ctx, id)
|
||||
if err != nil {
|
||||
return containerState{}, err
|
||||
}
|
||||
if data.Config.Labels["com.docker.compose.project"] != g.project ||
|
||||
data.Config.Labels["com.docker.compose.service"] != g.service {
|
||||
return gateInspection{}, errors.New("入口闸门身份不匹配")
|
||||
return containerState{}, errors.New("入口闸门身份不匹配")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
@@ -151,7 +108,7 @@ func (g *dockerGate) CloseIngress(ctx context.Context) (libraryfreeze.GateEviden
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return libraryfreeze.GateEvidence{}, fmt.Errorf("无法确认排空记录已清理:%w", err)
|
||||
}
|
||||
if err := g.request(bounded, "POST", "/containers/"+data.ID+"/kill?signal=SIGTERM", nil); err != nil {
|
||||
if err := g.api.request(bounded, "POST", "/containers/"+data.ID+"/kill?signal=SIGTERM", nil); err != nil {
|
||||
return libraryfreeze.GateEvidence{}, err
|
||||
}
|
||||
deadline := time.Now().Add(g.timeout)
|
||||
@@ -202,7 +159,7 @@ func (g *dockerGate) OpenIngress(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
if !data.State.Running {
|
||||
if err := g.request(bounded, "POST", "/containers/"+data.ID+"/start", nil); err != nil {
|
||||
if err := g.api.request(bounded, "POST", "/containers/"+data.ID+"/start", nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
package librarymaintenance
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// targetQuiescer 回答"后台写入者是不是已经空了":
|
||||
// - 目标库:未结清的后台操作、未完成的解析(这两张表就是 app 的后台账本);
|
||||
// - 目标队列:asynq 里还在排队/在跑/待重试的任务。
|
||||
//
|
||||
// 为什么要单独做:HTTP 入口排空只覆盖连接;app 内的 asynq worker 会被上游的
|
||||
// SIGTERM exit(1) 切断,正在跑的任务就这样被腰斩。窗口必须先等它们结束。
|
||||
type targetQuiescer struct {
|
||||
pool *pgxpool.Pool
|
||||
redisAddr string
|
||||
redisPass string
|
||||
redisDB int
|
||||
timeout time.Duration
|
||||
queueMatch string
|
||||
}
|
||||
|
||||
func newTargetQuiescer(ctx context.Context, databaseURL, redisAddr, redisPass string, redisDB int, timeout time.Duration) (*targetQuiescer, error) {
|
||||
if databaseURL == "" || redisAddr == "" {
|
||||
return nil, errors.New("后台静默检查缺少目标库或队列地址")
|
||||
}
|
||||
pool, err := pgxpool.New(ctx, databaseURL)
|
||||
if err != nil {
|
||||
return nil, errors.New("后台静默检查连不上目标库")
|
||||
}
|
||||
if timeout <= 0 {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
return &targetQuiescer{pool: pool, redisAddr: redisAddr, redisPass: redisPass, redisDB: redisDB,
|
||||
timeout: timeout, queueMatch: "asynq:*"}, nil
|
||||
}
|
||||
|
||||
func (q *targetQuiescer) Close() { q.pool.Close() }
|
||||
|
||||
func (q *targetQuiescer) Idle(ctx context.Context) (bool, string, error) {
|
||||
var pendingOps, unsettled int64
|
||||
// task_pending_ops / knowledges 是 app 自己的后台账本:不看它们只看 HTTP 会漏。
|
||||
if err := q.pool.QueryRow(ctx, `SELECT
|
||||
(SELECT count(*) FROM task_pending_ops),
|
||||
(SELECT count(*) FROM knowledges WHERE deleted_at IS NULL
|
||||
AND (parse_status IS DISTINCT FROM 'completed' OR pending_subtasks_count IS NULL OR pending_subtasks_count<>0))`).
|
||||
Scan(&pendingOps, &unsettled); err != nil {
|
||||
return false, "", fmt.Errorf("读不到后台账本:%w", err)
|
||||
}
|
||||
depth, err := q.queueDepth(ctx)
|
||||
if err != nil {
|
||||
return false, "", err
|
||||
}
|
||||
detail := fmt.Sprintf("pending_ops=%d unsettled_knowledges=%d asynq_active=%d", pendingOps, unsettled, depth)
|
||||
return pendingOps == 0 && unsettled == 0 && depth == 0, detail, nil
|
||||
}
|
||||
|
||||
// queueDepth 统计 asynq 里"还没结束"的任务数(排队/在跑/待重试)。
|
||||
// archived/completed 是历史,不算忙。
|
||||
func (q *targetQuiescer) queueDepth(ctx context.Context) (int64, error) {
|
||||
conn, err := dialRedis(q.redisAddr, q.redisPass, q.redisDB, q.timeout)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("连不上目标队列:%w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
keys, err := conn.scan(ctx, q.queueMatch)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("扫描目标队列失败:%w", err)
|
||||
}
|
||||
var total int64
|
||||
for _, key := range keys {
|
||||
suffix := key[strings.LastIndex(key, ":"):]
|
||||
switch suffix {
|
||||
case ":pending", ":active", ":inprogress":
|
||||
n, err := conn.intCmd(ctx, "LLEN", key)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
total += n
|
||||
case ":scheduled", ":retry":
|
||||
n, err := conn.intCmd(ctx, "ZCARD", key)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
total += n
|
||||
}
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
|
||||
// ---- 最小 RESP 客户端:只用到 AUTH/SELECT/SCAN/LLEN/ZCARD,不引第三方库 ----
|
||||
|
||||
type redisConn struct {
|
||||
conn net.Conn
|
||||
reader *bufio.Reader
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func dialRedis(addr, password string, db int, timeout time.Duration) (*redisConn, error) {
|
||||
dialer := &net.Dialer{Timeout: timeout}
|
||||
conn, err := dialer.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = conn.SetDeadline(time.Now().Add(timeout))
|
||||
c := &redisConn{conn: conn, reader: bufio.NewReader(conn), timeout: timeout}
|
||||
if password != "" {
|
||||
if _, err := c.do("AUTH", password); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if db != 0 {
|
||||
if _, err := c.do("SELECT", strconv.Itoa(db)); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *redisConn) Close() error { return c.conn.Close() }
|
||||
|
||||
func (c *redisConn) do(args ...string) (any, error) {
|
||||
_ = c.conn.SetDeadline(time.Now().Add(c.timeout))
|
||||
var builder strings.Builder
|
||||
builder.WriteString("*" + strconv.Itoa(len(args)) + "\r\n")
|
||||
for _, arg := range args {
|
||||
builder.WriteString("$" + strconv.Itoa(len(arg)) + "\r\n" + arg + "\r\n")
|
||||
}
|
||||
if _, err := c.conn.Write([]byte(builder.String())); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.read()
|
||||
}
|
||||
|
||||
func (c *redisConn) read() (any, error) {
|
||||
line, err := c.reader.ReadString('\n')
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
line = strings.TrimRight(line, "\r\n")
|
||||
if line == "" {
|
||||
return nil, errors.New("empty redis reply")
|
||||
}
|
||||
switch line[0] {
|
||||
case '+':
|
||||
return line[1:], nil
|
||||
case '-':
|
||||
return nil, errors.New(line[1:])
|
||||
case ':':
|
||||
value, err := strconv.ParseInt(line[1:], 10, 64)
|
||||
return value, err
|
||||
case '$':
|
||||
length, err := strconv.Atoi(line[1:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if length < 0 {
|
||||
return nil, nil
|
||||
}
|
||||
buf := make([]byte, length+2)
|
||||
if _, err := ioReadFull(c.reader, buf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return string(buf[:length]), nil
|
||||
case '*':
|
||||
count, err := strconv.Atoi(line[1:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]any, 0, count)
|
||||
for i := 0; i < count; i++ {
|
||||
item, err := c.read()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items, nil
|
||||
default:
|
||||
return nil, errors.New("unsupported redis reply")
|
||||
}
|
||||
}
|
||||
|
||||
func ioReadFull(reader *bufio.Reader, buf []byte) (int, error) {
|
||||
total := 0
|
||||
for total < len(buf) {
|
||||
n, err := reader.Read(buf[total:])
|
||||
total += n
|
||||
if err != nil {
|
||||
return total, err
|
||||
}
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
|
||||
func (c *redisConn) scan(ctx context.Context, match string) ([]string, error) {
|
||||
var keys []string
|
||||
cursor := "0"
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reply, err := c.do("SCAN", cursor, "MATCH", match, "COUNT", "1000")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items, ok := reply.([]any)
|
||||
if !ok || len(items) != 2 {
|
||||
return nil, errors.New("unexpected SCAN reply")
|
||||
}
|
||||
next, _ := items[0].(string)
|
||||
batch, _ := items[1].([]any)
|
||||
for _, item := range batch {
|
||||
if key, ok := item.(string); ok {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
}
|
||||
if next == "0" || next == "" {
|
||||
return keys, nil
|
||||
}
|
||||
cursor = next
|
||||
}
|
||||
}
|
||||
|
||||
func (c *redisConn) intCmd(ctx context.Context, cmd string, args ...string) (int64, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
reply, err := c.do(append([]string{cmd}, args...)...)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
value, ok := reply.(int64)
|
||||
if !ok {
|
||||
return 0, errors.New("unexpected integer reply")
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
@@ -56,7 +56,12 @@ type Config struct {
|
||||
Database string
|
||||
Index string
|
||||
Bucket string
|
||||
Timeout time.Duration
|
||||
// 后台静默检查需要的运行时依赖(不写进维护记录)。
|
||||
DatabaseURL string
|
||||
RedisAddr string
|
||||
RedisPassword string
|
||||
RedisDB int
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
type Manager struct {
|
||||
@@ -68,6 +73,18 @@ type Manager struct {
|
||||
timeout time.Duration
|
||||
client *http.Client
|
||||
gate *dockerGate
|
||||
api *dockerAPI
|
||||
quiescer *targetQuiescer
|
||||
}
|
||||
|
||||
// Close 释放拓扑/静默检查持有的连接。
|
||||
func (m *Manager) Close() {
|
||||
if m.api != nil {
|
||||
m.api.Close()
|
||||
}
|
||||
if m.quiescer != nil {
|
||||
m.quiescer.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func New(cfg Config) (*Manager, error) {
|
||||
@@ -102,9 +119,13 @@ func New(cfg Config) (*Manager, error) {
|
||||
return nil, err
|
||||
}
|
||||
target.Fingerprint = fingerprint
|
||||
api, err := newDockerAPI(cfg.DockerSocket, cfg.Timeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
manager := &Manager{target: target, source: project, docker: cfg.DockerSocket,
|
||||
writers: writers, nonWriters: cfg.NonWriters, timeout: cfg.Timeout,
|
||||
client: &http.Client{Timeout: 5 * time.Second}}
|
||||
client: &http.Client{Timeout: 5 * time.Second}, api: api}
|
||||
if cfg.IngressService != "" || cfg.IngressDrainFile != "" {
|
||||
gate, err := newDockerGate(cfg.DockerSocket, project, cfg.IngressService, cfg.IngressDrainFile, cfg.Timeout)
|
||||
if err != nil {
|
||||
@@ -112,6 +133,14 @@ func New(cfg Config) (*Manager, error) {
|
||||
}
|
||||
manager.gate = gate
|
||||
}
|
||||
if cfg.DatabaseURL != "" && cfg.RedisAddr != "" {
|
||||
quiescer, err := newTargetQuiescer(context.Background(), cfg.DatabaseURL, cfg.RedisAddr,
|
||||
cfg.RedisPassword, cfg.RedisDB, cfg.Timeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
manager.quiescer = quiescer
|
||||
}
|
||||
return manager, nil
|
||||
}
|
||||
|
||||
@@ -159,6 +188,11 @@ func (m *Manager) Open(root string) (*libraryfreeze.Coordinator, *libraryfreeze.
|
||||
control.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
if err := coordinator.SetTargetFingerprint(m.target.Fingerprint); err != nil {
|
||||
coordinator.Close()
|
||||
control.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
if m.gate != nil {
|
||||
if err := coordinator.SetGate(m.gate); err != nil {
|
||||
coordinator.Close()
|
||||
@@ -166,6 +200,17 @@ func (m *Manager) Open(root string) (*libraryfreeze.Coordinator, *libraryfreeze.
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
// 后台静默检查是实例级窗口的必备条件:没有它就等于只排空了 HTTP。
|
||||
if m.quiescer == nil {
|
||||
coordinator.Close()
|
||||
control.Close()
|
||||
return nil, nil, errors.New("缺少后台静默检查(目标库/队列未配置),拒绝开实例级窗口")
|
||||
}
|
||||
if err := coordinator.SetQuiescer(m.quiescer); err != nil {
|
||||
coordinator.Close()
|
||||
control.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
return coordinator, control, nil
|
||||
}
|
||||
|
||||
@@ -270,3 +315,82 @@ func DatabaseIdentity(raw string) (string, error) {
|
||||
}
|
||||
return parsed.Host + "/" + database, nil
|
||||
}
|
||||
|
||||
const composeServiceLabel = "com.docker.compose.service"
|
||||
|
||||
// VerifyTopology 强制"入口唯一":
|
||||
// - 写入者不许发布任何宿主机端口(否则就存在绕闸直连,维护窗口覆盖不到);
|
||||
// - 入口闸门必须存在、必须是独立服务,并且发布了入口 URL 用的那个端口。
|
||||
//
|
||||
// 任何一条不满足都拒绝开窗口——拓扑错了,"维护"就只是关了一半的门。
|
||||
func (m *Manager) VerifyTopology(ctx context.Context) error {
|
||||
items, err := m.api.listProject(ctx, m.target.Project)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
byService := make(map[string]containerSummary, len(items))
|
||||
for _, item := range items {
|
||||
name := item.Labels[composeServiceLabel]
|
||||
if name == "" {
|
||||
return errors.New("项目里有容器缺少 compose service 标签,无法确认写入者边界")
|
||||
}
|
||||
if _, duplicated := byService[name]; duplicated {
|
||||
return fmt.Errorf("项目里服务 %s 有多个实例,无法确认写入者边界", name)
|
||||
}
|
||||
byService[name] = item
|
||||
}
|
||||
for _, writer := range m.writers {
|
||||
item, ok := byService[writer]
|
||||
if !ok {
|
||||
return fmt.Errorf("声明的写入者 %s 不存在", writer)
|
||||
}
|
||||
state, err := m.api.inspect(ctx, item.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ports := state.publishedPorts(); len(ports) > 0 {
|
||||
return fmt.Errorf("写入者 %s 直接发布了端口 %s:存在绕开入口闸门的直连通道,拒绝开维护窗口",
|
||||
writer, strings.Join(ports, ","))
|
||||
}
|
||||
}
|
||||
if m.gate == nil {
|
||||
return errors.New("实例级维护必须声明入口闸门")
|
||||
}
|
||||
for _, writer := range m.writers {
|
||||
if writer == m.gate.service {
|
||||
return errors.New("入口闸门不能同时被声明为写入者")
|
||||
}
|
||||
}
|
||||
gateItem, ok := byService[m.gate.service]
|
||||
if !ok {
|
||||
return fmt.Errorf("声明的入口闸门 %s 不存在", m.gate.service)
|
||||
}
|
||||
gateState, err := m.api.inspect(ctx, gateItem.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
published := gateState.publishedPorts()
|
||||
if len(published) == 0 {
|
||||
return fmt.Errorf("入口闸门 %s 没有发布任何端口:外部无法访问,入口定义不成立", m.gate.service)
|
||||
}
|
||||
// 入口 URL 的端口必须真的是这个闸门发布的端口。
|
||||
parsed, err := url.Parse(m.target.Ingress)
|
||||
if err != nil || parsed.Host == "" {
|
||||
return errors.New("目标入口地址无效")
|
||||
}
|
||||
hostPort := parsed.Port()
|
||||
if hostPort == "" {
|
||||
if parsed.Scheme == "https" {
|
||||
hostPort = "443"
|
||||
} else {
|
||||
hostPort = "80"
|
||||
}
|
||||
}
|
||||
for _, entry := range published {
|
||||
if strings.Contains(entry, ":"+hostPort+"->") {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("入口 %s 的端口 %s 不是闸门发布的端口(%s):入口指向了别的服务",
|
||||
m.target.Ingress, hostPort, strings.Join(published, ","))
|
||||
}
|
||||
|
||||
@@ -132,3 +132,24 @@ func TestDatabaseIdentityDropsCredentials(t *testing.T) {
|
||||
t.Fatal("invalid DSN accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// 写入者只要发布了宿主机端口,就存在绕开闸门的直连通道。
|
||||
func TestPublishedPortsDetectsDirectBypass(t *testing.T) {
|
||||
var state containerState
|
||||
state.HostConfig.PortBindings = map[string][]struct {
|
||||
HostIP string `json:"HostIp"`
|
||||
HostPort string `json:"HostPort"`
|
||||
}{"8080/tcp": {{HostIP: "127.0.0.1", HostPort: "18081"}}}
|
||||
ports := state.publishedPorts()
|
||||
if len(ports) != 1 || !strings.Contains(ports[0], "18081") {
|
||||
t.Fatalf("publishedPorts=%v", ports)
|
||||
}
|
||||
var bare containerState
|
||||
bare.HostConfig.PortBindings = map[string][]struct {
|
||||
HostIP string `json:"HostIp"`
|
||||
HostPort string `json:"HostPort"`
|
||||
}{"8080/tcp": nil}
|
||||
if got := bare.publishedPorts(); len(got) != 0 {
|
||||
t.Fatalf("unpublished container reported ports: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user