Files
vHost/backend/internal/isolation/runtime_maintenance.go
T

518 lines
18 KiB
Go

package isolation
import (
"context"
"debug/buildinfo"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"time"
)
type RuntimeProbeSpec struct {
Project ProjectSpec `json:"project"`
Runtime string `json:"runtime"`
Version string `json:"version"`
ProjectName string `json:"projectName"`
EntryFile string `json:"entryFile,omitempty"`
Running bool `json:"running"`
}
type RuntimeObservation struct {
InstalledVersion string `json:"installedVersion"`
RunningVersion string `json:"runningVersion,omitempty"`
Healthy bool `json:"healthy"`
Detail string `json:"detail,omitempty"`
}
type PHPMaintenanceSpec struct {
Branch string `json:"branch"`
JobID uint64 `json:"jobId"`
Action string `json:"action"`
}
type PHPState struct {
Version string `json:"version"`
Extensions []string `json:"extensions"`
BackupPath string `json:"backupPath,omitempty"`
}
type RuntimeMaintenance interface {
ProbeRuntime(context.Context, RuntimeProbeSpec) (RuntimeObservation, error)
MaintainPHP(context.Context, PHPMaintenanceSpec) (PHPState, error)
CopyPythonDependencies(context.Context, PanelRuntimeSpec, string) error
}
func (c *Client) ProbeRuntime(ctx context.Context, spec RuntimeProbeSpec) (RuntimeObservation, error) {
var result RuntimeObservation
err := c.request(ctx, "/v1/runtime/probe", spec, &result)
return result, err
}
func (c *Client) MaintainPHP(ctx context.Context, spec PHPMaintenanceSpec) (PHPState, error) {
var result PHPState
err := c.requestLong(ctx, "/v1/runtime/php/maintenance", spec, &result)
return result, err
}
func (c *Client) CopyPythonDependencies(ctx context.Context, spec PanelRuntimeSpec, old string) error {
return c.requestLong(ctx, "/v1/runtime/python/dependencies", struct {
Spec PanelRuntimeSpec `json:"spec"`
Previous string `json:"previous"`
}{spec, old}, nil)
}
var exactPHPVersionPattern = regexp.MustCompile(`^[5-9]\.[0-9]\.[0-9]{1,4}$`)
var maintenanceHostPattern = regexp.MustCompile(`^sv[a-f0-9]{10}$`)
func maintenanceProjectMatches(host, name string) bool {
return maintenanceHostPattern.MatchString(host) && panelProjectNamePattern.MatchString(name) && (name == host || strings.HasPrefix(name, host+"_"))
}
func phpInstallationState(ctx context.Context, branch string) (PHPState, error) {
if !phpVersionPattern.MatchString(branch) {
return PHPState{}, errors.New("invalid PHP branch")
}
root := filepath.Join("/www/server/php", strings.ReplaceAll(branch, ".", ""))
if requirePhysicalDirectory(root) != nil {
return PHPState{}, errors.New("PHP branch is not installed")
}
cmd := exec.CommandContext(ctx, filepath.Join(root, "bin/php"), "-r", `echo json_encode(["version"=>PHP_VERSION,"extensions"=>get_loaded_extensions()]);`)
cmd.Env = []string{"PATH=/usr/bin:/bin", "LANG=C"}
data, err := cmd.Output()
if err != nil {
return PHPState{}, fmt.Errorf("read PHP version: %w", err)
}
var state PHPState
if json.Unmarshal(data, &state) != nil || !exactPHPVersionPattern.MatchString(state.Version) || !strings.HasPrefix(state.Version, branch+".") {
return state, errors.New("PHP returned invalid version metadata")
}
slices.Sort(state.Extensions)
return state, nil
}
func (a Agent) maintainPHP(w http.ResponseWriter, r *http.Request) {
var spec PHPMaintenanceSpec
if decodeMaintenance(r, &spec) != nil || !phpVersionPattern.MatchString(spec.Branch) || !slices.Contains([]string{"inspect", "backup", "restore", "complete"}, spec.Action) || (spec.Action != "inspect" && spec.JobID == 0) {
http.Error(w, "invalid PHP maintenance request", 400)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Minute)
defer cancel()
state, err := a.maintainPHPBranch(ctx, spec)
if err != nil {
http.Error(w, err.Error(), 412)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(state)
}
func decodeMaintenance(r *http.Request, out any) error {
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(out); err != nil {
return err
}
if err := decoder.Decode(&struct{}{}); err != io.EOF {
return errors.New("unexpected trailing JSON")
}
return nil
}
func (a Agent) maintainPHPBranch(ctx context.Context, spec PHPMaintenanceSpec) (PHPState, error) {
if spec.Action == "inspect" {
return phpInstallationState(ctx, spec.Branch)
}
base := a.BackupRoot
if base == "" {
base = "/www/backup/sea-vhost"
}
if !filepath.IsAbs(base) || filepath.Clean(base) != base {
return PHPState{}, errors.New("invalid backup root")
}
branch := strings.ReplaceAll(spec.Branch, ".", "")
root := filepath.Join("/www/server/php", branch)
backup := filepath.Join(base, "runtime", "php", branch, strconv.FormatUint(spec.JobID, 10))
if err := os.MkdirAll(filepath.Dir(backup), 0700); err != nil {
return PHPState{}, err
}
if spec.Action == "backup" {
if info, err := os.Lstat(backup); err == nil {
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return PHPState{}, errors.New("unsafe PHP backup")
}
return readPHPSnapshot(backup, spec.Branch)
}
state, err := phpInstallationState(ctx, spec.Branch)
if err != nil {
return state, err
}
stage, err := os.MkdirTemp(filepath.Dir(backup), ".snapshot-")
if err != nil {
return state, err
}
defer os.RemoveAll(stage)
if err = a.command(ctx, "cp", "-a", "--", root, filepath.Join(stage, "installation")); err != nil {
return state, err
}
state.BackupPath = backup
data, _ := json.Marshal(state)
if err = os.WriteFile(filepath.Join(stage, "manifest.json"), data, 0600); err != nil {
return state, err
}
if err = os.Rename(stage, backup); err != nil {
return state, err
}
return state, nil
}
saved, err := readPHPSnapshot(backup, spec.Branch)
if err != nil {
return saved, err
}
if spec.Action == "complete" {
if err = os.WriteFile(filepath.Join(backup, "retention-start"), []byte(time.Now().UTC().Format(time.RFC3339)), 0600); err != nil {
return saved, err
}
a.prunePHPSnapshots(filepath.Join(base, "runtime", "php"))
return saved, nil
}
if requirePhysicalDirectory(filepath.Join(backup, "installation")) != nil {
return saved, errors.New("PHP snapshot installation unavailable")
}
stage, err := os.MkdirTemp("/www/server/php", ".sea-restore-")
if err != nil {
return saved, err
}
defer os.RemoveAll(stage)
if err = a.command(ctx, "cp", "-a", "--", filepath.Join(backup, "installation"), filepath.Join(stage, "installation")); err != nil {
return saved, err
}
if err = a.command(ctx, "/etc/init.d/php-fpm-"+branch, "stop"); err != nil {
return saved, err
}
if requirePhysicalDirectory(root) != nil {
return saved, errors.New("unsafe PHP restore destination")
}
failed := filepath.Join(stage, "replaced")
if err = os.Rename(root, failed); err != nil {
return saved, err
}
if err = os.Rename(filepath.Join(stage, "installation"), root); err != nil {
_ = os.Rename(failed, root)
return saved, err
}
if err = a.command(ctx, "/etc/init.d/php-fpm-"+branch, "start"); err != nil {
return saved, err
}
return phpInstallationState(ctx, spec.Branch)
}
// Only finalized Sea vHost snapshots expire. An interrupted task keeps its
// unsealed backup until an administrator resolves that task.
func (a Agent) prunePHPSnapshots(base string) {
branches, err := os.ReadDir(base)
if err != nil {
return
}
for _, branch := range branches {
if !branch.IsDir() || !regexp.MustCompile("^[5-9][0-9]$").MatchString(branch.Name()) {
continue
}
root := filepath.Join(base, branch.Name())
if requirePhysicalDirectory(root) != nil {
continue
}
jobs, err := os.ReadDir(root)
if err != nil {
continue
}
for _, job := range jobs {
if _, err = strconv.ParseUint(job.Name(), 10, 64); err != nil || !job.IsDir() {
continue
}
path := filepath.Join(root, job.Name())
if _, err = readPHPSnapshot(path, branch.Name()[:1]+"."+branch.Name()[1:]); err != nil {
continue
}
info, err := os.Lstat(filepath.Join(path, "retention-start"))
if err != nil || !info.Mode().IsRegular() || time.Since(info.ModTime()) < 14*24*time.Hour {
continue
}
_ = os.RemoveAll(path)
}
}
}
// Expiry runs independently of future updates; unresolved snapshots are never
// sealed and therefore remain available for administrator recovery.
func (a Agent) RunRuntimeBackupExpiry(ctx context.Context) {
base := a.BackupRoot
if base == "" {
base = "/www/backup/sea-vhost"
}
if !filepath.IsAbs(base) || filepath.Clean(base) != base {
return
}
prune := func() { a.prunePHPSnapshots(filepath.Join(base, "runtime", "php")) }
prune()
ticker := time.NewTicker(time.Hour)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
prune()
}
}
}
func readPHPSnapshot(backup, branch string) (PHPState, error) {
if requirePhysicalDirectory(backup) != nil {
return PHPState{}, errors.New("PHP snapshot unavailable")
}
data, err := os.ReadFile(filepath.Join(backup, "manifest.json"))
if err != nil {
return PHPState{}, err
}
var state PHPState
if json.Unmarshal(data, &state) != nil || !exactPHPVersionPattern.MatchString(state.Version) || !strings.HasPrefix(state.Version, branch+".") || state.BackupPath != backup {
return state, errors.New("invalid PHP snapshot manifest")
}
return state, nil
}
func (a Agent) probeRuntime(w http.ResponseWriter, r *http.Request) {
var spec RuntimeProbeSpec
if decodeMaintenance(r, &spec) != nil || !maintenanceProjectMatches(spec.Project.HostName, spec.ProjectName) || !validProjectRunPath(spec.Project.RunPath) || spec.Project.TenantID == 0 {
http.Error(w, "invalid runtime probe", 400)
return
}
result, err := a.probeRuntimeState(r.Context(), spec)
if err != nil {
http.Error(w, err.Error(), 412)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(result)
}
func (a Agent) probeRuntimeState(ctx context.Context, spec RuntimeProbeSpec) (RuntimeObservation, error) {
root, err := a.projectPath(spec.Project)
if err != nil {
return RuntimeObservation{}, err
}
working, err := physicalRunDirectory(root, spec.Project.RunPath)
if err != nil {
return RuntimeObservation{}, err
}
result := RuntimeObservation{}
var executable string
switch spec.Runtime {
case "PHP":
state, err := phpInstallationState(ctx, spec.Version)
if err != nil {
return result, err
}
result.InstalledVersion = state.Version
executable = filepath.Join("/www/server/php", strings.ReplaceAll(spec.Version, ".", ""), "sbin/php-fpm")
if !spec.Running {
result.Detail = "站点已停止,等待启动验证"
return result, nil
}
// Probe the private PID/socket directly; no Nginx config is modified.
runRoot := a.PHPRunRoot
if runRoot == "" {
runRoot = "/run/sea-vhost-php"
}
pid, err := readPID(filepath.Join(runRoot, spec.ProjectName, "php-fpm.pid"))
if err != nil {
return result, err
}
if !processUsesExecutable(ctx, pid, spec.Project.HostName, executable, working, false) {
result.Detail = "PHP-FPM 仍在使用旧程序或进程身份不匹配"
return result, nil
}
conn, err := net.DialTimeout("unix", filepath.Join(runRoot, spec.ProjectName, "php-fpm.sock"), time.Second)
if err != nil {
return result, err
}
_ = conn.Close()
result.RunningVersion = state.Version
result.Healthy = true
return result, nil
case "Python":
if !supportedPythonSourceVersion(spec.Version) {
return result, errors.New("invalid Python version")
}
manager := a.PythonManagerRoot
if manager == "" {
manager = "/www/server/python_manager/versions"
}
executable = filepath.Join(manager, spec.Version, "bin/python3")
result.InstalledVersion = spec.Version
case "Node.js":
if !regexp.MustCompile(`^v[0-9]+\.[0-9]+\.[0-9]+$`).MatchString(spec.Version) {
return result, errors.New("invalid Node version")
}
executable = filepath.Join("/www/server/nodejs", spec.Version, "bin/node")
result.InstalledVersion = spec.Version
case "Java":
if !regexp.MustCompile(`^(?:jdk-)?[0-9]+(?:\.[0-9]+){0,3}(?:_[0-9]+)?$`).MatchString(spec.Version) {
return result, errors.New("invalid JDK version")
}
executable = filepath.Join("/www/server/java", spec.Version, "bin/java")
if info, err := os.Stat(filepath.Join("/www/server/java", spec.Version)); err == nil && info.Mode().IsRegular() {
executable = filepath.Join("/www/server/java", spec.Version)
}
result.InstalledVersion = spec.Version
case "Go":
if !validExecutablePath(spec.EntryFile) {
return result, errors.New("invalid Go entry")
}
executable = filepath.Join(working, spec.EntryFile)
guard, err := os.OpenRoot(working)
if err != nil {
return result, err
}
defer guard.Close()
entry, err := guard.Open(spec.EntryFile)
if err != nil {
return result, err
}
defer entry.Close()
info, err := buildinfo.Read(entry)
if err != nil {
return result, errors.New("无法读取 Go 二进制编译版本,请上传带有 Go 构建信息的程序")
}
result.InstalledVersion = info.GoVersion
if info.GoVersion != spec.Version {
result.Detail = "二进制尚未使用目标 Go 版本重新编译"
return result, nil
}
default:
return result, errors.New("unsupported runtime probe")
}
if _, err = os.Stat(executable); err != nil {
return result, errors.New("runtime executable unavailable")
}
if !spec.Running {
result.Detail = "站点已停止,等待启动验证"
return result, nil
}
pids, err := identityPIDsForRuntimeProbe(spec.Project.HostName)
if err != nil {
return result, err
}
for _, pid := range pids {
if processUsesExecutable(ctx, pid, spec.Project.HostName, executable, working, true) {
result.RunningVersion = result.InstalledVersion
result.Healthy = true
return result, nil
}
}
result.Detail = "未找到使用目标版本的站点进程"
return result, nil
}
func (a Agent) copyPythonDependencies(w http.ResponseWriter, r *http.Request) {
var input struct {
Spec PanelRuntimeSpec `json:"spec"`
Previous string `json:"previous"`
}
if decodeMaintenance(r, &input) != nil || input.Spec.Runtime != "Python" || !supportedPythonSourceVersion(input.Previous) || !supportedPythonSourceVersion(input.Spec.Version) || !maintenanceProjectMatches(input.Spec.Project.HostName, input.Spec.ProjectName) || input.Spec.Project.TenantID == 0 {
http.Error(w, "invalid Python migration", 400)
return
}
root, err := a.projectPath(input.Spec.Project)
if err != nil {
http.Error(w, "invalid project", 412)
return
}
working, err := physicalRunDirectory(root, input.Spec.Project.RunPath)
if err != nil {
http.Error(w, "unsafe run directory", 412)
return
}
parent := filepath.Join(working, ".sea-runtime/python")
oldPython := filepath.Join(parent, input.Spec.ProjectName+"-"+input.Previous, "bin/python3")
newPython := filepath.Join(parent, input.Spec.ProjectName+"-"+input.Spec.Version, "bin/python3")
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Minute)
defer cancel()
manager := a.PythonManagerRoot
if manager == "" {
manager = "/www/server/python_manager/versions"
}
if err = a.repairManagedPythonAccess(ctx, filepath.Join(manager, input.Previous), input.Previous); err != nil {
http.Error(w, "previous shared Python installation is unavailable", 412)
return
}
// Both commands drop UID before executing tenant-controlled venv content.
cmd := tenantMaintenanceCommand(ctx, input.Spec.Project.HostName, oldPython, "-m", "pip", "freeze")
var dependencies cappedDependencyBuffer
cmd.Stdout = &dependencies
err = cmd.Run()
if err != nil {
http.Error(w, "cannot export previous Python dependencies", 412)
return
}
if dependencies.exceeded {
http.Error(w, "Python dependency list too large", 412)
return
}
data := dependencies.data
if strings.TrimSpace(string(data)) != "" {
cmd = pythonDependencyRestoreCommand(ctx, input.Spec.Project.HostName, newPython)
cmd.Stdin = strings.NewReader(string(data))
cmd.Stdout, cmd.Stderr = io.Discard, io.Discard
if installErr := cmd.Run(); installErr != nil {
http.Error(w, "Python dependency restore failed; previous environment retained", 412)
return
}
}
w.WriteHeader(200)
}
const pythonDependencyRestore = `import os,sys,tempfile,subprocess
with tempfile.TemporaryDirectory(prefix=".sea-migrate-",dir=sys.argv[1]) as directory:
requirements=os.path.join(directory,"requirements.txt")
fd=os.open(requirements,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
with os.fdopen(fd,"wb") as output:
output.write(sys.stdin.buffer.read(1048577))
result=subprocess.run([sys.executable,"-m","pip","install","--disable-pip-version-check","-r",requirements],stdin=subprocess.DEVNULL)
sys.exit(result.returncode)
`
func pythonDependencyRestoreCommand(ctx context.Context, identity, python string) *exec.Cmd {
// A root-created stdin pipe can be read via inherited FD 0, but reopening
// /dev/stdin after dropping UID can fail its inode permission check. Create
// a private requirements file as the tenant instead, and always remove it.
return tenantMaintenanceCommand(ctx, identity, python, "-c", pythonDependencyRestore, filepath.Dir(filepath.Dir(python)))
}
func tenantMaintenanceCommand(ctx context.Context, identity string, args ...string) *exec.Cmd {
cmd := exec.CommandContext(ctx, "/usr/sbin/runuser", append([]string{"-u", identity, "--"}, args...)...)
// runuser does not remove every inherited environment variable. Never let
// an own-UID helper or tenant-controlled Python read the agent's token.
cmd.Env = []string{"PATH=/usr/bin:/bin", "HOME=/nonexistent", "LANG=C", "PIP_NO_CACHE_DIR=1"}
return cmd
}
type cappedDependencyBuffer struct {
data []byte
exceeded bool
}
func (b *cappedDependencyBuffer) Write(p []byte) (int, error) {
n := len(p)
remaining := (1 << 20) - len(b.data)
if n > remaining {
b.exceeded = true
p = p[:remaining]
}
b.data = append(b.data, p...)
return n, nil
}