2001 lines
78 KiB
Go
2001 lines
78 KiB
Go
package service
|
||
|
||
import (
|
||
"context"
|
||
"crypto/rand"
|
||
"encoding/base64"
|
||
"encoding/hex"
|
||
"errors"
|
||
"fmt"
|
||
"log/slog"
|
||
"os"
|
||
"path"
|
||
"regexp"
|
||
"slices"
|
||
"strings"
|
||
"sync"
|
||
"time"
|
||
|
||
"sea-vhost/internal/auth"
|
||
fileguard "sea-vhost/internal/files"
|
||
"sea-vhost/internal/isolation"
|
||
"sea-vhost/internal/nodefiles"
|
||
"sea-vhost/internal/panel"
|
||
"sea-vhost/internal/scope"
|
||
"sea-vhost/internal/secrets"
|
||
"sea-vhost/internal/store"
|
||
)
|
||
|
||
var ErrQuotaSuspended = errors.New("tenant quota suspended")
|
||
|
||
const maxDomainsPerSite = 100
|
||
|
||
var slugPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,48}[a-z0-9]$`)
|
||
var domainPattern = regexp.MustCompile(`^(?i:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+)$`)
|
||
|
||
type Projects struct {
|
||
scheduleInit sync.Once
|
||
scheduleSlots chan struct{}
|
||
hostAccessGates sync.Map
|
||
fileOpener func(context.Context, string) (*nodefiles.Root, error)
|
||
store *store.Store
|
||
panel panel.Interface
|
||
isolation isolation.Interface
|
||
credentials *secrets.Box
|
||
rootDomain, tenantRoot string
|
||
ftpCertificateDomain string
|
||
domainApproval bool
|
||
storageQuota *StorageQuota
|
||
certificateMu sync.Mutex
|
||
domainMu sync.Mutex
|
||
runtimeMu sync.Mutex
|
||
maintenanceGate sync.RWMutex
|
||
nodeGates sync.Map
|
||
runtimeCatalog panel.RuntimeCatalog
|
||
runtimeCatalogExpires time.Time
|
||
runtimeCatalogLoading chan struct{}
|
||
runtimeInstallJobs map[string]bool
|
||
reservedDomains []string
|
||
}
|
||
|
||
type CreateProjectInput struct {
|
||
OwnerTenantID *uint64 `json:"-"`
|
||
OwnershipSpecified bool `json:"-"`
|
||
NodeID uint64 `json:"nodeId"`
|
||
PlanID uint64 `json:"planId"`
|
||
Name, Runtime, Version, RunPath, CustomDomain string
|
||
AutoSSL bool
|
||
existingSiteID int64
|
||
existingSourcePath, existingDomain string
|
||
}
|
||
|
||
type AdoptProjectInput struct {
|
||
NodeID uint64
|
||
PlanID uint64
|
||
TenantID uint64
|
||
PanelSiteID int64
|
||
Name string
|
||
Runtime string
|
||
Version string
|
||
RunPath string
|
||
AutoSSL bool
|
||
}
|
||
|
||
type CreatedProject struct {
|
||
Project store.Project `json:"project"`
|
||
Credentials struct {
|
||
FTPUsername string `json:"ftpUsername"`
|
||
FTPPassword string `json:"ftpPassword"`
|
||
FTPHost string `json:"ftpHost"`
|
||
FTPTLSPolicy string `json:"ftpTLSPolicy"`
|
||
DatabaseName string `json:"databaseName"`
|
||
DatabaseUsername string `json:"databaseUsername"`
|
||
DatabasePassword string `json:"databasePassword"`
|
||
HostLogin string `json:"hostLogin"`
|
||
HostPassword string `json:"hostPassword"`
|
||
} `json:"credentials"`
|
||
}
|
||
|
||
type CreateSiteInput struct {
|
||
Name, Runtime, Version, RunPath, CustomDomain string
|
||
AutoSSL bool
|
||
}
|
||
|
||
type DeploymentCheck struct {
|
||
Runtime string `json:"runtime"`
|
||
EntryFile string `json:"entryFile"`
|
||
Ready bool `json:"ready"`
|
||
AdapterReady bool `json:"adapterReady"`
|
||
Size int64 `json:"size,omitempty"`
|
||
Message string `json:"message"`
|
||
}
|
||
|
||
func NewProjects(database *store.Store, panelClient panel.Interface, isolator isolation.Interface, rootDomain, tenantRoot string, domainApproval bool, credentialSecret, ftpCertificateDomain string, reservedDomains ...string) *Projects {
|
||
reserved := []string{strings.ToLower(strings.TrimSuffix(rootDomain, "."))}
|
||
for _, domain := range reservedDomains {
|
||
domain = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), "."))
|
||
if domain != "" {
|
||
reserved = append(reserved, domain)
|
||
}
|
||
}
|
||
return &Projects{store: database, panel: panelClient, isolation: isolator, credentials: secrets.New(credentialSecret), rootDomain: rootDomain, tenantRoot: tenantRoot, ftpCertificateDomain: ftpCertificateDomain, domainApproval: domainApproval, storageQuota: NewStorageQuota(database, panelClient, isolator, tenantRoot), runtimeInstallJobs: map[string]bool{}, reservedDomains: reserved}
|
||
}
|
||
|
||
func (s *Projects) RunStorageQuotaMonitor(ctx context.Context, interval time.Duration) {
|
||
s.storageQuota.Run(ctx, interval)
|
||
}
|
||
|
||
func (s *Projects) RunLifecycleMonitor(ctx context.Context, interval time.Duration) {
|
||
process := func() { s.processHostLifecycle(ctx) }
|
||
process()
|
||
ticker := time.NewTicker(interval)
|
||
defer ticker.Stop()
|
||
for {
|
||
select {
|
||
case <-ctx.Done():
|
||
return
|
||
case <-ticker.C:
|
||
process()
|
||
}
|
||
}
|
||
}
|
||
|
||
func (s *Projects) purgeExpiredTenant(ctx context.Context, tenant store.TenantSummary, projects []store.Project, plan store.Plan) error {
|
||
if tenant.BackupPurgeAfter == nil {
|
||
return errors.New("backup expiry is missing")
|
||
}
|
||
for _, project := range projects {
|
||
databases, err := s.store.ListDatabaseResources(ctx, tenant.ID, &project.ID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
oldArchive, databaseCount, err := s.store.TenantBackupDetails(ctx, tenant.ID, project.ID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
spec := isolation.ProjectSpec{TenantID: tenant.ID, HostName: project.HostName, RunPath: project.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit)}
|
||
for _, database := range databases {
|
||
if database.Name != project.HostName || database.Username != project.HostName {
|
||
return errors.New("inconsistent managed database identity")
|
||
}
|
||
spec.Databases = append(spec.Databases, database.Name)
|
||
}
|
||
if oldArchive != "" && databaseCount >= len(databases) {
|
||
if verifyErr := s.isolation.VerifyProjectBackup(ctx, isolation.ProjectBackup{TenantID: tenant.ID, HostName: project.HostName, ArchivePath: oldArchive, DatabaseCount: databaseCount}); verifyErr != nil {
|
||
databaseCount = -1
|
||
}
|
||
}
|
||
if oldArchive == "" || databaseCount < len(databases) {
|
||
for _, database := range databases {
|
||
if accessErr := s.isolation.ConfigureDatabaseAccess(ctx, isolation.DatabaseAccessSpec{Project: spec, Database: database.Name, ReadOnly: true, BlockCleanup: true}); accessErr != nil {
|
||
return fmt.Errorf("freeze database for recovery backup: %w", accessErr)
|
||
}
|
||
}
|
||
backup, backupErr := s.isolation.CreateProjectBackup(ctx, spec)
|
||
if backupErr != nil {
|
||
return fmt.Errorf("backup %s: %w", project.HostName, backupErr)
|
||
}
|
||
if backup.ArchivePath == "" || backup.HostName != project.HostName || backup.TenantID != tenant.ID || backup.DatabaseCount != len(databases) {
|
||
return fmt.Errorf("backup %s returned inconsistent identity", project.HostName)
|
||
}
|
||
if verifyErr := s.isolation.VerifyProjectBackup(ctx, backup); verifyErr != nil {
|
||
_ = s.isolation.DeleteProjectBackup(context.WithoutCancel(ctx), backup)
|
||
return fmt.Errorf("verify recovery backup %s: %w", project.HostName, verifyErr)
|
||
}
|
||
// A delayed cleanup must still retain a newly created backup for 14 days.
|
||
backupExpiresAt := time.Now().UTC().Add(14 * 24 * time.Hour)
|
||
if backupErr = s.store.CreateTenantBackup(ctx, tenant.ID, project.ID, project.HostName, backup.ArchivePath, backup.SizeBytes, backupExpiresAt, backup.DatabaseCount); backupErr != nil {
|
||
_ = s.isolation.DeleteProjectBackup(context.WithoutCancel(ctx), backup)
|
||
return fmt.Errorf("record backup %s: %w", project.HostName, backupErr)
|
||
}
|
||
if oldArchive != "" && oldArchive != backup.ArchivePath {
|
||
_ = s.isolation.DeleteProjectBackup(ctx, isolation.ProjectBackup{TenantID: tenant.ID, HostName: project.HostName, ArchivePath: oldArchive})
|
||
}
|
||
}
|
||
sites, err := s.store.ListSites(ctx, tenant.ID, project.ID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
for _, site := range sites {
|
||
siteSpec := isolation.ProjectSpec{TenantID: tenant.ID, HostName: project.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)}
|
||
_ = s.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, false)
|
||
if site.Runtime == "PHP" {
|
||
_ = s.isolation.RemovePHPIdentity(ctx, isolation.PHPIdentitySpec{Project: siteSpec, SiteName: lifecycleSiteName(project, site), Domain: site.Domain, Version: site.Version, ProcessLimit: uint32(site.ProcessLimit)})
|
||
} else {
|
||
_ = s.panel.RemoveRuntime(ctx, panel.RuntimeSpec{ProjectName: lifecycleSiteName(project, site), Runtime: site.Runtime, Version: site.Version, Path: project.Path, RunPath: site.RunPath, Domain: site.Domain, RunUser: project.HostName, Port: site.BackendPort, ProcessLimit: site.ProcessLimit})
|
||
}
|
||
_ = s.isolation.RemoveWebProtection(ctx, isolation.WebProtectionSpec{Project: siteSpec, Domain: site.Domain})
|
||
if err = s.panel.DeleteSite(ctx, site.PanelSiteID, site.Domain); err != nil {
|
||
return fmt.Errorf("delete panel site %s: %w", site.Domain, err)
|
||
}
|
||
}
|
||
ftps, err := s.store.ListFTPResources(ctx, tenant.ID, &project.ID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
for _, ftp := range ftps {
|
||
if err = s.panel.DeleteFTP(ctx, ftp.PanelID, ftp.Username); err != nil {
|
||
return fmt.Errorf("delete FTP %s: %w", ftp.Username, err)
|
||
}
|
||
}
|
||
for _, database := range databases {
|
||
if err = s.panel.DeleteDatabase(ctx, database.PanelID, database.Name); err != nil {
|
||
return fmt.Errorf("delete database %s: %w", database.Name, err)
|
||
}
|
||
}
|
||
if err = s.isolation.PurgeProject(ctx, spec); err != nil {
|
||
return fmt.Errorf("purge directory %s: %w", project.HostName, err)
|
||
}
|
||
}
|
||
return s.store.MarkTenantPurged(ctx, tenant.ID)
|
||
}
|
||
|
||
func lifecycleSiteName(project store.Project, site store.Site) string {
|
||
if site.Primary {
|
||
return project.HostName
|
||
}
|
||
return fmt.Sprintf("%s_%d", project.HostName, site.ID)
|
||
}
|
||
|
||
func (s *Projects) ConfigureProjectNetwork(ctx context.Context, projectID uint64, ipID *uint64, dedicated bool, httpPort, httpsPort int) error {
|
||
return s.withNodeMaintenance(ctx, func() error { return s.configureProjectNetwork(ctx, projectID, ipID, dedicated, httpPort, httpsPort) })
|
||
}
|
||
|
||
func (s *Projects) configureProjectNetwork(ctx context.Context, projectID uint64, ipID *uint64, dedicated bool, httpPort, httpsPort int) error {
|
||
projects, err := s.store.ListAdminProjects(ctx)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
var project *store.AdminProject
|
||
for index := range projects {
|
||
if projects[index].ID == projectID {
|
||
project = &projects[index]
|
||
break
|
||
}
|
||
}
|
||
if project == nil {
|
||
return store.ErrNotFound
|
||
}
|
||
address := ""
|
||
if dedicated {
|
||
if ipID == nil {
|
||
return errors.New("dedicated ip is required")
|
||
}
|
||
ip, lookupErr := s.store.IPAddress(ctx, *ipID)
|
||
if lookupErr != nil {
|
||
return lookupErr
|
||
}
|
||
if !ip.Enabled || ip.AllocationMode != "dedicated" || ip.NodeID != project.NodeID {
|
||
return errors.New("ip is not available for dedicated allocation")
|
||
}
|
||
if ip.AssignedSites > 0 && !(project.DedicatedIP && project.IPAddress == ip.Address) {
|
||
return errors.New("dedicated ip is already assigned")
|
||
}
|
||
address = ip.Address
|
||
} else {
|
||
ipID = nil
|
||
}
|
||
plan, _, err := s.store.PlanAndUsage(ctx, project.TenantID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
spec := isolation.NginxNetworkSpec{Project: isolation.ProjectSpec{TenantID: project.TenantID, HostName: project.HostName, RunPath: project.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit)}, Domain: project.Domain, IPAddress: address, Dedicated: dedicated, HTTPPort: httpPort, HTTPSPort: httpsPort}
|
||
if err = s.isolation.ConfigureNginxNetwork(ctx, spec); err != nil {
|
||
return err
|
||
}
|
||
return s.store.SetProjectNetwork(ctx, projectID, ipID, dedicated, httpPort, httpsPort)
|
||
}
|
||
|
||
// ReconcileIdentities upgrades existing managed hosts from the legacy shared
|
||
// www runtime to locked per-host Linux identities before the API accepts
|
||
// tenant traffic. A partial migration is treated as a startup failure.
|
||
func (s *Projects) ReconcileIdentities(ctx context.Context) error {
|
||
projects, err := s.store.AllProjects(ctx)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
var failures []error
|
||
for _, project := range projects {
|
||
err := func() error {
|
||
ctx := scope.WithProject(ctx, project.ID, project.NodeID)
|
||
_ = s.store.SetHostIdentityVerified(ctx, project.ID, false)
|
||
plan, _, planErr := s.store.PlanAndUsage(ctx, project.TenantID)
|
||
if planErr != nil {
|
||
return fmt.Errorf("read plan for %s: %w", project.HostName, planErr)
|
||
}
|
||
baseSpec := isolation.ProjectSpec{
|
||
TenantID: project.TenantID, HostName: project.HostName, RunPath: project.RunPath,
|
||
StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit),
|
||
}
|
||
prepared, prepareErr := s.isolation.Prepare(ctx, baseSpec)
|
||
if prepareErr != nil || path.Clean(prepared.RootPath) != path.Clean(project.Path) || prepared.RunUser != project.HostName {
|
||
if prepareErr == nil {
|
||
prepareErr = errors.New("隔离代理返回了不一致的主机身份")
|
||
}
|
||
return fmt.Errorf("reconcile host %s: %w", project.HostName, prepareErr)
|
||
}
|
||
ftpUsername, ftpErr := s.store.FTPUsername(ctx, project.TenantID, project.ID)
|
||
if ftpErr == nil {
|
||
if ftpErr = s.isolation.ConfigureFTPIdentity(ctx, isolation.FTPIdentitySpec{Project: baseSpec, Username: ftpUsername}); ftpErr != nil {
|
||
return fmt.Errorf("reconcile FTP identity for %s: %w", project.HostName, ftpErr)
|
||
}
|
||
} else if !errors.Is(ftpErr, store.ErrNotFound) {
|
||
return ftpErr
|
||
}
|
||
sites, listErr := s.store.ListSites(ctx, project.TenantID, project.ID)
|
||
if listErr != nil {
|
||
return listErr
|
||
}
|
||
for _, site := range sites {
|
||
if site.PanelSiteID <= 0 {
|
||
continue
|
||
}
|
||
siteSpec := baseSpec
|
||
siteSpec.RunPath = site.RunPath
|
||
siteSpec.ProcessLimit = uint32(site.ProcessLimit)
|
||
if _, prepareErr = s.isolation.Prepare(ctx, siteSpec); prepareErr != nil {
|
||
return fmt.Errorf("reconcile site directory %s: %w", site.Domain, prepareErr)
|
||
}
|
||
if site.Runtime == "Node.js" || site.Runtime == "Python" {
|
||
if err = s.isolation.PreparePanelRuntime(ctx, isolation.PanelRuntimeSpec{Project: siteSpec, Runtime: site.Runtime, Version: site.Version, ProjectName: lifecycleSiteName(project, site)}); err != nil {
|
||
return fmt.Errorf("reconcile %s panel compatibility for %s: %w", site.Runtime, site.Domain, err)
|
||
}
|
||
}
|
||
if err = s.panel.MigrateRuntimeIdentity(ctx, site.PanelSiteID, project.HostName, site.Status == "running"); err != nil {
|
||
return fmt.Errorf("reconcile runtime identity for %s: %w", site.Domain, err)
|
||
}
|
||
if site.Runtime == "PHP" {
|
||
phpSpec, phpErr := s.phpIdentitySpec(ctx, project, site)
|
||
if phpErr != nil {
|
||
return phpErr
|
||
}
|
||
if phpErr = s.isolation.ConfigurePHPIdentity(ctx, phpSpec); phpErr != nil {
|
||
return fmt.Errorf("reconcile PHP identity for %s: %w", site.Domain, phpErr)
|
||
}
|
||
if site.Status != "running" {
|
||
if phpErr = s.isolation.SetPHPIdentityState(ctx, phpSpec, false); phpErr != nil {
|
||
return fmt.Errorf("restore stopped PHP state for %s: %w", site.Domain, phpErr)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
suspended, _, err := s.store.TenantQuotaSuspension(ctx, project.TenantID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if suspended {
|
||
if err = s.isolation.FreezeWrites(ctx, baseSpec); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
if err = s.store.SetHostIdentityVerified(ctx, project.ID, true); err != nil {
|
||
return err
|
||
}
|
||
if !suspended && s.store.HostWritable(ctx, project.TenantID) == nil {
|
||
resources, err := s.store.ListFTPResources(ctx, project.TenantID, &project.ID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
for _, ftp := range resources {
|
||
if !ftp.Enabled {
|
||
continue
|
||
}
|
||
if err = s.panel.SetFTPState(ctx, ftp.PanelID, ftp.Username, true); err != nil {
|
||
_ = s.store.SetHostIdentityVerified(context.WithoutCancel(ctx), project.ID, false)
|
||
return err
|
||
}
|
||
}
|
||
}
|
||
return nil
|
||
}()
|
||
if err != nil {
|
||
failures = append(failures, err)
|
||
}
|
||
}
|
||
return errors.Join(failures...)
|
||
}
|
||
|
||
func (s *Projects) CheckStorageWrite(ctx context.Context, tenantID, additionalBytes uint64) error {
|
||
return s.storageQuota.CheckWrite(ctx, tenantID, additionalBytes)
|
||
}
|
||
|
||
func (s *Projects) ensureTenantWritable(ctx context.Context, tenantID uint64) error {
|
||
if err := s.store.HostWritable(ctx, tenantID); err != nil {
|
||
return err
|
||
}
|
||
suspended, reason, err := s.store.TenantQuotaSuspension(ctx, tenantID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if suspended {
|
||
return fmt.Errorf("%w: %s", ErrQuotaSuspended, reason)
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func (s *Projects) RuntimeCatalog(ctx context.Context) (panel.RuntimeCatalog, error) {
|
||
if s.store != nil {
|
||
return s.panel.RuntimeCatalog(ctx)
|
||
}
|
||
for {
|
||
now := time.Now()
|
||
s.runtimeMu.Lock()
|
||
if now.Before(s.runtimeCatalogExpires) && s.runtimeCatalog != nil {
|
||
catalog := cloneRuntimeCatalog(s.runtimeCatalog)
|
||
s.runtimeMu.Unlock()
|
||
return catalog, nil
|
||
}
|
||
if s.runtimeCatalogLoading != nil {
|
||
loading := s.runtimeCatalogLoading
|
||
s.runtimeMu.Unlock()
|
||
select {
|
||
case <-ctx.Done():
|
||
return nil, ctx.Err()
|
||
case <-loading:
|
||
continue
|
||
}
|
||
}
|
||
loading := make(chan struct{})
|
||
s.runtimeCatalogLoading = loading
|
||
s.runtimeMu.Unlock()
|
||
catalog, err := s.panel.RuntimeCatalog(ctx)
|
||
s.runtimeMu.Lock()
|
||
if err == nil {
|
||
s.runtimeCatalog = cloneRuntimeCatalog(catalog)
|
||
s.runtimeCatalogExpires = time.Now().Add(time.Minute)
|
||
}
|
||
close(loading)
|
||
s.runtimeCatalogLoading = nil
|
||
s.runtimeMu.Unlock()
|
||
return cloneRuntimeCatalog(catalog), err
|
||
}
|
||
}
|
||
|
||
func cloneRuntimeCatalog(source panel.RuntimeCatalog) panel.RuntimeCatalog {
|
||
if source == nil {
|
||
return panel.RuntimeCatalog{}
|
||
}
|
||
result := make(panel.RuntimeCatalog, len(source))
|
||
for runtimeName, versions := range source {
|
||
result[runtimeName] = append([]string(nil), versions...)
|
||
}
|
||
return result
|
||
}
|
||
|
||
func (s *Projects) RuntimeEnvironments(ctx context.Context) ([]panel.RuntimeEnvironment, error) {
|
||
items, err := s.panel.RuntimeEnvironments(ctx)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if s.store != nil {
|
||
jobs, jobErr := s.store.RuntimeJobs(ctx)
|
||
if jobErr != nil {
|
||
return nil, jobErr
|
||
}
|
||
for _, job := range jobs {
|
||
if job.Action != "install" || (job.Status != "queued" && job.Status != "running" && job.Status != "interrupted") {
|
||
continue
|
||
}
|
||
for index := range items {
|
||
if items[index].Name == job.Runtime && !slices.Contains(items[index].Installing, job.TargetVersion) {
|
||
items[index].Installing = append(items[index].Installing, job.TargetVersion)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
s.runtimeMu.Lock()
|
||
defer s.runtimeMu.Unlock()
|
||
for index := range items {
|
||
prefix := items[index].Name + "/"
|
||
for key := range s.runtimeInstallJobs {
|
||
if strings.HasPrefix(key, prefix) {
|
||
version := strings.TrimPrefix(key, prefix)
|
||
if !slices.Contains(items[index].Installing, version) {
|
||
items[index].Installing = append(items[index].Installing, version)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return items, nil
|
||
}
|
||
|
||
func (s *Projects) InstallRuntimeComponent(ctx context.Context, runtimeName string) error {
|
||
if err := s.panel.InstallRuntimeComponent(ctx, runtimeName); err != nil {
|
||
return err
|
||
}
|
||
s.invalidateRuntimeCatalog()
|
||
return nil
|
||
}
|
||
|
||
func (s *Projects) installRuntimeEnvironmentLegacy(ctx context.Context, runtimeName, version string) error {
|
||
if runtimeName == "Python" {
|
||
items, err := s.panel.RuntimeEnvironments(ctx)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
allowed := false
|
||
for _, item := range items {
|
||
if item.Name == runtimeName && item.ComponentStatus == panel.RuntimeComponentReady && slices.Contains(item.Available, version) && !slices.Contains(item.Installed, version) {
|
||
allowed = true
|
||
break
|
||
}
|
||
}
|
||
if !allowed {
|
||
return errors.New("Python version is not the latest installable patch of a supported branch")
|
||
}
|
||
key := runtimeName + "/" + version
|
||
s.runtimeMu.Lock()
|
||
if s.runtimeInstallJobs[key] {
|
||
s.runtimeMu.Unlock()
|
||
return errors.New("runtime version installation is already running")
|
||
}
|
||
s.runtimeInstallJobs[key] = true
|
||
s.runtimeMu.Unlock()
|
||
go func() {
|
||
installCtx, cancel := context.WithTimeout(context.Background(), 2*time.Hour)
|
||
defer cancel()
|
||
installErr := s.isolation.InstallPythonRuntime(installCtx, version)
|
||
s.runtimeMu.Lock()
|
||
delete(s.runtimeInstallJobs, key)
|
||
s.runtimeCatalog = nil
|
||
s.runtimeCatalogExpires = time.Time{}
|
||
s.runtimeMu.Unlock()
|
||
if installErr != nil {
|
||
slog.Error("Python runtime installation failed", "version", version, "error", installErr)
|
||
if s.store != nil {
|
||
_ = s.store.EnqueueAdminNotification(context.Background(), "critical", "runtime", "Python 运行环境安装失败", fmt.Sprintf("Python %s:%v", version, installErr))
|
||
}
|
||
}
|
||
}()
|
||
return nil
|
||
}
|
||
if err := s.panel.InstallRuntimeEnvironment(ctx, runtimeName, version); err != nil {
|
||
return err
|
||
}
|
||
s.invalidateRuntimeCatalog()
|
||
return nil
|
||
}
|
||
|
||
func (s *Projects) invalidateRuntimeCatalog() {
|
||
s.runtimeMu.Lock()
|
||
s.runtimeCatalog = nil
|
||
s.runtimeCatalogExpires = time.Time{}
|
||
s.runtimeMu.Unlock()
|
||
}
|
||
|
||
func (s *Projects) Create(ctx context.Context, user store.User, input CreateProjectInput) (CreatedProject, error) {
|
||
if input.NodeID == 0 || input.PlanID == 0 {
|
||
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 user.TenantID == nil || user.Role == "host" {
|
||
return CreatedProject{}, errors.New("tenant account required")
|
||
}
|
||
if err := s.ensureTenantWritable(ctx, *user.TenantID); err != nil {
|
||
return CreatedProject{}, err
|
||
}
|
||
slug := strings.ToLower(strings.TrimSpace(input.Name))
|
||
if !slugPattern.MatchString(slug) {
|
||
return CreatedProject{}, errors.New("项目名称仅允许 3-50 位小写字母、数字和连字符")
|
||
}
|
||
allowedRuntime := map[string]bool{"PHP": true, "Node.js": true, "Python": true, "Go": true, "Java": true}
|
||
if !allowedRuntime[input.Runtime] {
|
||
return CreatedProject{}, errors.New("不支持的运行环境")
|
||
}
|
||
runPath, err := normalizeRunPath(input.RunPath)
|
||
if err != nil {
|
||
return CreatedProject{}, err
|
||
}
|
||
customDomain, customDomainStatus := "", ""
|
||
if input.existingSiteID == 0 {
|
||
customDomain, customDomainStatus, err = s.customDomain(ctx, input.CustomDomain)
|
||
if err != nil {
|
||
return CreatedProject{}, err
|
||
}
|
||
}
|
||
input.Version = strings.TrimSpace(input.Version)
|
||
catalog, err := s.panel.RuntimeCatalog(ctx)
|
||
if err != nil {
|
||
return CreatedProject{}, fmt.Errorf("无法读取宝塔运行环境: %w", err)
|
||
}
|
||
versionAvailable := false
|
||
for _, version := range catalog[input.Runtime] {
|
||
if version == input.Version {
|
||
versionAvailable = true
|
||
break
|
||
}
|
||
}
|
||
if !versionAvailable {
|
||
return CreatedProject{}, errors.New("所选运行版本未安装或已不可用")
|
||
}
|
||
plan, err := s.store.Plan(ctx, input.PlanID)
|
||
if err != nil {
|
||
return CreatedProject{}, err
|
||
}
|
||
processLimit := int(plan.ProcessLimit)
|
||
ftpTLSPolicy, err := s.ftpTLSPolicy(ctx)
|
||
if err != nil {
|
||
return CreatedProject{}, err
|
||
}
|
||
hostName, err := randomHostName()
|
||
if err != nil {
|
||
return CreatedProject{}, errors.New("无法生成安全主机名")
|
||
}
|
||
defaultDomain := hostName + "." + node.RootDomain
|
||
domain := defaultDomain
|
||
if input.existingSiteID > 0 {
|
||
domain = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(input.existingDomain), "."))
|
||
if !domainPattern.MatchString(domain) || strings.TrimSpace(input.existingSourcePath) == "" {
|
||
return CreatedProject{}, errors.New("待接管宝塔站点信息无效")
|
||
}
|
||
customDomain, customDomainStatus = defaultDomain, "approved"
|
||
}
|
||
root := path.Join(node.TenantRoot, hostName)
|
||
port := 0
|
||
hostPassword, err := randomPassword()
|
||
if err != nil {
|
||
return CreatedProject{}, errors.New("无法生成主机登录密码")
|
||
}
|
||
hostPasswordHash, err := auth.HashPassword(hostPassword)
|
||
if err != nil {
|
||
return CreatedProject{}, errors.New("无法保护主机登录密码")
|
||
}
|
||
projectID, err := s.store.InsertProject(ctx, store.NewProject{TenantID: *user.TenantID, OwnerTenantID: input.OwnerTenantID, OwnershipSpecified: input.OwnershipSpecified, NodeID: node.ID, PlanID: plan.ID, HostName: hostName, Slug: slug, Runtime: input.Runtime, Version: input.Version, Path: root, RunPath: runPath, Domain: domain, BackendPort: port, ProcessLimit: processLimit, AutoSSL: input.AutoSSL, HostPasswordHash: hostPasswordHash})
|
||
if err != nil {
|
||
return CreatedProject{}, err
|
||
}
|
||
createdRecord, err := s.store.Project(ctx, *user.TenantID, projectID)
|
||
if err != nil {
|
||
return CreatedProject{}, err
|
||
}
|
||
port = createdRecord.BackendPort
|
||
ctx = scope.WithProject(ctx, projectID, node.ID)
|
||
isolationSpec := isolation.ProjectSpec{TenantID: *user.TenantID, HostName: hostName, RunPath: runPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(processLimit)}
|
||
prepared, err := s.isolation.Prepare(ctx, isolationSpec)
|
||
if err != nil {
|
||
_ = s.isolation.Quarantine(context.WithoutCancel(ctx), isolationSpec)
|
||
_ = s.store.MarkProjectFailed(context.WithoutCancel(ctx), projectID, err.Error())
|
||
return CreatedProject{}, fmt.Errorf("创建主机隔离环境失败: %w", err)
|
||
}
|
||
if path.Clean(prepared.RootPath) != path.Clean(root) {
|
||
_ = s.isolation.Quarantine(context.WithoutCancel(ctx), isolationSpec)
|
||
err = errors.New("隔离代理返回了不一致的主机目录")
|
||
_ = s.store.MarkProjectFailed(context.WithoutCancel(ctx), projectID, err.Error())
|
||
return CreatedProject{}, err
|
||
}
|
||
if input.existingSiteID > 0 {
|
||
if err = s.isolation.ImportLegacyProject(ctx, isolation.LegacyImportSpec{Project: isolationSpec, SourcePath: input.existingSourcePath}); err != nil {
|
||
_ = s.isolation.Quarantine(context.WithoutCancel(ctx), isolationSpec)
|
||
_ = s.store.MarkProjectFailed(context.WithoutCancel(ctx), projectID, err.Error())
|
||
return CreatedProject{}, fmt.Errorf("复制原宝塔站点数据失败: %w", err)
|
||
}
|
||
}
|
||
|
||
var siteID, ftpID, databaseID int64
|
||
ftpUser := hostName
|
||
dbName := hostName
|
||
dbUser := dbName
|
||
ftpPassword, err := randomPanelPassword()
|
||
if err != nil {
|
||
return failBeforeResources(s, ctx, isolationSpec, projectID, errors.New("无法生成 FTP 密码"))
|
||
}
|
||
dbPassword, err := randomPanelPassword()
|
||
if err != nil {
|
||
return failBeforeResources(s, ctx, isolationSpec, projectID, errors.New("无法生成数据库密码"))
|
||
}
|
||
ftpPasswordCipher, err := s.credentials.Seal(credentialLabel("ftp", projectID), ftpPassword)
|
||
if err != nil {
|
||
return failBeforeResources(s, ctx, isolationSpec, projectID, errors.New("无法加密 FTP 密码"))
|
||
}
|
||
dbPasswordCipher, err := s.credentials.Seal(credentialLabel("database", projectID), dbPassword)
|
||
if err != nil {
|
||
return failBeforeResources(s, ctx, isolationSpec, projectID, errors.New("无法加密数据库密码"))
|
||
}
|
||
protectionSpec := isolation.WebProtectionSpec{Project: isolationSpec, Domain: domain}
|
||
protectionApplied := false
|
||
phpIdentitySpec := isolation.PHPIdentitySpec{Project: isolationSpec, SiteName: hostName, Domain: domain, Version: input.Version, ProcessLimit: uint32(processLimit)}
|
||
phpIdentityConfigured := false
|
||
adopted := false
|
||
fail := func(cause error) (CreatedProject, error) {
|
||
if databaseID > 0 {
|
||
_ = s.panel.DeleteDatabase(context.WithoutCancel(ctx), databaseID, dbName)
|
||
}
|
||
if ftpID > 0 {
|
||
_ = s.panel.DeleteFTP(context.WithoutCancel(ctx), ftpID, ftpUser)
|
||
}
|
||
if protectionApplied {
|
||
_ = s.isolation.RemoveWebProtection(context.WithoutCancel(ctx), protectionSpec)
|
||
}
|
||
if phpIdentityConfigured {
|
||
_ = s.isolation.RemovePHPIdentity(context.WithoutCancel(ctx), phpIdentitySpec)
|
||
}
|
||
if adopted {
|
||
_ = s.panel.RollbackAdoption(context.WithoutCancel(ctx), siteID, domain, input.existingSourcePath)
|
||
} else if siteID > 0 {
|
||
_ = s.panel.DeleteSite(context.WithoutCancel(ctx), siteID, domain)
|
||
}
|
||
_ = s.isolation.Quarantine(context.WithoutCancel(ctx), isolationSpec)
|
||
_ = s.store.MarkProjectFailed(context.WithoutCancel(ctx), projectID, cause.Error())
|
||
return CreatedProject{}, cause
|
||
}
|
||
siteSpec := panel.SiteSpec{Name: hostName, Domain: domain, Path: root, RunPath: runPath, Runtime: input.Runtime, Version: input.Version, RunUser: prepared.RunUser, Port: port, ProcessLimit: processLimit}
|
||
if input.existingSiteID > 0 {
|
||
siteID = input.existingSiteID
|
||
err = s.panel.AdoptSite(ctx, siteID, input.existingSourcePath, siteSpec)
|
||
adopted = err == nil
|
||
} else {
|
||
siteID, err = s.panel.CreateSite(ctx, siteSpec)
|
||
}
|
||
if err != nil {
|
||
return fail(fmt.Errorf("创建或接管宝塔站点失败: %w", err))
|
||
}
|
||
if adopted {
|
||
if err = s.panel.AddDomain(ctx, siteID, domain, defaultDomain); err != nil {
|
||
return fail(fmt.Errorf("添加平台默认域名失败: %w", err))
|
||
}
|
||
}
|
||
// aaPanel's site creation may recursively reset the document root to www:www.
|
||
// Reassert the managed owner and group after that privileged mutation; do
|
||
// not expose a project whose filesystem boundary could not be restored.
|
||
repaired, repairErr := s.isolation.Prepare(ctx, isolationSpec)
|
||
if repairErr != nil || repaired.RootPath != prepared.RootPath || repaired.RunUser != prepared.RunUser {
|
||
if repairErr == nil {
|
||
repairErr = errors.New("隔离代理返回了不一致的主机身份")
|
||
}
|
||
return fail(fmt.Errorf("宝塔建站后恢复主机目录隔离失败: %w", repairErr))
|
||
}
|
||
if err = s.isolation.ApplyWebProtection(ctx, protectionSpec); err != nil {
|
||
return fail(fmt.Errorf("启用站点基础防护失败: %w", err))
|
||
}
|
||
protectionApplied = true
|
||
if input.Runtime == "PHP" {
|
||
if err = s.isolation.ConfigurePHPIdentity(ctx, phpIdentitySpec); err != nil {
|
||
return fail(fmt.Errorf("创建独立 PHP 运行身份失败: %w", err))
|
||
}
|
||
phpIdentityConfigured = true
|
||
}
|
||
ftpID, err = s.panel.CreateFTP(ctx, ftpUser, ftpPassword, root, int64(plan.StorageBytes))
|
||
if err != nil {
|
||
return fail(fmt.Errorf("创建 FTP 失败: %w", err))
|
||
}
|
||
if err = s.isolation.ConfigureFTPIdentity(ctx, isolation.FTPIdentitySpec{Project: isolationSpec, Username: ftpUser}); err != nil {
|
||
return fail(fmt.Errorf("绑定 FTP 独立身份失败: %w", err))
|
||
}
|
||
// aaPanel's FTP account creation also resets the FTP root itself to www:www
|
||
// on some Pure-FTPd builds. Reassert the application-owned root after the
|
||
// account exists so Web file operations work without granting the API user
|
||
// membership in the shared www group.
|
||
repaired, repairErr = s.isolation.Prepare(ctx, isolationSpec)
|
||
if repairErr != nil || repaired.RootPath != prepared.RootPath || repaired.RunUser != prepared.RunUser {
|
||
if repairErr == nil {
|
||
repairErr = errors.New("隔离代理返回了不一致的主机身份")
|
||
}
|
||
return fail(fmt.Errorf("宝塔创建 FTP 后恢复主机目录隔离失败: %w", repairErr))
|
||
}
|
||
databaseID, err = s.panel.CreateDatabase(ctx, dbName, dbUser, dbPassword, siteID)
|
||
if err != nil {
|
||
return fail(fmt.Errorf("创建数据库失败: %w", err))
|
||
}
|
||
initialStatus := "awaiting_upload"
|
||
if input.Runtime == "PHP" {
|
||
initialStatus = "running"
|
||
} else if err = s.panel.SetSiteState(ctx, siteID, domain, false); err != nil {
|
||
return fail(fmt.Errorf("关闭未部署站点的公开访问失败: %w", err))
|
||
}
|
||
if customDomain != "" && customDomainStatus == "approved" {
|
||
if err = s.panel.AddDomain(ctx, siteID, domain, customDomain); err != nil {
|
||
return fail(fmt.Errorf("绑定自定义域名失败: %w", err))
|
||
}
|
||
}
|
||
if err = s.store.CompleteProject(ctx, projectID, siteID, ftpID, databaseID, ftpUser, dbName, dbUser, ftpPasswordCipher, dbPasswordCipher, initialStatus, customDomain, customDomainStatus, adopted); err != nil {
|
||
return fail(err)
|
||
}
|
||
project, err := s.store.Project(ctx, *user.TenantID, projectID)
|
||
if err != nil {
|
||
return CreatedProject{}, err
|
||
}
|
||
if input.AutoSSL {
|
||
sites, listErr := s.store.ListSites(ctx, project.TenantID, project.ID)
|
||
if listErr == nil {
|
||
for _, site := range sites {
|
||
if site.Primary {
|
||
_, _ = s.requestAutoCertificate(context.WithoutCancel(ctx), project, site)
|
||
break
|
||
}
|
||
}
|
||
if refreshed, refreshErr := s.store.Project(ctx, project.TenantID, project.ID); refreshErr == nil {
|
||
project = refreshed
|
||
}
|
||
}
|
||
}
|
||
result := CreatedProject{Project: project}
|
||
result.Credentials.FTPUsername = ftpUser
|
||
result.Credentials.FTPPassword = ftpPassword
|
||
result.Credentials.FTPHost = defaultDomain
|
||
result.Credentials.FTPTLSPolicy = ftpTLSPolicy
|
||
result.Credentials.DatabaseName = dbName
|
||
result.Credentials.DatabaseUsername = dbUser
|
||
result.Credentials.DatabasePassword = dbPassword
|
||
result.Credentials.HostLogin = hostName
|
||
result.Credentials.HostPassword = hostPassword
|
||
return result, nil
|
||
}
|
||
|
||
func (s *Projects) Adopt(ctx context.Context, input AdoptProjectInput) (CreatedProject, error) {
|
||
if input.TenantID == 0 || input.PanelSiteID <= 0 {
|
||
return CreatedProject{}, errors.New("用户或宝塔站点编号无效")
|
||
}
|
||
items, err := s.panel.ListUnmanagedSites(ctx)
|
||
if err != nil {
|
||
return CreatedProject{}, fmt.Errorf("读取可接管宝塔站点失败: %w", err)
|
||
}
|
||
var selected *panel.ExistingSite
|
||
for index := range items {
|
||
if items[index].ID == input.PanelSiteID {
|
||
selected = &items[index]
|
||
break
|
||
}
|
||
}
|
||
if selected == nil {
|
||
return CreatedProject{}, errors.New("宝塔站点不存在、已被接管或不在允许目录")
|
||
}
|
||
if s.isReservedDomain(selected.Domain) {
|
||
return CreatedProject{}, errors.New("平台管理域名或保留域名不能迁移给用户")
|
||
}
|
||
tenantID := input.TenantID
|
||
return s.Create(ctx, store.User{TenantID: &tenantID, Role: "tenant"}, CreateProjectInput{NodeID: input.NodeID, PlanID: input.PlanID, Name: input.Name, Runtime: input.Runtime, Version: input.Version, RunPath: input.RunPath, AutoSSL: input.AutoSSL, existingSiteID: selected.ID, existingSourcePath: selected.Path, existingDomain: selected.Domain})
|
||
}
|
||
|
||
func (s *Projects) UnmanagedPanelSites(ctx context.Context) ([]panel.ExistingSite, error) {
|
||
items, err := s.panel.ListUnmanagedSites(ctx)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
filtered := make([]panel.ExistingSite, 0, len(items))
|
||
for _, item := range items {
|
||
if !s.isReservedDomain(item.Domain) {
|
||
filtered = append(filtered, item)
|
||
}
|
||
}
|
||
return filtered, nil
|
||
}
|
||
|
||
func failBeforeResources(s *Projects, ctx context.Context, spec isolation.ProjectSpec, projectID uint64, cause error) (CreatedProject, error) {
|
||
_ = s.isolation.Quarantine(context.WithoutCancel(ctx), spec)
|
||
_ = s.store.MarkProjectFailed(context.WithoutCancel(ctx), projectID, cause.Error())
|
||
return CreatedProject{}, cause
|
||
}
|
||
|
||
func (s *Projects) Credentials(ctx context.Context, user store.User, projectID uint64) (CreatedProject, error) {
|
||
project, err := s.authorizedProject(ctx, user, projectID)
|
||
if err != nil {
|
||
return CreatedProject{}, err
|
||
}
|
||
stored, err := s.store.Credentials(ctx, project.TenantID, project.ID)
|
||
if err != nil {
|
||
return CreatedProject{}, err
|
||
}
|
||
ftpPassword, err := s.credentials.Open(credentialLabel("ftp", project.ID), stored.FTPPasswordCipher)
|
||
if err != nil {
|
||
return CreatedProject{}, errors.New("FTP 凭据无法解密,请重置密码")
|
||
}
|
||
databasePassword, err := s.credentials.Open(credentialLabel("database", project.ID), stored.DatabasePasswordCipher)
|
||
if err != nil {
|
||
return CreatedProject{}, errors.New("数据库凭据无法解密,请重置密码")
|
||
}
|
||
result := CreatedProject{Project: project}
|
||
result.Credentials.FTPUsername = stored.FTPUsername
|
||
result.Credentials.FTPPassword = ftpPassword
|
||
result.Credentials.FTPHost, err = s.store.ProjectAssignedDomain(ctx, project.TenantID, project.ID)
|
||
if err != nil {
|
||
return CreatedProject{}, err
|
||
}
|
||
result.Credentials.FTPTLSPolicy = s.store.Setting(ctx, fmt.Sprintf("node/%d/ftp_tls_policy", project.NodeID), "unknown")
|
||
result.Credentials.DatabaseName = stored.DatabaseName
|
||
result.Credentials.DatabaseUsername = stored.DatabaseUsername
|
||
result.Credentials.DatabasePassword = databasePassword
|
||
result.Credentials.HostLogin = project.HostName
|
||
return result, nil
|
||
}
|
||
|
||
func (s *Projects) ftpTLSPolicy(ctx context.Context) (string, error) {
|
||
certificateDomain := s.ftpCertificateDomain
|
||
if s.store != nil {
|
||
node, err := s.store.Node(ctx, scope.Node(ctx))
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
certificateDomain = node.FTPCertificateDomain
|
||
}
|
||
policy := "plain_allowed_no_certificate"
|
||
if strings.TrimSpace(certificateDomain) != "" {
|
||
var err error
|
||
policy, err = s.isolation.ConfigureFTPTLS(ctx, certificateDomain)
|
||
if err != nil {
|
||
return "", errors.New("FTP TLS 配置失败,请检查 FTP 证书来源域名")
|
||
}
|
||
}
|
||
if s.store != nil {
|
||
if err := s.store.SetSetting(ctx, fmt.Sprintf("node/%d/ftp_tls_policy", scope.Node(ctx)), policy); err != nil {
|
||
return "", err
|
||
}
|
||
}
|
||
return policy, nil
|
||
}
|
||
|
||
func (s *Projects) ResetHostPassword(ctx context.Context, user store.User, projectID uint64) (string, error) {
|
||
if user.Role == "host" {
|
||
return "", errors.New("请使用用户账号重置主机登录密码")
|
||
}
|
||
project, err := s.authorizedProject(ctx, user, projectID)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
password, err := randomPassword()
|
||
if err != nil {
|
||
return "", errors.New("无法生成主机登录密码")
|
||
}
|
||
hash, err := auth.HashPassword(password)
|
||
if err != nil {
|
||
return "", errors.New("无法保护主机登录密码")
|
||
}
|
||
if err = s.store.ResetHostPassword(ctx, project.TenantID, project.ID, hash); err != nil {
|
||
return "", err
|
||
}
|
||
return password, nil
|
||
}
|
||
|
||
func credentialLabel(kind string, projectID uint64) string {
|
||
return fmt.Sprintf("%s:%d", kind, projectID)
|
||
}
|
||
|
||
func (s *Projects) Sites(ctx context.Context, user store.User, projectID uint64) ([]store.Site, error) {
|
||
project, err := s.authorizedProject(ctx, user, projectID)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return s.store.ListSites(ctx, project.TenantID, project.ID)
|
||
}
|
||
|
||
// CheckDeployment performs a read-only preflight. It deliberately does not
|
||
// call aaPanel: the root-capable broker must only receive a runtime mutation
|
||
// after the uploaded entry file and the version-specific adapter are known.
|
||
func (s *Projects) CheckDeployment(ctx context.Context, user store.User, projectID, siteID uint64, requestedEntry string) (DeploymentCheck, error) {
|
||
project, err := s.authorizedProject(ctx, user, projectID)
|
||
if err != nil {
|
||
return DeploymentCheck{}, err
|
||
}
|
||
site, err := s.store.Site(ctx, project.TenantID, project.ID, siteID)
|
||
if err != nil {
|
||
return DeploymentCheck{}, err
|
||
}
|
||
if site.Runtime == "PHP" {
|
||
return DeploymentCheck{Runtime: site.Runtime, Ready: true, AdapterReady: true, Message: "PHP 网站由 Nginx/PHP-FPM 直接运行,无需单独创建语言进程"}, nil
|
||
}
|
||
if site.Status != "awaiting_upload" {
|
||
return DeploymentCheck{}, errors.New("仅待上传的网站可以执行部署检查")
|
||
}
|
||
entry, err := normalizeDeploymentEntry(site.Runtime, requestedEntry)
|
||
if err != nil {
|
||
return DeploymentCheck{}, err
|
||
}
|
||
relative := path.Join(strings.TrimPrefix(site.RunPath, "/"), entry)
|
||
result := DeploymentCheck{Runtime: site.Runtime, EntryFile: entry, AdapterReady: true}
|
||
projectFiles, err := s.OpenFiles(scope.WithProject(ctx, project.ID, project.NodeID), project.Path)
|
||
if err != nil {
|
||
return DeploymentCheck{}, err
|
||
}
|
||
defer projectFiles.Close()
|
||
info, err := projectFiles.Lstat(relative)
|
||
if err == nil && !info.Mode().IsRegular() {
|
||
err = fileguard.ErrNotRegular
|
||
}
|
||
if err != nil {
|
||
if errors.Is(err, os.ErrNotExist) {
|
||
result.Message = "入口文件不存在,请先通过 FTP 或文件管理上传"
|
||
return result, nil
|
||
}
|
||
if errors.Is(err, fileguard.ErrNotRegular) {
|
||
result.Message = "入口路径必须指向普通文件"
|
||
return result, nil
|
||
}
|
||
return DeploymentCheck{}, errors.New("入口文件路径无效或不可访问")
|
||
}
|
||
if info.Size() <= 0 {
|
||
result.Message = "入口文件为空,不能用于部署"
|
||
return result, nil
|
||
}
|
||
result.Ready = true
|
||
result.Size = info.Size()
|
||
result.Message = "入口文件检查通过,可以创建宝塔语言项目并验证运行状态"
|
||
return result, nil
|
||
}
|
||
|
||
func (s *Projects) DeploySite(ctx context.Context, user store.User, projectID, siteID uint64, requestedEntry string) (store.Site, error) {
|
||
check, err := s.CheckDeployment(ctx, user, projectID, siteID, requestedEntry)
|
||
if err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
if !check.Ready || !check.AdapterReady {
|
||
return store.Site{}, errors.New(check.Message)
|
||
}
|
||
project, err := s.authorizedProject(ctx, user, projectID)
|
||
if err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
ctx = scope.WithProject(ctx, project.ID, project.NodeID)
|
||
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.Runtime == "PHP" {
|
||
return site, nil
|
||
}
|
||
if site.PanelSiteID <= 0 {
|
||
return store.Site{}, errors.New("宝塔网站尚未创建完成")
|
||
}
|
||
plan, _, err := s.store.PlanAndUsage(ctx, project.TenantID)
|
||
if err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
isolationSpec := isolation.ProjectSpec{TenantID: project.TenantID, HostName: project.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)}
|
||
prepared, err := s.isolation.Prepare(ctx, isolationSpec)
|
||
if err != nil || path.Clean(prepared.RootPath) != path.Clean(project.Path) {
|
||
if err == nil {
|
||
err = errors.New("隔离代理返回了不一致的主机目录")
|
||
}
|
||
return store.Site{}, fmt.Errorf("部署前恢复主机目录隔离失败: %w", err)
|
||
}
|
||
if site.Runtime == "Go" {
|
||
relativeEntry := path.Join(strings.TrimPrefix(site.RunPath, "/"), check.EntryFile)
|
||
if err = s.isolation.PrepareExecutable(ctx, isolation.ExecutableSpec{Project: isolationSpec, RelativePath: relativeEntry}); err != nil {
|
||
return store.Site{}, fmt.Errorf("无法将 Go 入口设置为可执行文件: %w", err)
|
||
}
|
||
}
|
||
if site.Runtime == "Node.js" {
|
||
// aaPanel's free Node project module refuses to start any package.json
|
||
// project when npm leaves no node_modules directory (valid for a
|
||
// dependency-free application). Create only that exact directory through
|
||
// an os.Root-confined helper; dependency installation remains aaPanel's job.
|
||
relativeModules := path.Join(strings.TrimPrefix(site.RunPath, "/"), "node_modules")
|
||
projectFiles, openErr := s.OpenFiles(ctx, project.Path)
|
||
if openErr != nil {
|
||
return store.Site{}, openErr
|
||
}
|
||
defer projectFiles.Close()
|
||
if err = projectFiles.MkdirAll(relativeModules, 0770); err != nil {
|
||
return store.Site{}, fmt.Errorf("准备 Node.js 依赖目录失败: %w", err)
|
||
}
|
||
}
|
||
runtimeProjectName := project.HostName
|
||
if !site.Primary {
|
||
runtimeProjectName = fmt.Sprintf("%s_%d", project.HostName, site.ID)
|
||
}
|
||
if site.Runtime == "Node.js" || site.Runtime == "Python" {
|
||
if err = s.isolation.PreparePanelRuntime(ctx, isolation.PanelRuntimeSpec{Project: isolationSpec, Runtime: site.Runtime, Version: site.Version, ProjectName: runtimeProjectName}); err != nil {
|
||
return store.Site{}, fmt.Errorf("准备宝塔 %s 隔离身份失败: %w", site.Runtime, err)
|
||
}
|
||
}
|
||
runtimeSpec := panel.RuntimeSpec{
|
||
ProjectName: runtimeProjectName, Runtime: site.Runtime, Version: site.Version,
|
||
Path: project.Path, RunPath: site.RunPath, EntryFile: check.EntryFile,
|
||
Domain: site.Domain, RunUser: prepared.RunUser, Port: site.BackendPort, ProcessLimit: site.ProcessLimit,
|
||
}
|
||
runtimeSpec.Runner, err = s.prepareSavedRunner(ctx, project, site, check.EntryFile, site.Version)
|
||
if err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
|
||
if err = s.panel.ConfigureRuntime(ctx, runtimeSpec); err != nil {
|
||
return store.Site{}, fmt.Errorf("创建宝塔 %s 项目失败: %w", site.Runtime, err)
|
||
}
|
||
rollbackRuntime := func() {
|
||
rollback := context.WithoutCancel(ctx)
|
||
_ = s.panel.SetSiteState(rollback, site.PanelSiteID, site.Domain, false)
|
||
if reset, ok := s.panel.(panel.RuntimeResetter); ok {
|
||
_ = reset.ResetManagedRuntime(rollback, site.PanelSiteID, site.Domain)
|
||
} else {
|
||
_ = s.panel.RemoveRuntime(rollback, runtimeSpec)
|
||
}
|
||
}
|
||
repaired, repairErr := s.isolation.Prepare(ctx, isolationSpec)
|
||
if repairErr != nil || path.Clean(repaired.RootPath) != path.Clean(project.Path) || repaired.RunUser != prepared.RunUser {
|
||
rollbackRuntime()
|
||
if repairErr == nil {
|
||
repairErr = errors.New("隔离代理返回了不一致的主机身份")
|
||
}
|
||
return store.Site{}, fmt.Errorf("宝塔创建语言项目后恢复目录隔离失败: %w", repairErr)
|
||
}
|
||
if err = s.panel.ConfigureProxy(ctx, site.PanelSiteID, site.Domain, site.BackendPort); err != nil {
|
||
rollbackRuntime()
|
||
return store.Site{}, fmt.Errorf("创建语言项目反向代理失败: %w", err)
|
||
}
|
||
if err = s.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, true); err != nil {
|
||
rollbackRuntime()
|
||
return store.Site{}, fmt.Errorf("开放已部署网站失败: %w", err)
|
||
}
|
||
if err = s.restoreSiteIsolation(ctx, project, site.RunPath, site.ProcessLimit); err != nil {
|
||
rollbackRuntime()
|
||
return store.Site{}, fmt.Errorf("开放网站后恢复目录隔离失败: %w", err)
|
||
}
|
||
// Broker operations are idempotent. If this database commit fails, a retry
|
||
// observes the already-managed runtime/proxy and safely completes the state
|
||
// transition without creating a duplicate root-owned process.
|
||
if err = s.store.CompleteSiteDeployment(ctx, project.TenantID, project.ID, site.ID); err != nil {
|
||
return store.Site{}, fmt.Errorf("保存部署状态失败,可安全重试: %w", err)
|
||
}
|
||
if site.AutoSSL {
|
||
if deployed, e := s.store.Site(ctx, project.TenantID, project.ID, site.ID); e == nil {
|
||
_, _ = s.requestAutoCertificate(context.WithoutCancel(ctx), project, deployed)
|
||
}
|
||
}
|
||
return s.store.Site(ctx, project.TenantID, project.ID, site.ID)
|
||
}
|
||
|
||
func (s *Projects) CreateSite(ctx context.Context, user store.User, projectID uint64, input CreateSiteInput) (store.Site, error) {
|
||
project, err := s.authorizedProject(ctx, user, projectID)
|
||
if err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
ctx = scope.WithProject(ctx, project.ID, project.NodeID)
|
||
if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
if !project.AllowRuntimeChange && input.Runtime != project.Runtime {
|
||
return store.Site{}, errors.New("此主机仅允许使用已分配的语言;请联系管理员开启切换运行环境权限")
|
||
}
|
||
name := strings.ToLower(strings.TrimSpace(input.Name))
|
||
if !slugPattern.MatchString(name) {
|
||
return store.Site{}, errors.New("网站名称仅允许 3-50 位小写字母、数字和连字符")
|
||
}
|
||
runPath, err := normalizeRunPath(input.RunPath)
|
||
if err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
customDomain, customDomainStatus, err := s.customDomain(ctx, input.CustomDomain)
|
||
if err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
if err = s.validateRuntime(ctx, input.Runtime, strings.TrimSpace(input.Version)); err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
sites, err := s.store.ListSites(ctx, project.TenantID, project.ID)
|
||
if err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
planLimit, _, err := s.store.PlanAndUsage(ctx, project.TenantID)
|
||
if err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
if len(sites) >= min(20, int(planLimit.ProjectLimit)) {
|
||
return store.Site{}, errors.New("单台虚拟主机最多创建 20 个网站")
|
||
}
|
||
for _, existing := range sites {
|
||
if runPathsOverlap(existing.RunPath, runPath) {
|
||
return store.Site{}, errors.New("运行目录不能与另一个网站相同、包含或被其包含")
|
||
}
|
||
}
|
||
domainSuffix, err := randomHex(4)
|
||
if err != nil {
|
||
return store.Site{}, errors.New("无法生成网站域名")
|
||
}
|
||
node, err := s.store.Node(ctx, project.NodeID)
|
||
if err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
domain := project.HostName + "-" + domainSuffix + "." + node.RootDomain
|
||
port := 0
|
||
for candidate := project.BackendPort + 1; candidate < project.BackendPort+20; candidate++ {
|
||
used := false
|
||
for _, site := range sites {
|
||
used = used || site.BackendPort == candidate
|
||
}
|
||
if !used {
|
||
port = candidate
|
||
break
|
||
}
|
||
}
|
||
if port == 0 {
|
||
return store.Site{}, errors.New("主机运行端口已用尽")
|
||
}
|
||
|
||
siteID, err := s.store.InsertSite(ctx, store.NewSite{TenantID: project.TenantID, ProjectID: project.ID, Name: name, Domain: domain, RunPath: runPath, Runtime: input.Runtime, Version: strings.TrimSpace(input.Version), BackendPort: port, ProcessLimit: project.ProcessLimit, AutoSSL: input.AutoSSL})
|
||
if err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
plan, _, err := s.store.PlanAndUsage(ctx, project.TenantID)
|
||
if err != nil {
|
||
_ = s.store.MarkSiteFailed(context.WithoutCancel(ctx), siteID, err.Error())
|
||
return store.Site{}, err
|
||
}
|
||
isolationSpec := isolation.ProjectSpec{TenantID: project.TenantID, HostName: project.HostName, RunPath: runPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit)}
|
||
prepared, err := s.isolation.Prepare(ctx, isolationSpec)
|
||
if err != nil || path.Clean(prepared.RootPath) != path.Clean(project.Path) {
|
||
if err == nil {
|
||
err = errors.New("隔离代理返回了不一致的主机目录")
|
||
}
|
||
_ = s.store.MarkSiteFailed(context.WithoutCancel(ctx), siteID, err.Error())
|
||
return store.Site{}, err
|
||
}
|
||
panelSiteID, err := s.panel.CreateSite(ctx, panel.SiteSpec{Name: project.HostName, Domain: domain, Path: project.Path, RunPath: runPath, Runtime: input.Runtime, Version: strings.TrimSpace(input.Version), RunUser: prepared.RunUser, Port: port, ProcessLimit: project.ProcessLimit})
|
||
if err != nil {
|
||
_ = s.store.MarkSiteFailed(context.WithoutCancel(ctx), siteID, err.Error())
|
||
return store.Site{}, fmt.Errorf("创建宝塔网站失败: %w", err)
|
||
}
|
||
// aaPanel may recursively reset ownership while creating a site. Reassert
|
||
// the host boundary before publishing the new website, as is done for the
|
||
// primary site during virtual-host creation.
|
||
repaired, repairErr := s.isolation.Prepare(ctx, isolationSpec)
|
||
if repairErr != nil || path.Clean(repaired.RootPath) != path.Clean(project.Path) || repaired.RunUser != prepared.RunUser {
|
||
if repairErr == nil {
|
||
repairErr = errors.New("隔离代理返回了不一致的主机身份")
|
||
}
|
||
_ = s.panel.DeleteSite(context.WithoutCancel(ctx), panelSiteID, domain)
|
||
_ = s.store.MarkSiteFailed(context.WithoutCancel(ctx), siteID, repairErr.Error())
|
||
return store.Site{}, fmt.Errorf("宝塔建站后恢复主机目录隔离失败: %w", repairErr)
|
||
}
|
||
protection := isolation.WebProtectionSpec{Project: isolationSpec, Domain: domain}
|
||
phpIdentity := isolation.PHPIdentitySpec{Project: isolationSpec, SiteName: fmt.Sprintf("%s_%d", project.HostName, siteID), Domain: domain, Version: strings.TrimSpace(input.Version), ProcessLimit: uint32(project.ProcessLimit)}
|
||
phpIdentityConfigured := false
|
||
fail := func(cause error) (store.Site, error) {
|
||
if phpIdentityConfigured {
|
||
_ = s.isolation.RemovePHPIdentity(context.WithoutCancel(ctx), phpIdentity)
|
||
}
|
||
_ = s.isolation.RemoveWebProtection(context.WithoutCancel(ctx), protection)
|
||
_ = s.panel.DeleteSite(context.WithoutCancel(ctx), panelSiteID, domain)
|
||
_ = s.store.MarkSiteFailed(context.WithoutCancel(ctx), siteID, cause.Error())
|
||
return store.Site{}, cause
|
||
}
|
||
if err = s.isolation.ApplyWebProtection(ctx, protection); err != nil {
|
||
return fail(fmt.Errorf("启用网站基础防护失败: %w", err))
|
||
}
|
||
if input.Runtime == "PHP" {
|
||
if err = s.isolation.ConfigurePHPIdentity(ctx, phpIdentity); err != nil {
|
||
return fail(fmt.Errorf("创建独立 PHP 运行身份失败: %w", err))
|
||
}
|
||
phpIdentityConfigured = true
|
||
}
|
||
status := "awaiting_upload"
|
||
if input.Runtime == "PHP" {
|
||
status = "running"
|
||
} else if err = s.panel.SetSiteState(ctx, panelSiteID, domain, false); err != nil {
|
||
return fail(fmt.Errorf("关闭未部署站点的公开访问失败: %w", err))
|
||
}
|
||
if customDomain != "" && customDomainStatus == "approved" {
|
||
if err = s.panel.AddDomain(ctx, panelSiteID, domain, customDomain); err != nil {
|
||
return fail(fmt.Errorf("绑定自定义域名失败: %w", err))
|
||
}
|
||
}
|
||
if err = s.store.CompleteSite(ctx, siteID, panelSiteID, status, customDomain, customDomainStatus); err != nil {
|
||
return fail(err)
|
||
}
|
||
items, err := s.store.ListSites(ctx, project.TenantID, project.ID)
|
||
if err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
for _, item := range items {
|
||
if item.ID == siteID {
|
||
if input.AutoSSL {
|
||
_, _ = s.requestAutoCertificate(context.WithoutCancel(ctx), project, item)
|
||
return s.store.Site(ctx, project.TenantID, project.ID, siteID)
|
||
}
|
||
return item, nil
|
||
}
|
||
}
|
||
return store.Site{}, store.ErrNotFound
|
||
}
|
||
|
||
func (s *Projects) SetSiteState(ctx context.Context, user store.User, projectID, siteID uint64, enabled bool) (store.Site, error) {
|
||
project, err := s.authorizedProject(ctx, user, projectID)
|
||
if err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
if enabled {
|
||
ctx = scope.WithProject(ctx, project.ID, project.NodeID)
|
||
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.Primary {
|
||
if err = s.SetState(ctx, user, projectID, enabled); err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
} else {
|
||
if site.Status != "running" && site.Status != "stopped" {
|
||
return store.Site{}, errors.New("网站尚未完成部署,不能执行启停操作")
|
||
}
|
||
var phpIdentity isolation.PHPIdentitySpec
|
||
if site.Runtime == "PHP" {
|
||
phpIdentity, err = s.phpIdentitySpec(ctx, project, site)
|
||
if err != nil {
|
||
return store.Site{}, err
|
||
}
|
||
if enabled {
|
||
if err = s.isolation.SetPHPIdentityState(ctx, phpIdentity, true); err != nil {
|
||
return store.Site{}, fmt.Errorf("启动独立 PHP 运行身份失败: %w", err)
|
||
}
|
||
}
|
||
}
|
||
if err = s.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, enabled); err != nil {
|
||
if !enabled && site.Runtime != "PHP" {
|
||
// Some aaPanel language modules acknowledge stop before their
|
||
// launcher has actually removed the listener. The broker verifies
|
||
// the port and reports that mismatch. Recover only processes owned
|
||
// by this host identity whose cwd is inside this site's exact run
|
||
// directory, then retry the idempotent panel/Nginx transition.
|
||
plan, _, planErr := s.store.PlanAndUsage(ctx, project.TenantID)
|
||
if planErr == nil {
|
||
runtimeSpec := isolation.RuntimeProcessSpec{Project: isolation.ProjectSpec{
|
||
TenantID: project.TenantID, HostName: project.HostName, RunPath: site.RunPath,
|
||
StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit),
|
||
}}
|
||
if terminateErr := s.isolation.TerminateRuntime(ctx, runtimeSpec); terminateErr == nil {
|
||
err = s.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, false)
|
||
} else {
|
||
err = fmt.Errorf("%w; 精确终止残留运行进程失败: %v", err, terminateErr)
|
||
}
|
||
} else {
|
||
err = fmt.Errorf("%w; 读取资源套餐失败: %v", err, planErr)
|
||
}
|
||
}
|
||
}
|
||
if err != nil {
|
||
if enabled && site.Runtime == "PHP" {
|
||
_ = s.isolation.SetPHPIdentityState(context.WithoutCancel(ctx), phpIdentity, false)
|
||
}
|
||
return store.Site{}, err
|
||
}
|
||
if !enabled && site.Runtime == "PHP" {
|
||
if err = s.isolation.SetPHPIdentityState(ctx, phpIdentity, false); err != nil {
|
||
_ = s.panel.SetSiteState(context.WithoutCancel(ctx), site.PanelSiteID, site.Domain, true)
|
||
_ = s.isolation.SetPHPIdentityState(context.WithoutCancel(ctx), phpIdentity, true)
|
||
return store.Site{}, fmt.Errorf("停止独立 PHP 运行身份失败: %w", err)
|
||
}
|
||
}
|
||
// aaPanel's language-project start handlers recursively chown the project
|
||
// directory to www:www. Restore Sea vHost's application-owned boundary
|
||
// after every successful start so Web file operations remain available
|
||
// without adding the API process to the shared www group.
|
||
if enabled && site.Runtime != "PHP" {
|
||
if err = s.restoreSiteIsolation(ctx, project, site.RunPath, site.ProcessLimit); err != nil {
|
||
_ = s.panel.SetSiteState(context.WithoutCancel(ctx), site.PanelSiteID, site.Domain, false)
|
||
return store.Site{}, fmt.Errorf("启动后恢复主机目录隔离失败: %w", err)
|
||
}
|
||
}
|
||
state := "stopped"
|
||
if enabled {
|
||
state = "running"
|
||
}
|
||
if err = s.store.SetSiteState(ctx, project.TenantID, project.ID, site.ID, state); err != nil {
|
||
// Restore the panel state when the local state transition cannot be
|
||
// committed, so the control plane never knowingly reports the inverse.
|
||
_ = s.panel.SetSiteState(context.WithoutCancel(ctx), site.PanelSiteID, site.Domain, !enabled)
|
||
if site.Runtime == "PHP" {
|
||
_ = s.isolation.SetPHPIdentityState(context.WithoutCancel(ctx), phpIdentity, !enabled)
|
||
}
|
||
if !enabled && site.Runtime != "PHP" {
|
||
// A rollback from stopped to running invokes the same aaPanel chown.
|
||
// If ownership cannot be restored, leave the runtime stopped.
|
||
if repairErr := s.restoreSiteIsolation(context.WithoutCancel(ctx), project, site.RunPath, site.ProcessLimit); repairErr != nil {
|
||
_ = s.panel.SetSiteState(context.WithoutCancel(ctx), site.PanelSiteID, site.Domain, false)
|
||
}
|
||
}
|
||
return store.Site{}, err
|
||
}
|
||
}
|
||
updated, readErr := s.store.Site(ctx, project.TenantID, project.ID, site.ID)
|
||
if readErr == nil {
|
||
if _, supported := s.isolation.(isolation.RuntimeMaintenance); supported {
|
||
_ = s.verifyRuntimeTarget(ctx, store.RuntimeTarget{Site: updated, Project: project, HostName: project.HostName})
|
||
}
|
||
}
|
||
return updated, readErr
|
||
}
|
||
|
||
func (s *Projects) DeleteSite(ctx context.Context, user store.User, projectID, siteID uint64) error {
|
||
project, err := s.authorizedProject(ctx, user, projectID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
site, err := s.store.Site(ctx, project.TenantID, project.ID, siteID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if site.Primary {
|
||
return errors.New("主站不能在网站列表中删除")
|
||
}
|
||
plan, _, err := s.store.PlanAndUsage(ctx, project.TenantID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
isolationSpec := isolation.ProjectSpec{TenantID: project.TenantID, HostName: project.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)}
|
||
protection := isolation.WebProtectionSpec{Project: isolationSpec, Domain: site.Domain}
|
||
var phpIdentity isolation.PHPIdentitySpec
|
||
if site.Runtime == "PHP" {
|
||
phpIdentity = isolation.PHPIdentitySpec{Project: isolationSpec, SiteName: fmt.Sprintf("%s_%d", project.HostName, site.ID), Domain: site.Domain, Version: site.Version, ProcessLimit: uint32(site.ProcessLimit)}
|
||
if err = s.isolation.SetPHPIdentityState(ctx, phpIdentity, false); err != nil {
|
||
return fmt.Errorf("停止独立 PHP 运行身份失败: %w", err)
|
||
}
|
||
}
|
||
// Runtime start handlers may have left the retained source owned by
|
||
// www:www. Repair it before deleting the privileged panel resources; site
|
||
// deletion intentionally retains source for the tenant to download or trash.
|
||
if err = s.restoreSiteIsolation(ctx, project, site.RunPath, site.ProcessLimit); err != nil {
|
||
return fmt.Errorf("删除网站前恢复主机目录隔离失败: %w", err)
|
||
}
|
||
if err = s.isolation.RemoveWebProtection(ctx, protection); err != nil {
|
||
if site.Runtime == "PHP" {
|
||
_ = s.isolation.SetPHPIdentityState(context.WithoutCancel(ctx), phpIdentity, true)
|
||
}
|
||
return fmt.Errorf("移除网站防护配置失败: %w", err)
|
||
}
|
||
if err = s.panel.DeleteSite(ctx, site.PanelSiteID, site.Domain); err != nil {
|
||
_ = s.isolation.ApplyWebProtection(context.WithoutCancel(ctx), protection)
|
||
if site.Runtime == "PHP" {
|
||
_ = s.isolation.SetPHPIdentityState(context.WithoutCancel(ctx), phpIdentity, true)
|
||
}
|
||
return fmt.Errorf("删除宝塔网站失败: %w", err)
|
||
}
|
||
if site.Runtime == "PHP" {
|
||
_ = s.isolation.RemovePHPIdentity(context.WithoutCancel(ctx), phpIdentity)
|
||
}
|
||
// The site no longer serves this directory, so aaPanel's immutable
|
||
// open_basedir file is no longer needed. Cleanup is best effort here;
|
||
// PrepareTrash can safely recover the same exact file after an interruption.
|
||
_ = s.isolation.ReleaseRunPath(context.WithoutCancel(ctx), isolationSpec)
|
||
if err = s.store.DeleteSite(ctx, project.TenantID, project.ID, site.ID); err != nil {
|
||
_ = s.store.MarkSiteFailed(context.WithoutCancel(ctx), site.ID, "panel site deleted but local record cleanup failed: "+err.Error())
|
||
return err
|
||
}
|
||
// The run directory and uploaded source are deliberately retained inside
|
||
// the host root. Deleting a website only removes its serving configuration.
|
||
return nil
|
||
}
|
||
|
||
func (s *Projects) BindDomain(ctx context.Context, user store.User, projectID uint64, domain string) (store.DomainResource, error) {
|
||
s.domainMu.Lock()
|
||
defer s.domainMu.Unlock()
|
||
project, err := s.authorizedProject(ctx, user, projectID)
|
||
if err != nil {
|
||
return store.DomainResource{}, err
|
||
}
|
||
ctx = scope.WithProject(ctx, project.ID, project.NodeID)
|
||
if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil {
|
||
return store.DomainResource{}, err
|
||
}
|
||
sites, err := s.store.ListSites(ctx, project.TenantID, project.ID)
|
||
if err != nil {
|
||
return store.DomainResource{}, err
|
||
}
|
||
for _, site := range sites {
|
||
if site.Primary {
|
||
return s.bindSiteDomain(ctx, project, site, domain)
|
||
}
|
||
}
|
||
return store.DomainResource{}, store.ErrNotFound
|
||
}
|
||
|
||
func (s *Projects) BindSiteDomain(ctx context.Context, user store.User, projectID, siteID uint64, domain string) (store.DomainResource, error) {
|
||
s.domainMu.Lock()
|
||
defer s.domainMu.Unlock()
|
||
project, err := s.authorizedProject(ctx, user, projectID)
|
||
if err != nil {
|
||
return store.DomainResource{}, err
|
||
}
|
||
ctx = scope.WithProject(ctx, project.ID, project.NodeID)
|
||
if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil {
|
||
return store.DomainResource{}, err
|
||
}
|
||
site, err := s.store.Site(ctx, project.TenantID, project.ID, siteID)
|
||
if err != nil {
|
||
return store.DomainResource{}, err
|
||
}
|
||
return s.bindSiteDomain(ctx, project, site, domain)
|
||
}
|
||
|
||
func (s *Projects) bindSiteDomain(ctx context.Context, project store.Project, site store.Site, domain string) (store.DomainResource, error) {
|
||
domain, desiredStatus, err := s.customDomain(ctx, domain)
|
||
if err != nil {
|
||
return store.DomainResource{}, err
|
||
}
|
||
if domain == "" {
|
||
return store.DomainResource{}, errors.New("域名不能为空")
|
||
}
|
||
if site.Status == "provisioning" || site.Status == "failed" || site.PanelSiteID <= 0 {
|
||
return store.DomainResource{}, errors.New("网站尚未完成部署,不能绑定域名")
|
||
}
|
||
// Reserve the globally unique domain before mutating aaPanel. This keeps a
|
||
// concurrent request from binding the same name to a second managed site.
|
||
if err = s.store.AddCustomDomainForSite(ctx, project.TenantID, project.ID, site.ID, domain, "pending", maxDomainsPerSite); err != nil {
|
||
if errors.Is(err, store.ErrDomainLimit) {
|
||
return store.DomainResource{}, fmt.Errorf("网站域名总数已达到上限(%d,含默认域名)", maxDomainsPerSite)
|
||
}
|
||
return store.DomainResource{}, errors.New("域名已被使用或无法保存")
|
||
}
|
||
item, err := s.store.DomainByName(ctx, project.TenantID, project.ID, site.ID, domain)
|
||
if err != nil {
|
||
return store.DomainResource{}, err
|
||
}
|
||
filingRequired := s.store.Setting(ctx, "filing_required", "false") == "true"
|
||
if err = s.store.InitializeCustomDomainPolicy(ctx, item.ID, site.Domain, filingRequired); err != nil {
|
||
return store.DomainResource{}, err
|
||
}
|
||
item.ResolutionMode = "cname"
|
||
item.CNAME = site.Domain
|
||
if filingRequired {
|
||
item.FilingStatus = "pending"
|
||
desiredStatus = "pending"
|
||
} else {
|
||
item.FilingStatus = "exempt"
|
||
}
|
||
if desiredStatus == "pending" {
|
||
return item, nil
|
||
}
|
||
if err = s.panel.AddDomain(ctx, site.PanelSiteID, site.Domain, domain); err != nil {
|
||
_ = s.store.DeletePendingDomain(context.WithoutCancel(ctx), item.ID)
|
||
return store.DomainResource{}, err
|
||
}
|
||
if err = s.store.SetDomainStatus(ctx, item.ID, "pending", "approved"); err != nil {
|
||
// The panel binding remains registered and the pending row remains visible
|
||
// to an administrator, which is safer than losing track of the domain.
|
||
return store.DomainResource{}, err
|
||
}
|
||
if site.AutoSSL {
|
||
_, _ = s.requestAutoCertificate(context.WithoutCancel(ctx), project, site)
|
||
}
|
||
item.Status = "approved"
|
||
return item, nil
|
||
}
|
||
|
||
func (s *Projects) ReviewDomain(ctx context.Context, domainID uint64, approved bool) (store.DomainResource, error) {
|
||
s.domainMu.Lock()
|
||
defer s.domainMu.Unlock()
|
||
item, err := s.store.DomainByID(ctx, domainID)
|
||
if err != nil {
|
||
return store.DomainResource{}, err
|
||
}
|
||
if item.Kind != "custom" || item.Status != "pending" {
|
||
return store.DomainResource{}, errors.New("域名不在待审核状态")
|
||
}
|
||
if approved && s.store.Setting(ctx, "filing_required", "false") == "true" && item.FilingStatus != "approved" {
|
||
return store.DomainResource{}, errors.New("该域名尚未通过备案审核")
|
||
}
|
||
if !approved {
|
||
if err = s.store.SetDomainStatus(ctx, item.ID, "pending", "rejected"); err != nil {
|
||
return store.DomainResource{}, err
|
||
}
|
||
item.Status = "rejected"
|
||
return item, nil
|
||
}
|
||
if err = s.ensureTenantWritable(ctx, item.TenantID); err != nil {
|
||
return store.DomainResource{}, err
|
||
}
|
||
if item.PanelSiteID <= 0 {
|
||
return store.DomainResource{}, errors.New("目标网站尚未完成部署")
|
||
}
|
||
if err = s.panel.AddDomain(ctx, item.PanelSiteID, item.SiteAssignedDomain, item.Domain); err != nil {
|
||
return store.DomainResource{}, fmt.Errorf("宝塔绑定域名失败: %w", err)
|
||
}
|
||
if err = s.store.SetDomainStatus(ctx, item.ID, "pending", "approved"); err != nil {
|
||
return store.DomainResource{}, err
|
||
}
|
||
if item.AutoSSL {
|
||
project, projectErr := s.store.Project(ctx, item.TenantID, item.ProjectID)
|
||
site, siteErr := s.store.Site(ctx, item.TenantID, item.ProjectID, item.SiteID)
|
||
if projectErr == nil && siteErr == nil {
|
||
_, _ = s.requestAutoCertificate(context.WithoutCancel(ctx), project, site)
|
||
}
|
||
}
|
||
item.Status = "approved"
|
||
return item, nil
|
||
}
|
||
|
||
func (s *Projects) SetState(ctx context.Context, user store.User, projectID uint64, enabled bool) error {
|
||
project, err := s.authorizedProject(ctx, user, projectID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if enabled {
|
||
ctx = scope.WithProject(ctx, project.ID, project.NodeID)
|
||
if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
if project.Status != "running" && project.Status != "stopped" {
|
||
return errors.New("项目尚未完成部署,不能执行启停操作")
|
||
}
|
||
var phpIdentity isolation.PHPIdentitySpec
|
||
if project.Runtime == "PHP" {
|
||
sites, listErr := s.store.ListSites(ctx, project.TenantID, project.ID)
|
||
if listErr != nil {
|
||
return listErr
|
||
}
|
||
var primary *store.Site
|
||
for index := range sites {
|
||
if sites[index].Primary {
|
||
primary = &sites[index]
|
||
break
|
||
}
|
||
}
|
||
if primary == nil {
|
||
return errors.New("主站记录不存在")
|
||
}
|
||
phpIdentity, err = s.phpIdentitySpec(ctx, project, *primary)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if enabled {
|
||
if err = s.isolation.SetPHPIdentityState(ctx, phpIdentity, true); err != nil {
|
||
return fmt.Errorf("启动独立 PHP 运行身份失败: %w", err)
|
||
}
|
||
}
|
||
}
|
||
if err = s.panel.SetSiteState(ctx, project.PanelSiteID, project.Domain, enabled); err != nil {
|
||
if enabled && project.Runtime == "PHP" {
|
||
_ = s.isolation.SetPHPIdentityState(context.WithoutCancel(ctx), phpIdentity, false)
|
||
}
|
||
return err
|
||
}
|
||
if !enabled && project.Runtime == "PHP" {
|
||
if err = s.isolation.SetPHPIdentityState(ctx, phpIdentity, false); err != nil {
|
||
_ = s.panel.SetSiteState(context.WithoutCancel(ctx), project.PanelSiteID, project.Domain, true)
|
||
_ = s.isolation.SetPHPIdentityState(context.WithoutCancel(ctx), phpIdentity, true)
|
||
return fmt.Errorf("停止独立 PHP 运行身份失败: %w", err)
|
||
}
|
||
}
|
||
if enabled && project.Runtime != "PHP" {
|
||
if err = s.restoreSiteIsolation(ctx, project, project.RunPath, project.ProcessLimit); err != nil {
|
||
_ = s.panel.SetSiteState(context.WithoutCancel(ctx), project.PanelSiteID, project.Domain, false)
|
||
return fmt.Errorf("启动后恢复主机目录隔离失败: %w", err)
|
||
}
|
||
}
|
||
state := "stopped"
|
||
if enabled {
|
||
state = "running"
|
||
}
|
||
if err = s.store.SetProjectState(ctx, project.TenantID, projectID, state); err != nil {
|
||
_ = s.panel.SetSiteState(context.WithoutCancel(ctx), project.PanelSiteID, project.Domain, !enabled)
|
||
if project.Runtime == "PHP" {
|
||
_ = s.isolation.SetPHPIdentityState(context.WithoutCancel(ctx), phpIdentity, !enabled)
|
||
}
|
||
if !enabled && project.Runtime != "PHP" {
|
||
if repairErr := s.restoreSiteIsolation(context.WithoutCancel(ctx), project, project.RunPath, project.ProcessLimit); repairErr != nil {
|
||
_ = s.panel.SetSiteState(context.WithoutCancel(ctx), project.PanelSiteID, project.Domain, false)
|
||
}
|
||
}
|
||
return err
|
||
}
|
||
if _, supported := s.isolation.(isolation.RuntimeMaintenance); supported {
|
||
if sites, e := s.store.ListSites(ctx, project.TenantID, project.ID); e == nil {
|
||
for _, site := range sites {
|
||
if site.Primary {
|
||
_ = s.verifyRuntimeTarget(ctx, store.RuntimeTarget{Site: site, Project: project, HostName: project.HostName})
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func (s *Projects) restoreSiteIsolation(ctx context.Context, project store.Project, runPath string, processLimit int) error {
|
||
plan, _, err := s.store.PlanAndUsage(ctx, project.TenantID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
spec := isolation.ProjectSpec{
|
||
TenantID: project.TenantID, HostName: project.HostName, RunPath: runPath,
|
||
StorageBytes: plan.StorageBytes, ProcessLimit: uint32(processLimit),
|
||
}
|
||
prepared, err := s.isolation.Prepare(ctx, spec)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if path.Clean(prepared.RootPath) != path.Clean(project.Path) || prepared.RunUser == "" {
|
||
return errors.New("隔离代理返回了不一致的主机目录或运行身份")
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func (s *Projects) phpIdentitySpec(ctx context.Context, project store.Project, site store.Site) (isolation.PHPIdentitySpec, error) {
|
||
ctx = scope.WithProject(ctx, project.ID, project.NodeID)
|
||
plan, _, err := s.store.PlanAndUsage(ctx, project.TenantID)
|
||
if err != nil {
|
||
return isolation.PHPIdentitySpec{}, err
|
||
}
|
||
siteName := fmt.Sprintf("%s_%d", project.HostName, site.ID)
|
||
if site.Primary {
|
||
siteName = project.HostName
|
||
}
|
||
return isolation.PHPIdentitySpec{
|
||
Project: isolation.ProjectSpec{
|
||
TenantID: project.TenantID, HostName: project.HostName, RunPath: site.RunPath,
|
||
StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit),
|
||
},
|
||
SiteName: siteName, Domain: site.Domain, Version: site.Version, ProcessLimit: uint32(site.ProcessLimit),
|
||
}, nil
|
||
}
|
||
|
||
func (s *Projects) SetRunPath(ctx context.Context, user store.User, projectID uint64, requested string) (store.Project, error) {
|
||
project, err := s.authorizedProject(ctx, user, projectID)
|
||
if err != nil {
|
||
return store.Project{}, err
|
||
}
|
||
ctx = scope.WithProject(ctx, project.ID, project.NodeID)
|
||
if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil {
|
||
return store.Project{}, err
|
||
}
|
||
runPath, err := normalizeRunPath(requested)
|
||
if err != nil {
|
||
return store.Project{}, err
|
||
}
|
||
if project.Status == "failed" || project.Status == "provisioning" {
|
||
return store.Project{}, errors.New("项目尚未完成部署,不能修改运行目录")
|
||
}
|
||
if project.Runtime != "PHP" && project.Status != "awaiting_upload" {
|
||
return store.Project{}, errors.New("语言项目部署后不能直接修改运行目录,请新建网站后重新部署")
|
||
}
|
||
if project.RunPath == runPath {
|
||
return project, nil
|
||
}
|
||
sites, err := s.store.ListSites(ctx, project.TenantID, project.ID)
|
||
if err != nil {
|
||
return store.Project{}, err
|
||
}
|
||
for _, site := range sites {
|
||
if !site.Primary && runPathsOverlap(site.RunPath, runPath) {
|
||
return store.Project{}, errors.New("运行目录不能与另一个网站相同、包含或被其包含")
|
||
}
|
||
}
|
||
plan, _, err := s.store.PlanAndUsage(ctx, project.TenantID)
|
||
if err != nil {
|
||
return store.Project{}, err
|
||
}
|
||
spec := isolation.ProjectSpec{TenantID: project.TenantID, HostName: project.HostName, RunPath: runPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit)}
|
||
prepared, err := s.isolation.Prepare(ctx, spec)
|
||
if err != nil {
|
||
return store.Project{}, fmt.Errorf("准备运行目录失败: %w", err)
|
||
}
|
||
if path.Clean(prepared.RootPath) != path.Clean(project.Path) {
|
||
return store.Project{}, errors.New("隔离代理返回了不一致的主机目录")
|
||
}
|
||
if err = s.panel.SetSiteRunPath(ctx, project.PanelSiteID, runPath); err != nil {
|
||
return store.Project{}, fmt.Errorf("宝塔设置运行目录失败: %w", err)
|
||
}
|
||
if err = s.isolation.ApplyWebProtection(ctx, isolation.WebProtectionSpec{Project: spec, Domain: project.Domain}); err != nil {
|
||
_ = s.panel.SetSiteRunPath(context.WithoutCancel(ctx), project.PanelSiteID, project.RunPath)
|
||
return store.Project{}, fmt.Errorf("更新运行目录后恢复站点防护失败: %w", err)
|
||
}
|
||
if err = s.store.SetProjectRunPath(ctx, project.TenantID, projectID, runPath); err != nil {
|
||
_ = s.panel.SetSiteRunPath(context.WithoutCancel(ctx), project.PanelSiteID, project.RunPath)
|
||
return store.Project{}, err
|
||
}
|
||
project.RunPath = runPath
|
||
return project, nil
|
||
}
|
||
|
||
func (s *Projects) PrepareTrash(ctx context.Context, user store.User, projectID uint64) error {
|
||
project, err := s.authorizedProject(ctx, user, projectID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
plan, _, err := s.store.PlanAndUsage(ctx, project.TenantID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
return s.isolation.PrepareTrash(ctx, isolation.ProjectSpec{
|
||
TenantID: project.TenantID, HostName: project.HostName, RunPath: "/",
|
||
StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit),
|
||
})
|
||
}
|
||
|
||
func runPathsOverlap(left, right string) bool {
|
||
left = path.Clean(left)
|
||
right = path.Clean(right)
|
||
if left == "/" || right == "/" {
|
||
return true
|
||
}
|
||
return left == right || strings.HasPrefix(left, right+"/") || strings.HasPrefix(right, left+"/")
|
||
}
|
||
|
||
func (s *Projects) authorizedProject(ctx context.Context, user store.User, projectID uint64) (store.Project, error) {
|
||
if user.TenantID == nil {
|
||
return store.Project{}, errors.New("tenant account required")
|
||
}
|
||
if user.ProjectID != nil && *user.ProjectID != projectID {
|
||
return store.Project{}, store.ErrNotFound
|
||
}
|
||
return s.store.ProjectForUser(ctx, user, projectID)
|
||
}
|
||
|
||
func (s *Projects) validateRuntime(ctx context.Context, runtimeName, versionName string) error {
|
||
allowedRuntime := map[string]bool{"PHP": true, "Node.js": true, "Python": true, "Go": true, "Java": true}
|
||
if !allowedRuntime[runtimeName] {
|
||
return errors.New("不支持的运行环境")
|
||
}
|
||
catalog, err := s.panel.RuntimeCatalog(ctx)
|
||
if err != nil {
|
||
return fmt.Errorf("无法读取宝塔运行环境: %w", err)
|
||
}
|
||
for _, version := range catalog[runtimeName] {
|
||
if version == versionName {
|
||
return nil
|
||
}
|
||
}
|
||
return errors.New("所选运行版本未安装或已不可用")
|
||
}
|
||
|
||
func normalizeDeploymentEntry(runtimeName, requested string) (string, error) {
|
||
entry := strings.TrimSpace(requested)
|
||
if entry == "" {
|
||
entry = map[string]string{"Node.js": "package.json", "Python": "app.py", "Go": "app", "Java": "app.jar"}[runtimeName]
|
||
}
|
||
if len(entry) > 255 || strings.HasPrefix(entry, "/") || strings.Contains(entry, "\\") || path.Clean(entry) != entry || entry == "." || entry == ".." || strings.HasPrefix(entry, "../") {
|
||
return "", errors.New("入口文件必须是运行目录内的安全相对路径")
|
||
}
|
||
for _, segment := range strings.Split(entry, "/") {
|
||
if segment == "" || segment == "." || segment == ".." || len(segment) > 100 {
|
||
return "", errors.New("入口文件路径无效")
|
||
}
|
||
for _, character := range segment {
|
||
if !(character >= 'a' && character <= 'z') && !(character >= 'A' && character <= 'Z') && !(character >= '0' && character <= '9') && !strings.ContainsRune("._-", character) {
|
||
return "", errors.New("入口文件仅允许字母、数字、点、下划线、连字符与目录分隔符")
|
||
}
|
||
}
|
||
}
|
||
switch runtimeName {
|
||
case "Node.js":
|
||
if path.Base(entry) != "package.json" {
|
||
return "", errors.New("Node.js 项目必须以 package.json 部署,并提供 scripts.start")
|
||
}
|
||
case "Python":
|
||
if path.Ext(entry) != ".py" {
|
||
return "", errors.New("Python 入口必须是 .py 文件")
|
||
}
|
||
case "Java":
|
||
if path.Ext(entry) != ".jar" {
|
||
return "", errors.New("Java 入口必须是 .jar 文件")
|
||
}
|
||
case "Go":
|
||
if path.Ext(entry) != "" {
|
||
return "", errors.New("Go 入口应为不带扩展名的已编译 Linux 可执行文件")
|
||
}
|
||
default:
|
||
return "", errors.New("该运行环境不需要语言项目部署检查")
|
||
}
|
||
return entry, nil
|
||
}
|
||
|
||
func (s *Projects) customDomain(ctx context.Context, requested string) (string, string, error) {
|
||
if s.store != nil && strings.TrimSpace(requested) != "" {
|
||
nodes, err := s.store.Nodes(ctx)
|
||
if err != nil {
|
||
return "", "", err
|
||
}
|
||
candidate := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(requested), "."))
|
||
for _, n := range nodes {
|
||
if candidate == n.RootDomain || strings.HasSuffix(candidate, "."+n.RootDomain) || candidate == n.FTPCertificateDomain {
|
||
return "", "", errors.New("平台节点默认域名与证书域名不能自绑定")
|
||
}
|
||
}
|
||
}
|
||
|
||
domain := strings.ToLower(strings.TrimSpace(requested))
|
||
if domain == "" {
|
||
return "", "", nil
|
||
}
|
||
if !domainPattern.MatchString(domain) {
|
||
return "", "", errors.New("域名格式不正确")
|
||
}
|
||
if s.isReservedDomain(domain) {
|
||
return "", "", errors.New("该域名属于平台保留域名,不能由用户绑定")
|
||
}
|
||
status := "approved"
|
||
if s.store.DomainApproval(ctx, s.domainApproval) {
|
||
status = "pending"
|
||
}
|
||
return domain, status, nil
|
||
}
|
||
|
||
func (s *Projects) isReservedDomain(domain string) bool {
|
||
domain = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), "."))
|
||
for _, reserved := range s.reservedDomains {
|
||
if domain == reserved || strings.HasSuffix(domain, "."+reserved) {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
func normalizeRunPath(value string) (string, error) {
|
||
value = strings.TrimSpace(value)
|
||
if value == "" || value == "/" {
|
||
return "/", nil
|
||
}
|
||
if strings.Contains(value, "\\") {
|
||
return "", errors.New("运行目录必须使用 / 分隔")
|
||
}
|
||
if !strings.HasPrefix(value, "/") {
|
||
value = "/" + value
|
||
}
|
||
if len(value) > 255 || path.Clean(value) != value {
|
||
return "", errors.New("运行目录必须是规范的站点内相对目录")
|
||
}
|
||
for _, segment := range strings.Split(strings.TrimPrefix(value, "/"), "/") {
|
||
if segment == "" || segment == "." || segment == ".." || len(segment) > 80 {
|
||
return "", errors.New("运行目录包含无效路径段")
|
||
}
|
||
for _, character := range segment {
|
||
if !(character >= 'a' && character <= 'z') && !(character >= 'A' && character <= 'Z') && !(character >= '0' && character <= '9') && !strings.ContainsRune("._-", character) {
|
||
return "", errors.New("运行目录仅允许字母、数字、点、下划线和连字符")
|
||
}
|
||
}
|
||
}
|
||
return value, nil
|
||
}
|
||
|
||
func randomHostName() (string, error) {
|
||
data := make([]byte, 5)
|
||
if _, err := rand.Read(data); err != nil {
|
||
return "", err
|
||
}
|
||
return "sv" + hex.EncodeToString(data), nil
|
||
}
|
||
func randomHex(size int) (string, error) {
|
||
data := make([]byte, size)
|
||
if _, err := rand.Read(data); err != nil {
|
||
return "", err
|
||
}
|
||
return hex.EncodeToString(data), nil
|
||
}
|
||
func randomPassword() (string, error) {
|
||
data := make([]byte, 21)
|
||
if _, err := rand.Read(data); err != nil {
|
||
return "", err
|
||
}
|
||
return base64.RawURLEncoding.EncodeToString(data), nil
|
||
}
|
||
|
||
// aaPanel's FTP and database forms accept at most 20 ASCII letters and digits.
|
||
// Twenty independently selected base-62 characters still provide about 119 bits
|
||
// of entropy, while avoiding silently rejected punctuation and overlong values.
|
||
func randomPanelPassword() (string, error) {
|
||
const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||
const length = 20
|
||
result := make([]byte, length)
|
||
// Rejection sampling avoids modulo bias because 248 is the largest multiple
|
||
// of 62 that fits in a byte range.
|
||
for index := range result {
|
||
for {
|
||
var sample [1]byte
|
||
if _, err := rand.Read(sample[:]); err != nil {
|
||
return "", err
|
||
}
|
||
if sample[0] < 248 {
|
||
result[index] = alphabet[int(sample[0])%len(alphabet)]
|
||
break
|
||
}
|
||
}
|
||
}
|
||
return string(result), nil
|
||
}
|
||
|
||
func (s *Projects) nodeGate(ctx context.Context) *sync.RWMutex {
|
||
if scope.Node(ctx) == 1 {
|
||
return &s.maintenanceGate
|
||
}
|
||
gate, _ := s.nodeGates.LoadOrStore(scope.Node(ctx), &sync.RWMutex{})
|
||
return gate.(*sync.RWMutex)
|
||
}
|