feat: import Sea vHost single-server testing release
This commit is contained in:
commit
248badd33e
441 files changed
+63221
No files matched your search
@@ -0,0 +1,270 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"sea-vhost/internal/isolation"
|
||||
"sea-vhost/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
maxManualCertificateBytes = 96 << 10
|
||||
maxManualPrivateKeyBytes = 32 << 10
|
||||
)
|
||||
|
||||
// RequestAutoCertificate enables automatic certificate management and runs a
|
||||
// complete HTTP-01 issuance cycle. aaPanel's ACME order endpoint does not
|
||||
// deploy the resulting certificate by itself, so the panel adapter also waits
|
||||
// for a valid order and explicitly installs it on the managed site.
|
||||
func (s *Projects) RequestAutoCertificate(ctx context.Context, user store.User, projectID, siteID uint64) (store.Site, error) {
|
||||
project, err := s.authorizedProject(ctx, user, projectID)
|
||||
if err != nil {
|
||||
return store.Site{}, err
|
||||
}
|
||||
if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil {
|
||||
return store.Site{}, err
|
||||
}
|
||||
site, err := s.store.Site(ctx, project.TenantID, project.ID, siteID)
|
||||
if err != nil {
|
||||
return store.Site{}, err
|
||||
}
|
||||
return s.requestAutoCertificate(ctx, project, site)
|
||||
}
|
||||
|
||||
func (s *Projects) DisableCertificate(ctx context.Context, user store.User, projectID, siteID uint64) (store.Site, error) {
|
||||
project, err := s.authorizedProject(ctx, user, projectID)
|
||||
if err != nil {
|
||||
return store.Site{}, err
|
||||
}
|
||||
if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil {
|
||||
return store.Site{}, err
|
||||
}
|
||||
site, err := s.store.Site(ctx, project.TenantID, project.ID, siteID)
|
||||
if err != nil {
|
||||
return store.Site{}, err
|
||||
}
|
||||
if site.PanelSiteID <= 0 || site.Status == "provisioning" || site.Status == "failed" {
|
||||
return store.Site{}, errors.New("网站尚未完成创建,不能关闭证书")
|
||||
}
|
||||
if err = s.panel.DisableCertificate(ctx, site.PanelSiteID, site.Domain); err != nil {
|
||||
return store.Site{}, fmt.Errorf("宝塔关闭证书失败: %w", err)
|
||||
}
|
||||
if err = s.store.SetCertificateOff(ctx, project.TenantID, project.ID, site.ID); err != nil {
|
||||
return store.Site{}, fmt.Errorf("证书已关闭,但保存状态失败: %w", err)
|
||||
}
|
||||
return s.store.Site(ctx, project.TenantID, project.ID, site.ID)
|
||||
}
|
||||
|
||||
func (s *Projects) requestAutoCertificate(ctx context.Context, project store.Project, site store.Site) (store.Site, error) {
|
||||
if site.Status != "running" {
|
||||
return store.Site{}, errors.New("请先部署并启动网站,再使用 HTTP-01 申请证书;未运行的网站可使用 DNS-01 或上传证书")
|
||||
}
|
||||
if site.PanelSiteID <= 0 || site.Status == "provisioning" || site.Status == "failed" {
|
||||
return store.Site{}, errors.New("网站尚未完成创建,不能申请证书")
|
||||
}
|
||||
identity, err := s.phpIdentitySpec(ctx, project, site)
|
||||
protection := isolation.WebProtectionSpec{Project: identity.Project, Domain: site.Domain}
|
||||
if err != nil {
|
||||
return store.Site{}, err
|
||||
}
|
||||
if err = s.isolation.ApplyWebProtection(ctx, protection); err != nil {
|
||||
return store.Site{}, fmt.Errorf("准备 HTTP-01 验证目录失败: %w", err)
|
||||
}
|
||||
domains, err := s.siteCertificateDomains(ctx, project, site)
|
||||
if err != nil {
|
||||
return store.Site{}, err
|
||||
}
|
||||
if err = s.store.SetAutoCertificateStatus(ctx, project.TenantID, project.ID, site.ID, "pending", ""); err != nil {
|
||||
return store.Site{}, err
|
||||
}
|
||||
|
||||
// aaPanel keeps ACME orders in a shared panel-level store. Serializing the
|
||||
// short order/deploy transaction prevents one tenant's operation from being
|
||||
// interleaved with another tenant's retry.
|
||||
s.certificateMu.Lock()
|
||||
err = s.panel.RequestCertificate(ctx, site.PanelSiteID, project.Path, domains)
|
||||
s.certificateMu.Unlock()
|
||||
if err != nil {
|
||||
_ = s.store.SetAutoCertificateStatus(context.WithoutCancel(ctx), project.TenantID, project.ID, site.ID, "failed", err.Error())
|
||||
return store.Site{}, fmt.Errorf("宝塔自动证书申请失败: %w", err)
|
||||
}
|
||||
if err = s.store.SetAutoCertificateStatus(ctx, project.TenantID, project.ID, site.ID, "active", ""); err != nil {
|
||||
return store.Site{}, fmt.Errorf("证书已部署,但保存状态失败: %w", err)
|
||||
}
|
||||
return s.store.Site(ctx, project.TenantID, project.ID, site.ID)
|
||||
}
|
||||
|
||||
func (s *Projects) siteCertificateDomains(ctx context.Context, project store.Project, site store.Site) ([]string, error) {
|
||||
domains := []string{strings.ToLower(strings.TrimSpace(site.Domain))}
|
||||
resources, err := s.store.ListDomains(ctx, project.TenantID, &project.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen := map[string]struct{}{domains[0]: {}}
|
||||
for _, item := range resources {
|
||||
name := strings.ToLower(strings.TrimSpace(item.Domain))
|
||||
if item.SiteID != site.ID || item.Status != "approved" || name == "" {
|
||||
continue
|
||||
}
|
||||
if _, exists := seen[name]; exists {
|
||||
continue
|
||||
}
|
||||
seen[name] = struct{}{}
|
||||
domains = append(domains, name)
|
||||
if len(domains) > maxDomainsPerSite {
|
||||
return nil, fmt.Errorf("网站证书域名数量超过上限(%d)", maxDomainsPerSite)
|
||||
}
|
||||
}
|
||||
return domains, nil
|
||||
}
|
||||
|
||||
// InstallManualCertificate validates the complete certificate/key pair before
|
||||
// passing it to the privileged broker. The private key is never persisted by
|
||||
// Sea vHost or included in an audit message.
|
||||
func (s *Projects) InstallManualCertificate(ctx context.Context, user store.User, projectID, siteID uint64, certificatePEM, privateKeyPEM string) (store.Site, error) {
|
||||
project, err := s.authorizedProject(ctx, user, projectID)
|
||||
if err != nil {
|
||||
return store.Site{}, err
|
||||
}
|
||||
if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil {
|
||||
return store.Site{}, err
|
||||
}
|
||||
site, err := s.store.Site(ctx, project.TenantID, project.ID, siteID)
|
||||
if err != nil {
|
||||
return store.Site{}, err
|
||||
}
|
||||
if site.PanelSiteID <= 0 || site.Status == "provisioning" || site.Status == "failed" {
|
||||
return store.Site{}, errors.New("网站尚未完成创建,不能安装证书")
|
||||
}
|
||||
|
||||
domains, err := s.siteCertificateDomains(ctx, project, site)
|
||||
if err != nil {
|
||||
return store.Site{}, err
|
||||
}
|
||||
if err = validateManualCertificate(certificatePEM, privateKeyPEM, domains, time.Now()); err != nil {
|
||||
return store.Site{}, err
|
||||
}
|
||||
if err = s.panel.InstallCertificate(ctx, site.PanelSiteID, site.Domain, privateKeyPEM, certificatePEM); err != nil {
|
||||
return store.Site{}, fmt.Errorf("宝塔安装证书失败: %w", err)
|
||||
}
|
||||
leaf, err := manualCertificateLeaf(certificatePEM)
|
||||
if err != nil {
|
||||
return store.Site{}, err
|
||||
}
|
||||
if err = s.store.SetManualCertificateActive(ctx, project.TenantID, project.ID, site.ID, leaf.NotAfter); err != nil {
|
||||
return store.Site{}, fmt.Errorf("证书已安装,但保存状态失败: %w", err)
|
||||
}
|
||||
return s.store.Site(ctx, project.TenantID, project.ID, site.ID)
|
||||
}
|
||||
|
||||
func manualCertificateLeaf(certificatePEM string) (*x509.Certificate, error) {
|
||||
block, _ := pem.Decode([]byte(certificatePEM))
|
||||
if block == nil || block.Type != "CERTIFICATE" {
|
||||
return nil, errors.New("未找到有效的 PEM 证书")
|
||||
}
|
||||
certificate, err := x509.ParseCertificate(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, errors.New("证书链包含无法解析的证书")
|
||||
}
|
||||
return certificate, nil
|
||||
}
|
||||
|
||||
func validateManualCertificate(certificatePEM, privateKeyPEM string, domains []string, now time.Time) error {
|
||||
if len(certificatePEM) == 0 || len(certificatePEM) > maxManualCertificateBytes {
|
||||
return errors.New("证书链不能为空且不得超过 96 KiB")
|
||||
}
|
||||
if len(privateKeyPEM) == 0 || len(privateKeyPEM) > maxManualPrivateKeyBytes {
|
||||
return errors.New("私钥不能为空且不得超过 32 KiB")
|
||||
}
|
||||
|
||||
certificateData := []byte(certificatePEM)
|
||||
var leaf *x509.Certificate
|
||||
certificateCount := 0
|
||||
for len(bytes.TrimSpace(certificateData)) > 0 {
|
||||
block, rest := pem.Decode(certificateData)
|
||||
if block == nil || block.Type != "CERTIFICATE" {
|
||||
return errors.New("证书链必须仅包含 PEM CERTIFICATE 块")
|
||||
}
|
||||
certificate, err := x509.ParseCertificate(block.Bytes)
|
||||
if err != nil {
|
||||
return errors.New("证书链包含无法解析的证书")
|
||||
}
|
||||
if leaf == nil {
|
||||
leaf = certificate
|
||||
}
|
||||
certificateCount++
|
||||
certificateData = rest
|
||||
}
|
||||
if leaf == nil || certificateCount == 0 {
|
||||
return errors.New("未找到有效的 PEM 证书")
|
||||
}
|
||||
if leaf.IsCA {
|
||||
return errors.New("证书链首张证书不能是 CA 证书")
|
||||
}
|
||||
if now.Before(leaf.NotBefore) || !now.Before(leaf.NotAfter) {
|
||||
return errors.New("网站证书尚未生效或已过期")
|
||||
}
|
||||
if len(leaf.ExtKeyUsage) > 0 {
|
||||
validUsage := false
|
||||
for _, usage := range leaf.ExtKeyUsage {
|
||||
if usage == x509.ExtKeyUsageServerAuth || usage == x509.ExtKeyUsageAny {
|
||||
validUsage = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !validUsage {
|
||||
return errors.New("证书不允许用于 TLS Web 服务器")
|
||||
}
|
||||
}
|
||||
for _, domain := range domains {
|
||||
if err := leaf.VerifyHostname(domain); err != nil {
|
||||
return fmt.Errorf("证书不包含已启用域名 %s", domain)
|
||||
}
|
||||
}
|
||||
|
||||
keyBlock, keyRest := pem.Decode([]byte(privateKeyPEM))
|
||||
if keyBlock == nil || len(bytes.TrimSpace(keyRest)) != 0 {
|
||||
return errors.New("私钥必须是且只能是一个 PEM 私钥块")
|
||||
}
|
||||
if x509.IsEncryptedPEMBlock(keyBlock) || strings.Contains(strings.ToUpper(keyBlock.Type), "ENCRYPTED") {
|
||||
return errors.New("不支持加密私钥,请上传无口令 PEM 私钥")
|
||||
}
|
||||
privateKey, err := parsePrivateKey(keyBlock.Bytes)
|
||||
if err != nil {
|
||||
return errors.New("私钥格式无效,仅支持 PKCS#8、PKCS#1 或 EC 私钥")
|
||||
}
|
||||
signer, ok := privateKey.(crypto.Signer)
|
||||
if !ok {
|
||||
return errors.New("私钥类型不能用于 TLS 签名")
|
||||
}
|
||||
certificatePublic, err := x509.MarshalPKIXPublicKey(leaf.PublicKey)
|
||||
if err != nil {
|
||||
return errors.New("证书公钥格式无效")
|
||||
}
|
||||
privatePublic, err := x509.MarshalPKIXPublicKey(signer.Public())
|
||||
if err != nil || !bytes.Equal(certificatePublic, privatePublic) {
|
||||
return errors.New("证书与私钥不匹配")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parsePrivateKey(der []byte) (any, error) {
|
||||
if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
|
||||
return key, nil
|
||||
}
|
||||
if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
|
||||
return key, nil
|
||||
}
|
||||
if key, err := x509.ParseECPrivateKey(der); err == nil {
|
||||
return key, nil
|
||||
}
|
||||
return nil, errors.New("unsupported private key")
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"math/big"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestValidateManualCertificate(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
certificate, privateKey := testCertificatePair(t, []string{"site.hosts.example.com", "www.example.com"}, now)
|
||||
if err := validateManualCertificate(certificate, privateKey, []string{"site.hosts.example.com", "www.example.com"}, now); err != nil {
|
||||
t.Fatalf("valid certificate rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateManualCertificateRejectsMissingDomain(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
certificate, privateKey := testCertificatePair(t, []string{"site.hosts.example.com"}, now)
|
||||
err := validateManualCertificate(certificate, privateKey, []string{"site.hosts.example.com", "www.example.com"}, now)
|
||||
if err == nil || !strings.Contains(err.Error(), "www.example.com") {
|
||||
t.Fatalf("missing domain error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateManualCertificateRejectsMismatchedKey(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
certificate, _ := testCertificatePair(t, []string{"site.hosts.example.com"}, now)
|
||||
_, privateKey := testCertificatePair(t, []string{"site.hosts.example.com"}, now)
|
||||
err := validateManualCertificate(certificate, privateKey, []string{"site.hosts.example.com"}, now)
|
||||
if err == nil || !strings.Contains(err.Error(), "不匹配") {
|
||||
t.Fatalf("mismatched key error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateManualCertificateRejectsTrailingPEMData(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
certificate, privateKey := testCertificatePair(t, []string{"site.hosts.example.com"}, now)
|
||||
err := validateManualCertificate(certificate+"not-pem", privateKey, []string{"site.hosts.example.com"}, now)
|
||||
if err == nil || !strings.Contains(err.Error(), "PEM CERTIFICATE") {
|
||||
t.Fatalf("trailing data error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func testCertificatePair(t *testing.T, domains []string, now time.Time) (string, string) {
|
||||
t.Helper()
|
||||
publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{CommonName: domains[0]},
|
||||
DNSNames: domains,
|
||||
NotBefore: now.Add(-time.Hour),
|
||||
NotAfter: now.Add(24 * time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, template, template, publicKey, privateKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keyDER, err := x509.MarshalPKCS8PrivateKey(privateKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
certificatePEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
|
||||
privateKeyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER})
|
||||
return string(certificatePEM), string(privateKeyPEM)
|
||||
}
|
||||
@@ -0,0 +1,570 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/acme"
|
||||
|
||||
"sea-vhost/internal/dnsprovider"
|
||||
"sea-vhost/internal/scope"
|
||||
"sea-vhost/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
acmeAccountSecretKey = "acme-account-key-v1"
|
||||
certificateCooldown = 5 * time.Minute
|
||||
dnsCredentialCooldown = time.Minute
|
||||
dnsPropagationLimit = 3 * time.Minute
|
||||
dnsCleanupAttempts = 3
|
||||
dnsCleanupAttemptLimit = 10 * time.Second
|
||||
dnsCleanupRetryDelay = 250 * time.Millisecond
|
||||
)
|
||||
|
||||
type DNSCredentialInput struct {
|
||||
VerificationToken string `json:"verificationToken"`
|
||||
Label string `json:"label"`
|
||||
Provider string `json:"provider"`
|
||||
ZoneName string `json:"zoneName"`
|
||||
Credential dnsprovider.Credential `json:"credential"`
|
||||
}
|
||||
|
||||
func (s *Projects) ListDNSCredentials(ctx context.Context, user store.User, platform bool) ([]store.DNSCredential, error) {
|
||||
owner, err := dnsCredentialOwner(user, platform)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.store.ListDNSCredentials(ctx, owner)
|
||||
}
|
||||
|
||||
func (s *Projects) SaveDNSCredential(ctx context.Context, user store.User, platform bool, id uint64, input DNSCredentialInput) (store.DNSCredential, error) {
|
||||
owner, err := dnsCredentialOwner(user, platform)
|
||||
if err != nil {
|
||||
return store.DNSCredential{}, err
|
||||
}
|
||||
label := strings.TrimSpace(input.Label)
|
||||
provider := strings.ToLower(strings.TrimSpace(input.Provider))
|
||||
zone := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(input.ZoneName), "."))
|
||||
if len(label) < 2 || len(label) > 80 {
|
||||
return store.DNSCredential{}, errors.New("凭据名称应为 2 至 80 个字符")
|
||||
}
|
||||
if !domainPattern.MatchString(zone) {
|
||||
return store.DNSCredential{}, errors.New("DNS 区域域名格式不正确")
|
||||
}
|
||||
if err = dnsprovider.Validate(provider, input.Credential); err != nil {
|
||||
return store.DNSCredential{}, err
|
||||
}
|
||||
if err=s.verifyDNSZoneChoice(user,platform,input);err!=nil{return store.DNSCredential{},err}
|
||||
plain, err := json.Marshal(input.Credential)
|
||||
if err != nil {
|
||||
return store.DNSCredential{}, err
|
||||
}
|
||||
if len(plain) > 3072 {
|
||||
return store.DNSCredential{}, errors.New("DNS 凭据内容过大")
|
||||
}
|
||||
secretRef, err := randomSecretRef()
|
||||
if err != nil {
|
||||
return store.DNSCredential{}, err
|
||||
}
|
||||
ciphertext, err := s.credentials.Seal("dns-credential:"+secretRef, string(plain))
|
||||
if err != nil {
|
||||
return store.DNSCredential{}, err
|
||||
}
|
||||
scopeKey := "platform"
|
||||
if owner != nil {
|
||||
scopeKey = fmt.Sprintf("tenant:%d", *owner)
|
||||
}
|
||||
if id == 0 {
|
||||
count, countErr := s.store.CountDNSCredentials(ctx, owner)
|
||||
if countErr != nil {
|
||||
return store.DNSCredential{}, errors.New("无法核对 DNS 凭据数量")
|
||||
}
|
||||
limit := 200
|
||||
if owner != nil {
|
||||
limit = 50
|
||||
}
|
||||
if count >= limit {
|
||||
return store.DNSCredential{}, fmt.Errorf("DNS 凭据数量已达到上限(%d)", limit)
|
||||
}
|
||||
id, err = s.store.InsertDNSCredential(ctx, store.NewDNSCredential{TenantID: owner, ScopeKey: scopeKey, SecretRef: secretRef, Label: label, Provider: provider, ZoneName: zone, CredentialCiphertext: ciphertext})
|
||||
} else {
|
||||
err = s.store.UpdateDNSCredential(ctx, id, owner, label, provider, zone, secretRef, ciphertext)
|
||||
}
|
||||
if err != nil {
|
||||
return store.DNSCredential{}, fmt.Errorf("保存 DNS 凭据失败: %w", err)
|
||||
}
|
||||
return s.store.DNSCredential(ctx, id, owner)
|
||||
}
|
||||
|
||||
func (s *Projects) DeleteDNSCredential(ctx context.Context, user store.User, platform bool, id uint64) error {
|
||||
owner, err := dnsCredentialOwner(user, platform)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.store.DeleteDNSCredential(ctx, id, owner)
|
||||
}
|
||||
|
||||
// TestDNSCredential verifies only the minimum permission needed by DNS-01:
|
||||
// create one unpredictable TXT record inside the configured zone and delete
|
||||
// that exact provider record ID. It deliberately does not contact an ACME CA.
|
||||
func (s *Projects) TestDNSCredential(ctx context.Context, user store.User, platform bool, id uint64) (store.DNSCredential, error) {
|
||||
owner, err := dnsCredentialOwner(user, platform)
|
||||
if err != nil {
|
||||
return store.DNSCredential{}, err
|
||||
}
|
||||
credential, err := s.store.DNSCredential(ctx, id, owner)
|
||||
if err != nil {
|
||||
return store.DNSCredential{}, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
if err = s.store.BeginDNSCredentialTest(ctx, id, owner, credential.SecretRef, now, dnsCredentialCooldown); err != nil {
|
||||
return store.DNSCredential{}, err
|
||||
}
|
||||
|
||||
testErr := func() error {
|
||||
provider, providerErr := s.dnsProvider(credential)
|
||||
if providerErr != nil {
|
||||
return providerErr
|
||||
}
|
||||
nonce, nonceErr := randomSecretRef()
|
||||
if nonceErr != nil {
|
||||
return errors.New("无法生成 DNS 测试记录")
|
||||
}
|
||||
fqdn := "_svh-check-" + nonce[:12] + "." + credential.ZoneName
|
||||
if len(fqdn) > 253 {
|
||||
return errors.New("DNS 区域域名过长,无法创建测试记录")
|
||||
}
|
||||
value, valueErr := randomSecretRef()
|
||||
if valueErr != nil {
|
||||
return errors.New("无法生成 DNS 测试值")
|
||||
}
|
||||
return verifyDNSCredential(ctx, provider, fqdn, "sea-vhost-verification="+value)
|
||||
}()
|
||||
|
||||
failure := ""
|
||||
if testErr != nil {
|
||||
failure = testErr.Error()
|
||||
}
|
||||
completeCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
if completeErr := s.store.CompleteDNSCredentialTest(completeCtx, id, owner, credential.SecretRef, testErr == nil, failure); completeErr != nil {
|
||||
if testErr == nil {
|
||||
return store.DNSCredential{}, errors.New("DNS 测试已完成,但无法保存测试状态")
|
||||
}
|
||||
slog.Warn("cannot persist DNS credential test result", "credential_id", id, "error", completeErr)
|
||||
}
|
||||
if testErr != nil {
|
||||
return store.DNSCredential{}, fmt.Errorf("DNS 凭据测试失败: %w", testErr)
|
||||
}
|
||||
return s.store.DNSCredential(ctx, id, owner)
|
||||
}
|
||||
|
||||
func verifyDNSCredential(ctx context.Context, provider dnsprovider.Provider, fqdn, value string) error {
|
||||
recordID, err := provider.Present(ctx, fqdn, value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建 TXT 记录失败: %w", err)
|
||||
}
|
||||
cleanupCtx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
|
||||
defer cancel()
|
||||
if err = cleanupDNSRecord(cleanupCtx, provider, recordID); err != nil {
|
||||
return fmt.Errorf("TXT 记录已创建但精确删除失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cleanupDNSRecord(ctx context.Context, provider dnsprovider.Provider, recordID string) error {
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < dnsCleanupAttempts; attempt++ {
|
||||
attemptCtx, cancel := context.WithTimeout(ctx, dnsCleanupAttemptLimit)
|
||||
lastErr = provider.Cleanup(attemptCtx, recordID)
|
||||
cancel()
|
||||
if lastErr == nil {
|
||||
return nil
|
||||
}
|
||||
if attempt == dnsCleanupAttempts-1 {
|
||||
break
|
||||
}
|
||||
timer := time.NewTimer(time.Duration(attempt+1) * dnsCleanupRetryDelay)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return errors.Join(lastErr, ctx.Err())
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
return lastErr
|
||||
}
|
||||
|
||||
func dnsCredentialOwner(user store.User, platform bool) (*uint64, error) {
|
||||
if platform {
|
||||
if user.Role != "admin" {
|
||||
return nil, errors.New("需要管理员权限")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
if user.Role != "tenant" || user.TenantID == nil {
|
||||
return nil, errors.New("只有用户账号可以管理 DNS 凭据")
|
||||
}
|
||||
value := *user.TenantID
|
||||
return &value, nil
|
||||
}
|
||||
|
||||
func randomSecretRef() (string, error) {
|
||||
data := make([]byte, 16)
|
||||
if _, err := rand.Read(data); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(data), nil
|
||||
}
|
||||
|
||||
func (s *Projects) RequestDNSCertificate(ctx context.Context, user store.User, projectID, siteID uint64) (store.Site, store.CertificateAutomation, error) {
|
||||
project, err := s.authorizedProject(ctx, user, projectID)
|
||||
if err != nil {
|
||||
return store.Site{}, store.CertificateAutomation{}, err
|
||||
}
|
||||
if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil {
|
||||
return store.Site{}, store.CertificateAutomation{}, err
|
||||
}
|
||||
site, err := s.store.Site(ctx, project.TenantID, project.ID, siteID)
|
||||
if err != nil {
|
||||
return store.Site{}, store.CertificateAutomation{}, err
|
||||
}
|
||||
if err = s.issueDNSCertificate(ctx, project, site); err != nil {
|
||||
return store.Site{}, store.CertificateAutomation{}, err
|
||||
}
|
||||
updated, err := s.store.Site(ctx, project.TenantID, project.ID, site.ID)
|
||||
if err != nil {
|
||||
return store.Site{}, store.CertificateAutomation{}, err
|
||||
}
|
||||
automation, err := s.store.CertificateAutomation(ctx, project.TenantID, project.ID, site.ID)
|
||||
return updated, automation, err
|
||||
}
|
||||
|
||||
func (s *Projects) CertificateAutomation(ctx context.Context, user store.User, projectID, siteID uint64) (store.CertificateAutomation, error) {
|
||||
project, err := s.authorizedProject(ctx, user, projectID)
|
||||
if err != nil {
|
||||
return store.CertificateAutomation{}, err
|
||||
}
|
||||
return s.store.CertificateAutomation(ctx, project.TenantID, project.ID, siteID)
|
||||
}
|
||||
|
||||
func (s *Projects) issueDNSCertificate(ctx context.Context, project store.Project, site store.Site) (resultErr error) {
|
||||
ctx = scope.WithProject(ctx, project.ID, project.NodeID)
|
||||
if site.PanelSiteID <= 0 || site.Status == "provisioning" || site.Status == "failed" {
|
||||
return errors.New("网站尚未完成创建,不能申请证书")
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
if err := s.store.BeginDNSCertificateAttempt(ctx, project.TenantID, project.ID, site.ID, now, certificateCooldown); err != nil {
|
||||
if errors.Is(err, store.ErrCertificateCooldown) {
|
||||
return errors.New("证书签发请求过于频繁,请五分钟后重试")
|
||||
}
|
||||
return err
|
||||
}
|
||||
completed := false
|
||||
defer func() {
|
||||
if !completed {
|
||||
message := "DNS-01 证书签发失败"
|
||||
if resultErr != nil {
|
||||
message = resultErr.Error()
|
||||
}
|
||||
_ = s.store.CompleteDNSCertificateAttempt(context.WithoutCancel(ctx), project.TenantID, project.ID, site.ID, nil, message, time.Now().UTC())
|
||||
}
|
||||
}()
|
||||
|
||||
domains, err := s.siteCertificateDomains(ctx, project, site)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
credentials, err := s.store.CertificateDNSCredentials(ctx, project.TenantID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
routes, err := routeDNSCredentials(domains, s.nodeRootDomain(ctx), credentials)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
accountKey, err := s.acmeAccountKey(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取 ACME 账户失败: %w", err)
|
||||
}
|
||||
client := &acme.Client{Key: accountKey, DirectoryURL: acme.LetsEncryptURL}
|
||||
if _, err = client.Register(ctx, &acme.Account{}, acme.AcceptTOS); err != nil && !errors.Is(err, acme.ErrAccountAlreadyExists) {
|
||||
return fmt.Errorf("注册 ACME 账户失败: %w", err)
|
||||
}
|
||||
order, err := client.AuthorizeOrder(ctx, acme.DomainIDs(domains...))
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建 ACME 订单失败: %w", err)
|
||||
}
|
||||
|
||||
type challengeRecord struct {
|
||||
provider dnsprovider.Provider
|
||||
recordID string
|
||||
fqdn, value, authzURL string
|
||||
challenge *acme.Challenge
|
||||
}
|
||||
records := make([]challengeRecord, 0, len(order.AuthzURLs))
|
||||
defer func() {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
defer cancel()
|
||||
for index := len(records) - 1; index >= 0; index-- {
|
||||
if err := cleanupDNSRecord(cleanupCtx, records[index].provider, records[index].recordID); err != nil {
|
||||
slog.Warn("ACME TXT cleanup failed", "site_id", site.ID, "record", records[index].fqdn, "error", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for _, authzURL := range order.AuthzURLs {
|
||||
authorization, authErr := client.GetAuthorization(ctx, authzURL)
|
||||
if authErr != nil {
|
||||
return fmt.Errorf("读取 ACME 验证失败: %w", authErr)
|
||||
}
|
||||
if authorization.Status == acme.StatusValid {
|
||||
continue
|
||||
}
|
||||
var challenge *acme.Challenge
|
||||
for _, candidate := range authorization.Challenges {
|
||||
if candidate.Type == "dns-01" {
|
||||
challenge = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
if challenge == nil {
|
||||
return fmt.Errorf("域名 %s 不支持 DNS-01 验证", authorization.Identifier.Value)
|
||||
}
|
||||
value, challengeErr := client.DNS01ChallengeRecord(challenge.Token)
|
||||
if challengeErr != nil {
|
||||
return challengeErr
|
||||
}
|
||||
identifier := strings.ToLower(strings.TrimPrefix(authorization.Identifier.Value, "*."))
|
||||
credential, found := routes[identifier]
|
||||
if !found {
|
||||
return fmt.Errorf("域名 %s 没有可用的 DNS 凭据", identifier)
|
||||
}
|
||||
provider, providerErr := s.dnsProvider(credential)
|
||||
if providerErr != nil {
|
||||
return providerErr
|
||||
}
|
||||
fqdn := "_acme-challenge." + identifier
|
||||
recordID, presentErr := provider.Present(ctx, fqdn, value)
|
||||
if presentErr != nil {
|
||||
return fmt.Errorf("写入 %s 的 TXT 记录失败: %w", identifier, presentErr)
|
||||
}
|
||||
records = append(records, challengeRecord{provider: provider, recordID: recordID, fqdn: fqdn, value: value, authzURL: authzURL, challenge: challenge})
|
||||
}
|
||||
for _, record := range records {
|
||||
if err = waitForTXT(ctx, record.fqdn, record.value, dnsPropagationLimit); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, record := range records {
|
||||
if _, err = client.Accept(ctx, record.challenge); err != nil {
|
||||
return fmt.Errorf("提交 DNS 验证失败: %w", err)
|
||||
}
|
||||
if _, err = client.WaitAuthorization(ctx, record.authzURL); err != nil {
|
||||
return fmt.Errorf("DNS 验证未通过: %w", err)
|
||||
}
|
||||
}
|
||||
order, err = client.WaitOrder(ctx, order.URI)
|
||||
if err != nil {
|
||||
return fmt.Errorf("等待 ACME 订单失败: %w", err)
|
||||
}
|
||||
certificateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
csr, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{DNSNames: domains}, certificateKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
derChain, _, err := client.CreateOrderCert(ctx, order.FinalizeURL, csr, true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("签发证书失败: %w", err)
|
||||
}
|
||||
if len(derChain) == 0 {
|
||||
return errors.New("ACME 未返回证书")
|
||||
}
|
||||
leaf, err := x509.ParseCertificate(derChain[0])
|
||||
if err != nil {
|
||||
return errors.New("ACME 返回的证书格式无效")
|
||||
}
|
||||
keyDER, err := x509.MarshalPKCS8PrivateKey(certificateKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
privateKeyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER})
|
||||
var certificatePEM strings.Builder
|
||||
for _, der := range derChain {
|
||||
_ = pem.Encode(&certificatePEM, &pem.Block{Type: "CERTIFICATE", Bytes: der})
|
||||
}
|
||||
|
||||
s.certificateMu.Lock()
|
||||
err = s.panel.InstallCertificate(ctx, site.PanelSiteID, site.Domain, string(privateKeyPEM), certificatePEM.String())
|
||||
s.certificateMu.Unlock()
|
||||
if err != nil {
|
||||
return fmt.Errorf("宝塔安装 DNS 证书失败: %w", err)
|
||||
}
|
||||
if err = s.store.CompleteDNSCertificateAttempt(ctx, project.TenantID, project.ID, site.ID, &leaf.NotAfter, "", time.Now().UTC()); err != nil {
|
||||
return fmt.Errorf("证书已安装,但保存续期状态失败: %w", err)
|
||||
}
|
||||
completed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func routeDNSCredentials(domains []string, rootDomain string, credentials []store.DNSCredential) (map[string]store.DNSCredential, error) {
|
||||
rootDomain = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(rootDomain), "."))
|
||||
routes := make(map[string]store.DNSCredential, len(domains))
|
||||
for _, rawDomain := range domains {
|
||||
domain := strings.ToLower(strings.TrimPrefix(strings.TrimSuffix(strings.TrimSpace(rawDomain), "."), "*."))
|
||||
platformDomain := domain == rootDomain || strings.HasSuffix(domain, "."+rootDomain)
|
||||
bestLength := -1
|
||||
var best store.DNSCredential
|
||||
for _, credential := range credentials {
|
||||
isPlatform := credential.TenantID == nil
|
||||
if isPlatform != platformDomain {
|
||||
continue
|
||||
}
|
||||
zone := strings.ToLower(strings.TrimSuffix(credential.ZoneName, "."))
|
||||
if domain != zone && !strings.HasSuffix(domain, "."+zone) {
|
||||
continue
|
||||
}
|
||||
if len(zone) > bestLength {
|
||||
best, bestLength = credential, len(zone)
|
||||
}
|
||||
}
|
||||
if bestLength < 0 {
|
||||
if platformDomain {
|
||||
return nil, fmt.Errorf("管理员尚未配置平台根域 %s 的 DNS 凭据", rootDomain)
|
||||
}
|
||||
return nil, fmt.Errorf("用户尚未配置可管理域名 %s 的 DNS 凭据", domain)
|
||||
}
|
||||
routes[domain] = best
|
||||
}
|
||||
return routes, nil
|
||||
}
|
||||
|
||||
func (s *Projects) dnsProvider(credential store.DNSCredential) (dnsprovider.Provider, error) {
|
||||
plain, err := s.credentials.Open("dns-credential:"+credential.SecretRef, credential.CredentialCiphertext)
|
||||
if err != nil {
|
||||
return nil, errors.New("DNS 凭据无法解密,请重新保存")
|
||||
}
|
||||
var secret dnsprovider.Credential
|
||||
if err = json.Unmarshal([]byte(plain), &secret); err != nil {
|
||||
return nil, errors.New("DNS 凭据格式无效,请重新保存")
|
||||
}
|
||||
return dnsprovider.New(credential.Provider, credential.ZoneName, secret)
|
||||
}
|
||||
|
||||
func (s *Projects) acmeAccountKey(ctx context.Context) (crypto.Signer, error) {
|
||||
ciphertext, err := s.store.SystemSecret(ctx, acmeAccountSecretKey)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
key, keyErr := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if keyErr != nil {
|
||||
return nil, keyErr
|
||||
}
|
||||
der, keyErr := x509.MarshalPKCS8PrivateKey(key)
|
||||
if keyErr != nil {
|
||||
return nil, keyErr
|
||||
}
|
||||
sealed, keyErr := s.credentials.Seal("system:"+acmeAccountSecretKey, string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der})))
|
||||
if keyErr != nil {
|
||||
return nil, keyErr
|
||||
}
|
||||
if keyErr = s.store.InsertSystemSecretIfAbsent(ctx, acmeAccountSecretKey, sealed); keyErr != nil {
|
||||
return nil, keyErr
|
||||
}
|
||||
ciphertext, err = s.store.SystemSecret(ctx, acmeAccountSecretKey)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
plain, err := s.credentials.Open("system:"+acmeAccountSecretKey, ciphertext)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
block, rest := pem.Decode([]byte(plain))
|
||||
if block == nil || len(strings.TrimSpace(string(rest))) != 0 {
|
||||
return nil, errors.New("ACME 账户密钥格式无效")
|
||||
}
|
||||
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
signer, ok := key.(crypto.Signer)
|
||||
if !ok {
|
||||
return nil, errors.New("ACME 账户密钥类型无效")
|
||||
}
|
||||
return signer, nil
|
||||
}
|
||||
|
||||
func waitForTXT(ctx context.Context, fqdn, wanted string, limit time.Duration) error {
|
||||
deadline := time.Now().Add(limit)
|
||||
for {
|
||||
values, err := net.DefaultResolver.LookupTXT(ctx, fqdn)
|
||||
if err == nil {
|
||||
for _, value := range values {
|
||||
if value == wanted {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return fmt.Errorf("等待 %s 的 TXT 记录生效超时", fqdn)
|
||||
}
|
||||
timer := time.NewTimer(5 * time.Second)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Projects) RunCertificateRenewalMonitor(ctx context.Context, interval time.Duration) {
|
||||
if interval < time.Hour {
|
||||
interval = 12 * time.Hour
|
||||
}
|
||||
run := func() {
|
||||
renewalCtx, cancel := context.WithTimeout(ctx, 30*time.Minute)
|
||||
defer cancel()
|
||||
items, err := s.store.DueDNSCertificateRenewals(renewalCtx, time.Now().UTC(), 25)
|
||||
if err != nil {
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
slog.Error("read DNS certificate renewals", "error", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, item := range items {
|
||||
if err = s.issueDNSCertificate(renewalCtx, item.Project, item.Site); err != nil {
|
||||
slog.Warn("DNS certificate renewal failed", "site_id", item.Site.ID, "error", err)
|
||||
s.store.LogEvent(context.WithoutCancel(renewalCtx), &item.Project.TenantID, nil, "renew", "dns_certificate", fmt.Sprintf("%d", item.Site.ID), "system", false, "DNS-01 自动续期失败")
|
||||
} else {
|
||||
s.store.LogEvent(context.WithoutCancel(renewalCtx), &item.Project.TenantID, nil, "renew", "dns_certificate", fmt.Sprintf("%d", item.Site.ID), "system", true, "DNS-01 自动续期并部署成功")
|
||||
}
|
||||
}
|
||||
}
|
||||
run()
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
run()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"sea-vhost/internal/store"
|
||||
)
|
||||
|
||||
type dnsCredentialTestProvider struct {
|
||||
presentName, presentValue string
|
||||
cleanedID string
|
||||
cleanupCalls int
|
||||
cleanupFailures int
|
||||
cleanupErr error
|
||||
}
|
||||
|
||||
func (p *dnsCredentialTestProvider) Present(_ context.Context, name, value string) (string, error) {
|
||||
p.presentName, p.presentValue = name, value
|
||||
return "provider-record-42", nil
|
||||
}
|
||||
func (p *dnsCredentialTestProvider) CreateRecord(ctx context.Context, name, _ string, value string) (string, error) {
|
||||
return p.Present(ctx, name, value)
|
||||
}
|
||||
|
||||
func (p *dnsCredentialTestProvider) Cleanup(_ context.Context, id string) error {
|
||||
p.cleanedID = id
|
||||
p.cleanupCalls++
|
||||
if p.cleanupFailures > 0 {
|
||||
p.cleanupFailures--
|
||||
return errors.New("temporary provider failure")
|
||||
}
|
||||
return p.cleanupErr
|
||||
}
|
||||
|
||||
func TestRouteDNSCredentialsSeparatesPlatformAndTenantZones(t *testing.T) {
|
||||
tenantID := uint64(8)
|
||||
platform := store.DNSCredential{ID: 1, ZoneName: "example.net"}
|
||||
tenant := store.DNSCredential{ID: 2, TenantID: &tenantID, ZoneName: "customer.example"}
|
||||
routes, err := routeDNSCredentials([]string{"sv1.hosts.example.net", "www.customer.example"}, "hosts.example.net", []store.DNSCredential{tenant, platform})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if routes["sv1.hosts.example.net"].ID != platform.ID {
|
||||
t.Fatal("assigned domain did not select platform credential")
|
||||
}
|
||||
if routes["www.customer.example"].ID != tenant.ID {
|
||||
t.Fatal("custom domain did not select tenant credential")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteDNSCredentialsUsesLongestZoneSuffix(t *testing.T) {
|
||||
tenantID := uint64(8)
|
||||
credentials := []store.DNSCredential{
|
||||
{ID: 1, TenantID: &tenantID, ZoneName: "example.com"},
|
||||
{ID: 2, TenantID: &tenantID, ZoneName: "app.example.com"},
|
||||
}
|
||||
routes, err := routeDNSCredentials([]string{"www.app.example.com"}, "hosts.platform.test", credentials)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if routes["www.app.example.com"].ID != 2 {
|
||||
t.Fatal("did not select longest matching DNS zone")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteDNSCredentialsWillNotUseTenantKeyForPlatformDomain(t *testing.T) {
|
||||
tenantID := uint64(8)
|
||||
_, err := routeDNSCredentials([]string{"sv1.hosts.example.net"}, "hosts.example.net", []store.DNSCredential{{ID: 2, TenantID: &tenantID, ZoneName: "example.net"}})
|
||||
if err == nil {
|
||||
t.Fatal("tenant credential must not manage the platform root domain")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyDNSCredentialCreatesAndDeletesExactRecord(t *testing.T) {
|
||||
provider := &dnsCredentialTestProvider{}
|
||||
if err := verifyDNSCredential(context.Background(), provider, "_svh-check-a.example.com", "verification-value"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if provider.presentName != "_svh-check-a.example.com" || provider.presentValue != "verification-value" {
|
||||
t.Fatalf("unexpected TXT record: %q %q", provider.presentName, provider.presentValue)
|
||||
}
|
||||
if provider.cleanedID != "provider-record-42" {
|
||||
t.Fatalf("cleanup used %q instead of exact provider record id", provider.cleanedID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyDNSCredentialReportsCleanupFailure(t *testing.T) {
|
||||
provider := &dnsCredentialTestProvider{cleanupErr: errors.New("delete denied")}
|
||||
err := verifyDNSCredential(context.Background(), provider, "_svh-check-a.example.com", "verification-value")
|
||||
if err == nil || provider.cleanedID != "provider-record-42" || provider.cleanupCalls != dnsCleanupAttempts {
|
||||
t.Fatal("cleanup permission failure was not reported")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyDNSCredentialRetriesTransientCleanupFailure(t *testing.T) {
|
||||
provider := &dnsCredentialTestProvider{cleanupFailures: 1}
|
||||
if err := verifyDNSCredential(context.Background(), provider, "_svh-check-a.example.com", "verification-value"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if provider.cleanupCalls != 2 {
|
||||
t.Fatalf("cleanup calls = %d, want 2", provider.cleanupCalls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sea-vhost/internal/dnsprovider"
|
||||
"sea-vhost/internal/store"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type DNSZoneChoice struct {
|
||||
dnsprovider.Zone
|
||||
VerificationToken string `json:"verificationToken"`
|
||||
}
|
||||
type dnsZoneProof struct {
|
||||
Owner, Provider, Hash, ID, Zone string
|
||||
Expires int64
|
||||
}
|
||||
|
||||
func credentialHash(c dnsprovider.Credential) string {
|
||||
c.ZoneID = ""
|
||||
raw, _ := json.Marshal(c)
|
||||
sum := sha256.Sum256(raw)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
func (s *Projects) DiscoverDNSZones(ctx context.Context, u store.User, platform bool, input DNSCredentialInput) ([]DNSZoneChoice, error) {
|
||||
owner, err := dnsCredentialOwner(u, platform)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ownerKey := "platform"
|
||||
if owner != nil {
|
||||
ownerKey = fmt.Sprintf("tenant:%d", *owner)
|
||||
}
|
||||
hint := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(input.ZoneName), "."))
|
||||
if hint != "" && !domainPattern.MatchString(hint) {
|
||||
return nil, errors.New("指定域名格式无效")
|
||||
}
|
||||
zones, err := dnsprovider.DiscoverZones(ctx, input.Provider, input.Credential, hint)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := []DNSZoneChoice{}
|
||||
for _, z := range zones {
|
||||
if !domainPattern.MatchString(z.Name) {
|
||||
continue
|
||||
}
|
||||
proof := dnsZoneProof{Owner: ownerKey, Provider: input.Provider, Hash: credentialHash(input.Credential), ID: z.ID, Zone: z.Name, Expires: time.Now().Add(15 * time.Minute).Unix()}
|
||||
raw, _ := json.Marshal(proof)
|
||||
token, e := s.credentials.Seal("dns-zone-choice", string(raw))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = append(out, DNSZoneChoice{Zone: z, VerificationToken: hex.EncodeToString(token)})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (s *Projects) verifyDNSZoneChoice(u store.User, platform bool, input DNSCredentialInput) error {
|
||||
owner, e := dnsCredentialOwner(u, platform)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
ownerKey := "platform"
|
||||
if owner != nil {
|
||||
ownerKey = fmt.Sprintf("tenant:%d", *owner)
|
||||
}
|
||||
raw, e := hex.DecodeString(input.VerificationToken)
|
||||
if e != nil || len(raw) > 4096 {
|
||||
return errors.New("请先读取并选择 DNS 域名")
|
||||
}
|
||||
plain, e := s.credentials.Open("dns-zone-choice", raw)
|
||||
if e != nil {
|
||||
return errors.New("DNS 域名选择已失效,请重新读取")
|
||||
}
|
||||
var p dnsZoneProof
|
||||
if json.Unmarshal([]byte(plain), &p) != nil || p.Owner != ownerKey || p.Provider != input.Provider || p.Hash != credentialHash(input.Credential) || p.Zone != input.ZoneName || p.Expires < time.Now().Unix() {
|
||||
return errors.New("DNS 域名选择已失效或票据已变更,请重新读取")
|
||||
}
|
||||
if (input.Provider == "cloudflare" || input.Provider == "dnsmgr") && input.Credential.ZoneID != p.ID {
|
||||
return errors.New("DNS 区域编号与已验证域名不一致")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"sea-vhost/internal/dnsprovider"
|
||||
"sea-vhost/internal/secrets"
|
||||
"sea-vhost/internal/store"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDNSZoneChoiceBindsOwnerCredentialAndZone(t *testing.T) {
|
||||
s := &Projects{credentials: secrets.New("dns-proof-test-secret-at-least-thirty-two-bytes")}
|
||||
owner := uint64(12)
|
||||
u := store.User{Role: "tenant", TenantID: &owner}
|
||||
c := dnsprovider.Credential{APIToken: "fixture-api-token-with-sufficient-length", ZoneID: "zone12345678"}
|
||||
proof := dnsZoneProof{Owner: "tenant:12", Provider: "cloudflare", Hash: credentialHash(c), ID: c.ZoneID, Zone: "example.com", Expires: time.Now().Add(time.Minute).Unix()}
|
||||
raw, _ := json.Marshal(proof)
|
||||
sealed, e := s.credentials.Seal("dns-zone-choice", string(raw))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
input := DNSCredentialInput{Provider: "cloudflare", ZoneName: "example.com", Credential: c, VerificationToken: hex.EncodeToString(sealed)}
|
||||
if e = s.verifyDNSZoneChoice(u, false, input); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
other := input
|
||||
other.ZoneName = "victim.example"
|
||||
if s.verifyDNSZoneChoice(u, false, other) == nil {
|
||||
t.Fatal("zone substitution accepted")
|
||||
}
|
||||
other = input
|
||||
other.Credential.ZoneID = "another-zone"
|
||||
if s.verifyDNSZoneChoice(u, false, other) == nil {
|
||||
t.Fatal("zone ID substitution accepted")
|
||||
}
|
||||
other = input
|
||||
other.Credential.APIToken = "different-api-token"
|
||||
if s.verifyDNSZoneChoice(u, false, other) == nil {
|
||||
t.Fatal("credential substitution accepted")
|
||||
}
|
||||
second := uint64(13)
|
||||
if s.verifyDNSZoneChoice(store.User{Role: "tenant", TenantID: &second}, false, input) == nil {
|
||||
t.Fatal("cross-account proof accepted")
|
||||
}
|
||||
if s.verifyDNSZoneChoice(store.User{Role: "admin"}, true, input) == nil {
|
||||
t.Fatal("tenant proof accepted as platform credentials")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"sea-vhost/internal/store"
|
||||
)
|
||||
|
||||
// ProvisionDomainDNS creates an exact, provider-tracked CNAME for an approved
|
||||
// customer domain. Platform credentials are never used for a customer's zone;
|
||||
// routeDNSCredentials enforces that ownership boundary.
|
||||
func (s *Projects) ProvisionDomainDNS(ctx context.Context, user store.User, domainID uint64) (store.DomainResource, error) {
|
||||
s.domainMu.Lock()
|
||||
defer s.domainMu.Unlock()
|
||||
item, err := s.authorizedDomain(ctx, user, domainID)
|
||||
if err != nil {
|
||||
return store.DomainResource{}, err
|
||||
}
|
||||
if item.Kind != "custom" || item.Status != "approved" {
|
||||
return store.DomainResource{}, errors.New("仅已批准的自绑定域名可以创建托管解析")
|
||||
}
|
||||
if item.DNSRecordID != "" {
|
||||
return store.DomainResource{}, errors.New("该域名已有托管 DNS 记录,请先删除原记录")
|
||||
}
|
||||
target := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(item.SiteAssignedDomain), "."))
|
||||
if !domainPattern.MatchString(target) || s.isReservedDomain(item.Domain) {
|
||||
return store.DomainResource{}, errors.New("域名解析目标或域名范围无效")
|
||||
}
|
||||
credentials, err := s.store.CertificateDNSCredentials(ctx, item.TenantID)
|
||||
if err != nil {
|
||||
return store.DomainResource{}, err
|
||||
}
|
||||
routes, err := routeDNSCredentials([]string{item.Domain}, s.nodeRootDomain(ctx), credentials)
|
||||
if err != nil {
|
||||
return store.DomainResource{}, err
|
||||
}
|
||||
credential := routes[strings.ToLower(strings.TrimSuffix(item.Domain, "."))]
|
||||
provider, err := s.dnsProvider(credential)
|
||||
if err != nil {
|
||||
return store.DomainResource{}, err
|
||||
}
|
||||
recordID, err := provider.CreateRecord(ctx, item.Domain, "CNAME", target)
|
||||
if err != nil {
|
||||
_ = s.store.SetDomainDNSError(context.WithoutCancel(ctx), item.ID, err.Error())
|
||||
return store.DomainResource{}, fmt.Errorf("创建 CNAME 记录失败: %w", err)
|
||||
}
|
||||
if err = s.store.SetDomainDNSRecord(ctx, item.ID, credential.ID, recordID, "CNAME"); err != nil {
|
||||
cleanupErr := cleanupDNSRecord(context.WithoutCancel(ctx), provider, recordID)
|
||||
if cleanupErr != nil {
|
||||
return store.DomainResource{}, fmt.Errorf("DNS 记录已创建但状态保存和回滚均失败: %w", errors.Join(err, cleanupErr))
|
||||
}
|
||||
return store.DomainResource{}, err
|
||||
}
|
||||
return s.store.DomainByID(ctx, item.ID)
|
||||
}
|
||||
|
||||
func (s *Projects) RemoveDomainDNS(ctx context.Context, user store.User, domainID uint64) (store.DomainResource, error) {
|
||||
s.domainMu.Lock()
|
||||
defer s.domainMu.Unlock()
|
||||
return s.removeDomainDNS(ctx, user, domainID)
|
||||
}
|
||||
|
||||
func (s *Projects) removeDomainDNS(ctx context.Context, user store.User, domainID uint64) (store.DomainResource, error) {
|
||||
item, err := s.authorizedDomain(ctx, user, domainID)
|
||||
if err != nil {
|
||||
return store.DomainResource{}, err
|
||||
}
|
||||
if item.DNSCredentialID == nil || item.DNSRecordID == "" {
|
||||
return store.DomainResource{}, errors.New("该域名没有托管 DNS 记录")
|
||||
}
|
||||
owner, err := s.store.ProjectOwner(ctx, item.ProjectID)
|
||||
if err != nil || owner == nil {
|
||||
return store.DomainResource{}, errors.New("当前主机未绑定可管理此 DNS 凭据的用户")
|
||||
}
|
||||
credential, err := s.store.DNSCredential(ctx, *item.DNSCredentialID, owner)
|
||||
if err != nil {
|
||||
return store.DomainResource{}, errors.New("创建该记录的 DNS 凭据已不可用,无法安全删除远端记录")
|
||||
}
|
||||
provider, err := s.dnsProvider(credential)
|
||||
if err != nil {
|
||||
return store.DomainResource{}, err
|
||||
}
|
||||
if err = cleanupDNSRecord(ctx, provider, item.DNSRecordID); err != nil {
|
||||
_ = s.store.SetDomainDNSError(context.WithoutCancel(ctx), item.ID, err.Error())
|
||||
return store.DomainResource{}, fmt.Errorf("删除 DNS 记录失败: %w", err)
|
||||
}
|
||||
if err = s.store.ClearDomainDNSRecord(ctx, item.ID, credential.ID, item.DNSRecordID); err != nil {
|
||||
return store.DomainResource{}, errors.New("远端记录已删除,但本地状态清理失败,请刷新后核对")
|
||||
}
|
||||
return s.store.DomainByID(ctx, item.ID)
|
||||
}
|
||||
|
||||
// UnbindDomain keeps the row until both tracked external resources are gone,
|
||||
// so a failed operation remains visible and can be retried safely.
|
||||
func (s *Projects) UnbindDomain(ctx context.Context, user store.User, domainID uint64) error {
|
||||
if user.Role == "admin" {
|
||||
item, err := s.store.DomainByID(ctx, domainID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
release, err := s.BeginHostAccess(item.ProjectID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
}
|
||||
s.domainMu.Lock()
|
||||
defer s.domainMu.Unlock()
|
||||
item, err := s.authorizedDomain(ctx, user, domainID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if item.Kind != "custom" {
|
||||
return errors.New("默认主机域名随主机管理,不能单独解绑")
|
||||
}
|
||||
if item.DNSRecordID != "" {
|
||||
if _, err = s.removeDomainDNS(ctx, user, domainID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if item.PanelSiteID > 0 {
|
||||
if err = s.panel.DeleteDomain(ctx, item.PanelSiteID, item.SiteAssignedDomain, item.Domain); err != nil {
|
||||
return fmt.Errorf("移除宝塔域名绑定失败,可重试: %w", err)
|
||||
}
|
||||
}
|
||||
return s.store.DeleteCustomDomain(ctx, item.ID, item.ProjectID)
|
||||
}
|
||||
|
||||
func (s *Projects) authorizedDomain(ctx context.Context, user store.User, domainID uint64) (store.DomainResource, error) {
|
||||
item, err := s.store.DomainByID(ctx, domainID)
|
||||
if err != nil {
|
||||
return store.DomainResource{}, err
|
||||
}
|
||||
if user.Role != "admin" {
|
||||
if (user.Role != "tenant" && user.Role != "host") || user.TenantID == nil {
|
||||
return store.DomainResource{}, store.ErrNotFound
|
||||
}
|
||||
if _, err = s.store.ProjectForUser(ctx, user, item.ProjectID); err != nil {
|
||||
return store.DomainResource{}, err
|
||||
}
|
||||
if err = s.ensureTenantWritable(ctx, item.TenantID); err != nil {
|
||||
return store.DomainResource{}, err
|
||||
}
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCustomDomainRejectsEveryPlatformReservedZone(t *testing.T) {
|
||||
projects := &Projects{reservedDomains: []string{"hosts.example.com", "console.example.com", "ftp.example.com"}}
|
||||
tests := []string{
|
||||
"hosts.example.com",
|
||||
"tenant.hosts.example.com",
|
||||
"console.example.com",
|
||||
"login.console.example.com",
|
||||
"ftp.example.com",
|
||||
"files.ftp.example.com",
|
||||
}
|
||||
for _, domain := range tests {
|
||||
_, _, err := projects.customDomain(context.Background(), domain)
|
||||
if err == nil || !strings.Contains(err.Error(), "平台保留域名") {
|
||||
t.Errorf("reserved domain %q was accepted: %v", domain, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"sea-vhost/internal/nodefiles"
|
||||
)
|
||||
|
||||
func (s *Projects) WithFileOpener(open func(context.Context, string) (*nodefiles.Root, error)) *Projects {
|
||||
s.fileOpener = open
|
||||
return s
|
||||
}
|
||||
func (s *Projects) OpenFiles(ctx context.Context, root string) (*nodefiles.Root, error) {
|
||||
if s.fileOpener != nil {
|
||||
return s.fileOpener(ctx, root)
|
||||
}
|
||||
return nodefiles.New(ctx, filepath.Base(root), func(_ context.Context, q nodefiles.Request) (nodefiles.Response, error) {
|
||||
return nodefiles.Execute(root, q), nil
|
||||
}), nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sea-vhost/internal/isolation"
|
||||
"sea-vhost/internal/panel"
|
||||
"sea-vhost/internal/scope"
|
||||
"sea-vhost/internal/store"
|
||||
)
|
||||
|
||||
func (s *Projects) ManageFTP(ctx context.Context, u store.User, id uint64, action string) (string, error) {
|
||||
p, e := s.authorizedProject(ctx, u, id)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
ctx = scope.WithProject(ctx, p.ID, p.NodeID)
|
||||
if action != "disable" {
|
||||
if e = s.ensureTenantWritable(ctx, p.TenantID); e != nil {
|
||||
return "", e
|
||||
}
|
||||
}
|
||||
rows, e := s.store.ListFTPResources(ctx, p.TenantID, &id)
|
||||
if e != nil || len(rows) != 1 {
|
||||
return "", errors.New("FTP 账号不存在")
|
||||
}
|
||||
ftp := rows[0]
|
||||
plan, _, e := s.store.PlanAndUsage(ctx, p.TenantID)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
agent, ok := s.isolation.(isolation.FTPManager)
|
||||
if !ok {
|
||||
return "", errors.New("节点未支持 FTP 管理")
|
||||
}
|
||||
spec := isolation.ProjectSpec{TenantID: p.TenantID, HostName: p.HostName, RunPath: p.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(p.ProcessLimit)}
|
||||
switch action {
|
||||
case "enable", "disable":
|
||||
enabled := action == "enable"
|
||||
if e = s.panel.SetFTPState(ctx, ftp.PanelID, ftp.Username, enabled); e != nil {
|
||||
return "", e
|
||||
}
|
||||
if e = s.store.SetFTPEnabled(ctx, p.ID, enabled); e != nil {
|
||||
_ = s.panel.SetFTPState(context.WithoutCancel(ctx), ftp.PanelID, ftp.Username, ftp.Enabled)
|
||||
return "", e
|
||||
}
|
||||
if !enabled {
|
||||
if e = agent.DisconnectFTP(ctx, spec); e != nil {
|
||||
return "", errors.New("FTP 已停用,旧连接断开失败,请稍后重试")
|
||||
}
|
||||
}
|
||||
return "", nil
|
||||
case "reset":
|
||||
adapter, ok := s.panel.(panel.CredentialManager)
|
||||
if !ok {
|
||||
return "", errors.New("面板未支持改密")
|
||||
}
|
||||
stored, e := s.store.Credentials(ctx, p.TenantID, p.ID)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
old, e := s.credentials.Open(credentialLabel("ftp", p.ID), stored.FTPPasswordCipher)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
password, e := randomPanelPassword()
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
cipher, e := s.credentials.Seal(credentialLabel("ftp", p.ID), password)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
if e = adapter.SetFTPPassword(ctx, ftp.PanelID, ftp.Username, password); e != nil {
|
||||
return "", e
|
||||
}
|
||||
if e = s.store.SetFTPPasswordCipher(ctx, p.ID, cipher); e != nil {
|
||||
_ = adapter.SetFTPPassword(context.WithoutCancel(ctx), ftp.PanelID, ftp.Username, old)
|
||||
return "", e
|
||||
}
|
||||
if e = agent.DisconnectFTP(ctx, spec); e != nil {
|
||||
return password, errors.New("密码已更新,旧连接断开失败,请停用后重新启用 FTP")
|
||||
}
|
||||
return password, nil
|
||||
default:
|
||||
return "", errors.New("不支持的 FTP 操作")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sea-vhost/internal/isolation"
|
||||
"sea-vhost/internal/scope"
|
||||
"sea-vhost/internal/store"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Projects) processHostLifecycle(ctx context.Context) {
|
||||
now := time.Now().UTC()
|
||||
if err := s.store.AdvanceHostLifecycle(ctx, now); err != nil {
|
||||
return
|
||||
}
|
||||
hosts, err := s.store.HostLifecycles(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, h := range hosts {
|
||||
operation, cancel := context.WithTimeout(scope.WithProject(ctx, h.ProjectID, h.NodeID), 15*time.Minute)
|
||||
err = s.withHostOwnershipChange(operation, h.ProjectID, func() error {
|
||||
// Reload after acquiring the host lock: a restore may have won the race.
|
||||
current, e := s.store.HostLifecycle(operation, h.ProjectID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if current.State != "grace" && current.State != "recycle" {
|
||||
return nil
|
||||
}
|
||||
if e = s.suspendLifecycleHost(operation, current); e != nil {
|
||||
return e
|
||||
}
|
||||
if current.State == "recycle" && current.PurgeAfter != nil && !current.PurgeAfter.After(time.Now().UTC()) {
|
||||
p, e := s.store.Project(operation, current.TenantID, current.ProjectID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
plan, _, e := s.store.PlanAndUsage(operation, current.TenantID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
return s.purgeExpiredTenant(operation, store.TenantSummary{ID: current.TenantID, Name: p.HostName, BackupPurgeAfter: current.BackupPurgeAfter}, []store.Project{p}, plan)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
_ = s.store.RecordRecycleError(context.WithoutCancel(operation), h.ProjectID, err.Error())
|
||||
_ = s.store.EnqueueAdminNotification(context.WithoutCancel(operation), "critical", "lifecycle", "主机停用或回收清理未完成", fmt.Sprintf("主机 #%d,节点 %d:%v", h.ProjectID, h.NodeID, err))
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
backups, err := s.store.ExpiredTenantBackups(ctx, now, 100)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, backup := range backups {
|
||||
op := scope.WithNode(ctx, backup.NodeID)
|
||||
if err = s.isolation.DeleteProjectBackup(op, isolation.ProjectBackup{TenantID: backup.TenantID, HostName: backup.HostName, ArchivePath: backup.ArchivePath, SizeBytes: backup.SizeBytes}); err == nil {
|
||||
_ = s.store.MarkTenantBackupDeleted(op, backup.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// suspension is repeatable and attempts every service even if one fails.
|
||||
func (s *Projects) suspendLifecycleHost(ctx context.Context, h store.HostLifecycle) error {
|
||||
p, err := s.store.Project(ctx, h.TenantID, h.ProjectID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
plan, _, err := s.store.PlanAndUsage(ctx, h.TenantID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sites, err := s.store.ListSites(ctx, h.TenantID, h.ProjectID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var failures []error
|
||||
for _, site := range sites {
|
||||
if site.Runtime == "PHP" {
|
||||
phpSpec, e := s.phpIdentitySpec(ctx, p, site)
|
||||
if e != nil {
|
||||
failures = append(failures, e)
|
||||
} else if e = s.isolation.SetPHPIdentityState(ctx, phpSpec, false); e != nil {
|
||||
failures = append(failures, e)
|
||||
}
|
||||
}
|
||||
if site.PanelSiteID > 0 {
|
||||
if e := s.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, false); e != nil {
|
||||
failures = append(failures, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
spec := isolation.ProjectSpec{TenantID: h.TenantID, HostName: p.HostName, RunPath: p.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(p.ProcessLimit)}
|
||||
if e := s.isolation.TerminateProcesses(ctx, spec); e != nil {
|
||||
failures = append(failures, e)
|
||||
}
|
||||
ftps, e := s.store.ListFTPResources(ctx, h.TenantID, &h.ProjectID)
|
||||
if e != nil {
|
||||
failures = append(failures, e)
|
||||
}
|
||||
for _, ftp := range ftps {
|
||||
if e = s.panel.SetFTPState(ctx, ftp.PanelID, ftp.Username, false); e != nil {
|
||||
failures = append(failures, e)
|
||||
}
|
||||
}
|
||||
databases, e := s.store.ListDatabaseResources(ctx, h.TenantID, &h.ProjectID)
|
||||
if e != nil {
|
||||
failures = append(failures, e)
|
||||
}
|
||||
for _, db := range databases {
|
||||
if e = s.isolation.ConfigureDatabaseAccess(ctx, isolation.DatabaseAccessSpec{Project: spec, Database: db.Name, ReadOnly: true, BlockCleanup: true}); e != nil {
|
||||
failures = append(failures, e)
|
||||
}
|
||||
}
|
||||
if manager, ok := s.isolation.(isolation.CredentialSessions); ok {
|
||||
if e = manager.DisconnectCredentialSessions(ctx, spec); e != nil {
|
||||
failures = append(failures, e)
|
||||
}
|
||||
} else {
|
||||
failures = append(failures, errors.New("节点不支持撤销 FTP 与数据库现有连接"))
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return errors.Join(failures...)
|
||||
}
|
||||
if e = s.store.ForceTenantStopped(ctx, h.TenantID); e != nil {
|
||||
return e
|
||||
}
|
||||
return s.store.RecordRecycleError(ctx, h.ProjectID, "")
|
||||
}
|
||||
func (s *Projects) RecycleManagedHost(ctx context.Context, id uint64) error {
|
||||
return s.withHostOwnershipChange(ctx, id, func() error {
|
||||
if err := s.store.RecycleHost(ctx, id, time.Now().UTC()); err != nil {
|
||||
return err
|
||||
}
|
||||
h, err := s.store.HostLifecycle(ctx, id)
|
||||
if err == nil {
|
||||
err = s.suspendLifecycleHost(ctx, h)
|
||||
}
|
||||
if err != nil {
|
||||
_ = s.store.RecordRecycleError(context.WithoutCancel(ctx), id, err.Error())
|
||||
return fmt.Errorf("主机已进入回收期,部分服务停用失败,调度器将重试:%w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
func (s *Projects) RestoreManagedHost(ctx context.Context, id uint64) error {
|
||||
return s.withHostOwnershipChange(ctx, id, func() error {
|
||||
// Complete suspension before lifting the access barrier; websites stay stopped.
|
||||
h, err := s.store.HostLifecycle(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if h.State != "recycle" {
|
||||
return errors.New("主机不在回收期")
|
||||
}
|
||||
if err = s.suspendLifecycleHost(ctx, h); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.store.RestoreHost(ctx, id, time.Now().UTC())
|
||||
})
|
||||
}
|
||||
func (s *Projects) UpdateManagedNode(ctx context.Context, id uint64, input store.Node) error {
|
||||
return s.withNodeMaintenanceWait(scope.WithNode(ctx, id), 10*time.Second, func() error { return s.store.UpdateNodeMetadata(ctx, id, input) })
|
||||
}
|
||||
func (s *Projects) DeleteManagedNode(ctx context.Context, id uint64) error {
|
||||
return s.withNodeMaintenanceWait(scope.WithNode(ctx, id), 10*time.Second, func() error { return s.store.DeleteNode(ctx, id) })
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sea-vhost/internal/auth"
|
||||
"sea-vhost/internal/scope"
|
||||
"sea-vhost/internal/store"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Projects) hostAccessGate(id uint64) *sync.RWMutex {
|
||||
gate, _ := s.hostAccessGates.LoadOrStore(id, &sync.RWMutex{})
|
||||
return gate.(*sync.RWMutex)
|
||||
}
|
||||
func (s *Projects) BeginHostAccess(id uint64) (func(), error) {
|
||||
gate := s.hostAccessGate(id)
|
||||
if !gate.TryRLock() {
|
||||
return nil, store.ErrManagementLocked
|
||||
}
|
||||
return gate.RUnlock, nil
|
||||
}
|
||||
func (s *Projects) withHostOwnershipChange(ctx context.Context, id uint64, operation func() error) error {
|
||||
gate := s.hostAccessGate(id)
|
||||
deadline := time.NewTimer(10 * time.Second)
|
||||
defer deadline.Stop()
|
||||
for !gate.TryLock() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-deadline.C:
|
||||
return errors.New("主机正在处理访问请求,请稍后重试")
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
defer gate.Unlock()
|
||||
return s.withNodeMaintenanceWait(ctx, 10*time.Second, operation)
|
||||
}
|
||||
|
||||
func (s *Projects) AssignUnassignedHost(ctx context.Context, id, version, target uint64) error {
|
||||
return s.withHostOwnershipChange(ctx, id, func() error { return s.store.BindUnassignedHost(ctx, id, version, target) })
|
||||
}
|
||||
func (s *Projects) ResetManagedHostLogin(ctx context.Context, id, version uint64) (string, error) {
|
||||
var password string
|
||||
err := s.withHostOwnershipChange(ctx, id, func() error {
|
||||
hosts, e := s.store.ListAdminProjects(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
var host *store.AdminProject
|
||||
for i := range hosts {
|
||||
if hosts[i].ID == id {
|
||||
host = &hosts[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if host == nil {
|
||||
return store.ErrNotFound
|
||||
}
|
||||
if host.ManagementLocked {
|
||||
return store.ErrManagementLocked
|
||||
}
|
||||
if host.OwnershipVersion != version {
|
||||
return errors.New("主机归属已变化,请重新预览")
|
||||
}
|
||||
password, e = randomPassword()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
hash, e := auth.HashPassword(password)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
return s.store.ResetHostPassword(ctx, host.TenantID, id, hash)
|
||||
})
|
||||
return password, err
|
||||
}
|
||||
|
||||
// A resource namespace is permanent. Customer ownership may be absent or
|
||||
// change later without renaming the UID, directory, database or FTP identity.
|
||||
func (s *Projects) CreateManagedHost(ctx context.Context, ownerTenantID uint64, input CreateProjectInput) (CreatedProject, error) {
|
||||
if ownerTenantID > 0 {
|
||||
if _, err := s.store.TenantOwner(ctx, ownerTenantID); err != nil {
|
||||
return CreatedProject{}, errors.New("用户不存在或已停用")
|
||||
}
|
||||
}
|
||||
if input.NodeID == 0 || input.PlanID == 0 {
|
||||
return CreatedProject{}, errors.New("请选择节点和套餐")
|
||||
}
|
||||
if _, err := s.store.Plan(ctx, input.PlanID); err != nil {
|
||||
return CreatedProject{}, errors.New("套餐不存在")
|
||||
}
|
||||
node, err := s.store.Node(ctx, input.NodeID)
|
||||
if err != nil || !node.Enabled {
|
||||
return CreatedProject{}, errors.New("节点不可用")
|
||||
}
|
||||
ctx = scope.WithNode(ctx, node.ID)
|
||||
if err = s.validateRuntime(ctx, input.Runtime, input.Version); err != nil {
|
||||
return CreatedProject{}, err
|
||||
}
|
||||
namespace, err := s.store.NewResourceNamespace(ctx, input.PlanID)
|
||||
if err != nil {
|
||||
return CreatedProject{}, err
|
||||
}
|
||||
input.OwnershipSpecified = true
|
||||
input.OwnerTenantID = nil
|
||||
if ownerTenantID > 0 {
|
||||
input.OwnerTenantID = &ownerTenantID
|
||||
}
|
||||
result, err := s.Create(ctx, store.User{Role: "tenant", TenantID: &namespace}, input)
|
||||
if err != nil {
|
||||
_ = s.store.DeleteUnusedResourceNamespace(context.WithoutCancel(ctx), namespace)
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sea-vhost/internal/scope"
|
||||
)
|
||||
|
||||
func (s *Projects) nodeRootDomain(ctx context.Context) string {
|
||||
if s.store != nil {
|
||||
n, err := s.store.Node(ctx, scope.Node(ctx))
|
||||
if err == nil {
|
||||
return n.RootDomain
|
||||
}
|
||||
}
|
||||
return s.rootDomain
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Projects) withNodeMaintenance(ctx context.Context, operation func() error) error {
|
||||
return s.withNodeMaintenanceWait(ctx, 0, operation)
|
||||
}
|
||||
|
||||
func (s *Projects) withNodeMaintenanceWait(ctx context.Context, wait time.Duration, operation func() error) error {
|
||||
gate := s.nodeGate(ctx)
|
||||
deadline := time.Now().Add(wait)
|
||||
for !gate.TryLock() {
|
||||
if wait == 0 || !time.Now().Before(deadline) {
|
||||
return errors.New("节点正在执行主机操作或环境维护,请稍后重试")
|
||||
}
|
||||
timer := time.NewTimer(50 * time.Millisecond)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
defer gate.Unlock()
|
||||
blocked, err := s.store.RuntimeMutationBlocked(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if blocked {
|
||||
return errors.New("请先完成当前节点的运行环境维护任务")
|
||||
}
|
||||
return operation()
|
||||
}
|
||||
func (s *Projects) ReconcileNodeIdentities(ctx context.Context) error {
|
||||
return s.withNodeMaintenanceWait(ctx, 10*time.Second, func() error { return s.ReconcileIdentities(ctx) })
|
||||
}
|
||||
func (s *Projects) ApplyHostSubscription(ctx context.Context, id, plan uint64, expiry *time.Time) error {
|
||||
return s.withNodeMaintenance(ctx, func() error {
|
||||
if err := s.store.SetHostSubscription(ctx, id, plan, expiry); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.ReconcileIdentities(ctx)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"sea-vhost/internal/auth"
|
||||
"sea-vhost/internal/isolation"
|
||||
"sea-vhost/internal/panel"
|
||||
"sea-vhost/internal/scope"
|
||||
"sea-vhost/internal/store"
|
||||
)
|
||||
|
||||
var ErrOwnershipIncomplete = errors.New("归属变更未完成,主机管理已锁定,请按原目标和策略恢复")
|
||||
|
||||
type OwnershipCredentials struct {
|
||||
HostPassword string `json:"hostPassword,omitempty"`
|
||||
FTPPassword string `json:"ftpPassword,omitempty"`
|
||||
DatabasePassword string `json:"databasePassword,omitempty"`
|
||||
}
|
||||
|
||||
// Ownership changes never rename a resource namespace, Unix identity or directory.
|
||||
// Persist staged credentials before native mutations so an explicit recovery can
|
||||
// repeat those mutations with the same passwords after a timeout or restart.
|
||||
func (s *Projects) ChangeHostOwner(ctx context.Context, id, version, target uint64, mode string, stop, resume bool) (OwnershipCredentials, error) {
|
||||
var result OwnershipCredentials
|
||||
if mode != "preserve" && mode != "reset" {
|
||||
return result, errors.New("请选择保留或重置凭据")
|
||||
}
|
||||
err := s.withHostOwnershipChange(ctx, id, func() error {
|
||||
hosts, e := s.store.ListAdminProjects(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
var host *store.AdminProject
|
||||
for i := range hosts {
|
||||
if hosts[i].ID == id {
|
||||
host = &hosts[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if host == nil {
|
||||
return store.ErrNotFound
|
||||
}
|
||||
if host.OwnershipVersion != version {
|
||||
return errors.New("主机归属已变化,请重新预览")
|
||||
}
|
||||
if !host.ManagementLocked && ((host.OwnerTenantID == nil && target == 0) || (host.OwnerTenantID != nil && *host.OwnerTenantID == target)) {
|
||||
return nil
|
||||
}
|
||||
ctx = scope.WithProject(ctx, id, host.NodeID)
|
||||
var manager panel.CredentialManager
|
||||
var sessions isolation.CredentialSessions
|
||||
if mode == "reset" {
|
||||
var ok bool
|
||||
manager, ok = s.panel.(panel.CredentialManager)
|
||||
if !ok {
|
||||
return errors.New("面板尚未支持凭据重置")
|
||||
}
|
||||
sessions, ok = s.isolation.(isolation.CredentialSessions)
|
||||
if !ok {
|
||||
return errors.New("节点尚未支持旧连接注销")
|
||||
}
|
||||
}
|
||||
label := fmt.Sprintf("ownership-change:%d:%d", id, version)
|
||||
var cipher []byte
|
||||
if !host.ManagementLocked && mode == "reset" {
|
||||
result.HostPassword, e = randomPassword()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
result.FTPPassword, e = randomPanelPassword()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
result.DatabasePassword, e = randomPanelPassword()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
raw, _ := json.Marshal(result)
|
||||
cipher, e = s.credentials.Seal(label, string(raw))
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
pending, e := s.store.BeginOwnershipChange(ctx, id, version, target, mode, stop, resume, cipher)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
// From this point any failure is deliberately fail-closed and recoverable.
|
||||
finish := func() error {
|
||||
if mode == "reset" {
|
||||
raw, e := s.credentials.Open(label, pending.CredentialsCipher)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if e = json.Unmarshal([]byte(raw), &result); e != nil {
|
||||
return e
|
||||
}
|
||||
if result.HostPassword == "" || result.FTPPassword == "" || result.DatabasePassword == "" {
|
||||
return errors.New("staged credentials missing")
|
||||
}
|
||||
}
|
||||
if stop {
|
||||
sites, e := s.store.ListSites(ctx, host.TenantID, id)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
for _, site := range sites {
|
||||
if site.PanelSiteID == 0 {
|
||||
continue
|
||||
}
|
||||
e = s.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, false)
|
||||
if e != nil && site.Runtime != "PHP" {
|
||||
plan, _, planErr := s.store.PlanAndUsage(ctx, host.TenantID)
|
||||
if planErr != nil {
|
||||
return planErr
|
||||
}
|
||||
if terminateErr := s.isolation.TerminateRuntime(ctx, isolation.RuntimeProcessSpec{Project: isolation.ProjectSpec{TenantID: host.TenantID, HostName: host.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)}}); terminateErr != nil {
|
||||
return terminateErr
|
||||
}
|
||||
e = s.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, false)
|
||||
}
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if site.Runtime == "PHP" {
|
||||
spec, e := s.phpIdentitySpec(ctx, host.Project, site)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if e = s.isolation.SetPHPIdentityState(ctx, spec, false); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if site.Primary {
|
||||
e = s.store.SetProjectState(ctx, host.TenantID, id, "stopped")
|
||||
} else {
|
||||
e = s.store.SetSiteState(ctx, host.TenantID, id, site.ID, "stopped")
|
||||
}
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
}
|
||||
var hash string
|
||||
var ftpCipher, dbCipher []byte
|
||||
if mode == "reset" {
|
||||
ftps, e := s.store.ListFTPResources(ctx, host.TenantID, &id)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
var ftp *store.FTPResource
|
||||
for i := range ftps {
|
||||
if ftps[i].ProjectID == id {
|
||||
ftp = &ftps[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
dbs, e := s.store.ListDatabaseResources(ctx, host.TenantID, &id)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
var database *store.DatabaseResource
|
||||
for i := range dbs {
|
||||
if dbs[i].ProjectID == id {
|
||||
database = &dbs[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if ftp == nil || database == nil {
|
||||
return errors.New("native resources missing")
|
||||
}
|
||||
if e = manager.SetFTPPassword(ctx, ftp.PanelID, ftp.Username, result.FTPPassword); e != nil {
|
||||
return e
|
||||
}
|
||||
if e = manager.SetDatabasePassword(ctx, database.PanelID, database.Username, result.DatabasePassword); e != nil {
|
||||
return e
|
||||
}
|
||||
plan, _, e := s.store.PlanAndUsage(ctx, host.TenantID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if e = sessions.DisconnectCredentialSessions(ctx, isolation.ProjectSpec{TenantID: host.TenantID, HostName: host.HostName, RunPath: host.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(host.ProcessLimit)}); e != nil {
|
||||
return e
|
||||
}
|
||||
hash, e = auth.HashPassword(result.HostPassword)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
ftpCipher, e = s.credentials.Seal(credentialLabel("ftp", id), result.FTPPassword)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
dbCipher, e = s.credentials.Seal(credentialLabel("database", id), result.DatabasePassword)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return s.store.CompleteOwnershipChange(ctx, id, version, target, mode, hash, ftpCipher, dbCipher)
|
||||
}
|
||||
if e = finish(); e != nil {
|
||||
return ErrOwnershipIncomplete
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return OwnershipCredentials{}, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sea-vhost/internal/isolation"
|
||||
"sea-vhost/internal/scope"
|
||||
"sea-vhost/internal/store"
|
||||
)
|
||||
|
||||
func (s *Projects) PHPMyAdmin(ctx context.Context, u store.User, id uint64, q isolation.PHPMyAdminRequest) (isolation.PHPMyAdminResponse, error) {
|
||||
p, e := s.authorizedProject(ctx, u, id)
|
||||
if e != nil {
|
||||
return isolation.PHPMyAdminResponse{}, e
|
||||
}
|
||||
ctx = scope.WithProject(ctx, p.ID, p.NodeID)
|
||||
if q.Method == "POST" {
|
||||
if e = s.ensureTenantWritable(ctx, p.TenantID); e != nil {
|
||||
return isolation.PHPMyAdminResponse{}, e
|
||||
}
|
||||
}
|
||||
stored, e := s.store.Credentials(ctx, p.TenantID, p.ID)
|
||||
if e != nil {
|
||||
return isolation.PHPMyAdminResponse{}, e
|
||||
}
|
||||
password, e := s.credentials.Open(credentialLabel("database", p.ID), stored.DatabasePasswordCipher)
|
||||
if e != nil {
|
||||
return isolation.PHPMyAdminResponse{}, errors.New("无法解密数据库凭据")
|
||||
}
|
||||
plan, _, e := s.store.PlanAndUsage(ctx, p.TenantID)
|
||||
if e != nil {
|
||||
return isolation.PHPMyAdminResponse{}, e
|
||||
}
|
||||
q.Project = isolation.ProjectSpec{TenantID: p.TenantID, HostName: p.HostName, RunPath: p.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(p.ProcessLimit)}
|
||||
q.Username = stored.DatabaseUsername
|
||||
q.Password = password
|
||||
proxy, ok := s.isolation.(isolation.PHPMyAdminProxy)
|
||||
if !ok {
|
||||
return isolation.PHPMyAdminResponse{}, fmt.Errorf("节点未支持 phpMyAdmin")
|
||||
}
|
||||
return proxy.PHPMyAdmin(ctx, q)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,86 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRandomHostNameIsOpaqueAndDNSCompatible(t *testing.T) {
|
||||
pattern := regexp.MustCompile(`^sv[0-9a-f]{10}$`)
|
||||
seen := make(map[string]bool, 128)
|
||||
for range 128 {
|
||||
name, err := randomHostName()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !pattern.MatchString(name) {
|
||||
t.Fatalf("unexpected host name %q", name)
|
||||
}
|
||||
if seen[name] {
|
||||
t.Fatalf("duplicate host name %q", name)
|
||||
}
|
||||
seen[name] = true
|
||||
}
|
||||
}
|
||||
|
||||
func TestRandomPanelPasswordMeetsAaPanelContract(t *testing.T) {
|
||||
pattern := regexp.MustCompile(`^[A-Za-z0-9]{20}$`)
|
||||
seen := make(map[string]bool, 128)
|
||||
for range 128 {
|
||||
password, err := randomPanelPassword()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !pattern.MatchString(password) {
|
||||
t.Fatalf("unexpected panel password %q", password)
|
||||
}
|
||||
if seen[password] {
|
||||
t.Fatalf("duplicate panel password %q", password)
|
||||
}
|
||||
seen[password] = true
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRunPathKeepsProjectInsideHostRoot(t *testing.T) {
|
||||
for input, want := range map[string]string{"": "/", "/": "/", "public": "/public", "/apps/web/dist": "/apps/web/dist", "/.output/public": "/.output/public"} {
|
||||
got, err := normalizeRunPath(input)
|
||||
if err != nil || got != want {
|
||||
t.Fatalf("normalizeRunPath(%q) = %q, %v; want %q", input, got, err, want)
|
||||
}
|
||||
}
|
||||
for _, input := range []string{"/../etc", "/public/../etc", "/public//assets", `C:\\Windows`, "/has space", "/public/"} {
|
||||
if _, err := normalizeRunPath(input); err == nil {
|
||||
t.Fatalf("normalizeRunPath(%q) accepted an unsafe path", input)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeDeploymentEntry(t *testing.T) {
|
||||
for runtime, expected := range map[string]string{"Node.js": "package.json", "Python": "app.py", "Go": "app", "Java": "app.jar"} {
|
||||
got, err := normalizeDeploymentEntry(runtime, "")
|
||||
if err != nil || got != expected {
|
||||
t.Fatalf("normalizeDeploymentEntry(%q) = %q, %v", runtime, got, err)
|
||||
}
|
||||
}
|
||||
for _, test := range []struct{ runtime, entry string }{
|
||||
{"Java", "../../etc/passwd"}, {"Java", "/app.jar"}, {"Java", "app.sh"},
|
||||
{"Node.js", `..\\server.js`}, {"Python", "app.txt"}, {"Go", "app.exe"},
|
||||
} {
|
||||
if _, err := normalizeDeploymentEntry(test.runtime, test.entry); err == nil {
|
||||
t.Fatalf("normalizeDeploymentEntry(%q, %q) accepted unsafe input", test.runtime, test.entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunPathsOverlap(t *testing.T) {
|
||||
for _, pair := range [][2]string{{"/", "/public"}, {"/app", "/app"}, {"/app", "/app/public"}, {"/app/public", "/app"}} {
|
||||
if !runPathsOverlap(pair[0], pair[1]) {
|
||||
t.Fatalf("expected %q and %q to overlap", pair[0], pair[1])
|
||||
}
|
||||
}
|
||||
for _, pair := range [][2]string{{"/app", "/application"}, {"/site-a", "/site-b"}, {"/apps/a", "/apps/b"}} {
|
||||
if runPathsOverlap(pair[0], pair[1]) {
|
||||
t.Fatalf("did not expect %q and %q to overlap", pair[0], pair[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,737 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"path"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"sea-vhost/internal/cluster"
|
||||
"sea-vhost/internal/isolation"
|
||||
"sea-vhost/internal/panel"
|
||||
"sea-vhost/internal/scope"
|
||||
"sea-vhost/internal/store"
|
||||
)
|
||||
|
||||
var ErrRuntimeSwitchPending = errors.New("该主机的网站正在切换运行环境,请等待切换完成或核验结果")
|
||||
var ErrNodeConfigurationBusy = errors.New("节点正在调整主机配置,请稍后重试")
|
||||
|
||||
func runtimeBranch(name, version string) string {
|
||||
value := strings.TrimPrefix(strings.TrimPrefix(strings.TrimPrefix(version, "jdk-"), "go"), "v")
|
||||
parts := strings.Split(value, ".")
|
||||
if name == "Node.js" || name == "Java" {
|
||||
return parts[0]
|
||||
}
|
||||
if len(parts) < 2 {
|
||||
return ""
|
||||
}
|
||||
return strings.Join(parts[:2], ".")
|
||||
}
|
||||
func runtimeVersionNewer(a, b string) bool {
|
||||
normalize := func(v string) []string {
|
||||
return strings.FieldsFunc(strings.TrimLeft(v, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"), func(r rune) bool { return r == '.' || r == '_' })
|
||||
}
|
||||
x, y := normalize(a), normalize(b)
|
||||
for i := 0; i < max(len(x), len(y)); i++ {
|
||||
var left, right int
|
||||
if i < len(x) {
|
||||
left, _ = strconv.Atoi(x[i])
|
||||
}
|
||||
if i < len(y) {
|
||||
right, _ = strconv.Atoi(y[i])
|
||||
}
|
||||
if left != right {
|
||||
return left > right
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (s *Projects) InstallRuntimeEnvironment(ctx context.Context, name, version string) error {
|
||||
if s.store == nil {
|
||||
return s.installRuntimeEnvironmentLegacy(ctx, name, version)
|
||||
}
|
||||
items, err := s.panel.RuntimeEnvironments(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
allowed := false
|
||||
for _, item := range items {
|
||||
if item.Name == name && item.ComponentStatus == panel.RuntimeComponentReady && slices.Contains(item.Available, version) && !slices.Contains(item.Installed, version) && !slices.Contains(item.Installing, version) {
|
||||
allowed = true
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
return errors.New("请选择清单中尚未安装的运行环境版本")
|
||||
}
|
||||
_, err = s.store.CreateRuntimeJob(ctx, store.RuntimeJob{Action: "install", Runtime: name, TargetVersion: version})
|
||||
return err
|
||||
}
|
||||
func (s *Projects) SubmitPHPPatch(ctx context.Context, branch, target string) (uint64, error) {
|
||||
items, err := s.panel.RuntimeEnvironments(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for _, item := range items {
|
||||
if item.Name != "PHP" {
|
||||
continue
|
||||
}
|
||||
for _, patch := range item.Patches {
|
||||
if patch.Branch == branch && patch.Latest == target && patch.UpdateAvailable {
|
||||
return s.store.CreateRuntimeJob(ctx, store.RuntimeJob{Action: "php_patch", Runtime: "PHP", FromVersion: patch.Installed, TargetVersion: target})
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0, errors.New("该 PHP 分支没有匹配的稳定补丁更新")
|
||||
}
|
||||
func (s *Projects) SubmitRuntimeMigration(ctx context.Context, siteID uint64, target string, allowBranchChange bool, entryFile string) (uint64, error) {
|
||||
t, err := s.runtimeTarget(ctx, siteID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if t.Site.Status != "running" && t.Site.Status != "stopped" {
|
||||
return 0, errors.New("仅已部署且正常运行或已停止的站点可以迁移运行环境")
|
||||
}
|
||||
if t.Site.Version == target && t.Site.Runtime != "Go" {
|
||||
return 0, errors.New("站点已经使用该版本")
|
||||
}
|
||||
if runtimeBranch(t.Site.Runtime, t.Site.Version) != runtimeBranch(t.Site.Runtime, target) && !allowBranchChange {
|
||||
return 0, errors.New("跨分支升级必须单独确认")
|
||||
}
|
||||
items, err := s.panel.RuntimeEnvironments(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
installed := false
|
||||
for _, item := range items {
|
||||
if item.Name == t.Site.Runtime && slices.Contains(item.Installed, target) {
|
||||
installed = true
|
||||
}
|
||||
}
|
||||
if !installed {
|
||||
return 0, errors.New("请先安装目标运行环境")
|
||||
}
|
||||
id := siteID
|
||||
if t.Site.Runtime == "Go" {
|
||||
if entryFile == "" {
|
||||
return 0, errors.New("请上传独立的新程序文件,并填写 Go 目标程序文件名;旧程序需要保留用于回退")
|
||||
}
|
||||
entryFile, err = normalizeDeploymentEntry("Go", entryFile)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return s.store.CreateRuntimeJob(ctx, store.RuntimeJob{Action: "migrate", Runtime: t.Site.Runtime, FromVersion: t.Site.Version, TargetVersion: target, EntryFile: entryFile, SiteID: &id})
|
||||
}
|
||||
func (s *Projects) runtimeTarget(ctx context.Context, id uint64) (store.RuntimeTarget, error) {
|
||||
items, err := s.store.RuntimeTargets(ctx)
|
||||
if err != nil {
|
||||
return store.RuntimeTarget{}, err
|
||||
}
|
||||
for _, item := range items {
|
||||
if item.Site.ID == id {
|
||||
return item, nil
|
||||
}
|
||||
}
|
||||
return store.RuntimeTarget{}, store.ErrNotFound
|
||||
}
|
||||
func (s *Projects) RuntimeMaintenanceState(ctx context.Context) ([]store.RuntimeTarget, []store.RuntimeJob, error) {
|
||||
t, err := s.store.RuntimeTargets(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
j, err := s.store.RuntimeJobs(ctx)
|
||||
return t, j, err
|
||||
}
|
||||
func (s *Projects) ResumeRuntimeMaintenance(ctx context.Context, id uint64) error {
|
||||
return s.store.RetryRuntimeJob(ctx, id)
|
||||
}
|
||||
func (s *Projects) SubmitRuntimeCheck(ctx context.Context) (uint64, error) {
|
||||
return s.store.CreateRuntimeJob(ctx, store.RuntimeJob{Action: "check", Runtime: "all", TargetVersion: "-"})
|
||||
}
|
||||
|
||||
func (s *Projects) RunRuntimeMaintenance(ctx context.Context) {
|
||||
if err := s.store.InterruptRuntimeJobs(ctx); err != nil {
|
||||
slog.Error("cannot recover runtime maintenance jobs", "error", err)
|
||||
return
|
||||
}
|
||||
workers := make(chan struct{}, 4)
|
||||
var running sync.WaitGroup
|
||||
defer running.Wait()
|
||||
ticker := time.NewTicker(2 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
select {
|
||||
case workers <- struct{}{}:
|
||||
default:
|
||||
continue
|
||||
}
|
||||
job, err := s.store.ClaimRuntimeJob(ctx)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
<-workers
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("cannot claim runtime maintenance", "error", err)
|
||||
<-workers
|
||||
continue
|
||||
}
|
||||
running.Add(1)
|
||||
go func() { defer running.Done(); defer func() { <-workers }(); s.executeRuntimeJob(ctx, job) }()
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *Projects) executeRuntimeJob(parent context.Context, job store.RuntimeJob) {
|
||||
parent = scope.WithNode(parent, job.NodeID)
|
||||
// Component installation belongs to the panel and must not freeze unrelated
|
||||
// host operations. Site configuration switches own only their target host.
|
||||
if (job.Action == "runtime_change" || job.Action == "migrate") && job.SiteID != nil {
|
||||
target, e := s.runtimeTarget(parent, *job.SiteID)
|
||||
if e != nil {
|
||||
_ = s.store.UpdateRuntimeJob(parent, job.ID, "failed", "failed", "网站已不存在")
|
||||
return
|
||||
}
|
||||
// Use the same lock order as tenant requests: host first, then the node.
|
||||
// A tenant's failed runtime change must never freeze unrelated hosts.
|
||||
hostGate := s.hostAccessGate(target.Project.ID)
|
||||
hostGate.Lock()
|
||||
defer hostGate.Unlock()
|
||||
s.nodeGate(parent).RLock()
|
||||
defer s.nodeGate(parent).RUnlock()
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(parent, 2*time.Hour)
|
||||
defer cancel()
|
||||
phase := func(value string) error { return s.store.UpdateRuntimeJob(ctx, job.ID, "running", value, "") }
|
||||
var err error
|
||||
switch job.Action {
|
||||
case "check":
|
||||
err = phase("checking")
|
||||
if err == nil {
|
||||
err = s.CheckRuntimeUpdates(ctx)
|
||||
}
|
||||
case "install":
|
||||
err = phase("installing")
|
||||
installed, installing := false, false
|
||||
if items, inventoryErr := s.panel.RuntimeEnvironments(ctx); inventoryErr == nil {
|
||||
for _, item := range items {
|
||||
if item.Name == job.Runtime {
|
||||
installed = slices.Contains(item.Installed, job.TargetVersion)
|
||||
installing = slices.Contains(item.Installing, job.TargetVersion)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err == nil && !installed && !installing {
|
||||
if job.Runtime == "Python" {
|
||||
err = s.isolation.InstallPythonRuntime(ctx, job.TargetVersion)
|
||||
} else {
|
||||
err = s.panel.InstallRuntimeEnvironment(ctx, job.Runtime, job.TargetVersion)
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
err = s.waitRuntimeInstalled(ctx, job.Runtime, job.TargetVersion)
|
||||
}
|
||||
case "php_patch":
|
||||
err = s.applyPHPPatch(ctx, job, phase)
|
||||
case "runtime_change":
|
||||
err = s.changeRuntimeSite(ctx, job, phase)
|
||||
case "migrate":
|
||||
err = s.migrateRuntimeSite(ctx, job, phase)
|
||||
default:
|
||||
err = errors.New("unknown runtime maintenance action")
|
||||
}
|
||||
s.invalidateRuntimeCatalog()
|
||||
finishCtx, finishCancel := context.WithTimeout(context.WithoutCancel(parent), 30*time.Second)
|
||||
defer finishCancel()
|
||||
current, readErr := s.store.RuntimeJob(finishCtx, job.ID)
|
||||
if readErr == nil && (current.Status == "rolled_back" || current.Status == "interrupted") {
|
||||
if err != nil {
|
||||
_ = s.store.EnqueueAdminNotification(finishCtx, "critical", "runtime", "运行环境维护需要关注", fmt.Sprintf("任务 #%d %s %s(%s):%s", job.ID, job.Runtime, job.TargetVersion, current.Status, current.Message))
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
status := "failed"
|
||||
if parent.Err() != nil || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, cluster.ErrUncertain) {
|
||||
status = "interrupted"
|
||||
}
|
||||
_ = s.store.UpdateRuntimeJob(finishCtx, job.ID, status, "failed", err.Error())
|
||||
_ = s.store.EnqueueAdminNotification(finishCtx, "critical", "runtime", "运行环境维护失败", fmt.Sprintf("任务 #%d %s %s:%v", job.ID, job.Runtime, job.TargetVersion, err))
|
||||
return
|
||||
}
|
||||
_ = s.store.UpdateRuntimeJob(finishCtx, job.ID, "completed", "verified", "目标版本已核验;原本停止的站点保持停止,待启动后核验进程")
|
||||
}
|
||||
|
||||
// Coordinate with host identity changes and unfinished site switches, not
|
||||
// long-running panel component installations or patch updates.
|
||||
func (s *Projects) BeginRuntimeMutation(ctx context.Context) (func(), error) {
|
||||
if !s.nodeGate(ctx).TryRLock() {
|
||||
return nil, ErrNodeConfigurationBusy
|
||||
}
|
||||
blocked, err := s.store.RuntimeMutationBlocked(ctx)
|
||||
if err != nil || blocked {
|
||||
s.nodeGate(ctx).RUnlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, ErrRuntimeSwitchPending
|
||||
}
|
||||
return s.nodeGate(ctx).RUnlock, nil
|
||||
}
|
||||
func (s *Projects) waitRuntimeInstalled(ctx context.Context, name, version string) error {
|
||||
for {
|
||||
items, err := s.panel.RuntimeEnvironments(ctx)
|
||||
if err == nil {
|
||||
for _, item := range items {
|
||||
if item.Name == name && slices.Contains(item.Installed, version) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(10 * time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *Projects) applyPHPPatch(ctx context.Context, job store.RuntimeJob, phase func(string) error) error {
|
||||
agent, ok := s.isolation.(isolation.RuntimeMaintenance)
|
||||
if !ok {
|
||||
return errors.New("PHP maintenance agent unavailable")
|
||||
}
|
||||
adapter, ok := s.panel.(panel.RuntimeMaintenance)
|
||||
if !ok {
|
||||
return errors.New("PHP maintenance adapter unavailable")
|
||||
}
|
||||
branch := runtimeBranch("PHP", job.TargetVersion)
|
||||
if err := phase("backing_up"); err != nil {
|
||||
return err
|
||||
}
|
||||
snapshot, err := agent.MaintainPHP(ctx, isolation.PHPMaintenanceSpec{Branch: branch, JobID: job.ID, Action: "backup"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data, _ := json.Marshal(snapshot)
|
||||
if err = s.store.SaveRuntimeRollback(ctx, job.ID, string(data), true); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = phase("installing"); err != nil {
|
||||
return err
|
||||
}
|
||||
pending, err := adapter.PHPRuntimeUpdatePending(ctx, branch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
current, err := agent.MaintainPHP(ctx, isolation.PHPMaintenanceSpec{Branch: branch, Action: "inspect"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current.Version != job.TargetVersion && !pending {
|
||||
if err = adapter.UpdatePHPRuntime(ctx, branch, job.TargetVersion); err != nil {
|
||||
return s.interruptRuntimeJob(job, "补丁更新提交状态待确认:"+err.Error())
|
||||
}
|
||||
}
|
||||
// Allow the panel worker to pick up an acknowledged task before judging it
|
||||
// complete. A brief empty response must never trigger a concurrent rollback.
|
||||
idleSamples := 0
|
||||
for {
|
||||
pending, err = adapter.PHPRuntimeUpdatePending(ctx, branch)
|
||||
if err != nil {
|
||||
return s.interruptRuntimeJob(job, "无法确认宝塔更新队列是否结束:"+err.Error())
|
||||
}
|
||||
current, err = agent.MaintainPHP(ctx, isolation.PHPMaintenanceSpec{Branch: branch, Action: "inspect"})
|
||||
if !pending {
|
||||
idleSamples++
|
||||
} else {
|
||||
idleSamples = 0
|
||||
}
|
||||
if idleSamples >= 3 {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return s.interruptRuntimeJob(job, "更新任务仍在面板队列中,请恢复核验,避免与更新任务并发回滚")
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
}
|
||||
if err == nil && current.Version != job.TargetVersion {
|
||||
err = fmt.Errorf("更新后实际 PHP 版本为 %s,期望 %s", current.Version, job.TargetVersion)
|
||||
}
|
||||
if err == nil {
|
||||
for _, extension := range snapshot.Extensions {
|
||||
if !slices.Contains(current.Extensions, extension) {
|
||||
err = fmt.Errorf("更新后缺少 PHP 扩展 %s", extension)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
if err = phase("restarting"); err == nil {
|
||||
err = s.refreshPHPBranch(ctx, branch)
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
_, _ = agent.MaintainPHP(ctx, isolation.PHPMaintenanceSpec{Branch: branch, JobID: job.ID, Action: "complete"})
|
||||
return nil
|
||||
}
|
||||
restoreCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Minute)
|
||||
defer cancel()
|
||||
_ = s.store.UpdateRuntimeJob(restoreCtx, job.ID, "running", "rolling_back", err.Error())
|
||||
if _, restoreErr := agent.MaintainPHP(restoreCtx, isolation.PHPMaintenanceSpec{Branch: branch, JobID: job.ID, Action: "restore"}); restoreErr != nil {
|
||||
return s.interruptRuntimeJob(job, fmt.Sprintf("更新失败:%v;恢复失败:%v", err, restoreErr))
|
||||
}
|
||||
if restoreErr := s.refreshPHPBranch(restoreCtx, branch); restoreErr != nil {
|
||||
return s.interruptRuntimeJob(job, "恢复后站点核验失败:"+restoreErr.Error())
|
||||
}
|
||||
_ = s.store.UpdateRuntimeJob(restoreCtx, job.ID, "rolled_back", "rolled_back", "更新未通过验证,已恢复更新前环境:"+err.Error())
|
||||
_, _ = agent.MaintainPHP(restoreCtx, isolation.PHPMaintenanceSpec{Branch: branch, JobID: job.ID, Action: "complete"})
|
||||
return err
|
||||
}
|
||||
func (s *Projects) interruptRuntimeJob(job store.RuntimeJob, message string) error {
|
||||
ctx, cancel := context.WithTimeout(scope.WithNode(context.Background(), job.NodeID), 10*time.Second)
|
||||
defer cancel()
|
||||
_ = s.store.UpdateRuntimeJob(ctx, job.ID, "interrupted", job.Phase, message)
|
||||
return errors.New(message)
|
||||
}
|
||||
func (s *Projects) refreshPHPBranch(ctx context.Context, branch string) error {
|
||||
targets, err := s.store.RuntimeTargets(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, target := range targets {
|
||||
site := target.Site
|
||||
if site.Runtime != "PHP" || site.Version != branch {
|
||||
continue
|
||||
}
|
||||
if site.Status != "running" {
|
||||
continue
|
||||
}
|
||||
if err = s.refreshPHPBranchSite(ctx, site.ID, target.Project.ID, branch); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Projects) refreshPHPBranchSite(ctx context.Context, siteID, projectID uint64, branch string) error {
|
||||
// Only the short refresh of our private FPM pool needs a host lock. The
|
||||
// panel's compilation/installation phase holds no tenant access locks.
|
||||
hostGate := s.hostAccessGate(projectID)
|
||||
hostGate.Lock()
|
||||
defer hostGate.Unlock()
|
||||
s.nodeGate(ctx).RLock()
|
||||
defer s.nodeGate(ctx).RUnlock()
|
||||
target, err := s.runtimeTarget(ctx, siteID)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if target.Site.Runtime != "PHP" || target.Site.Version != branch || target.Site.Status != "running" {
|
||||
return nil
|
||||
}
|
||||
spec, err := s.phpIdentitySpec(ctx, target.Project, target.Site)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = s.isolation.SetPHPIdentityState(ctx, spec, false); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = s.isolation.SetPHPIdentityState(ctx, spec, true); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.verifyRuntimeTarget(ctx, target)
|
||||
}
|
||||
func (s *Projects) runtimeProbeSpec(target store.RuntimeTarget) isolation.RuntimeProbeSpec {
|
||||
return isolation.RuntimeProbeSpec{Project: isolation.ProjectSpec{TenantID: target.Site.TenantID, HostName: target.HostName, RunPath: target.Site.RunPath, StorageBytes: 1, ProcessLimit: uint32(target.Site.ProcessLimit)}, Runtime: target.Site.Runtime, Version: target.Site.Version, ProjectName: lifecycleSiteName(target.Project, target.Site), Running: target.Site.Status == "running"}
|
||||
}
|
||||
func (s *Projects) verifyRuntimeTarget(ctx context.Context, target store.RuntimeTarget) error {
|
||||
ctx = scope.WithProject(ctx, target.Project.ID, target.Project.NodeID)
|
||||
agent, ok := s.isolation.(isolation.RuntimeMaintenance)
|
||||
if !ok {
|
||||
return errors.New("runtime probe agent unavailable")
|
||||
}
|
||||
spec := s.runtimeProbeSpec(target)
|
||||
if target.Site.Runtime != "PHP" {
|
||||
adapter, ok := s.panel.(panel.RuntimeMaintenance)
|
||||
if !ok {
|
||||
return errors.New("runtime adapter unavailable")
|
||||
}
|
||||
runtime, err := adapter.ManagedRuntime(ctx, target.Site.PanelSiteID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
spec.EntryFile = runtime.EntryFile
|
||||
}
|
||||
observation, err := agent.ProbeRuntime(ctx, spec)
|
||||
if err != nil {
|
||||
_ = s.store.SaveRuntimeObservation(ctx, target.Site.ID, "", "", false, err.Error())
|
||||
return err
|
||||
}
|
||||
_ = s.store.SaveRuntimeObservation(ctx, target.Site.ID, observation.InstalledVersion, observation.RunningVersion, observation.Healthy, observation.Detail)
|
||||
if spec.Running && !observation.Healthy {
|
||||
return errors.New(observation.Detail)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Projects) migrateRuntimeSite(ctx context.Context, job store.RuntimeJob, phase func(string) error) error {
|
||||
if job.SiteID == nil {
|
||||
return errors.New("missing site")
|
||||
}
|
||||
target, err := s.runtimeTarget(ctx, *job.SiteID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx = scope.WithProject(ctx, target.Project.ID, target.Project.NodeID)
|
||||
if target.Site.Version != job.FromVersion && target.Site.Version != job.TargetVersion {
|
||||
return errors.New("站点当前版本与迁移任务不一致")
|
||||
}
|
||||
agent, ok := s.isolation.(isolation.RuntimeMaintenance)
|
||||
if !ok {
|
||||
return errors.New("runtime migration agent unavailable")
|
||||
}
|
||||
adapter, ok := s.panel.(panel.RuntimeMaintenance)
|
||||
if !ok {
|
||||
return errors.New("runtime migration adapter unavailable")
|
||||
}
|
||||
if err = s.ensureTenantWritable(ctx, target.Site.TenantID); err != nil {
|
||||
return err
|
||||
}
|
||||
oldSite := target.Site
|
||||
probe := s.runtimeProbeSpec(target)
|
||||
probe.Version = job.TargetVersion
|
||||
probe.Running = false
|
||||
var oldRuntime panel.RuntimeSpec
|
||||
if target.Site.Runtime != "PHP" {
|
||||
oldRuntime, err = adapter.ManagedRuntime(ctx, target.Site.PanelSiteID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
probe.EntryFile = oldRuntime.EntryFile
|
||||
if target.Site.Runtime == "Go" {
|
||||
probe.EntryFile = job.EntryFile
|
||||
if probe.EntryFile == oldRuntime.EntryFile {
|
||||
return errors.New("Go 更新必须使用独立的新程序文件,保留旧文件用于回退")
|
||||
}
|
||||
}
|
||||
// Persist the original record before modifying the broker.
|
||||
if job.RollbackData != "" {
|
||||
if json.Unmarshal([]byte(job.RollbackData), &oldRuntime) != nil {
|
||||
return errors.New("invalid persisted rollback record")
|
||||
}
|
||||
}
|
||||
data, _ := json.Marshal(oldRuntime)
|
||||
if err = s.store.SaveRuntimeRollback(ctx, job.ID, string(data), true); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err = phase("preparing"); err != nil {
|
||||
return err
|
||||
}
|
||||
if target.Site.Runtime == "Python" {
|
||||
spec := isolation.PanelRuntimeSpec{Project: probe.Project, Runtime: "Python", Version: job.TargetVersion, ProjectName: probe.ProjectName}
|
||||
if err = s.isolation.PreparePanelRuntime(ctx, spec); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = agent.CopyPythonDependencies(ctx, spec, job.FromVersion); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
preflight, err := agent.ProbeRuntime(ctx, probe)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if target.Site.Runtime == "Go" && preflight.InstalledVersion != job.TargetVersion {
|
||||
return errors.New("请先使用目标 Go SDK 重新编译并上传程序,再执行版本切换")
|
||||
}
|
||||
if target.Site.Runtime == "Go" {
|
||||
if err = s.isolation.PrepareExecutable(ctx, isolation.ExecutableSpec{Project: probe.Project, RelativePath: path.Join(strings.TrimPrefix(target.Site.RunPath, "/"), job.EntryFile)}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err = phase("switching"); err != nil {
|
||||
return err
|
||||
}
|
||||
apply := func(version string, rollback bool) error {
|
||||
if target.Site.Runtime == "PHP" {
|
||||
newSite := oldSite
|
||||
newSite.Version = version
|
||||
spec, e := s.phpIdentitySpec(ctx, target.Project, newSite)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if e = s.isolation.ConfigurePHPIdentity(ctx, spec); e != nil {
|
||||
return e
|
||||
}
|
||||
if oldSite.Status == "stopped" {
|
||||
return s.isolation.SetPHPIdentityState(ctx, spec, false)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
next := oldRuntime
|
||||
next.Version = version
|
||||
if target.Site.Runtime == "Go" && !rollback {
|
||||
next.EntryFile = job.EntryFile
|
||||
}
|
||||
current, lookupErr := adapter.ManagedRuntime(ctx, target.Site.PanelSiteID)
|
||||
if lookupErr != nil {
|
||||
return lookupErr
|
||||
}
|
||||
if stopErr := s.panel.SetRuntimeState(ctx, current, false); stopErr != nil {
|
||||
// Some Python modules remove/stop only their launcher. Terminate
|
||||
// residual processes only under this host UID and exact run tree.
|
||||
if terminateErr := s.isolation.TerminateRuntime(ctx, isolation.RuntimeProcessSpec{Project: probe.Project}); terminateErr != nil {
|
||||
return fmt.Errorf("停止迁移前进程失败: %v; %w", stopErr, terminateErr)
|
||||
}
|
||||
if stopErr = s.panel.SetRuntimeState(ctx, current, false); stopErr != nil {
|
||||
return stopErr
|
||||
}
|
||||
}
|
||||
if next.Runner {
|
||||
if _, e := s.prepareSavedRunner(ctx, target.Project, target.Site, next.EntryFile, next.Version); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
replaceErr := adapter.ReplaceManagedRuntime(ctx, target.Site.PanelSiteID, next)
|
||||
// aaPanel project creation may recursively chown the directory to www,
|
||||
// including when creation fails and the broker restores the old record.
|
||||
if repairErr := s.restoreSiteIsolation(ctx, target.Project, target.Site.RunPath, target.Site.ProcessLimit); repairErr != nil {
|
||||
return fmt.Errorf("恢复站点目录隔离失败: %w", repairErr)
|
||||
}
|
||||
if replaceErr != nil {
|
||||
return replaceErr
|
||||
}
|
||||
if oldSite.Status == "stopped" {
|
||||
return s.panel.SetRuntimeState(ctx, next, false)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
err = apply(job.TargetVersion, false)
|
||||
if err == nil {
|
||||
err = phase("verifying")
|
||||
}
|
||||
if err == nil {
|
||||
target.Site.Version = job.TargetVersion
|
||||
err = s.verifyRuntimeTarget(ctx, target)
|
||||
}
|
||||
if err == nil && oldSite.Version != job.TargetVersion {
|
||||
err = s.store.ChangeSiteRuntimeVersion(ctx, oldSite, job.TargetVersion)
|
||||
}
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
restoreCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Minute)
|
||||
defer cancel()
|
||||
ctx = restoreCtx
|
||||
if restoreErr := apply(job.FromVersion, true); restoreErr != nil {
|
||||
return s.interruptRuntimeJob(job, fmt.Sprintf("切换失败:%v;旧版本恢复失败:%v", err, restoreErr))
|
||||
}
|
||||
if oldSite.Version == job.TargetVersion && job.FromVersion != job.TargetVersion {
|
||||
if restoreErr := s.store.ChangeSiteRuntimeVersion(restoreCtx, oldSite, job.FromVersion); restoreErr != nil {
|
||||
return s.interruptRuntimeJob(job, "恢复旧版后保存版本记录失败:"+restoreErr.Error())
|
||||
}
|
||||
}
|
||||
target.Site = oldSite
|
||||
target.Site.Version = job.FromVersion
|
||||
if verifyErr := s.verifyRuntimeTarget(restoreCtx, target); verifyErr != nil {
|
||||
return s.interruptRuntimeJob(job, "旧版本配置已恢复,但运行核验失败:"+verifyErr.Error())
|
||||
}
|
||||
_ = s.store.UpdateRuntimeJob(restoreCtx, job.ID, "rolled_back", "rolled_back", "切换失败,已恢复旧版本:"+err.Error())
|
||||
return err
|
||||
}
|
||||
func (s *Projects) RunRuntimeUpdateChecks(ctx context.Context) {
|
||||
runNode := func(ctx context.Context) {
|
||||
if !s.nodeGate(ctx).TryRLock() {
|
||||
return
|
||||
}
|
||||
defer s.nodeGate(ctx).RUnlock()
|
||||
checkCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
defer cancel()
|
||||
if blocked, err := s.store.RuntimeMutationBlocked(checkCtx); err != nil || blocked {
|
||||
return
|
||||
}
|
||||
if err := s.CheckRuntimeUpdates(checkCtx); err != nil {
|
||||
slog.Warn("runtime update check failed", "error", err)
|
||||
}
|
||||
}
|
||||
run := func() {
|
||||
nodes, err := s.store.Nodes(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, n := range nodes {
|
||||
if n.Enabled {
|
||||
runNode(scope.WithNode(ctx, n.ID))
|
||||
}
|
||||
}
|
||||
}
|
||||
run()
|
||||
ticker := time.NewTicker(6 * time.Hour)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
run()
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *Projects) CheckRuntimeUpdates(ctx context.Context) error {
|
||||
if s.store != nil {
|
||||
if _, err := s.ftpTLSPolicy(ctx); err != nil {
|
||||
_ = s.store.EnqueueAdminNotification(context.WithoutCancel(ctx), "critical", "ftp", "节点 FTP 证书同步失败", fmt.Sprintf("节点 %d:%v", scope.Node(ctx), err))
|
||||
return err
|
||||
}
|
||||
}
|
||||
if pruner, ok := s.isolation.(interface{ PruneRuntimeBackups(context.Context) error }); ok {
|
||||
if err := pruner.PruneRuntimeBackups(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
items, err := s.panel.RuntimeEnvironments(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, item := range items {
|
||||
if item.Name == "PHP" {
|
||||
for _, patch := range item.Patches {
|
||||
if patch.UpdateAvailable {
|
||||
_ = s.store.NotifyRuntimeRelease(ctx, "PHP/"+patch.Latest, "PHP 补丁更新可用", patch.Installed+" → "+patch.Latest+",请在环境配置中执行更新")
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
for _, installed := range item.Installed {
|
||||
latest := installed
|
||||
for _, version := range item.Available {
|
||||
if runtimeBranch(item.Name, installed) == runtimeBranch(item.Name, version) && runtimeVersionNewer(version, latest) {
|
||||
latest = version
|
||||
}
|
||||
}
|
||||
if latest != installed {
|
||||
_ = s.store.NotifyRuntimeRelease(ctx, item.Name+"/"+latest, item.Name+" 更新可用", installed+" → "+latest+",安装后需要切换项目并验证生效")
|
||||
}
|
||||
}
|
||||
}
|
||||
targets, err := s.store.RuntimeTargets(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, target := range targets {
|
||||
if target.Site.Status == "running" || target.Site.Status == "stopped" {
|
||||
_ = s.verifyRuntimeTarget(ctx, target)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package service
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestPatchBranchesNeverImplicitlyCrossLanguageBranches(t *testing.T) {
|
||||
for _, test := range []struct{ name, version, branch string }{
|
||||
{"PHP", "8.4.27", "8.4"}, {"Python", "3.12.15", "3.12"}, {"Python", "3.13.17", "3.13"},
|
||||
{"Node.js", "v24.22.1", "24"}, {"Java", "jdk-21.0.9", "21"}, {"Go", "go1.27.3", "1.27"},
|
||||
} {
|
||||
if got := runtimeBranch(test.name, test.version); got != test.branch {
|
||||
t.Fatalf("%s %s branch=%s", test.name, test.version, got)
|
||||
}
|
||||
}
|
||||
if !runtimeVersionNewer("3.12.15", "3.12.9") || runtimeVersionNewer("go1.27.1", "go1.27.3") {
|
||||
t.Fatal("patch versions were compared lexically")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sea-vhost/internal/isolation"
|
||||
"sea-vhost/internal/panel"
|
||||
"sea-vhost/internal/schedulerbridge"
|
||||
"sea-vhost/internal/scope"
|
||||
)
|
||||
|
||||
func (s *Projects) ConfigureSystemScheduler(ctx context.Context, v schedulerbridge.Config) error {
|
||||
if e := v.Validate(); e != nil {
|
||||
return e
|
||||
}
|
||||
node, e := s.store.Node(ctx, v.NodeID)
|
||||
if e != nil || !node.Enabled {
|
||||
return errors.New("节点不可用")
|
||||
}
|
||||
ctx = scope.WithNode(ctx, v.NodeID)
|
||||
agent, ok := s.isolation.(isolation.SchedulerBridge)
|
||||
if !ok {
|
||||
return errors.New("节点未支持调度触发器")
|
||||
}
|
||||
native, ok := s.panel.(panel.SystemScheduler)
|
||||
if !ok {
|
||||
return errors.New("宝塔代理未支持系统计划任务")
|
||||
}
|
||||
if e = agent.ConfigureSchedulerBridge(ctx, v); e != nil {
|
||||
return e
|
||||
}
|
||||
_, e = native.EnsureSystemScheduler(ctx)
|
||||
return e
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sea-vhost/internal/panel"
|
||||
"sea-vhost/internal/scope"
|
||||
"sea-vhost/internal/store"
|
||||
)
|
||||
|
||||
func (s *Projects) SubmitSiteRuntime(ctx context.Context, u store.User, projectID, siteID uint64, runtime, version, entry string) (uint64, error) {
|
||||
p, err := s.authorizedProject(ctx, u, projectID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
ctx = scope.WithProject(ctx, p.ID, p.NodeID)
|
||||
site, err := s.store.Site(ctx, p.TenantID, p.ID, siteID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if runtime != site.Runtime && !p.AllowRuntimeChange {
|
||||
return 0, errors.New("管理员未允许此主机切换运行环境")
|
||||
}
|
||||
if err = s.ensureTenantWritable(ctx, p.TenantID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err = s.validateRuntime(ctx, runtime, version); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if site.Status != "running" && site.Status != "stopped" && site.Status != "awaiting_upload" {
|
||||
return 0, errors.New("当前状态不能切换运行环境")
|
||||
}
|
||||
if site.Runtime == runtime && site.Version == version && (runtime != "Go" || site.Status == "awaiting_upload") {
|
||||
return 0, errors.New("网站已使用此版本")
|
||||
}
|
||||
if runtime == "Go" && site.Runtime == "Go" && site.Status != "awaiting_upload" {
|
||||
if entry == "" {
|
||||
return 0, errors.New("请上传目标 Go SDK 编译的新程序,并填写独立程序文件名")
|
||||
}
|
||||
entry, err = normalizeDeploymentEntry("Go", entry)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
ownershipVersion, err := s.store.HostOwnershipVersion(ctx, p.ID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return s.store.CreateRuntimeJob(ctx, store.RuntimeJob{OwnershipVersion: &ownershipVersion, Action: "runtime_change", Runtime: runtime, FromVersion: site.Version, TargetVersion: version, EntryFile: entry, SiteID: &siteID})
|
||||
}
|
||||
func (s *Projects) changeRuntimeSite(ctx context.Context, job store.RuntimeJob, phase func(string) error) error {
|
||||
if job.SiteID == nil {
|
||||
return errors.New("missing site")
|
||||
}
|
||||
t, err := s.runtimeTarget(ctx, *job.SiteID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx = scope.WithProject(ctx, t.Project.ID, t.Project.NodeID)
|
||||
ownershipVersion, err := s.store.HostOwnershipVersion(ctx, t.Project.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if job.OwnershipVersion != nil && ownershipVersion != *job.OwnershipVersion {
|
||||
return errors.New("主机归属已变更,原运行环境任务已取消,请由当前管理者重新提交")
|
||||
}
|
||||
p, err := s.store.Project(ctx, t.Site.TenantID, t.Project.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
u := store.User{Role: "host", TenantID: &p.TenantID, ProjectID: &p.ID}
|
||||
if _, err = s.authorizedProject(ctx, u, p.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = s.ensureTenantWritable(ctx, p.TenantID); err != nil {
|
||||
return err
|
||||
}
|
||||
if t.Site.Runtime == job.Runtime && t.Site.Version == job.TargetVersion && job.Runtime != "Go" {
|
||||
return nil
|
||||
}
|
||||
if t.Site.Runtime != job.Runtime && !p.AllowRuntimeChange {
|
||||
return errors.New("此主机的跨语言切换权限已撤销")
|
||||
}
|
||||
if err = s.validateRuntime(ctx, job.Runtime, job.TargetVersion); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = phase("switching"); err != nil {
|
||||
return err
|
||||
}
|
||||
if t.Site.Status == "running" {
|
||||
t.Site, err = s.SetSiteState(ctx, u, p.ID, t.Site.ID, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if t.Site.Runtime == job.Runtime && t.Site.Status != "awaiting_upload" {
|
||||
// The existing migration path verifies the new runtime and retains rollback data.
|
||||
return s.migrateRuntimeSite(ctx, job, phase)
|
||||
}
|
||||
if t.Site.Runtime == "PHP" {
|
||||
spec, e := s.phpIdentitySpec(ctx, p, t.Site)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if e = s.isolation.RemovePHPIdentity(ctx, spec); e != nil {
|
||||
return s.interruptRuntimeJob(job, e.Error())
|
||||
}
|
||||
} else if t.Site.Status != "awaiting_upload" {
|
||||
adapter, ok := s.panel.(panel.RuntimeResetter)
|
||||
if !ok {
|
||||
return errors.New("运行环境适配器不支持安全重置")
|
||||
}
|
||||
if err = adapter.ResetManagedRuntime(ctx, t.Site.PanelSiteID, t.Site.Domain); err != nil {
|
||||
return s.interruptRuntimeJob(job, err.Error())
|
||||
}
|
||||
}
|
||||
next := t.Site
|
||||
next.Runtime = job.Runtime
|
||||
next.Version = job.TargetVersion
|
||||
status := "awaiting_upload"
|
||||
if next.Runtime == "PHP" {
|
||||
spec, e := s.phpIdentitySpec(ctx, p, next)
|
||||
if e != nil {
|
||||
return s.interruptRuntimeJob(job, e.Error())
|
||||
}
|
||||
if e = s.isolation.ConfigurePHPIdentity(ctx, spec); e != nil {
|
||||
return s.interruptRuntimeJob(job, e.Error())
|
||||
}
|
||||
if e = s.isolation.SetPHPIdentityState(ctx, spec, false); e != nil {
|
||||
return s.interruptRuntimeJob(job, e.Error())
|
||||
}
|
||||
status = "stopped"
|
||||
}
|
||||
if err = s.store.ChangeSiteLanguage(ctx, t.Site, next.Runtime, next.Version, status); err != nil {
|
||||
return s.interruptRuntimeJob(job, err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sea-vhost/internal/hosting"
|
||||
"sea-vhost/internal/isolation"
|
||||
"sea-vhost/internal/scope"
|
||||
"sea-vhost/internal/store"
|
||||
)
|
||||
|
||||
func (s *Projects) WebsiteSettings(ctx context.Context, user store.User, projectID, siteID uint64) (hosting.WebsiteSettings, error) {
|
||||
p, e := s.authorizedProject(ctx, user, projectID)
|
||||
if e != nil {
|
||||
return hosting.WebsiteSettings{}, e
|
||||
}
|
||||
if _, e = s.store.Site(ctx, p.TenantID, p.ID, siteID); e != nil {
|
||||
return hosting.WebsiteSettings{}, e
|
||||
}
|
||||
return s.store.WebsiteSettings(ctx, siteID)
|
||||
}
|
||||
func (s *Projects) SetWebsiteSettings(ctx context.Context, user store.User, projectID, siteID uint64, v hosting.WebsiteSettings) error {
|
||||
if e := v.Validate(); e != nil {
|
||||
return e
|
||||
}
|
||||
p, e := s.authorizedProject(ctx, user, projectID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
ctx = scope.WithProject(ctx, p.ID, p.NodeID)
|
||||
if e = s.ensureTenantWritable(ctx, p.TenantID); e != nil {
|
||||
return e
|
||||
}
|
||||
site, e := s.store.Site(ctx, p.TenantID, p.ID, siteID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if v.ForceHTTPS && site.SSLStatus != "active" {
|
||||
return errors.New("请先安装有效 SSL 证书")
|
||||
}
|
||||
plan, _, e := s.store.PlanAndUsage(ctx, p.TenantID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
manager, ok := s.isolation.(isolation.SiteOperations)
|
||||
if !ok {
|
||||
return errors.New("节点暂不支持网站设置")
|
||||
}
|
||||
old, e := s.store.WebsiteSettings(ctx, siteID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
spec := isolation.WebsiteSpec{Project: isolation.ProjectSpec{TenantID: p.TenantID, HostName: p.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)}, SiteName: lifecycleSiteName(p, site), Domain: site.Domain, Runtime: site.Runtime, Settings: v}
|
||||
if e = manager.ConfigureWebsite(ctx, spec); e != nil {
|
||||
return e
|
||||
}
|
||||
if e = s.store.SaveWebsiteSettings(ctx, siteID, v); e != nil {
|
||||
spec.Settings = old
|
||||
_ = manager.ConfigureWebsite(context.WithoutCancel(ctx), spec)
|
||||
}
|
||||
return e
|
||||
}
|
||||
func (s *Projects) SiteLog(ctx context.Context, user store.User, projectID, siteID uint64, kind, search string, lines int) (isolation.SiteLog, error) {
|
||||
p, e := s.authorizedProject(ctx, user, projectID)
|
||||
if e != nil {
|
||||
return isolation.SiteLog{}, e
|
||||
}
|
||||
site, e := s.store.Site(ctx, p.TenantID, p.ID, siteID)
|
||||
if e != nil {
|
||||
return isolation.SiteLog{}, e
|
||||
}
|
||||
plan, _, e := s.store.PlanAndUsage(ctx, p.TenantID)
|
||||
if e != nil {
|
||||
return isolation.SiteLog{}, e
|
||||
}
|
||||
manager, ok := s.isolation.(isolation.SiteOperations)
|
||||
if !ok {
|
||||
return isolation.SiteLog{}, errors.New("节点暂不支持日志查看")
|
||||
}
|
||||
return manager.ReadSiteLog(ctx, isolation.SiteLogSpec{Project: isolation.ProjectSpec{TenantID: p.TenantID, HostName: p.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)}, SiteName: lifecycleSiteName(p, site), Domain: site.Domain, Kind: kind, Search: search, Lines: lines})
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sea-vhost/internal/hosting"
|
||||
"sea-vhost/internal/isolation"
|
||||
"sea-vhost/internal/panel"
|
||||
"sea-vhost/internal/scope"
|
||||
"sea-vhost/internal/store"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Projects) loadStartup(ctx context.Context, site store.Site) (hosting.Startup, error) {
|
||||
v := hosting.Startup{WorkDir: ".", Arguments: []string{}, Environment: map[string]string{}}
|
||||
raw, e := s.store.StartupCipher(ctx, site.ID)
|
||||
if e != nil {
|
||||
return v, e
|
||||
}
|
||||
if len(raw) > 0 {
|
||||
plain, e := s.credentials.Open(fmt.Sprintf("site-startup:%d", site.ID), raw)
|
||||
if e != nil {
|
||||
return v, e
|
||||
}
|
||||
e = json.Unmarshal([]byte(plain), &v)
|
||||
if e != nil {
|
||||
return v, e
|
||||
}
|
||||
if site.Runtime != "PHP" {
|
||||
if manager, ok := s.panel.(panel.RuntimeMaintenance); ok {
|
||||
if runtime, e := manager.ManagedRuntime(ctx, site.PanelSiteID); e == nil {
|
||||
v.EntryFile = runtime.EntryFile
|
||||
}
|
||||
}
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
if site.Runtime != "PHP" {
|
||||
if manager, ok := s.panel.(panel.RuntimeMaintenance); ok {
|
||||
if runtime, e := manager.ManagedRuntime(ctx, site.PanelSiteID); e == nil {
|
||||
v.EntryFile = runtime.EntryFile
|
||||
}
|
||||
}
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
func (s *Projects) prepareSavedRunner(ctx context.Context, p store.Project, site store.Site, entry, version string) (bool, error) {
|
||||
cipher, e := s.store.StartupCipher(ctx, site.ID)
|
||||
if e != nil || len(cipher) == 0 {
|
||||
return false, e
|
||||
}
|
||||
v, e := s.loadStartup(ctx, site)
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
v.EntryFile = entry
|
||||
plan, _, e := s.store.PlanAndUsage(ctx, p.TenantID)
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
manager, ok := s.isolation.(isolation.StartupManager)
|
||||
if !ok {
|
||||
return false, errors.New("节点不支持应用启动器")
|
||||
}
|
||||
e = manager.ConfigureStartup(ctx, isolation.StartupSpec{Project: isolation.ProjectSpec{TenantID: p.TenantID, HostName: p.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)}, SiteName: lifecycleSiteName(p, site), Runtime: site.Runtime, Version: version, Port: site.BackendPort, Config: v})
|
||||
return e == nil, e
|
||||
}
|
||||
func (s *Projects) Startup(ctx context.Context, user store.User, projectID, siteID uint64) (hosting.Startup, error) {
|
||||
p, e := s.authorizedProject(ctx, user, projectID)
|
||||
if e != nil {
|
||||
return hosting.Startup{}, e
|
||||
}
|
||||
site, e := s.store.Site(ctx, p.TenantID, p.ID, siteID)
|
||||
if e != nil {
|
||||
return hosting.Startup{}, e
|
||||
}
|
||||
return s.loadStartup(ctx, site)
|
||||
}
|
||||
func (s *Projects) SetStartup(ctx context.Context, user store.User, projectID, siteID uint64, v hosting.Startup) error {
|
||||
if e := v.Validate(); e != nil {
|
||||
return e
|
||||
}
|
||||
p, e := s.authorizedProject(ctx, user, projectID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
ctx = scope.WithProject(ctx, p.ID, p.NodeID)
|
||||
if e = s.ensureTenantWritable(ctx, p.TenantID); e != nil {
|
||||
return e
|
||||
}
|
||||
site, e := s.store.Site(ctx, p.TenantID, p.ID, siteID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if site.Runtime == "PHP" && (v.EntryFile != "" || len(v.Arguments) > 0 || v.WorkDir != ".") {
|
||||
return errors.New("PHP 使用网站运行目录,仅需配置环境变量")
|
||||
}
|
||||
if site.Runtime != "PHP" {
|
||||
entry, e := normalizeDeploymentEntry(site.Runtime, v.EntryFile)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
v.EntryFile = entry
|
||||
}
|
||||
old, e := s.loadStartup(ctx, site)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
manager, ok := s.isolation.(isolation.StartupManager)
|
||||
if !ok {
|
||||
return errors.New("节点暂不支持启动配置")
|
||||
}
|
||||
plan, _, e := s.store.PlanAndUsage(ctx, p.TenantID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
spec := isolation.StartupSpec{Project: isolation.ProjectSpec{TenantID: p.TenantID, HostName: p.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)}, SiteName: lifecycleSiteName(p, site), Runtime: site.Runtime, Version: site.Version, Port: site.BackendPort, Config: v}
|
||||
if site.Runtime != "PHP" && site.Status == "awaiting_upload" {
|
||||
raw, _ := json.Marshal(v)
|
||||
cipher, e := s.credentials.Seal(fmt.Sprintf("site-startup:%d", site.ID), string(raw))
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
return s.store.SaveStartupCipher(ctx, site.ID, cipher)
|
||||
}
|
||||
if e = manager.ConfigureStartup(ctx, spec); e != nil {
|
||||
return e
|
||||
}
|
||||
var restoreRuntime func(context.Context) error
|
||||
restore := func() error {
|
||||
rollback, cancel := context.WithTimeout(context.WithoutCancel(ctx), 60*time.Second)
|
||||
defer cancel()
|
||||
spec.Config = old
|
||||
err := manager.ConfigureStartup(rollback, spec)
|
||||
if restoreRuntime != nil {
|
||||
err = errors.Join(err, restoreRuntime(rollback))
|
||||
}
|
||||
return err
|
||||
}
|
||||
if site.Runtime == "PHP" {
|
||||
identity, e := s.phpIdentitySpec(ctx, p, site)
|
||||
if e != nil {
|
||||
restore()
|
||||
return e
|
||||
}
|
||||
restoreRuntime = func(rollback context.Context) error {
|
||||
err := s.isolation.ConfigurePHPIdentity(rollback, identity)
|
||||
if site.Status != "running" {
|
||||
err = errors.Join(err, s.isolation.SetPHPIdentityState(rollback, identity, false))
|
||||
}
|
||||
return err
|
||||
}
|
||||
if e = s.isolation.ConfigurePHPIdentity(ctx, identity); e != nil {
|
||||
restore()
|
||||
return e
|
||||
}
|
||||
if site.Status != "running" {
|
||||
if e = s.isolation.SetPHPIdentityState(ctx, identity, false); e != nil {
|
||||
return errors.Join(e, restore())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
adapter, ok := s.panel.(panel.RuntimeMaintenance)
|
||||
if !ok {
|
||||
restore()
|
||||
return errors.New("面板暂不支持启动配置替换")
|
||||
}
|
||||
runtime, e := adapter.ManagedRuntime(ctx, site.PanelSiteID)
|
||||
if e != nil {
|
||||
restore()
|
||||
return e
|
||||
}
|
||||
next := runtime
|
||||
restoreRuntime = func(rollback context.Context) error {
|
||||
err := adapter.ReplaceManagedRuntime(rollback, site.PanelSiteID, runtime)
|
||||
if site.Status != "running" {
|
||||
err = errors.Join(err, s.panel.SetSiteState(rollback, site.PanelSiteID, site.Domain, false))
|
||||
}
|
||||
return err
|
||||
}
|
||||
next.Runner = true
|
||||
next.EntryFile = v.EntryFile
|
||||
if e = adapter.ReplaceManagedRuntime(ctx, site.PanelSiteID, next); e != nil {
|
||||
restore()
|
||||
return e
|
||||
}
|
||||
if site.Status != "running" {
|
||||
if e = s.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, false); e != nil {
|
||||
return errors.Join(e, restore())
|
||||
}
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(v)
|
||||
cipher, e := s.credentials.Seal(fmt.Sprintf("site-startup:%d", site.ID), string(raw))
|
||||
if e != nil {
|
||||
return errors.Join(e, restore())
|
||||
}
|
||||
if e = s.store.SaveStartupCipher(ctx, site.ID, cipher); e != nil {
|
||||
return errors.Join(e, restore())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"sea-vhost/internal/isolation"
|
||||
"sea-vhost/internal/panel"
|
||||
"sea-vhost/internal/scope"
|
||||
"sea-vhost/internal/store"
|
||||
)
|
||||
|
||||
var ErrStorageQuotaExceeded = errors.New("storage quota exceeded")
|
||||
|
||||
type StorageQuota struct {
|
||||
store *store.Store
|
||||
panel panel.Interface
|
||||
isolation isolation.Interface
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func NewStorageQuota(database *store.Store, panelClient panel.Interface, isolator isolation.Interface, _ string) *StorageQuota {
|
||||
return &StorageQuota{store: database, panel: panelClient, isolation: isolator}
|
||||
}
|
||||
|
||||
// CheckWrite performs a fresh tenant-wide scan before a Web file write. This
|
||||
// is deliberately conservative: concurrent runtime writes can still create a
|
||||
// temporary overage, which the background monitor suspends on its next run.
|
||||
func (q *StorageQuota) CheckWrite(ctx context.Context, tenantID, additionalBytes uint64) error {
|
||||
used, limit, refreshErr := q.refreshTenant(ctx, tenantID)
|
||||
suspended, reason, stateErr := q.store.TenantQuotaSuspension(ctx, tenantID)
|
||||
if stateErr != nil {
|
||||
return stateErr
|
||||
}
|
||||
if suspended {
|
||||
return fmt.Errorf("%w: %s", ErrQuotaSuspended, reason)
|
||||
}
|
||||
if refreshErr != nil {
|
||||
return refreshErr
|
||||
}
|
||||
if used > limit || additionalBytes > limit-used {
|
||||
return ErrStorageQuotaExceeded
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (q *StorageQuota) Run(ctx context.Context, interval time.Duration) {
|
||||
if interval <= 0 {
|
||||
interval = time.Minute
|
||||
}
|
||||
q.refreshAll(ctx)
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
q.refreshAll(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (q *StorageQuota) refreshAll(ctx context.Context) {
|
||||
_ = q.store.PruneHostMetrics(ctx)
|
||||
hosts, err := q.store.AllProjects(ctx)
|
||||
if err != nil {
|
||||
slog.Error("storage quota tenant listing failed", "error", err)
|
||||
return
|
||||
}
|
||||
for _, host := range hosts {
|
||||
if host.Status == "failed" || host.Status == "provisioning" {
|
||||
continue
|
||||
}
|
||||
if _, _, err = q.refreshTenant(scope.WithProject(ctx, host.ID, host.NodeID), host.TenantID); err != nil && !errors.Is(err, store.ErrNotFound) {
|
||||
slog.Error("storage quota refresh failed", "project_id", host.ID, "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (q *StorageQuota) refreshTenant(ctx context.Context, tenantID uint64) (uint64, uint64, error) {
|
||||
if err := q.store.HostWritable(ctx, tenantID); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
if scope.Project(ctx) == 0 {
|
||||
return 0, 0, errors.New("host scope required for quota enforcement")
|
||||
}
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
projects, err := q.store.ListProjects(ctx, tenantID)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
var used uint64
|
||||
plan, _, err := q.store.PlanAndUsage(ctx, tenantID)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
sites, err := q.store.ListTenantSites(ctx, tenantID, nil)
|
||||
if err != nil {
|
||||
return used, plan.StorageBytes, err
|
||||
}
|
||||
databaseResources, err := q.store.ListDatabaseResources(ctx, tenantID, nil)
|
||||
if err != nil {
|
||||
return used, plan.StorageBytes, err
|
||||
}
|
||||
ftpResources, err := q.store.ListFTPResources(ctx, tenantID, nil)
|
||||
if err != nil {
|
||||
return used, plan.StorageBytes, err
|
||||
}
|
||||
databaseSizes := make(map[uint64]uint64, len(databaseResources))
|
||||
var databaseBytes uint64
|
||||
for _, database := range databaseResources {
|
||||
if database.PanelID <= 0 {
|
||||
return used, plan.StorageBytes, errors.New("managed database is missing its panel id")
|
||||
}
|
||||
size, sizeErr := q.panel.DatabaseSize(ctx, database.PanelID, database.Name)
|
||||
if sizeErr != nil {
|
||||
return used, plan.StorageBytes, fmt.Errorf("measure database %s: %w", database.Name, sizeErr)
|
||||
}
|
||||
if size > math.MaxUint64-databaseBytes {
|
||||
return used, plan.StorageBytes, errors.New("database usage overflow")
|
||||
}
|
||||
databaseBytes += size
|
||||
databaseSizes[database.ID] = size
|
||||
}
|
||||
domainsByProject := make(map[uint64][]string, len(projects))
|
||||
for _, site := range sites {
|
||||
domainsByProject[site.ProjectID] = append(domainsByProject[site.ProjectID], site.Domain)
|
||||
}
|
||||
for _, project := range projects {
|
||||
if err = q.isolation.ConfigureTrafficLimits(ctx, isolation.TrafficLimitSpec{Project: isolation.ProjectSpec{TenantID: tenantID, HostName: project.HostName, RunPath: project.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit)}, Domains: domainsByProject[project.ID], Mbps: plan.BandwidthMbps}); err != nil {
|
||||
return used, plan.StorageBytes, fmt.Errorf("enforce traffic policy: %w", err)
|
||||
}
|
||||
}
|
||||
var bandwidthBytes uint64
|
||||
var processCount uint32
|
||||
for _, project := range projects {
|
||||
resourceUsage, usageErr := q.isolation.ResourceUsage(ctx, isolation.ResourceUsageSpec{
|
||||
Project: isolation.ProjectSpec{TenantID: tenantID, HostName: project.HostName, RunPath: project.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit)},
|
||||
Domains: domainsByProject[project.ID],
|
||||
})
|
||||
if usageErr != nil {
|
||||
return used, plan.StorageBytes, fmt.Errorf("measure host %s resources: %w", project.HostName, usageErr)
|
||||
}
|
||||
if resourceUsage.StorageBytes > math.MaxUint64-used || resourceUsage.BandwidthBytes > math.MaxUint64-bandwidthBytes || resourceUsage.ProcessCount > math.MaxUint32-processCount {
|
||||
return used, plan.StorageBytes, errors.New("resource usage overflow")
|
||||
}
|
||||
var projectDatabase uint64
|
||||
for _, database := range databaseResources {
|
||||
if database.ProjectID == project.ID {
|
||||
projectDatabase += databaseSizes[database.ID]
|
||||
}
|
||||
}
|
||||
_ = q.store.RecordHostMetric(ctx, project.ID, store.HostMetric{CPUTicks: resourceUsage.CPUTicks, MemoryBytes: resourceUsage.MemoryBytes, ProcessCount: resourceUsage.ProcessCount, StorageBytes: resourceUsage.StorageBytes, DatabaseBytes: projectDatabase, BandwidthBytes: resourceUsage.BandwidthBytes})
|
||||
used += resourceUsage.StorageBytes
|
||||
bandwidthBytes += resourceUsage.BandwidthBytes
|
||||
processCount += resourceUsage.ProcessCount
|
||||
}
|
||||
databaseOver := databaseBytes >= plan.DatabaseBytes
|
||||
for _, database := range databaseResources {
|
||||
var owner *store.Project
|
||||
for i := range projects {
|
||||
if projects[i].ID == database.ProjectID {
|
||||
owner = &projects[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if owner == nil || database.Name != owner.HostName || database.Username != owner.HostName {
|
||||
return used, plan.StorageBytes, errors.New("inconsistent database owner")
|
||||
}
|
||||
if err = q.isolation.ConfigureDatabaseAccess(ctx, isolation.DatabaseAccessSpec{Project: isolation.ProjectSpec{TenantID: tenantID, HostName: owner.HostName, RunPath: owner.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(owner.ProcessLimit)}, Database: database.Name, ReadOnly: databaseOver}); err != nil {
|
||||
return used, plan.StorageBytes, fmt.Errorf("enforce database quota: %w", err)
|
||||
}
|
||||
}
|
||||
usage := store.Usage{StorageBytes: used, DatabaseBytes: databaseBytes, BandwidthBytes: bandwidthBytes, ProcessCount: processCount}
|
||||
now := time.Now()
|
||||
periodStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
|
||||
if err = q.store.UpdateQuotaMeasurement(ctx, tenantID, usage, periodStart, databaseSizes, databaseOver); err != nil {
|
||||
return used, plan.StorageBytes, err
|
||||
}
|
||||
reasons := make([]string, 0, 4)
|
||||
if used > plan.StorageBytes {
|
||||
reasons = append(reasons, "storage quota exceeded")
|
||||
}
|
||||
if databaseOver {
|
||||
reasons = append(reasons, "database quota exceeded")
|
||||
}
|
||||
if bandwidthBytes >= plan.BandwidthBytes {
|
||||
reasons = append(reasons, "bandwidth quota exceeded")
|
||||
}
|
||||
if processCount > plan.ProcessLimit {
|
||||
reasons = append(reasons, "process quota exceeded")
|
||||
}
|
||||
wasSuspended := false
|
||||
for _, project := range projects {
|
||||
wasSuspended = wasSuspended || project.Status == "quota_suspended"
|
||||
}
|
||||
if len(reasons) > 0 {
|
||||
if err = q.store.SetTenantQuotaSuspended(ctx, tenantID, strings.Join(reasons, ", ")); err != nil {
|
||||
return used, plan.StorageBytes, err
|
||||
}
|
||||
if !wasSuspended {
|
||||
_ = q.store.EnqueueAdminNotification(context.WithoutCancel(ctx), "critical", "quota", "虚拟主机资源超限", fmt.Sprintf("用户 %d 已暂停:%s", tenantID, strings.Join(reasons, ", ")))
|
||||
}
|
||||
var stopErrors []error
|
||||
for _, site := range sites {
|
||||
if site.PanelSiteID <= 0 || (site.Status != "running" && site.Status != "quota_suspended") {
|
||||
continue
|
||||
}
|
||||
if stopErr := q.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, false); stopErr != nil {
|
||||
stopErrors = append(stopErrors, fmt.Errorf("stop site %d: %w", site.ID, stopErr))
|
||||
}
|
||||
}
|
||||
for _, ftp := range ftpResources {
|
||||
if ftp.PanelID > 0 {
|
||||
if stopErr := q.panel.SetFTPState(ctx, ftp.PanelID, ftp.Username, false); stopErr != nil {
|
||||
stopErrors = append(stopErrors, fmt.Errorf("disable FTP %s: %w", ftp.Username, stopErr))
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, project := range projects {
|
||||
spec := isolation.ProjectSpec{TenantID: tenantID, HostName: project.HostName, RunPath: project.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit)}
|
||||
if stopErr := q.isolation.TerminateProcesses(ctx, spec); stopErr != nil {
|
||||
stopErrors = append(stopErrors, fmt.Errorf("terminate host %s processes: %w", project.HostName, stopErr))
|
||||
}
|
||||
if freezeErr := q.isolation.FreezeWrites(ctx, spec); freezeErr != nil {
|
||||
stopErrors = append(stopErrors, fmt.Errorf("freeze host %s writes: %w", project.HostName, freezeErr))
|
||||
}
|
||||
}
|
||||
return used, plan.StorageBytes, errors.Join(stopErrors...)
|
||||
}
|
||||
if wasSuspended {
|
||||
var enableErrors []error
|
||||
for _, project := range projects {
|
||||
spec := isolation.ProjectSpec{TenantID: tenantID, HostName: project.HostName, RunPath: project.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit)}
|
||||
prepared, prepareErr := q.isolation.Prepare(ctx, spec)
|
||||
if prepareErr != nil || filepath.Clean(prepared.RootPath) != filepath.Clean(project.Path) || prepared.RunUser != project.HostName {
|
||||
if prepareErr == nil {
|
||||
prepareErr = errors.New("isolation agent returned an inconsistent host identity")
|
||||
}
|
||||
enableErrors = append(enableErrors, fmt.Errorf("restore host %s writes: %w", project.HostName, prepareErr))
|
||||
}
|
||||
}
|
||||
if err = errors.Join(enableErrors...); err != nil {
|
||||
return used, plan.StorageBytes, err
|
||||
}
|
||||
for _, ftp := range ftpResources {
|
||||
if ftp.PanelID > 0 && ftp.Enabled {
|
||||
if enableErr := q.panel.SetFTPState(ctx, ftp.PanelID, ftp.Username, true); enableErr != nil {
|
||||
enableErrors = append(enableErrors, fmt.Errorf("enable FTP %s: %w", ftp.Username, enableErr))
|
||||
}
|
||||
}
|
||||
}
|
||||
if err = errors.Join(enableErrors...); err != nil {
|
||||
return used, plan.StorageBytes, err
|
||||
}
|
||||
if err = q.store.ClearTenantStorageSuspension(ctx, tenantID); err != nil {
|
||||
return used, plan.StorageBytes, err
|
||||
}
|
||||
}
|
||||
return used, plan.StorageBytes, nil
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sea-vhost/internal/hosting"
|
||||
"sea-vhost/internal/isolation"
|
||||
"sea-vhost/internal/scope"
|
||||
"sea-vhost/internal/store"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type scheduleConfig struct {
|
||||
Target string `json:"target"`
|
||||
Arguments []string `json:"arguments"`
|
||||
}
|
||||
|
||||
func (s *Projects) openSchedule(v *store.UserSchedule) error {
|
||||
plain, e := s.credentials.Open("user-schedule:"+v.SecretRef, v.ConfigCipher)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
var cfg scheduleConfig
|
||||
if e = json.Unmarshal([]byte(plain), &cfg); e != nil {
|
||||
return e
|
||||
}
|
||||
v.Target = cfg.Target
|
||||
v.Arguments = cfg.Arguments
|
||||
return nil
|
||||
}
|
||||
func (s *Projects) UserSchedules(ctx context.Context, u store.User) ([]store.UserSchedule, error) {
|
||||
if u.Role != "tenant" || u.TenantID == nil {
|
||||
return nil, store.ErrNotFound
|
||||
}
|
||||
rows, e := s.store.UserSchedules(ctx, u.ID)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
for i := range rows {
|
||||
if e = s.openSchedule(&rows[i]); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
func (s *Projects) SaveUserSchedule(ctx context.Context, u store.User, v store.UserSchedule) (uint64, error) {
|
||||
if u.Role != "tenant" || u.TenantID == nil {
|
||||
return 0, store.ErrNotFound
|
||||
}
|
||||
if len(strings.TrimSpace(v.Name)) < 1 || len(v.Name) > 120 {
|
||||
return 0, errors.New("请输入不超过 120 字节的任务名称")
|
||||
}
|
||||
if len(v.Cron) > 120 || len(v.Timezone) > 80 {
|
||||
return 0, errors.New("计划表达式或时区过长")
|
||||
}
|
||||
if v.Timezone == "" {
|
||||
v.Timezone = "Asia/Shanghai"
|
||||
}
|
||||
cron, e := hosting.ParseCron(v.Cron, v.Timezone)
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
next, e := cron.Next(time.Now())
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
ctx = scope.WithAccount(ctx, *u.TenantID)
|
||||
p, e := s.store.ProjectForUser(ctx, u, v.ProjectID)
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
release, e := s.BeginHostAccess(p.ID)
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
defer release()
|
||||
ctx = scope.WithProject(ctx, p.ID, p.NodeID)
|
||||
if e = s.ensureTenantWritable(ctx, p.TenantID); e != nil {
|
||||
return 0, e
|
||||
}
|
||||
site, e := s.store.Site(ctx, p.TenantID, p.ID, v.SiteID)
|
||||
if e != nil {
|
||||
return 0, store.ErrNotFound
|
||||
}
|
||||
params := hosting.Startup{Arguments: v.Arguments}
|
||||
if e = params.Validate(); e != nil {
|
||||
return 0, e
|
||||
}
|
||||
if len(v.Target) > 512 {
|
||||
return 0, errors.New("任务路径过长")
|
||||
}
|
||||
if v.Kind == "url" {
|
||||
uri, err := url.ParseRequestURI(v.Target)
|
||||
if err != nil || uri.IsAbs() || uri.Host != "" || !strings.HasPrefix(v.Target, "/") || strings.HasPrefix(v.Target, "//") || len(v.Arguments) > 0 {
|
||||
return 0, errors.New("URL 仅支持本站以 / 开头的路径,不能附带启动参数")
|
||||
}
|
||||
v.Version = ""
|
||||
if v.UseHTTPS && site.SSLStatus != "active" {
|
||||
return 0, errors.New("网站尚未启用 HTTPS")
|
||||
}
|
||||
} else {
|
||||
runtime := map[string]string{"php": "PHP", "python": "Python", "node": "Node.js"}[v.Kind]
|
||||
if runtime == "" || !hosting.ValidRelative(v.Target) {
|
||||
return 0, errors.New("请选择 PHP、Python、Node 脚本或本站 URL")
|
||||
}
|
||||
if e = s.validateRuntime(ctx, runtime, v.Version); e != nil {
|
||||
return 0, e
|
||||
}
|
||||
v.UseHTTPS = false
|
||||
}
|
||||
v.OwnershipVersion, e = s.store.ProjectOwnershipVersion(ctx, p.ID)
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
v.UserID = u.ID
|
||||
v.AccountID = *u.TenantID
|
||||
v.NextRunAt = next
|
||||
token := make([]byte, 16)
|
||||
if _, e = rand.Read(token); e != nil {
|
||||
return 0, e
|
||||
}
|
||||
v.SecretRef = hex.EncodeToString(token)
|
||||
plain, _ := json.Marshal(scheduleConfig{v.Target, v.Arguments})
|
||||
v.ConfigCipher, e = s.credentials.Seal("user-schedule:"+v.SecretRef, string(plain))
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
v.Target = ""
|
||||
v.Arguments = []string{}
|
||||
return s.store.SaveUserSchedule(ctx, v)
|
||||
}
|
||||
func (s *Projects) ScheduleRuns(ctx context.Context, u store.User, id uint64) ([]store.ScheduleRun, error) {
|
||||
if u.Role != "tenant" || u.TenantID == nil {
|
||||
return nil, store.ErrNotFound
|
||||
}
|
||||
if _, e := s.store.UserSchedule(ctx, u.ID, id); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
rows, e := s.store.ScheduleRuns(ctx, u.ID, id)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
for i := range rows {
|
||||
if len(rows[i].OutputCipher) > 0 {
|
||||
rows[i].Output, e = s.credentials.Open(fmt.Sprintf("schedule-run:%d", rows[i].ID), rows[i].OutputCipher)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// Called only by the authenticated controller tick sent by the panel's cron.
|
||||
func (s *Projects) DispatchUserSchedules(ctx context.Context) error {
|
||||
return s.dispatchUserSchedules(ctx, true)
|
||||
}
|
||||
func (s *Projects) QueueUserSchedules(ctx context.Context) error {
|
||||
return s.dispatchUserSchedules(ctx, false)
|
||||
}
|
||||
func (s *Projects) dispatchUserSchedules(ctx context.Context, wait bool) error {
|
||||
rows, e := s.store.DueSchedules(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
s.scheduleInit.Do(func() { s.scheduleSlots = make(chan struct{}, 4) })
|
||||
var wg sync.WaitGroup
|
||||
for _, v := range rows {
|
||||
select {
|
||||
case s.scheduleSlots <- struct{}{}:
|
||||
default:
|
||||
continue
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(v store.UserSchedule) {
|
||||
defer wg.Done()
|
||||
defer func() { <-s.scheduleSlots }()
|
||||
task, cancel := context.WithTimeout(context.WithoutCancel(ctx), 310*time.Second)
|
||||
defer cancel()
|
||||
s.executeUserSchedule(task, v)
|
||||
}(v)
|
||||
}
|
||||
if wait {
|
||||
wg.Wait()
|
||||
}
|
||||
return s.store.PruneSchedules(ctx)
|
||||
}
|
||||
func (s *Projects) executeUserSchedule(ctx context.Context, v store.UserSchedule) {
|
||||
cron, e := hosting.ParseCron(v.Cron, v.Timezone)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
next, e := cron.Next(time.Now())
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
u, e := s.store.UserByID(ctx, v.UserID)
|
||||
if e != nil || u.Role != "tenant" || u.TenantID == nil || *u.TenantID != v.AccountID {
|
||||
return
|
||||
}
|
||||
ctx = scope.WithAccount(ctx, v.AccountID)
|
||||
p, e := s.store.ProjectForUser(ctx, u, v.ProjectID)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
ctx = scope.WithProject(ctx, p.ID, p.NodeID)
|
||||
release, e := s.BeginHostAccess(p.ID)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
defer release()
|
||||
nodeRelease, e := s.BeginRuntimeMutation(ctx)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
defer nodeRelease()
|
||||
run, e := s.store.ClaimSchedule(ctx, v.ID, next, v.SecretRef)
|
||||
if e != nil || run == 0 {
|
||||
return
|
||||
}
|
||||
code := 1
|
||||
output := "计划任务未执行"
|
||||
state := "failed"
|
||||
defer func() {
|
||||
cipher, sealErr := s.credentials.Seal(fmt.Sprintf("schedule-run:%d", run), output)
|
||||
if sealErr != nil {
|
||||
cipher = nil
|
||||
}
|
||||
done, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||||
defer cancel()
|
||||
_ = s.store.FinishSchedule(done, v.ID, run, state, code, cipher)
|
||||
s.store.Log(done, &p.TenantID, u.ID, "execute", "schedule", fmt.Sprint(v.ID), "", state == "succeeded", "执行用户计划任务:"+v.Name)
|
||||
}()
|
||||
if e = s.openSchedule(&v); e != nil {
|
||||
return
|
||||
}
|
||||
if e = s.ensureTenantWritable(ctx, p.TenantID); e != nil {
|
||||
output = e.Error()
|
||||
return
|
||||
}
|
||||
site, e := s.store.Site(ctx, p.TenantID, p.ID, v.SiteID)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
plan, _, e := s.store.PlanAndUsage(ctx, p.TenantID)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
env, e := s.loadStartup(ctx, site)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
port, e := s.store.ScheduleSitePort(ctx, site.ID, v.UseHTTPS)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
executor, ok := s.isolation.(isolation.ScheduleExecutor)
|
||||
if !ok {
|
||||
output = "节点不支持计划任务"
|
||||
return
|
||||
}
|
||||
task, cancel := context.WithTimeout(ctx, 300*time.Second)
|
||||
defer cancel()
|
||||
result, e := executor.ExecuteSchedule(task, isolation.ScheduleExecutionSpec{Project: isolation.ProjectSpec{TenantID: p.TenantID, HostName: p.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)}, SiteName: lifecycleSiteName(p, site), Kind: v.Kind, Version: v.Version, Target: v.Target, Arguments: v.Arguments, Environment: env.Environment, Domain: site.Domain, Port: port, UseHTTPS: v.UseHTTPS})
|
||||
if e != nil {
|
||||
output = "节点任务执行失败或超时"
|
||||
return
|
||||
}
|
||||
code = result.ExitCode
|
||||
output = result.Output
|
||||
if result.Truncated {
|
||||
output += "\n[输出已截断至 64 KiB]"
|
||||
}
|
||||
if code == 0 {
|
||||
state = "succeeded"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user