271 lines
11 KiB
Go
271 lines
11 KiB
Go
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
|
|
}
|