feat: import Sea vHost single-server testing release
This commit is contained in:
commit
248badd33e
441 files changed
+63221
No files matched your search
@@ -0,0 +1,737 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"path"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"sea-vhost/internal/cluster"
|
||||
"sea-vhost/internal/isolation"
|
||||
"sea-vhost/internal/panel"
|
||||
"sea-vhost/internal/scope"
|
||||
"sea-vhost/internal/store"
|
||||
)
|
||||
|
||||
var ErrRuntimeSwitchPending = errors.New("该主机的网站正在切换运行环境,请等待切换完成或核验结果")
|
||||
var ErrNodeConfigurationBusy = errors.New("节点正在调整主机配置,请稍后重试")
|
||||
|
||||
func runtimeBranch(name, version string) string {
|
||||
value := strings.TrimPrefix(strings.TrimPrefix(strings.TrimPrefix(version, "jdk-"), "go"), "v")
|
||||
parts := strings.Split(value, ".")
|
||||
if name == "Node.js" || name == "Java" {
|
||||
return parts[0]
|
||||
}
|
||||
if len(parts) < 2 {
|
||||
return ""
|
||||
}
|
||||
return strings.Join(parts[:2], ".")
|
||||
}
|
||||
func runtimeVersionNewer(a, b string) bool {
|
||||
normalize := func(v string) []string {
|
||||
return strings.FieldsFunc(strings.TrimLeft(v, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"), func(r rune) bool { return r == '.' || r == '_' })
|
||||
}
|
||||
x, y := normalize(a), normalize(b)
|
||||
for i := 0; i < max(len(x), len(y)); i++ {
|
||||
var left, right int
|
||||
if i < len(x) {
|
||||
left, _ = strconv.Atoi(x[i])
|
||||
}
|
||||
if i < len(y) {
|
||||
right, _ = strconv.Atoi(y[i])
|
||||
}
|
||||
if left != right {
|
||||
return left > right
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (s *Projects) InstallRuntimeEnvironment(ctx context.Context, name, version string) error {
|
||||
if s.store == nil {
|
||||
return s.installRuntimeEnvironmentLegacy(ctx, name, version)
|
||||
}
|
||||
items, err := s.panel.RuntimeEnvironments(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
allowed := false
|
||||
for _, item := range items {
|
||||
if item.Name == name && item.ComponentStatus == panel.RuntimeComponentReady && slices.Contains(item.Available, version) && !slices.Contains(item.Installed, version) && !slices.Contains(item.Installing, version) {
|
||||
allowed = true
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
return errors.New("请选择清单中尚未安装的运行环境版本")
|
||||
}
|
||||
_, err = s.store.CreateRuntimeJob(ctx, store.RuntimeJob{Action: "install", Runtime: name, TargetVersion: version})
|
||||
return err
|
||||
}
|
||||
func (s *Projects) SubmitPHPPatch(ctx context.Context, branch, target string) (uint64, error) {
|
||||
items, err := s.panel.RuntimeEnvironments(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for _, item := range items {
|
||||
if item.Name != "PHP" {
|
||||
continue
|
||||
}
|
||||
for _, patch := range item.Patches {
|
||||
if patch.Branch == branch && patch.Latest == target && patch.UpdateAvailable {
|
||||
return s.store.CreateRuntimeJob(ctx, store.RuntimeJob{Action: "php_patch", Runtime: "PHP", FromVersion: patch.Installed, TargetVersion: target})
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0, errors.New("该 PHP 分支没有匹配的稳定补丁更新")
|
||||
}
|
||||
func (s *Projects) SubmitRuntimeMigration(ctx context.Context, siteID uint64, target string, allowBranchChange bool, entryFile string) (uint64, error) {
|
||||
t, err := s.runtimeTarget(ctx, siteID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if t.Site.Status != "running" && t.Site.Status != "stopped" {
|
||||
return 0, errors.New("仅已部署且正常运行或已停止的站点可以迁移运行环境")
|
||||
}
|
||||
if t.Site.Version == target && t.Site.Runtime != "Go" {
|
||||
return 0, errors.New("站点已经使用该版本")
|
||||
}
|
||||
if runtimeBranch(t.Site.Runtime, t.Site.Version) != runtimeBranch(t.Site.Runtime, target) && !allowBranchChange {
|
||||
return 0, errors.New("跨分支升级必须单独确认")
|
||||
}
|
||||
items, err := s.panel.RuntimeEnvironments(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
installed := false
|
||||
for _, item := range items {
|
||||
if item.Name == t.Site.Runtime && slices.Contains(item.Installed, target) {
|
||||
installed = true
|
||||
}
|
||||
}
|
||||
if !installed {
|
||||
return 0, errors.New("请先安装目标运行环境")
|
||||
}
|
||||
id := siteID
|
||||
if t.Site.Runtime == "Go" {
|
||||
if entryFile == "" {
|
||||
return 0, errors.New("请上传独立的新程序文件,并填写 Go 目标程序文件名;旧程序需要保留用于回退")
|
||||
}
|
||||
entryFile, err = normalizeDeploymentEntry("Go", entryFile)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return s.store.CreateRuntimeJob(ctx, store.RuntimeJob{Action: "migrate", Runtime: t.Site.Runtime, FromVersion: t.Site.Version, TargetVersion: target, EntryFile: entryFile, SiteID: &id})
|
||||
}
|
||||
func (s *Projects) runtimeTarget(ctx context.Context, id uint64) (store.RuntimeTarget, error) {
|
||||
items, err := s.store.RuntimeTargets(ctx)
|
||||
if err != nil {
|
||||
return store.RuntimeTarget{}, err
|
||||
}
|
||||
for _, item := range items {
|
||||
if item.Site.ID == id {
|
||||
return item, nil
|
||||
}
|
||||
}
|
||||
return store.RuntimeTarget{}, store.ErrNotFound
|
||||
}
|
||||
func (s *Projects) RuntimeMaintenanceState(ctx context.Context) ([]store.RuntimeTarget, []store.RuntimeJob, error) {
|
||||
t, err := s.store.RuntimeTargets(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
j, err := s.store.RuntimeJobs(ctx)
|
||||
return t, j, err
|
||||
}
|
||||
func (s *Projects) ResumeRuntimeMaintenance(ctx context.Context, id uint64) error {
|
||||
return s.store.RetryRuntimeJob(ctx, id)
|
||||
}
|
||||
func (s *Projects) SubmitRuntimeCheck(ctx context.Context) (uint64, error) {
|
||||
return s.store.CreateRuntimeJob(ctx, store.RuntimeJob{Action: "check", Runtime: "all", TargetVersion: "-"})
|
||||
}
|
||||
|
||||
func (s *Projects) RunRuntimeMaintenance(ctx context.Context) {
|
||||
if err := s.store.InterruptRuntimeJobs(ctx); err != nil {
|
||||
slog.Error("cannot recover runtime maintenance jobs", "error", err)
|
||||
return
|
||||
}
|
||||
workers := make(chan struct{}, 4)
|
||||
var running sync.WaitGroup
|
||||
defer running.Wait()
|
||||
ticker := time.NewTicker(2 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
select {
|
||||
case workers <- struct{}{}:
|
||||
default:
|
||||
continue
|
||||
}
|
||||
job, err := s.store.ClaimRuntimeJob(ctx)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
<-workers
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("cannot claim runtime maintenance", "error", err)
|
||||
<-workers
|
||||
continue
|
||||
}
|
||||
running.Add(1)
|
||||
go func() { defer running.Done(); defer func() { <-workers }(); s.executeRuntimeJob(ctx, job) }()
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *Projects) executeRuntimeJob(parent context.Context, job store.RuntimeJob) {
|
||||
parent = scope.WithNode(parent, job.NodeID)
|
||||
// Component installation belongs to the panel and must not freeze unrelated
|
||||
// host operations. Site configuration switches own only their target host.
|
||||
if (job.Action == "runtime_change" || job.Action == "migrate") && job.SiteID != nil {
|
||||
target, e := s.runtimeTarget(parent, *job.SiteID)
|
||||
if e != nil {
|
||||
_ = s.store.UpdateRuntimeJob(parent, job.ID, "failed", "failed", "网站已不存在")
|
||||
return
|
||||
}
|
||||
// Use the same lock order as tenant requests: host first, then the node.
|
||||
// A tenant's failed runtime change must never freeze unrelated hosts.
|
||||
hostGate := s.hostAccessGate(target.Project.ID)
|
||||
hostGate.Lock()
|
||||
defer hostGate.Unlock()
|
||||
s.nodeGate(parent).RLock()
|
||||
defer s.nodeGate(parent).RUnlock()
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(parent, 2*time.Hour)
|
||||
defer cancel()
|
||||
phase := func(value string) error { return s.store.UpdateRuntimeJob(ctx, job.ID, "running", value, "") }
|
||||
var err error
|
||||
switch job.Action {
|
||||
case "check":
|
||||
err = phase("checking")
|
||||
if err == nil {
|
||||
err = s.CheckRuntimeUpdates(ctx)
|
||||
}
|
||||
case "install":
|
||||
err = phase("installing")
|
||||
installed, installing := false, false
|
||||
if items, inventoryErr := s.panel.RuntimeEnvironments(ctx); inventoryErr == nil {
|
||||
for _, item := range items {
|
||||
if item.Name == job.Runtime {
|
||||
installed = slices.Contains(item.Installed, job.TargetVersion)
|
||||
installing = slices.Contains(item.Installing, job.TargetVersion)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err == nil && !installed && !installing {
|
||||
if job.Runtime == "Python" {
|
||||
err = s.isolation.InstallPythonRuntime(ctx, job.TargetVersion)
|
||||
} else {
|
||||
err = s.panel.InstallRuntimeEnvironment(ctx, job.Runtime, job.TargetVersion)
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
err = s.waitRuntimeInstalled(ctx, job.Runtime, job.TargetVersion)
|
||||
}
|
||||
case "php_patch":
|
||||
err = s.applyPHPPatch(ctx, job, phase)
|
||||
case "runtime_change":
|
||||
err = s.changeRuntimeSite(ctx, job, phase)
|
||||
case "migrate":
|
||||
err = s.migrateRuntimeSite(ctx, job, phase)
|
||||
default:
|
||||
err = errors.New("unknown runtime maintenance action")
|
||||
}
|
||||
s.invalidateRuntimeCatalog()
|
||||
finishCtx, finishCancel := context.WithTimeout(context.WithoutCancel(parent), 30*time.Second)
|
||||
defer finishCancel()
|
||||
current, readErr := s.store.RuntimeJob(finishCtx, job.ID)
|
||||
if readErr == nil && (current.Status == "rolled_back" || current.Status == "interrupted") {
|
||||
if err != nil {
|
||||
_ = s.store.EnqueueAdminNotification(finishCtx, "critical", "runtime", "运行环境维护需要关注", fmt.Sprintf("任务 #%d %s %s(%s):%s", job.ID, job.Runtime, job.TargetVersion, current.Status, current.Message))
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
status := "failed"
|
||||
if parent.Err() != nil || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, cluster.ErrUncertain) {
|
||||
status = "interrupted"
|
||||
}
|
||||
_ = s.store.UpdateRuntimeJob(finishCtx, job.ID, status, "failed", err.Error())
|
||||
_ = s.store.EnqueueAdminNotification(finishCtx, "critical", "runtime", "运行环境维护失败", fmt.Sprintf("任务 #%d %s %s:%v", job.ID, job.Runtime, job.TargetVersion, err))
|
||||
return
|
||||
}
|
||||
_ = s.store.UpdateRuntimeJob(finishCtx, job.ID, "completed", "verified", "目标版本已核验;原本停止的站点保持停止,待启动后核验进程")
|
||||
}
|
||||
|
||||
// Coordinate with host identity changes and unfinished site switches, not
|
||||
// long-running panel component installations or patch updates.
|
||||
func (s *Projects) BeginRuntimeMutation(ctx context.Context) (func(), error) {
|
||||
if !s.nodeGate(ctx).TryRLock() {
|
||||
return nil, ErrNodeConfigurationBusy
|
||||
}
|
||||
blocked, err := s.store.RuntimeMutationBlocked(ctx)
|
||||
if err != nil || blocked {
|
||||
s.nodeGate(ctx).RUnlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, ErrRuntimeSwitchPending
|
||||
}
|
||||
return s.nodeGate(ctx).RUnlock, nil
|
||||
}
|
||||
func (s *Projects) waitRuntimeInstalled(ctx context.Context, name, version string) error {
|
||||
for {
|
||||
items, err := s.panel.RuntimeEnvironments(ctx)
|
||||
if err == nil {
|
||||
for _, item := range items {
|
||||
if item.Name == name && slices.Contains(item.Installed, version) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(10 * time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *Projects) applyPHPPatch(ctx context.Context, job store.RuntimeJob, phase func(string) error) error {
|
||||
agent, ok := s.isolation.(isolation.RuntimeMaintenance)
|
||||
if !ok {
|
||||
return errors.New("PHP maintenance agent unavailable")
|
||||
}
|
||||
adapter, ok := s.panel.(panel.RuntimeMaintenance)
|
||||
if !ok {
|
||||
return errors.New("PHP maintenance adapter unavailable")
|
||||
}
|
||||
branch := runtimeBranch("PHP", job.TargetVersion)
|
||||
if err := phase("backing_up"); err != nil {
|
||||
return err
|
||||
}
|
||||
snapshot, err := agent.MaintainPHP(ctx, isolation.PHPMaintenanceSpec{Branch: branch, JobID: job.ID, Action: "backup"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data, _ := json.Marshal(snapshot)
|
||||
if err = s.store.SaveRuntimeRollback(ctx, job.ID, string(data), true); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = phase("installing"); err != nil {
|
||||
return err
|
||||
}
|
||||
pending, err := adapter.PHPRuntimeUpdatePending(ctx, branch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
current, err := agent.MaintainPHP(ctx, isolation.PHPMaintenanceSpec{Branch: branch, Action: "inspect"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current.Version != job.TargetVersion && !pending {
|
||||
if err = adapter.UpdatePHPRuntime(ctx, branch, job.TargetVersion); err != nil {
|
||||
return s.interruptRuntimeJob(job, "补丁更新提交状态待确认:"+err.Error())
|
||||
}
|
||||
}
|
||||
// Allow the panel worker to pick up an acknowledged task before judging it
|
||||
// complete. A brief empty response must never trigger a concurrent rollback.
|
||||
idleSamples := 0
|
||||
for {
|
||||
pending, err = adapter.PHPRuntimeUpdatePending(ctx, branch)
|
||||
if err != nil {
|
||||
return s.interruptRuntimeJob(job, "无法确认宝塔更新队列是否结束:"+err.Error())
|
||||
}
|
||||
current, err = agent.MaintainPHP(ctx, isolation.PHPMaintenanceSpec{Branch: branch, Action: "inspect"})
|
||||
if !pending {
|
||||
idleSamples++
|
||||
} else {
|
||||
idleSamples = 0
|
||||
}
|
||||
if idleSamples >= 3 {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return s.interruptRuntimeJob(job, "更新任务仍在面板队列中,请恢复核验,避免与更新任务并发回滚")
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
}
|
||||
if err == nil && current.Version != job.TargetVersion {
|
||||
err = fmt.Errorf("更新后实际 PHP 版本为 %s,期望 %s", current.Version, job.TargetVersion)
|
||||
}
|
||||
if err == nil {
|
||||
for _, extension := range snapshot.Extensions {
|
||||
if !slices.Contains(current.Extensions, extension) {
|
||||
err = fmt.Errorf("更新后缺少 PHP 扩展 %s", extension)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
if err = phase("restarting"); err == nil {
|
||||
err = s.refreshPHPBranch(ctx, branch)
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
_, _ = agent.MaintainPHP(ctx, isolation.PHPMaintenanceSpec{Branch: branch, JobID: job.ID, Action: "complete"})
|
||||
return nil
|
||||
}
|
||||
restoreCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Minute)
|
||||
defer cancel()
|
||||
_ = s.store.UpdateRuntimeJob(restoreCtx, job.ID, "running", "rolling_back", err.Error())
|
||||
if _, restoreErr := agent.MaintainPHP(restoreCtx, isolation.PHPMaintenanceSpec{Branch: branch, JobID: job.ID, Action: "restore"}); restoreErr != nil {
|
||||
return s.interruptRuntimeJob(job, fmt.Sprintf("更新失败:%v;恢复失败:%v", err, restoreErr))
|
||||
}
|
||||
if restoreErr := s.refreshPHPBranch(restoreCtx, branch); restoreErr != nil {
|
||||
return s.interruptRuntimeJob(job, "恢复后站点核验失败:"+restoreErr.Error())
|
||||
}
|
||||
_ = s.store.UpdateRuntimeJob(restoreCtx, job.ID, "rolled_back", "rolled_back", "更新未通过验证,已恢复更新前环境:"+err.Error())
|
||||
_, _ = agent.MaintainPHP(restoreCtx, isolation.PHPMaintenanceSpec{Branch: branch, JobID: job.ID, Action: "complete"})
|
||||
return err
|
||||
}
|
||||
func (s *Projects) interruptRuntimeJob(job store.RuntimeJob, message string) error {
|
||||
ctx, cancel := context.WithTimeout(scope.WithNode(context.Background(), job.NodeID), 10*time.Second)
|
||||
defer cancel()
|
||||
_ = s.store.UpdateRuntimeJob(ctx, job.ID, "interrupted", job.Phase, message)
|
||||
return errors.New(message)
|
||||
}
|
||||
func (s *Projects) refreshPHPBranch(ctx context.Context, branch string) error {
|
||||
targets, err := s.store.RuntimeTargets(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, target := range targets {
|
||||
site := target.Site
|
||||
if site.Runtime != "PHP" || site.Version != branch {
|
||||
continue
|
||||
}
|
||||
if site.Status != "running" {
|
||||
continue
|
||||
}
|
||||
if err = s.refreshPHPBranchSite(ctx, site.ID, target.Project.ID, branch); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Projects) refreshPHPBranchSite(ctx context.Context, siteID, projectID uint64, branch string) error {
|
||||
// Only the short refresh of our private FPM pool needs a host lock. The
|
||||
// panel's compilation/installation phase holds no tenant access locks.
|
||||
hostGate := s.hostAccessGate(projectID)
|
||||
hostGate.Lock()
|
||||
defer hostGate.Unlock()
|
||||
s.nodeGate(ctx).RLock()
|
||||
defer s.nodeGate(ctx).RUnlock()
|
||||
target, err := s.runtimeTarget(ctx, siteID)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if target.Site.Runtime != "PHP" || target.Site.Version != branch || target.Site.Status != "running" {
|
||||
return nil
|
||||
}
|
||||
spec, err := s.phpIdentitySpec(ctx, target.Project, target.Site)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = s.isolation.SetPHPIdentityState(ctx, spec, false); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = s.isolation.SetPHPIdentityState(ctx, spec, true); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.verifyRuntimeTarget(ctx, target)
|
||||
}
|
||||
func (s *Projects) runtimeProbeSpec(target store.RuntimeTarget) isolation.RuntimeProbeSpec {
|
||||
return isolation.RuntimeProbeSpec{Project: isolation.ProjectSpec{TenantID: target.Site.TenantID, HostName: target.HostName, RunPath: target.Site.RunPath, StorageBytes: 1, ProcessLimit: uint32(target.Site.ProcessLimit)}, Runtime: target.Site.Runtime, Version: target.Site.Version, ProjectName: lifecycleSiteName(target.Project, target.Site), Running: target.Site.Status == "running"}
|
||||
}
|
||||
func (s *Projects) verifyRuntimeTarget(ctx context.Context, target store.RuntimeTarget) error {
|
||||
ctx = scope.WithProject(ctx, target.Project.ID, target.Project.NodeID)
|
||||
agent, ok := s.isolation.(isolation.RuntimeMaintenance)
|
||||
if !ok {
|
||||
return errors.New("runtime probe agent unavailable")
|
||||
}
|
||||
spec := s.runtimeProbeSpec(target)
|
||||
if target.Site.Runtime != "PHP" {
|
||||
adapter, ok := s.panel.(panel.RuntimeMaintenance)
|
||||
if !ok {
|
||||
return errors.New("runtime adapter unavailable")
|
||||
}
|
||||
runtime, err := adapter.ManagedRuntime(ctx, target.Site.PanelSiteID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
spec.EntryFile = runtime.EntryFile
|
||||
}
|
||||
observation, err := agent.ProbeRuntime(ctx, spec)
|
||||
if err != nil {
|
||||
_ = s.store.SaveRuntimeObservation(ctx, target.Site.ID, "", "", false, err.Error())
|
||||
return err
|
||||
}
|
||||
_ = s.store.SaveRuntimeObservation(ctx, target.Site.ID, observation.InstalledVersion, observation.RunningVersion, observation.Healthy, observation.Detail)
|
||||
if spec.Running && !observation.Healthy {
|
||||
return errors.New(observation.Detail)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Projects) migrateRuntimeSite(ctx context.Context, job store.RuntimeJob, phase func(string) error) error {
|
||||
if job.SiteID == nil {
|
||||
return errors.New("missing site")
|
||||
}
|
||||
target, err := s.runtimeTarget(ctx, *job.SiteID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx = scope.WithProject(ctx, target.Project.ID, target.Project.NodeID)
|
||||
if target.Site.Version != job.FromVersion && target.Site.Version != job.TargetVersion {
|
||||
return errors.New("站点当前版本与迁移任务不一致")
|
||||
}
|
||||
agent, ok := s.isolation.(isolation.RuntimeMaintenance)
|
||||
if !ok {
|
||||
return errors.New("runtime migration agent unavailable")
|
||||
}
|
||||
adapter, ok := s.panel.(panel.RuntimeMaintenance)
|
||||
if !ok {
|
||||
return errors.New("runtime migration adapter unavailable")
|
||||
}
|
||||
if err = s.ensureTenantWritable(ctx, target.Site.TenantID); err != nil {
|
||||
return err
|
||||
}
|
||||
oldSite := target.Site
|
||||
probe := s.runtimeProbeSpec(target)
|
||||
probe.Version = job.TargetVersion
|
||||
probe.Running = false
|
||||
var oldRuntime panel.RuntimeSpec
|
||||
if target.Site.Runtime != "PHP" {
|
||||
oldRuntime, err = adapter.ManagedRuntime(ctx, target.Site.PanelSiteID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
probe.EntryFile = oldRuntime.EntryFile
|
||||
if target.Site.Runtime == "Go" {
|
||||
probe.EntryFile = job.EntryFile
|
||||
if probe.EntryFile == oldRuntime.EntryFile {
|
||||
return errors.New("Go 更新必须使用独立的新程序文件,保留旧文件用于回退")
|
||||
}
|
||||
}
|
||||
// Persist the original record before modifying the broker.
|
||||
if job.RollbackData != "" {
|
||||
if json.Unmarshal([]byte(job.RollbackData), &oldRuntime) != nil {
|
||||
return errors.New("invalid persisted rollback record")
|
||||
}
|
||||
}
|
||||
data, _ := json.Marshal(oldRuntime)
|
||||
if err = s.store.SaveRuntimeRollback(ctx, job.ID, string(data), true); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err = phase("preparing"); err != nil {
|
||||
return err
|
||||
}
|
||||
if target.Site.Runtime == "Python" {
|
||||
spec := isolation.PanelRuntimeSpec{Project: probe.Project, Runtime: "Python", Version: job.TargetVersion, ProjectName: probe.ProjectName}
|
||||
if err = s.isolation.PreparePanelRuntime(ctx, spec); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = agent.CopyPythonDependencies(ctx, spec, job.FromVersion); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
preflight, err := agent.ProbeRuntime(ctx, probe)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if target.Site.Runtime == "Go" && preflight.InstalledVersion != job.TargetVersion {
|
||||
return errors.New("请先使用目标 Go SDK 重新编译并上传程序,再执行版本切换")
|
||||
}
|
||||
if target.Site.Runtime == "Go" {
|
||||
if err = s.isolation.PrepareExecutable(ctx, isolation.ExecutableSpec{Project: probe.Project, RelativePath: path.Join(strings.TrimPrefix(target.Site.RunPath, "/"), job.EntryFile)}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err = phase("switching"); err != nil {
|
||||
return err
|
||||
}
|
||||
apply := func(version string, rollback bool) error {
|
||||
if target.Site.Runtime == "PHP" {
|
||||
newSite := oldSite
|
||||
newSite.Version = version
|
||||
spec, e := s.phpIdentitySpec(ctx, target.Project, newSite)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if e = s.isolation.ConfigurePHPIdentity(ctx, spec); e != nil {
|
||||
return e
|
||||
}
|
||||
if oldSite.Status == "stopped" {
|
||||
return s.isolation.SetPHPIdentityState(ctx, spec, false)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
next := oldRuntime
|
||||
next.Version = version
|
||||
if target.Site.Runtime == "Go" && !rollback {
|
||||
next.EntryFile = job.EntryFile
|
||||
}
|
||||
current, lookupErr := adapter.ManagedRuntime(ctx, target.Site.PanelSiteID)
|
||||
if lookupErr != nil {
|
||||
return lookupErr
|
||||
}
|
||||
if stopErr := s.panel.SetRuntimeState(ctx, current, false); stopErr != nil {
|
||||
// Some Python modules remove/stop only their launcher. Terminate
|
||||
// residual processes only under this host UID and exact run tree.
|
||||
if terminateErr := s.isolation.TerminateRuntime(ctx, isolation.RuntimeProcessSpec{Project: probe.Project}); terminateErr != nil {
|
||||
return fmt.Errorf("停止迁移前进程失败: %v; %w", stopErr, terminateErr)
|
||||
}
|
||||
if stopErr = s.panel.SetRuntimeState(ctx, current, false); stopErr != nil {
|
||||
return stopErr
|
||||
}
|
||||
}
|
||||
if next.Runner {
|
||||
if _, e := s.prepareSavedRunner(ctx, target.Project, target.Site, next.EntryFile, next.Version); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
replaceErr := adapter.ReplaceManagedRuntime(ctx, target.Site.PanelSiteID, next)
|
||||
// aaPanel project creation may recursively chown the directory to www,
|
||||
// including when creation fails and the broker restores the old record.
|
||||
if repairErr := s.restoreSiteIsolation(ctx, target.Project, target.Site.RunPath, target.Site.ProcessLimit); repairErr != nil {
|
||||
return fmt.Errorf("恢复站点目录隔离失败: %w", repairErr)
|
||||
}
|
||||
if replaceErr != nil {
|
||||
return replaceErr
|
||||
}
|
||||
if oldSite.Status == "stopped" {
|
||||
return s.panel.SetRuntimeState(ctx, next, false)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
err = apply(job.TargetVersion, false)
|
||||
if err == nil {
|
||||
err = phase("verifying")
|
||||
}
|
||||
if err == nil {
|
||||
target.Site.Version = job.TargetVersion
|
||||
err = s.verifyRuntimeTarget(ctx, target)
|
||||
}
|
||||
if err == nil && oldSite.Version != job.TargetVersion {
|
||||
err = s.store.ChangeSiteRuntimeVersion(ctx, oldSite, job.TargetVersion)
|
||||
}
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
restoreCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Minute)
|
||||
defer cancel()
|
||||
ctx = restoreCtx
|
||||
if restoreErr := apply(job.FromVersion, true); restoreErr != nil {
|
||||
return s.interruptRuntimeJob(job, fmt.Sprintf("切换失败:%v;旧版本恢复失败:%v", err, restoreErr))
|
||||
}
|
||||
if oldSite.Version == job.TargetVersion && job.FromVersion != job.TargetVersion {
|
||||
if restoreErr := s.store.ChangeSiteRuntimeVersion(restoreCtx, oldSite, job.FromVersion); restoreErr != nil {
|
||||
return s.interruptRuntimeJob(job, "恢复旧版后保存版本记录失败:"+restoreErr.Error())
|
||||
}
|
||||
}
|
||||
target.Site = oldSite
|
||||
target.Site.Version = job.FromVersion
|
||||
if verifyErr := s.verifyRuntimeTarget(restoreCtx, target); verifyErr != nil {
|
||||
return s.interruptRuntimeJob(job, "旧版本配置已恢复,但运行核验失败:"+verifyErr.Error())
|
||||
}
|
||||
_ = s.store.UpdateRuntimeJob(restoreCtx, job.ID, "rolled_back", "rolled_back", "切换失败,已恢复旧版本:"+err.Error())
|
||||
return err
|
||||
}
|
||||
func (s *Projects) RunRuntimeUpdateChecks(ctx context.Context) {
|
||||
runNode := func(ctx context.Context) {
|
||||
if !s.nodeGate(ctx).TryRLock() {
|
||||
return
|
||||
}
|
||||
defer s.nodeGate(ctx).RUnlock()
|
||||
checkCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
defer cancel()
|
||||
if blocked, err := s.store.RuntimeMutationBlocked(checkCtx); err != nil || blocked {
|
||||
return
|
||||
}
|
||||
if err := s.CheckRuntimeUpdates(checkCtx); err != nil {
|
||||
slog.Warn("runtime update check failed", "error", err)
|
||||
}
|
||||
}
|
||||
run := func() {
|
||||
nodes, err := s.store.Nodes(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, n := range nodes {
|
||||
if n.Enabled {
|
||||
runNode(scope.WithNode(ctx, n.ID))
|
||||
}
|
||||
}
|
||||
}
|
||||
run()
|
||||
ticker := time.NewTicker(6 * time.Hour)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
run()
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *Projects) CheckRuntimeUpdates(ctx context.Context) error {
|
||||
if s.store != nil {
|
||||
if _, err := s.ftpTLSPolicy(ctx); err != nil {
|
||||
_ = s.store.EnqueueAdminNotification(context.WithoutCancel(ctx), "critical", "ftp", "节点 FTP 证书同步失败", fmt.Sprintf("节点 %d:%v", scope.Node(ctx), err))
|
||||
return err
|
||||
}
|
||||
}
|
||||
if pruner, ok := s.isolation.(interface{ PruneRuntimeBackups(context.Context) error }); ok {
|
||||
if err := pruner.PruneRuntimeBackups(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
items, err := s.panel.RuntimeEnvironments(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, item := range items {
|
||||
if item.Name == "PHP" {
|
||||
for _, patch := range item.Patches {
|
||||
if patch.UpdateAvailable {
|
||||
_ = s.store.NotifyRuntimeRelease(ctx, "PHP/"+patch.Latest, "PHP 补丁更新可用", patch.Installed+" → "+patch.Latest+",请在环境配置中执行更新")
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
for _, installed := range item.Installed {
|
||||
latest := installed
|
||||
for _, version := range item.Available {
|
||||
if runtimeBranch(item.Name, installed) == runtimeBranch(item.Name, version) && runtimeVersionNewer(version, latest) {
|
||||
latest = version
|
||||
}
|
||||
}
|
||||
if latest != installed {
|
||||
_ = s.store.NotifyRuntimeRelease(ctx, item.Name+"/"+latest, item.Name+" 更新可用", installed+" → "+latest+",安装后需要切换项目并验证生效")
|
||||
}
|
||||
}
|
||||
}
|
||||
targets, err := s.store.RuntimeTargets(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, target := range targets {
|
||||
if target.Site.Status == "running" || target.Site.Status == "stopped" {
|
||||
_ = s.verifyRuntimeTarget(ctx, target)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user