Files

359 lines
12 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package cluster is controller-only: node selection, credentials, resource
// snapshots and operation history stay in the controller MySQL database.
package cluster
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"regexp"
"strings"
"time"
"sea-vhost/internal/controlwire"
"sea-vhost/internal/isolation"
"sea-vhost/internal/panel"
"sea-vhost/internal/scope"
"sea-vhost/internal/secrets"
"sea-vhost/internal/store"
)
var ErrUncertain = errors.New("节点操作结果待核验,未自动重试")
type Manager struct {
Store *store.Store
Box *secrets.Box
PanelSocket, AgentSocket, LocalToken string
}
type transport struct {
manager *Manager
kind string
}
func (m *Manager) Panel() *panel.BrokerClient {
return panel.NewTransportClient(&transport{manager: m, kind: "panel"}, 2*time.Hour)
}
func (m *Manager) Isolation() *isolation.Client {
return isolation.NewTransportClient(&transport{manager: m, kind: "isolation"})
}
func (m *Manager) CredentialLabel(id uint64) string { return fmt.Sprintf("node/%d/transport/v1", id) }
func (m *Manager) Pair(ctx context.Context, id uint64) (controlwire.ServerIdentity, error) {
node, err := m.Store.Node(ctx, id)
if err != nil {
return controlwire.ServerIdentity{}, err
}
credentials, identity, err := controlwire.Pair(id, node.Endpoint)
if err != nil {
return identity, err
}
raw, err := json.Marshal(credentials)
if err != nil {
return identity, err
}
cipher, err := m.Box.Seal(m.CredentialLabel(id), string(raw))
if err != nil {
return identity, err
}
return identity, m.Store.SetNodeCredentials(ctx, id, cipher)
}
func (m *Manager) client(node store.Node) (*http.Client, error) {
raw, err := m.Box.Open(m.CredentialLabel(node.ID), node.Credentials)
if err != nil {
return nil, errors.New("node transport credentials are unavailable")
}
var credentials controlwire.Credentials
if json.Unmarshal([]byte(raw), &credentials) != nil {
return nil, errors.New("node transport credentials are invalid")
}
tls, err := controlwire.ClientTLS(credentials)
if err != nil {
return nil, err
}
return &http.Client{Transport: &http.Transport{TLSClientConfig: tls, DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext, TLSHandshakeTimeout: 10 * time.Second, MaxIdleConnsPerHost: 4, ResponseHeaderTimeout: 2 * time.Hour}, Timeout: 2 * time.Hour, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("node redirect denied") }}, nil
}
func requestID() (string, error) {
raw := make([]byte, 16)
_, err := rand.Read(raw)
return hex.EncodeToString(raw), err
}
func (m *Manager) Probe(ctx context.Context, id uint64) error {
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
node, err := m.Store.Node(ctx, id)
if err != nil {
return err
}
if node.Transport == "local" {
return errors.New("local node is verified through its local services")
}
client, err := m.client(node)
if err != nil {
return err
}
defer client.CloseIdleConnections()
requestID, err := requestID()
if err != nil {
return err
}
req, err := controlwire.NewRequest("GET", node.Endpoint, "/v1/status", id, requestID, nil)
if err != nil {
return err
}
response, err := client.Do(req.WithContext(ctx))
if err != nil {
_ = m.Store.RecordNodeProbe(context.WithoutCancel(ctx), id, "节点连接或双向 TLS 校验失败")
return errors.New("节点连接或双向 TLS 校验失败")
}
defer response.Body.Close()
var status struct {
NodeID uint64 `json:"nodeId"`
Protocol string `json:"protocol"`
}
if response.StatusCode != 200 || json.NewDecoder(io.LimitReader(response.Body, 4096)).Decode(&status) != nil || status.NodeID != id || status.Protocol != controlwire.Version {
return errors.New("node identity or protocol mismatch")
}
return m.Store.RecordNodeProbe(ctx, id, "")
}
var hostPrefix = regexp.MustCompile(`^sv[a-f0-9]{10}(?:$|[._-])`)
func hostFromValue(value any) string {
switch v := value.(type) {
case map[string]any:
for _, key := range []string{"hostName", "HostName", "ProjectName", "projectName", "Name", "name", "Username", "username"} {
if text, ok := v[key].(string); ok && hostPrefix.MatchString(text) && (len(text) == 12 || (strings.EqualFold(key, "projectName") && strings.HasPrefix(text[12:], "_"))) {
return text[:12]
}
}
for _, key := range []string{"project", "Project", "site", "Site", "runtime", "Runtime", "spec"} {
if child, ok := v[key]; ok {
if host := hostFromValue(child); host != "" {
return host
}
}
}
}
return ""
}
func (m *Manager) Resolve(ctx context.Context, body []byte) (store.Node, error) {
id, explicit := scope.ExplicitNode(ctx)
if id == 0 {
id = 1
}
var value any
if len(body) > 0 && json.Unmarshal(body, &value) != nil {
return store.Node{}, errors.New("invalid execution request")
}
if host := hostFromValue(value); host != "" {
resolved, err := m.Store.NodeForHost(ctx, host)
if err != nil {
return store.Node{}, err
}
if explicit && id != resolved {
return store.Node{}, errors.New("resource belongs to another node")
}
id = resolved
}
node, err := m.Store.Node(ctx, id)
if err != nil {
return node, err
}
if !node.Enabled {
return node, errors.New("节点已停用")
}
return node, nil
}
func executionOperation(kind, route string, body []byte) (string, bool) {
if kind == "panel" {
var q struct {
Operation string `json:"operation"`
}
_ = json.Unmarshal(body, &q)
read := map[string]bool{"ping": true, "runtime_catalog": true, "runtime_capabilities": true, "runtime_environments": true, "list_unmanaged_sites": true, "managed_runtime": true, "php_update_pending": true, "database_size": true}
return "panel/" + q.Operation, read[q.Operation]
}
read := route == "/v1/database/phpmyadmin" || route == "/v1/site/log" || route == "/healthz" || route == "/v1/resources/usage" || route == "/v1/runtime/probe" || route == "/v1/runtime/backups/prune" || route == "/v1/lifecycle/backup/verify"
return "agent" + route, read
}
func (t *transport) RoundTrip(r *http.Request) (*http.Response, error) {
var body []byte
var err error
if r.Body != nil {
body, err = io.ReadAll(io.LimitReader(r.Body, controlwire.MaxEnvelopeBytes+1))
}
if r.Body != nil {
_ = r.Body.Close()
}
if err != nil || len(body) > controlwire.MaxEnvelopeBytes {
return nil, errors.New("execution request exceeds limit")
}
node, err := t.manager.Resolve(r.Context(), body)
if t.kind == "isolation" && r.URL.Path == "/v1/lifecycle/backup/delete" {
if id, explicit := scope.ExplicitNode(r.Context()); explicit {
node, err = t.manager.Store.Node(r.Context(), id)
if err == nil && !node.Enabled {
err = errors.New("节点已停用")
}
}
}
if err != nil {
return nil, err
}
if node.Transport == "local" {
socket := t.manager.PanelSocket
if t.kind == "isolation" {
socket = t.manager.AgentSocket
}
if socket == "" || t.manager.LocalToken == "" {
return nil, errors.New("local node is not configured")
}
local := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "unix", socket)
}}
defer local.CloseIdleConnections()
req := r.Clone(r.Context())
req.Body = io.NopCloser(bytes.NewReader(body))
req.ContentLength = int64(len(body))
req.Header.Set("Authorization", "Bearer "+t.manager.LocalToken)
return local.RoundTrip(req)
}
if t.kind == "panel" && r.URL.Path != "/v1/operations" {
return nil, errors.New("remote node does not expose panel setup endpoints")
}
operation, readOnly := executionOperation(t.kind, r.URL.Path, body)
if operation == "agent/v1/ftp/tls" || operation == "agent/v1/runtime/python/install" || operation == "agent/v1/runtime/php/maintenance" || operation == "panel/install_runtime_component" || operation == "panel/install_runtime_environment" || operation == "panel/update_php_runtime" {
r = r.WithContext(scope.WithProject(r.Context(), 0, node.ID))
}
if !readOnly {
blocked, e := t.manager.Store.NodeHasUnresolvedTask(r.Context(), node.ID)
if e != nil {
return nil, e
}
if blocked {
return nil, ErrUncertain
}
}
route := "/v1/isolation" + r.URL.Path
if t.kind == "isolation" && r.Method == http.MethodGet && r.URL.Path == "/healthz" {
route = "/v1/status"
}
var lease *store.NodeRegistryLease
if t.kind == "panel" {
lease, err = t.manager.Store.LockNodeRegistry(r.Context(), node.ID)
if err != nil {
return nil, err
}
defer lease.Close()
if !readOnly {
blocked, e := t.manager.Store.NodeHasUnresolvedTask(r.Context(), node.ID)
if e != nil {
return nil, e
}
if blocked {
return nil, ErrUncertain
}
}
snapshot, e := lease.Read(r.Context())
if e != nil {
return nil, e
}
body, e = json.Marshal(panel.ScopedExecution{Request: body, Registry: snapshot})
if e != nil {
return nil, e
}
route = "/v1/panel"
}
id, err := requestID()
if err != nil {
return nil, err
}
var task uint64
if !readOnly {
task, err = t.manager.Store.StartControlTask(r.Context(), node.ID, scope.Project(r.Context()), operation, id)
if err != nil {
return nil, err
}
}
finish := func(state, detail string) {
if task == 0 {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = t.manager.Store.FinishControlTask(ctx, task, state, detail)
}
client, err := t.manager.client(node)
if err != nil {
finish("failed", "节点身份配置无效")
return nil, err
}
defer client.CloseIdleConnections()
req, err := controlwire.NewRequest(r.Method, node.Endpoint, route, node.ID, id, body)
if err != nil {
finish("failed", "节点请求配置无效")
return nil, err
}
response, err := client.Do(req.WithContext(r.Context()))
if err != nil {
finish("uncertain", "连接中断,需要核对被控实际状态")
return nil, ErrUncertain
}
defer response.Body.Close()
result, err := io.ReadAll(io.LimitReader(response.Body, controlwire.MaxEnvelopeBytes+1))
if err != nil || len(result) > controlwire.MaxEnvelopeBytes {
finish("uncertain", "节点响应不完整")
return nil, ErrUncertain
}
if response.StatusCode != 200 {
detail := []rune(strings.TrimSpace(string(result)))
if len(detail) > 300 {
detail = detail[:300]
}
if !readOnly {
finish("uncertain", fmt.Sprintf("节点返回 HTTP %d:%s;请核对实际状态", response.StatusCode, string(detail)))
return nil, ErrUncertain
}
finish("uncertain", fmt.Sprintf("节点返回 HTTP %d,需要核对实际状态", response.StatusCode))
return &http.Response{StatusCode: response.StatusCode, Header: response.Header.Clone(), Body: io.NopCloser(bytes.NewReader(result)), Request: r}, nil
}
if lease != nil {
var out panel.ScopedResult
if json.Unmarshal(result, &out) != nil || len(out.Registry) == 0 || !json.Valid(out.Registry) {
finish("uncertain", "节点资源响应待核验")
return nil, ErrUncertain
}
if err = lease.Save(r.Context(), out.Registry); err != nil {
finish("uncertain", "资源登记回写失败")
return nil, ErrUncertain
}
result = out.Response
}
finish("succeeded", "")
_ = t.manager.Store.RecordNodeProbe(r.Context(), node.ID, "")
return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(bytes.NewReader(result)), Request: r}, nil
}
func (m *Manager) NodeDomains(ctx context.Context) ([]string, error) {
nodes, err := m.Store.Nodes(ctx)
if err != nil {
return nil, err
}
domains := []string{}
for _, node := range nodes {
if strings.TrimSpace(node.RootDomain) != "" {
domains = append(domains, node.RootDomain)
}
if node.FTPCertificateDomain != "" {
domains = append(domains, node.FTPCertificateDomain)
}
}
return domains, nil
}