1754 lines
70 KiB
Go
1754 lines
70 KiB
Go
package main
|
|
|
|
import (
|
|
"archive/zip"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"io/fs"
|
|
"maps"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
const reinstallCallerWaitBudget = 2*time.Hour + 20*time.Minute
|
|
const reinstallStartupObservation = 5 * time.Second
|
|
const reinstallRecoveryBudget = 45 * time.Second
|
|
const reinstallCanceledBeforeCommit = "reinstall request ended before any files were replaced"
|
|
const reinstallRollbackMarker = ".reinstall-rollback-"
|
|
const reinstallRollbackMetadataFile = "recovery.json"
|
|
const reinstallCommitMetadataKey = "__reinstallCommit"
|
|
const reinstallPendingStartupKey = "__reinstallPendingStartup"
|
|
const reinstallOperationMetadataKey = "__reinstallOperation"
|
|
const reinstallOutcomeMetadataKey = "__reinstallOutcome"
|
|
const reinstallStartupPendingCode = "reinstall_startup_pending"
|
|
const reinstallContainerLabel = "adpanel.reinstall"
|
|
|
|
type reinstallContainerContextKey struct{}
|
|
|
|
var errReinstallStartupPending = errors.New("reinstall startup pending")
|
|
var errReinstallUnmanagedVolume = errors.New("unmanaged runtime image volume")
|
|
var errReinstallInvalidMounts = errors.New("invalid replacement mounts")
|
|
var errReinstallMissingStartup = errors.New("template has no startup command and the runtime image has no default entrypoint or command")
|
|
|
|
// adpanel:reinstall-request-cap - configuration is not a file upload; bound
|
|
// decoding even before the daemon can verify the template-bound signature.
|
|
const maxReinstallRequestBytes = 4 << 20
|
|
|
|
type reinstallDockerConfig struct {
|
|
dockerTemplateConfig
|
|
ReadonlyRootfs bool `json:"readonlyRootfs"`
|
|
}
|
|
|
|
type reinstallRequest struct {
|
|
TemplateId string `json:"templateId"`
|
|
Docker *reinstallDockerConfig `json:"docker"`
|
|
StartupCommand string `json:"startupCommand"`
|
|
HostPort int `json:"hostPort"`
|
|
JavaVersion string `json:"javaVersion"`
|
|
OperationId string `json:"operationId"`
|
|
AcceptUntil int64 `json:"acceptUntil"`
|
|
ReplaceRuntime bool `json:"replaceRuntime"`
|
|
}
|
|
|
|
func validReinstallOperationID(id string) bool {
|
|
if len(id) != 32 {
|
|
return false
|
|
}
|
|
for _, ch := range id {
|
|
if (ch < '0' || ch > '9') && (ch < 'a' || ch > 'f') {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// adpanel:reinstall-outcome-recovery - the server lock and the same acceptance
|
|
// deadline as POST distinguish a terminal absence from an in-flight wipe.
|
|
func (a *Agent) handleReinstallResult(w http.ResponseWriter, r *http.Request, name string) {
|
|
id := r.URL.Query().Get("id")
|
|
until, err := strconv.ParseInt(r.URL.Query().Get("acceptUntil"), 10, 64)
|
|
if !validReinstallOperationID(id) || err != nil || until <= 0 {
|
|
jsonWrite(w, http.StatusBadRequest, map[string]any{"error": "invalid reinstall operation"})
|
|
return
|
|
}
|
|
_ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(reinstallRecoveryBudget))
|
|
result := map[string]any{"operationId": id, "state": "pending"}
|
|
if lock := a.tryLockServerOp(name); lock != nil {
|
|
defer lock.Unlock()
|
|
serverDir := a.serverDir(name)
|
|
meta, err := a.loadMetaChecked(serverDir, false)
|
|
if err == nil && meta[reinstallOperationMetadataKey] == id && meta[reinstallPendingStartupKey] == true && a.reconcileReinstallStartup(r.Context(), name, serverDir, meta) {
|
|
meta, err = a.loadMetaChecked(serverDir, false)
|
|
}
|
|
if err == nil {
|
|
if meta[reinstallOperationMetadataKey] == id {
|
|
if outcome, _ := meta[reinstallOutcomeMetadataKey].(string); meta[reinstallPendingStartupKey] != true && outcome != "" {
|
|
result["state"] = "completed"
|
|
result["outcome"] = outcome
|
|
result["hostPort"] = meta["hostPort"]
|
|
result["template"] = meta["template"]
|
|
}
|
|
} else if time.Now().UnixMilli() > until && meta[reinstallPendingStartupKey] != true && reinstallCanReportAbsence(serverDir, meta) {
|
|
result["state"] = "absent"
|
|
}
|
|
}
|
|
if result["state"] != "pending" {
|
|
powerState := "unknown"
|
|
inspectCtx, cancel := context.WithTimeout(r.Context(), 6*time.Second)
|
|
container, _, exists, inspectErr := a.inspectContainerForStats(inspectCtx, name)
|
|
cancel()
|
|
if inspectErr == nil {
|
|
switch {
|
|
case !exists || reinstallContainerIsStopped(container.State):
|
|
powerState = "stopped"
|
|
case container.State.Running && container.State.Status == "running":
|
|
powerState = "running"
|
|
}
|
|
}
|
|
if powerState != "unknown" || result["state"] == "completed" {
|
|
result["powerState"] = powerState
|
|
}
|
|
}
|
|
}
|
|
jsonWrite(w, http.StatusOK, result)
|
|
}
|
|
|
|
func readReinstallRequest(w http.ResponseWriter, r *http.Request, uploadLimit int64) (reinstallRequest, bool) {
|
|
var req reinstallRequest
|
|
if err := readJSON(w, r, min(uploadLimit, maxReinstallRequestBytes), &req); err != nil {
|
|
if errors.Is(err, errBodyTooLarge) {
|
|
jsonWrite(w, http.StatusRequestEntityTooLarge, map[string]any{"ok": false, "error": "reinstall configuration exceeds the request size limit"})
|
|
} else {
|
|
jsonWrite(w, http.StatusBadRequest, map[string]any{"ok": false, "error": "bad json", "detail": err.Error()})
|
|
}
|
|
return req, false
|
|
}
|
|
return req, true
|
|
}
|
|
|
|
func reinstallKeepsRuntime(template string, oldMeta map[string]any) bool {
|
|
oldTemplate := normalizeTemplateIdentifier(oldMeta["type"])
|
|
if oldTemplate == "" {
|
|
oldTemplate = normalizeTemplateIdentifier(oldMeta["template"])
|
|
}
|
|
return oldTemplate == "" || oldTemplate == template
|
|
}
|
|
|
|
func reinstallStoredRuntime(template string, oldMeta map[string]any, replaceRuntime bool) map[string]any {
|
|
runtimeConfig, _ := oldMeta["runtime"].(map[string]any)
|
|
if replaceRuntime || !reinstallKeepsRuntime(template, oldMeta) {
|
|
// adpanel:reinstall-template-policy - a template switch replaces
|
|
// execution settings, not the server's read-only or binding policy.
|
|
policy := map[string]any{}
|
|
preserveServerRuntimePolicy(policy, runtimeConfig)
|
|
return policy
|
|
}
|
|
return runtimeConfig
|
|
}
|
|
|
|
func reinstallMinecraftSelection(meta map[string]any) (string, string, error) {
|
|
fork, version := "", ""
|
|
if reinstallKeepsRuntime("minecraft", meta) {
|
|
fork = normalizeTemplateIdentifier(meta["fork"])
|
|
version = normalizeTemplateIdentifier(meta["version"])
|
|
}
|
|
fork, err := resolveMinecraftFork(fork)
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
version, err = resolveMinecraftVersion(version)
|
|
return fork, version, err
|
|
}
|
|
|
|
func managedRuntimeImage(template string, runtimeConfig map[string]any) (string, string) {
|
|
image := strings.TrimSpace(fmt.Sprint(runtimeConfig["image"]))
|
|
tag := strings.TrimSpace(fmt.Sprint(runtimeConfig["tag"]))
|
|
if image == "" || image == "<nil>" {
|
|
image = "node"
|
|
if template == "python" {
|
|
image = "python"
|
|
}
|
|
}
|
|
if tag == "" || tag == "<nil>" {
|
|
tag = "20-alpine"
|
|
if template == "python" {
|
|
tag = "3.12-slim"
|
|
}
|
|
}
|
|
return image, tag
|
|
}
|
|
|
|
func scaffoldReinstallFiles(template, serverDir, name, startFile string, hostPort int) error {
|
|
switch template {
|
|
case "python":
|
|
return scaffoldPython(serverDir, startFile)
|
|
case "nodejs", "discord-bot":
|
|
return scaffoldNode(serverDir, name, startFile, hostPort)
|
|
default:
|
|
if startFile != "" {
|
|
return writeGeneratedRuntimeFile(serverDir, filepath.Join(serverDir, filepath.Base(startFile)), nil, nil)
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// adpanel:reinstall-binding-policy - rebuilding files must not widen a
|
|
// server's listening interfaces or discard its disk and resource limits.
|
|
func buildReinstallMetadata(template string, hostPort int, oldMeta map[string]any) map[string]any {
|
|
meta := map[string]any{
|
|
"type": template, "template": template, "hostPort": hostPort,
|
|
"createdAt": time.Now().UnixMilli(),
|
|
}
|
|
preserveServerMetadataPolicy(meta, oldMeta)
|
|
startFile := defaultStartFileForType(template)
|
|
if reinstallKeepsRuntime(template, oldMeta) {
|
|
if storedStart, ok := oldMeta["start"].(string); ok && strings.TrimSpace(storedStart) != "" && strings.TrimSpace(storedStart) != "<nil>" {
|
|
startFile = strings.TrimSpace(storedStart)
|
|
}
|
|
}
|
|
if startFile != "" {
|
|
meta["start"] = startFile
|
|
}
|
|
if template == "minecraft" && reinstallKeepsRuntime(template, oldMeta) {
|
|
for _, key := range []string{"fork", "version"} {
|
|
if value, exists := oldMeta[key]; exists && value != nil {
|
|
meta[key] = value
|
|
}
|
|
}
|
|
}
|
|
// adpanel:reinstall-allocation-interface - a new pool port inherits the
|
|
// old primary interface unless its own allocation explicitly overrides it.
|
|
if oldPort, valid := parseStrictPortValue(oldMeta["hostPort"]); valid && oldPort != hostPort {
|
|
interfaces := serverPortAllocationIPs(oldMeta)
|
|
if oldIP := interfaces[oldPort]; oldIP != "" && interfaces[hostPort] == "" {
|
|
allocations, _ := meta["portAllocations"].([]any)
|
|
reboundAllocations := make([]any, len(allocations)+1)
|
|
copy(reboundAllocations, allocations)
|
|
reboundAllocations[len(allocations)] = map[string]any{"port": hostPort, "ip": oldIP}
|
|
meta["portAllocations"] = reboundAllocations
|
|
}
|
|
}
|
|
return meta
|
|
}
|
|
|
|
func createServerStagingDir(serverDir string) (string, error) {
|
|
// adpanel:reinstall-staging-owner - the leading dot keeps temporary
|
|
// replacement files out of the daemon's sanitized server namespace.
|
|
stagingDir := filepath.Join(filepath.Dir(serverDir), fmt.Sprintf(".%s.restore-staging-%d", filepath.Base(serverDir), time.Now().UnixMilli()))
|
|
return stagingDir, os.Mkdir(stagingDir, 0o700)
|
|
}
|
|
|
|
type reinstallJarDownload func(Downloader, context.Context, string, string) error
|
|
|
|
func (a *Agent) rebuildReinstallServer(w http.ResponseWriter, r *http.Request, name, serverDir, template string, hostPort int, oldMeta, oldRuntime, runtimeConfig map[string]any, operationID string, replaceRuntime bool, download reinstallJarDownload) {
|
|
// adpanel:reinstall-template-intent - a journaled reinstall must not
|
|
// replace the installed template even if runtime seeding refreshed its type.
|
|
installedTemplate := normalizeTemplateIdentifier(oldMeta["template"])
|
|
if operationID != "" && !replaceRuntime && (!reinstallKeepsRuntime(template, oldMeta) || (installedTemplate != "" && installedTemplate != template)) {
|
|
jsonWrite(w, http.StatusConflict, map[string]any{
|
|
"ok": false, "code": "reinstall_template_mismatch",
|
|
"error": "The panel and node have different templates for this server. No files were replaced. Ask an administrator to review the installed template before retrying.",
|
|
})
|
|
return
|
|
}
|
|
// adpanel:reinstall-storage-lock - a rebuild must serialize with uploads
|
|
// and editor saves, using the same serverOp -> uploadScope lock order.
|
|
releaseStorage, err := a.acquireUploadScope(r.Context(), a.fsScopeRootFor(name, serverDir))
|
|
if err != nil {
|
|
jsonWrite(w, http.StatusRequestTimeout, map[string]any{"ok": false, "error": reinstallCanceledBeforeCommit})
|
|
return
|
|
}
|
|
defer releaseStorage()
|
|
if info, err := os.Lstat(serverDir); err != nil || !info.IsDir() {
|
|
jsonWrite(w, http.StatusConflict, map[string]any{
|
|
"ok": false, "code": "reinstall_server_files_unavailable",
|
|
"error": "The original server directory is unavailable. No files were replaced. Contact an administrator before retrying.",
|
|
})
|
|
return
|
|
}
|
|
preserveServerRuntimePolicy(runtimeConfig, oldRuntime)
|
|
if replaceRuntime && oldMeta != nil {
|
|
oldMeta = maps.Clone(oldMeta)
|
|
delete(oldMeta, "start")
|
|
oldMeta["runtime"] = oldRuntime
|
|
}
|
|
|
|
meta := buildReinstallMetadata(template, hostPort, oldMeta)
|
|
if operationID != "" {
|
|
meta[reinstallOperationMetadataKey] = operationID
|
|
}
|
|
var stagingDir string
|
|
if template == "minecraft" {
|
|
stagingDir = a.stageMinecraftReinstall(w, r.Context(), name, serverDir, meta, runtimeConfig, download)
|
|
if stagingDir == "" {
|
|
return
|
|
}
|
|
} else if status, reason := a.preflightReinstallRuntime(r.Context(), name, template, runtimeConfig); reason != "" {
|
|
jsonWrite(w, status, map[string]any{"ok": false, "error": reason})
|
|
return
|
|
} else {
|
|
configureNonMinecraftReinstall(template, meta, runtimeConfig)
|
|
var err error
|
|
stagingDir, err = createServerStagingDir(serverDir)
|
|
if err != nil {
|
|
jsonWrite(w, http.StatusInternalServerError, map[string]any{"ok": false, "error": "could not prepare reinstall staging; no server files were replaced"})
|
|
return
|
|
}
|
|
}
|
|
defer os.RemoveAll(stagingDir)
|
|
if template != "minecraft" && !a.installReinstallTemplate(w, r.Context(), name, serverDir, stagingDir, hostPort, meta, runtimeConfig) {
|
|
return
|
|
}
|
|
stagedRuntime, _ := meta["runtime"].(map[string]any)
|
|
var preparedImage reinstallRuntimeImage
|
|
if runtimeImageRef(stagedRuntime) != "" {
|
|
var err error
|
|
preparedImage, err = a.stageReinstallRuntimeImage(r.Context(), name, template, serverDir, stagingDir, stagedRuntime)
|
|
if err != nil {
|
|
switch {
|
|
case errors.Is(err, errReinstallInstallerBudget):
|
|
writeReinstallStageQuotaRefusal(w)
|
|
case errors.Is(err, errReinstallMissingStartup):
|
|
jsonWrite(w, http.StatusBadRequest, map[string]any{"ok": false, "code": "reinstall_missing_startup", "error": err.Error() + ". No server files were replaced."})
|
|
case errors.Is(err, errReinstallUnmanagedVolume), errors.Is(err, errReinstallInvalidMounts):
|
|
jsonWrite(w, http.StatusBadRequest, map[string]any{"ok": false, "code": "reinstall_invalid_mounts", "error": err.Error() + ". No server files were replaced."})
|
|
default:
|
|
fmt.Printf("[reinstall] Could not stage image files for %s: %v\n", name, err)
|
|
jsonWrite(w, http.StatusInternalServerError, map[string]any{"ok": false, "error": "Could not stage files from the runtime image. No server files were replaced."})
|
|
}
|
|
return
|
|
}
|
|
}
|
|
if err := a.validateReinstallMounts(template, stagedRuntime, serverDir, stagingDir); err != nil {
|
|
jsonWrite(w, http.StatusBadRequest, map[string]any{
|
|
"ok": false, "code": "reinstall_invalid_mounts",
|
|
"error": "Invalid replacement mounts: " + err.Error() + ". No server files were replaced.",
|
|
})
|
|
return
|
|
}
|
|
bindings := a.reinstallPortBindings(name, serverDir, template, hostPort, meta, oldMeta, runtimeConfig)
|
|
if status, reason, stopped := a.stopForReinstall(r.Context(), name, serverDir, bindings); reason != "" {
|
|
if stopped {
|
|
reason = "The old container was stopped. " + reason
|
|
}
|
|
jsonWrite(w, status, map[string]any{"ok": false, "error": reason, "serverStopped": stopped})
|
|
return
|
|
}
|
|
var handoff reinstallFileHandoff
|
|
if code, err := a.commitReinstallFiles(serverDir, stagingDir, meta, &handoff); err != nil {
|
|
fmt.Printf("[reinstall] Failed to commit replacement for %s: %v\n", name, err)
|
|
if code == reinstallStartupPendingCode {
|
|
writeReinstallStartupPending(w)
|
|
return
|
|
}
|
|
message := "replacement files could not be committed"
|
|
switch code {
|
|
case "reinstall_meta_save_failed":
|
|
message = "rebuilt metadata could not be saved"
|
|
case "reinstall_cleanup_failed":
|
|
message = "replacement files were committed but the previous files could not be fully removed"
|
|
}
|
|
jsonWrite(w, http.StatusInternalServerError, map[string]any{
|
|
"ok": false, "code": code, "serverStopped": true, "reinstalled": code == "reinstall_cleanup_failed",
|
|
"error": message + "; contact an administrator before retrying",
|
|
})
|
|
return
|
|
}
|
|
handoff.image = preparedImage
|
|
a.finishReinstallServer(w, r, name, serverDir, template, hostPort, meta, runtimeConfig, &handoff)
|
|
}
|
|
|
|
// adpanel:reinstall-preflight - reject invalid runtime configuration before
|
|
// destroying the existing server, including images rejected by node policy.
|
|
func (a *Agent) preflightReinstallRuntime(ctx context.Context, name, template string, runtimeConfig map[string]any) (int, string) {
|
|
// adpanel:reinstall-managed-image - resolve the same image startup
|
|
// will use before the wipe, including missing legacy image metadata.
|
|
if isManagedProcessRuntime(template) {
|
|
image, tag := managedRuntimeImage(template, runtimeConfig)
|
|
runtimeConfig["image"], runtimeConfig["tag"] = image, tag
|
|
}
|
|
if reason := validateADPanelStartupScript(startupTemplateFromRuntime(runtimeConfig)); reason != "" {
|
|
return http.StatusBadRequest, reason
|
|
}
|
|
install := installConfigFromRuntime(runtimeConfig)
|
|
if install != nil {
|
|
if reason := validateTemplateInstallScript(install.Script); reason != "" {
|
|
return http.StatusBadRequest, reason
|
|
}
|
|
if reason := validateTemplateImageRef(install.Image); reason != "" {
|
|
return http.StatusBadRequest, reason
|
|
}
|
|
}
|
|
if image, ok := runtimeConfig["image"].(string); ok && strings.TrimSpace(image) != "" {
|
|
image = strings.TrimSpace(image)
|
|
tag := "latest"
|
|
if configuredTag, ok := runtimeConfig["tag"].(string); ok && strings.TrimSpace(configuredTag) != "" {
|
|
tag = strings.TrimSpace(configuredTag)
|
|
}
|
|
if !strings.Contains(image, "/") {
|
|
image = "docker.io/library/" + image
|
|
}
|
|
if reason := validateTemplateImageRef(image + ":" + tag); reason != "" {
|
|
return http.StatusBadRequest, reason
|
|
}
|
|
runtimeConfig["image"] = image
|
|
}
|
|
// adpanel:reinstall-image-preflight - an unavailable image must not
|
|
// stop the existing container or erase its files.
|
|
images := []string{runtimeImageRef(runtimeConfig)}
|
|
if install != nil {
|
|
images = append(images, install.Image)
|
|
}
|
|
if err := a.prepareReinstallImages(ctx, images...); err != nil {
|
|
fmt.Printf("[reinstall] Failed to prepare image for %s: %v\n", name, err)
|
|
return http.StatusInternalServerError, "a required Docker image could not be prepared; no server files were replaced"
|
|
}
|
|
return http.StatusOK, ""
|
|
}
|
|
|
|
func (a *Agent) prepareReinstallImages(ctx context.Context, images ...string) error {
|
|
pullCtx, pullCancel := context.WithTimeout(ctx, 10*time.Minute)
|
|
defer pullCancel()
|
|
for _, image := range images {
|
|
if image == "" {
|
|
continue
|
|
}
|
|
if err := a.docker.ensureImageAvailableAPI(pullCtx, image); err != nil {
|
|
return fmt.Errorf("prepare %q: %w", image, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *Agent) reinstallPortBindings(name, serverDir, template string, hostPort int, meta, oldMeta, runtimeConfig map[string]any) map[string][]dockerPortBinding {
|
|
managed := isManagedProcessRuntime(template)
|
|
if template == "minecraft" {
|
|
runtimeConfig, _ = meta["runtime"].(map[string]any)
|
|
} else {
|
|
meta["runtime"] = runtimeConfig
|
|
if image, _ := runtimeConfig["image"].(string); !managed && strings.TrimSpace(image) == "" {
|
|
return nil
|
|
}
|
|
}
|
|
containerPort := serverPrimaryContainerPort(name, template, runtimeConfig, hostPort, resourceLimitsFromMeta(meta))
|
|
// adpanel:reinstall-rebound-protocol - an incomplete panel snapshot must
|
|
// not erase the saved policy when a host-port-based runtime is rebound.
|
|
if runtimeConfig != nil && reinstallKeepsRuntime(template, oldMeta) {
|
|
protocols := runtimePortProtocolMap(runtimeConfig["portProtocols"])
|
|
oldRuntime, _ := oldMeta["runtime"].(map[string]any)
|
|
if protocols == nil {
|
|
protocols = make(map[int][]string)
|
|
}
|
|
for port, values := range runtimePortProtocolMap(oldRuntime["portProtocols"]) {
|
|
if len(protocols[port]) == 0 {
|
|
protocols[port] = values
|
|
}
|
|
}
|
|
if previousPort, valid := parseStrictPortValue(oldMeta["hostPort"]); valid && previousPort != hostPort && template != "minecraft" && containerPort == hostPort && len(protocols[containerPort]) == 0 {
|
|
previousContainerPort := previousPort
|
|
if !managed {
|
|
_, previousContainerPort = customRuntimeEnvironmentAndPort(name, template, startupTemplateFromRuntime(oldRuntime), oldRuntime, previousPort, resourceLimitsFromMeta(oldMeta))
|
|
}
|
|
if previousContainerPort == previousPort && len(protocols[previousPort]) > 0 {
|
|
protocols[containerPort] = protocols[previousPort]
|
|
}
|
|
}
|
|
if len(protocols) > 0 {
|
|
runtimeConfig["portProtocols"] = protocols
|
|
}
|
|
}
|
|
bindings, _ := a.buildStructuredPortBindings(serverDir, meta, hostPort, containerPort)
|
|
return bindings
|
|
}
|
|
|
|
// adpanel:reinstall-port-preflight - refuse conflicts before interrupting the
|
|
// live server, and recheck bindings it held after the container releases them.
|
|
func (a *Agent) checkReinstallPortBindings(ctx context.Context, bindings map[string][]dockerPortBinding, currentName string, currentBindings map[string][]dockerPortBinding) (int, string) {
|
|
status, reason := a.checkServerPortBindings(ctx, bindings, currentName, currentBindings)
|
|
if reason != "" {
|
|
return status, reason + "; no server files were replaced"
|
|
}
|
|
return status, ""
|
|
}
|
|
|
|
func (a *Agent) checkServerPortBindings(ctx context.Context, bindings map[string][]dockerPortBinding, currentName string, currentBindings map[string][]dockerPortBinding) (int, string) {
|
|
type hostProtocol struct{ port, protocol string }
|
|
currentIPs := make(map[hostProtocol][]string)
|
|
for containerBinding, hostBindings := range currentBindings {
|
|
_, protocol, _ := strings.Cut(containerBinding, "/")
|
|
for _, binding := range hostBindings {
|
|
key := hostProtocol{binding.HostPort, protocol}
|
|
currentIPs[key] = append(currentIPs[key], binding.HostIP)
|
|
}
|
|
}
|
|
protocolsByBinding := make(map[dockerPortBinding][]string)
|
|
for containerBinding, hostBindings := range bindings {
|
|
_, protocol, _ := strings.Cut(containerBinding, "/")
|
|
for _, binding := range hostBindings {
|
|
needsRelease := false
|
|
for _, currentIP := range currentIPs[hostProtocol{binding.HostPort, protocol}] {
|
|
if currentIP == "" || currentIP == binding.HostIP || net.ParseIP(currentIP).IsUnspecified() || net.ParseIP(binding.HostIP).IsUnspecified() {
|
|
needsRelease = true
|
|
break
|
|
}
|
|
}
|
|
if !needsRelease {
|
|
protocolsByBinding[binding] = append(protocolsByBinding[binding], protocol)
|
|
}
|
|
}
|
|
}
|
|
ctx, cancel := context.WithTimeout(ctx, 6*time.Second)
|
|
defer cancel()
|
|
for binding, protocols := range protocolsByBinding {
|
|
port, _ := strconv.Atoi(binding.HostPort)
|
|
available, _, _ := a.hostBindingAvailability(ctx, port, protocols, currentName, binding.HostIP)
|
|
if ctx.Err() != nil {
|
|
return http.StatusServiceUnavailable, "required host ports could not be verified"
|
|
}
|
|
if !available {
|
|
return http.StatusConflict, fmt.Sprintf("required host port %d is in use", port)
|
|
}
|
|
}
|
|
return http.StatusOK, ""
|
|
}
|
|
|
|
func (a *Agent) stopForReinstall(ctx context.Context, name, serverDir string, bindings map[string][]dockerPortBinding) (status int, reason string, stopped bool) {
|
|
if ctx.Err() != nil {
|
|
return http.StatusRequestTimeout, reinstallCanceledBeforeCommit, false
|
|
}
|
|
// adpanel:reinstall-container-owner - even a replacement with no ports
|
|
// must not tear down a container whose ownership check failed.
|
|
inspectCtx, cancel := context.WithTimeout(ctx, 6*time.Second)
|
|
current, currentName, exists, err := a.inspectContainerForStats(inspectCtx, name)
|
|
cancel()
|
|
if ctx.Err() != nil {
|
|
return http.StatusRequestTimeout, reinstallCanceledBeforeCommit, false
|
|
}
|
|
if err != nil {
|
|
fmt.Printf("[reinstall] Failed to verify existing container for %s: %v\n", name, err)
|
|
return http.StatusServiceUnavailable, "existing container ownership or ports could not be verified; no server files were replaced", false
|
|
}
|
|
// adpanel:reinstall-legacy-ownership - a same-name unlabeled container must also mount this server's files.
|
|
if _, labeled := dockerServerLabel(current.Labels, current.Config); exists && !labeled && !hasReinstallServerBind(current.Mounts, serverDir) {
|
|
return http.StatusServiceUnavailable, "existing container ownership could not be verified; no server files were replaced", false
|
|
}
|
|
// adpanel:reinstall-volume-ownership - rollback protects the server tree, not Docker-managed volumes.
|
|
for _, mount := range current.Mounts {
|
|
if mount.Type == "volume" {
|
|
return http.StatusConflict, "The current container uses Docker-managed volumes outside the server backup and rollback scope. Migrate their data into a server-directory mount before reinstalling. No server files were replaced.", false
|
|
}
|
|
}
|
|
var currentBindings map[string][]dockerPortBinding
|
|
if exists && current.State.Running {
|
|
currentBindings = current.HostConfig.PortBindings
|
|
}
|
|
status, reason = a.checkReinstallPortBindings(ctx, bindings, currentName, currentBindings)
|
|
if ctx.Err() != nil {
|
|
return http.StatusRequestTimeout, reinstallCanceledBeforeCommit, false
|
|
}
|
|
if reason != "" {
|
|
return status, reason, false
|
|
}
|
|
if exists && !validDockerContainerID(current.ID) {
|
|
return http.StatusServiceUnavailable, "existing container identity could not be verified; no server files were replaced", false
|
|
}
|
|
a.logs.killTail(name)
|
|
// adpanel:reinstall-container-id - do not re-resolve an inspected container by name during removal.
|
|
if exists {
|
|
step, failure := "stop", "failed to stop the existing server container gracefully"
|
|
var teardownErr error
|
|
teardownCtx := context.WithoutCancel(ctx)
|
|
stopped = reinstallContainerIsStopped(current.State)
|
|
if current.State.Running {
|
|
stopCtx, stopCancel := context.WithTimeout(teardownCtx, 30*time.Second)
|
|
teardownErr = a.docker.stop(stopCtx, current.ID)
|
|
stopCancel()
|
|
stopped = teardownErr == nil
|
|
}
|
|
if teardownErr == nil && ctx.Err() == nil {
|
|
step, failure = "remove", "failed to remove existing server container"
|
|
removeCtx, removeCancel := context.WithTimeout(teardownCtx, 30*time.Second)
|
|
teardownErr = a.docker.removeContainerAPI(removeCtx, current.ID, false)
|
|
removeCancel()
|
|
stopped = teardownErr == nil
|
|
}
|
|
if teardownErr != nil {
|
|
inspectCtx, inspectCancel := context.WithTimeout(context.Background(), 1500*time.Millisecond)
|
|
inspected, inspectErr := a.docker.inspectContainerAPI(inspectCtx, current.ID)
|
|
inspectCancel()
|
|
stopped = inspectErr == nil && reinstallContainerIsStopped(inspected.State)
|
|
}
|
|
if ctx.Err() != nil {
|
|
return http.StatusRequestTimeout, reinstallCanceledBeforeCommit, stopped
|
|
}
|
|
if teardownErr != nil {
|
|
fmt.Printf("[reinstall] Failed to %s container %s: %v\n", step, name, teardownErr)
|
|
return http.StatusInternalServerError, failure + "; no server files were replaced", stopped
|
|
}
|
|
fmt.Printf("[reinstall] Container removed for %s\n", name)
|
|
}
|
|
a.clearPendingServerStop(name)
|
|
if a.stdinMgr != nil {
|
|
a.stdinMgr.remove(name)
|
|
if currentName != "" && currentName != dockerContainerName(name) {
|
|
a.stdinMgr.remove(currentName)
|
|
}
|
|
}
|
|
|
|
status, reason = a.checkReinstallPortBindings(ctx, bindings, "", nil)
|
|
if ctx.Err() != nil {
|
|
return http.StatusRequestTimeout, reinstallCanceledBeforeCommit, true
|
|
}
|
|
return status, reason, true
|
|
}
|
|
|
|
func reinstallContainerIsStopped(state dockerContainerStateForStats) bool {
|
|
return !state.Running && (state.Status == "created" || state.Status == "exited" || state.Status == "dead")
|
|
}
|
|
|
|
func hasReinstallServerBind(mounts []dockerContainerMount, serverDir string) bool {
|
|
resolvedServer, err := filepath.EvalSymlinks(serverDir)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
for _, mount := range mounts {
|
|
if mount.Type != "bind" || !filepath.IsAbs(mount.Source) {
|
|
continue
|
|
}
|
|
if resolvedMount, err := filepath.EvalSymlinks(mount.Source); err == nil && (resolvedMount == resolvedServer || isUnder(resolvedServer, resolvedMount)) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// adpanel:reinstall-file-commit - keep the original tree and a recovery record
|
|
// until the replacement files and their matching metadata are both published.
|
|
type reinstallFileHandoff struct {
|
|
rollbackDir string
|
|
replacement uint64
|
|
image reinstallRuntimeImage
|
|
}
|
|
|
|
type reinstallRuntimeImage struct {
|
|
config imageConfig
|
|
}
|
|
|
|
func (handoff *reinstallFileHandoff) containerLabel() string {
|
|
return filepath.Base(handoff.rollbackDir)
|
|
}
|
|
|
|
func (a *Agent) commitReinstallFiles(serverDir, stagingDir string, meta map[string]any, retained ...*reinstallFileHandoff) (code string, err error) {
|
|
original, err := reinstallDirectoryInode(serverDir)
|
|
if err != nil {
|
|
return "reinstall_file_replace_failed", err
|
|
}
|
|
replacement, err := reinstallDirectoryInode(stagingDir)
|
|
if err != nil {
|
|
return "reinstall_file_replace_failed", err
|
|
}
|
|
rollbackDir, err := os.MkdirTemp(filepath.Dir(serverDir), "."+filepath.Base(serverDir)+reinstallRollbackMarker)
|
|
if err != nil {
|
|
return "reinstall_file_replace_failed", err
|
|
}
|
|
oldDir := filepath.Join(rollbackDir, "previous")
|
|
newDir := filepath.Join(rollbackDir, "replacement")
|
|
movedOld, committed := false, false
|
|
defer func() {
|
|
if committed && len(retained) != 0 {
|
|
return
|
|
}
|
|
if !committed && movedOld {
|
|
if restoreErr := restoreReinstallFiles(serverDir, rollbackDir, replacement); restoreErr != nil {
|
|
code = reinstallStartupPendingCode
|
|
err = errors.Join(err, fmt.Errorf("restore original directory: %w; original files retained at %s", restoreErr, oldDir))
|
|
return
|
|
}
|
|
}
|
|
if cleanupErr := removeReinstallRollback(rollbackDir); cleanupErr != nil {
|
|
cleanupErr = fmt.Errorf("remove rollback directory %s: %w", rollbackDir, cleanupErr)
|
|
if committed {
|
|
code = "reinstall_cleanup_failed"
|
|
}
|
|
err = errors.Join(err, cleanupErr)
|
|
}
|
|
}()
|
|
if err := a.recordReinstallRollbackMetadata(serverDir, rollbackDir, original, replacement); err != nil {
|
|
return "reinstall_meta_save_failed", err
|
|
}
|
|
if err := os.Rename(stagingDir, newDir); err != nil {
|
|
return "reinstall_file_replace_failed", err
|
|
}
|
|
if err := os.Rename(serverDir, oldDir); err != nil {
|
|
return "reinstall_file_replace_failed", err
|
|
}
|
|
movedOld = true
|
|
if err := os.Rename(newDir, serverDir); err != nil {
|
|
return "reinstall_file_replace_failed", err
|
|
}
|
|
committedMeta := maps.Clone(meta)
|
|
committedMeta[reinstallCommitMetadataKey] = filepath.Base(rollbackDir)
|
|
if len(retained) != 0 {
|
|
committedMeta[reinstallPendingStartupKey] = true
|
|
}
|
|
if err := a.saveMeta(serverDir, committedMeta); err != nil {
|
|
return "reinstall_meta_save_failed", err
|
|
}
|
|
committed = true
|
|
if len(retained) != 0 {
|
|
*retained[0] = reinstallFileHandoff{rollbackDir: rollbackDir, replacement: replacement}
|
|
}
|
|
return "", nil
|
|
}
|
|
|
|
type reinstallRollbackState struct {
|
|
MetadataDigest [sha256.Size]byte
|
|
Original uint64
|
|
Replacement uint64
|
|
PreviousMeta []byte `json:",omitempty"`
|
|
}
|
|
|
|
func reinstallDirectoryInode(path string) (uint64, error) {
|
|
info, err := os.Lstat(path)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
stat, ok := info.Sys().(*syscall.Stat_t)
|
|
if !info.IsDir() || !ok {
|
|
return 0, fmt.Errorf("%s is not a verifiable directory", path)
|
|
}
|
|
return uint64(stat.Ino), nil
|
|
}
|
|
|
|
func (a *Agent) recordReinstallRollbackMetadata(serverDir, rollbackDir string, original, replacement uint64) error {
|
|
data, err := os.ReadFile(a.metaPath(filepath.Base(serverDir)))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
record, err := json.Marshal(reinstallRollbackState{MetadataDigest: sha256.Sum256(data), Original: original, Replacement: replacement, PreviousMeta: data})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return os.WriteFile(filepath.Join(rollbackDir, reinstallRollbackMetadataFile), record, 0o600)
|
|
}
|
|
|
|
func restoreReinstallFiles(serverDir, rollbackDir string, replacementInode uint64) error {
|
|
if live, err := reinstallDirectoryInode(serverDir); err == nil {
|
|
if same, err := sameDevice(serverDir, rollbackDir); err != nil || !same || live != replacementInode {
|
|
return fmt.Errorf("live server path is not the recorded replacement directory")
|
|
}
|
|
replacement := filepath.Join(rollbackDir, "replacement")
|
|
if _, err := os.Lstat(replacement); !os.IsNotExist(err) {
|
|
return fmt.Errorf("cannot safely move replacement directory aside: %v", err)
|
|
}
|
|
if err := os.Rename(serverDir, replacement); err != nil {
|
|
return err
|
|
}
|
|
} else if !os.IsNotExist(err) {
|
|
return err
|
|
}
|
|
return os.Rename(filepath.Join(rollbackDir, "previous"), serverDir)
|
|
}
|
|
|
|
func removeReinstallRollback(rollbackDir string) error {
|
|
for _, tree := range []string{"previous", "replacement"} {
|
|
if err := os.RemoveAll(filepath.Join(rollbackDir, tree)); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return os.RemoveAll(rollbackDir)
|
|
}
|
|
|
|
func verifyReinstallRollback(handoff *reinstallFileHandoff) (reinstallRollbackState, error) {
|
|
var state reinstallRollbackState
|
|
data, err := os.ReadFile(filepath.Join(handoff.rollbackDir, reinstallRollbackMetadataFile))
|
|
if err != nil {
|
|
return state, err
|
|
}
|
|
if err := json.Unmarshal(data, &state); err != nil || state.Replacement != handoff.replacement || len(state.PreviousMeta) == 0 || sha256.Sum256(state.PreviousMeta) != state.MetadataDigest {
|
|
return state, fmt.Errorf("previous reinstall metadata could not be verified")
|
|
}
|
|
previous, err := reinstallDirectoryInode(filepath.Join(handoff.rollbackDir, "previous"))
|
|
if err != nil || previous != state.Original {
|
|
return state, fmt.Errorf("original reinstall files could not be verified")
|
|
}
|
|
return state, nil
|
|
}
|
|
|
|
func (a *Agent) rollbackFailedReinstall(serverDir string, handoff *reinstallFileHandoff) error {
|
|
state, err := verifyReinstallRollback(handoff)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := restoreReinstallFiles(serverDir, handoff.rollbackDir, handoff.replacement); err != nil {
|
|
return err
|
|
}
|
|
if err := writeServerMetadata(a.metaPath(filepath.Base(serverDir)), state.PreviousMeta); err != nil {
|
|
return err
|
|
}
|
|
if err := removeReinstallRollback(handoff.rollbackDir); err != nil {
|
|
fmt.Printf("[reinstall] Restored original files but could not clean %s: %v\n", handoff.rollbackDir, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *Agent) saveReinstallOutcome(serverDir string, handoff *reinstallFileHandoff, outcome string, confirmed bool) error {
|
|
meta, err := a.loadMetaChecked(serverDir, true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if meta[reinstallCommitMetadataKey] != filepath.Base(handoff.rollbackDir) {
|
|
return fmt.Errorf("replacement metadata no longer matches this operation")
|
|
}
|
|
if confirmed {
|
|
delete(meta, reinstallPendingStartupKey)
|
|
}
|
|
meta[reinstallOutcomeMetadataKey] = outcome
|
|
return a.saveMeta(serverDir, meta)
|
|
}
|
|
|
|
func (handoff *reinstallFileHandoff) ownsContainer(container dockerContainerInspectForStats) bool {
|
|
labels := container.Config.Labels
|
|
if labels == nil {
|
|
labels = container.Labels
|
|
}
|
|
_, owned := dockerServerLabel(container.Labels, container.Config)
|
|
return owned && validDockerContainerID(container.ID) && labels[reinstallContainerLabel] == handoff.containerLabel()
|
|
}
|
|
|
|
func (a *Agent) discardReinstallContainer(ctx context.Context, handoff *reinstallFileHandoff, container dockerContainerInspectForStats) bool {
|
|
if !handoff.ownsContainer(container) {
|
|
return false
|
|
}
|
|
if container.State.Running {
|
|
if a.docker.stop(ctx, container.ID) != nil {
|
|
return false
|
|
}
|
|
} else if !reinstallContainerIsStopped(container.State) {
|
|
return false
|
|
}
|
|
return a.docker.removeContainerAPI(ctx, container.ID, false) == nil
|
|
}
|
|
|
|
// adpanel:reinstall-startup-observation - a transient running state from a
|
|
// crash-looping replacement must not release the only rollback copy.
|
|
func (a *Agent) inspectReinstallStartup(ctx context.Context, name string, handoff *reinstallFileHandoff, observe bool) (container dockerContainerInspectForStats, exists, stable bool, err error) {
|
|
inspect := func() (dockerContainerInspectForStats, bool, error) {
|
|
inspectCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
|
defer cancel()
|
|
container, _, exists, err := a.inspectContainerForStats(inspectCtx, name)
|
|
return container, exists, err
|
|
}
|
|
isRunning := func(container dockerContainerInspectForStats) bool {
|
|
state := container.State
|
|
return state.Running && state.Status == "running" && state.Health.Status != "unhealthy" && (handoff == nil || handoff.ownsContainer(container))
|
|
}
|
|
initial, exists, err := inspect()
|
|
if err != nil || !exists || !isRunning(initial) {
|
|
return initial, exists, false, err
|
|
}
|
|
if !observe || handoff == nil {
|
|
return initial, true, true, nil
|
|
}
|
|
stableAfter := time.Now().Add(reinstallStartupObservation)
|
|
if startedAt, parseErr := time.Parse(time.RFC3339Nano, initial.State.StartedAt); parseErr == nil && !startedAt.After(time.Now()) {
|
|
stableAfter = startedAt.Add(reinstallStartupObservation)
|
|
}
|
|
container = initial
|
|
for {
|
|
wait := time.Until(stableAfter)
|
|
if container.State.Health.Status == "starting" {
|
|
wait = time.Second
|
|
} else if wait <= 0 {
|
|
return container, true, true, nil
|
|
}
|
|
timer := time.NewTimer(wait)
|
|
select {
|
|
case <-ctx.Done():
|
|
timer.Stop()
|
|
return container, true, false, ctx.Err()
|
|
case <-timer.C:
|
|
}
|
|
container, exists, err = inspect()
|
|
if err != nil || !exists || !isRunning(container) || !sameDockerContainerRun(initial, container) {
|
|
return container, exists, false, err
|
|
}
|
|
}
|
|
}
|
|
|
|
// adpanel:reinstall-outcome-recovery - resolve an uncertain startup only with verified files and Docker ownership.
|
|
func (a *Agent) reconcileReinstallStartup(ctx context.Context, name, serverDir string, meta map[string]any) bool {
|
|
rollbackName, _ := meta[reinstallCommitMetadataKey].(string)
|
|
if reinstallRollbackServerName(rollbackName) != name {
|
|
return false
|
|
}
|
|
a.beginLongOp(name, longOpReinstall)
|
|
defer a.endLongOp(name)
|
|
ctx, cancel := context.WithTimeout(ctx, reinstallRecoveryBudget)
|
|
defer cancel()
|
|
storageCtx, storageCancel := context.WithTimeout(ctx, 6*time.Second)
|
|
releaseStorage, err := a.acquireUploadScope(storageCtx, a.fsScopeRootFor(name, serverDir))
|
|
storageCancel()
|
|
if err != nil {
|
|
return false
|
|
}
|
|
defer releaseStorage()
|
|
rollbackDir := filepath.Join(filepath.Dir(serverDir), rollbackName)
|
|
if _, err := reinstallDirectoryInode(filepath.Join(rollbackDir, "replacement")); err == nil {
|
|
if err := a.recoverReinstallFiles(a.allDiskVolumeRoots(), serverDir, rollbackDir); err != nil {
|
|
return false
|
|
}
|
|
recovered, err := a.loadMetaChecked(serverDir, true)
|
|
return err == nil && recovered[reinstallPendingStartupKey] != true
|
|
}
|
|
replacement, err := reinstallDirectoryInode(serverDir)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
handoff := &reinstallFileHandoff{rollbackDir: rollbackDir, replacement: replacement}
|
|
if _, err := verifyReinstallRollback(handoff); err != nil {
|
|
return false
|
|
}
|
|
startupAcknowledged := meta[reinstallOutcomeMetadataKey] == "running"
|
|
container, exists, stable, err := a.inspectReinstallStartup(ctx, name, handoff, startupAcknowledged)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
if exists {
|
|
if !handoff.ownsContainer(container) {
|
|
return false
|
|
}
|
|
if startupAcknowledged && stable {
|
|
if a.saveReinstallOutcome(serverDir, handoff, "running", true) != nil {
|
|
return false
|
|
}
|
|
if err := removeReinstallRollback(handoff.rollbackDir); err != nil {
|
|
fmt.Printf("[reinstall] Could not remove previous files for %s: %v\n", name, err)
|
|
}
|
|
a.ensureLiveLogs(name)
|
|
return true
|
|
}
|
|
if !a.discardReinstallContainer(ctx, handoff, container) {
|
|
return false
|
|
}
|
|
}
|
|
if err := a.rollbackFailedReinstall(serverDir, handoff); err != nil {
|
|
fmt.Printf("[reinstall] Could not restore previous files for %s: %v\n", name, err)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (a *Agent) recoverReinstallFiles(roots []string, serverDir, rollbackDir string) error {
|
|
previous, err := reinstallDirectoryInode(filepath.Join(rollbackDir, "previous"))
|
|
hasPrevious := err == nil
|
|
if !hasPrevious && !os.IsNotExist(err) {
|
|
return err
|
|
}
|
|
record, err := os.ReadFile(filepath.Join(rollbackDir, reinstallRollbackMetadataFile))
|
|
if err != nil {
|
|
if !hasPrevious && os.IsNotExist(err) {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("reinstall recovery record is unavailable: %w", err)
|
|
}
|
|
var state reinstallRollbackState
|
|
if err := json.Unmarshal(record, &state); err != nil || state.Original == 0 || state.Replacement == 0 || state.Replacement == state.Original ||
|
|
(hasPrevious && state.Original != previous) {
|
|
return fmt.Errorf("reinstall recovery record does not match the original files")
|
|
}
|
|
staged, stagedErr := reinstallDirectoryInode(filepath.Join(rollbackDir, "replacement"))
|
|
if !os.IsNotExist(stagedErr) && (stagedErr != nil || staged != state.Replacement) {
|
|
return fmt.Errorf("reinstall recovery record does not match the staged files")
|
|
}
|
|
name := filepath.Base(serverDir)
|
|
data, err := os.ReadFile(a.metaPath(name))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var meta map[string]any
|
|
if err := json.Unmarshal(data, &meta); err != nil {
|
|
return err
|
|
}
|
|
if diskID, _ := meta["__diskId"].(string); strings.TrimSpace(diskID) != "" {
|
|
if _, ok := a.diskByID(diskID); !ok || a.serverVolumesRoot(name) != filepath.Dir(serverDir) {
|
|
return fmt.Errorf("server is not assigned to this volume")
|
|
}
|
|
} else {
|
|
for _, root := range roots {
|
|
if root != filepath.Dir(serverDir) {
|
|
if _, err := os.Lstat(filepath.Join(root, name)); !os.IsNotExist(err) {
|
|
return fmt.Errorf("legacy server's volume ownership is ambiguous")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if commitID, _ := meta[reinstallCommitMetadataKey].(string); commitID == filepath.Base(rollbackDir) {
|
|
live, liveErr := reinstallDirectoryInode(serverDir)
|
|
if meta[reinstallPendingStartupKey] == true {
|
|
if stagedErr != nil || (hasPrevious && !os.IsNotExist(liveErr)) || (!hasPrevious && (liveErr != nil || live != state.Original)) ||
|
|
len(state.PreviousMeta) == 0 || sha256.Sum256(state.PreviousMeta) != state.MetadataDigest {
|
|
return fmt.Errorf("replacement startup was never confirmed; both file trees were retained")
|
|
}
|
|
if hasPrevious {
|
|
if err := restoreReinstallFiles(serverDir, rollbackDir, state.Replacement); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if err := writeServerMetadata(a.metaPath(name), state.PreviousMeta); err != nil {
|
|
return err
|
|
}
|
|
} else if liveErr != nil || live != state.Replacement {
|
|
return fmt.Errorf("committed replacement directory is unavailable")
|
|
}
|
|
} else {
|
|
if sha256.Sum256(data) != state.MetadataDigest {
|
|
return fmt.Errorf("server metadata no longer matches this reinstall")
|
|
}
|
|
if hasPrevious {
|
|
if err := restoreReinstallFiles(serverDir, rollbackDir, state.Replacement); err != nil {
|
|
return err
|
|
}
|
|
} else if live, err := reinstallDirectoryInode(serverDir); err != nil || live != state.Original {
|
|
return fmt.Errorf("original directory is unavailable for reinstall recovery")
|
|
}
|
|
}
|
|
return removeReinstallRollback(rollbackDir)
|
|
}
|
|
|
|
func reinstallRollbackServerName(directory string) string {
|
|
marker := strings.LastIndex(directory, reinstallRollbackMarker)
|
|
if !strings.HasPrefix(directory, ".") || marker <= 1 {
|
|
return ""
|
|
}
|
|
name := directory[1:marker]
|
|
if _, err := strconv.ParseUint(directory[marker+len(reinstallRollbackMarker):], 10, 32); err != nil || sanitizeName(name) != name {
|
|
return ""
|
|
}
|
|
return name
|
|
}
|
|
|
|
// adpanel:reinstall-absence - metadata may still describe the original
|
|
// server even after its directory was detached by an incomplete handoff.
|
|
func reinstallCanReportAbsence(serverDir string, meta map[string]any) bool {
|
|
if _, err := reinstallDirectoryInode(serverDir); err != nil {
|
|
return false
|
|
}
|
|
entries, err := os.ReadDir(filepath.Dir(serverDir))
|
|
if err != nil {
|
|
return false
|
|
}
|
|
for _, entry := range entries {
|
|
if entry.IsDir() && reinstallRollbackServerName(entry.Name()) == filepath.Base(serverDir) && entry.Name() != meta[reinstallCommitMetadataKey] {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (a *Agent) recoverInterruptedServerOperations() {
|
|
a.cleanupPendingDeletes()
|
|
roots := a.allDiskVolumeRoots()
|
|
for _, root := range roots {
|
|
entries, err := os.ReadDir(root)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, entry := range entries {
|
|
dirName := entry.Name()
|
|
name := reinstallRollbackServerName(dirName)
|
|
if !entry.IsDir() || name == "" {
|
|
continue
|
|
}
|
|
rollbackDir := filepath.Join(root, dirName)
|
|
if err := a.recoverReinstallFiles(roots, filepath.Join(root, name), rollbackDir); err != nil {
|
|
fmt.Printf("[reinstall] Recovery needs administrator attention at %s: %v\n", rollbackDir, err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// adpanel:reinstall-download-quota - the temporary replacement must fit
|
|
// alongside existing files and backups under both storage limits.
|
|
func (a *Agent) reinstallDownloader(serverDir string, stagedBytes int64) (Downloader, error) {
|
|
downloader := a.quotaGuardedDownloader(serverDir)
|
|
serverQuotaCheck := downloader.quotaCheck
|
|
diskAllowance, _, _, diskLimited, diskError := a.diskCapacityAllowanceForPath(serverDir)
|
|
if diskError != nil || (diskLimited && diskAllowance <= 0) {
|
|
return Downloader{}, errDownloadQuotaExceeded
|
|
}
|
|
if diskLimited || serverQuotaCheck != nil {
|
|
downloader.quotaCheck = func(written int64) error {
|
|
if diskLimited && written > diskAllowance {
|
|
return errDownloadQuotaExceeded
|
|
}
|
|
if serverQuotaCheck != nil {
|
|
return serverQuotaCheck(written + stagedBytes)
|
|
}
|
|
return nil
|
|
}
|
|
if err := downloader.quotaCheck(0); err != nil {
|
|
return Downloader{}, err
|
|
}
|
|
}
|
|
return downloader, nil
|
|
}
|
|
|
|
func configureMinecraftReinstall(meta, runtimeConfig map[string]any) error {
|
|
fork, version, selectionError := reinstallMinecraftSelection(meta)
|
|
if selectionError != nil {
|
|
return selectionError
|
|
}
|
|
minecraftImage := defaultMinecraftProcessImage
|
|
minecraftTag := defaultMinecraftProcessTag
|
|
minecraftCommand := defaultMinecraftProcessCommand
|
|
minecraftWorkdir := defaultDataDirForType("minecraft")
|
|
rawJavaVersion := normalizeTemplateIdentifier(runtimeConfig["javaVersion"])
|
|
javaVersion := normalizeMinecraftJavaVersion(rawJavaVersion)
|
|
if rawJavaVersion != "" && javaVersion == "" {
|
|
return fmt.Errorf("unsupported minecraft java version")
|
|
}
|
|
storedImageRef := ""
|
|
if javaVersion == "" {
|
|
storedImageRef = runtimeImageRef(runtimeConfig)
|
|
}
|
|
if image, ok := runtimeConfig["image"].(string); ok && strings.TrimSpace(image) != "" {
|
|
minecraftImage = strings.TrimSpace(image)
|
|
}
|
|
if tag, ok := runtimeConfig["tag"].(string); ok && strings.TrimSpace(tag) != "" {
|
|
minecraftTag = strings.TrimSpace(tag)
|
|
}
|
|
if command, ok := runtimeConfig["command"].(string); ok && strings.TrimSpace(command) != "" {
|
|
minecraftCommand = strings.TrimSpace(command)
|
|
}
|
|
if workdir, ok := runtimeConfig["workdir"].(string); ok && strings.TrimSpace(workdir) != "" {
|
|
minecraftWorkdir = strings.TrimSpace(workdir)
|
|
}
|
|
if javaVersion == "" {
|
|
javaVersion = minecraftJavaVersionFromTag(minecraftTag)
|
|
}
|
|
if javaVersion != "" {
|
|
minecraftImage = defaultMinecraftProcessImage
|
|
minecraftTag = minecraftJavaTag(javaVersion)
|
|
}
|
|
for _, imageRef := range []string{storedImageRef, minecraftImage + ":" + minecraftTag} {
|
|
if imageRef == "" {
|
|
continue
|
|
}
|
|
if !strings.Contains(imageRef, "/") {
|
|
imageRef = "docker.io/library/" + imageRef
|
|
}
|
|
if reason := validateTemplateImageRef(imageRef); reason != "" {
|
|
return errors.New(reason)
|
|
}
|
|
}
|
|
|
|
minecraftRuntime := map[string]any{
|
|
"image": minecraftImage, "tag": minecraftTag, "command": minecraftCommand,
|
|
"workdir": minecraftWorkdir, "javaVersion": javaVersion,
|
|
}
|
|
// adpanel:reinstall-protocol-policy - explicit TCP/UDP allocations must
|
|
// survive a rebuild instead of widening to the Minecraft dual-protocol default.
|
|
for _, key := range []string{"providerId", "versionId", "ports", "portProtocols", "volumes", "env", "restart", "console", "readonlyRootfs", "readOnly", "bind_ip", "host_ip", "ip", "runAsRoot"} {
|
|
if value, exists := runtimeConfig[key]; exists && value != nil {
|
|
minecraftRuntime[key] = value
|
|
}
|
|
}
|
|
meta["fork"] = fork
|
|
meta["version"] = version
|
|
meta["start"] = "server.jar"
|
|
meta["runtime"] = minecraftRuntime
|
|
return nil
|
|
}
|
|
|
|
// adpanel:reinstall-stage - finish the download before touching the live
|
|
// server, using the same staging namespace and cleanup as a wipe restore.
|
|
func (a *Agent) stageMinecraftReinstall(w http.ResponseWriter, ctx context.Context, name, serverDir string, meta, runtimeConfig map[string]any, download reinstallJarDownload) string {
|
|
if err := configureMinecraftReinstall(meta, runtimeConfig); err != nil {
|
|
jsonWrite(w, http.StatusBadRequest, map[string]any{"ok": false, "error": err.Error()})
|
|
return ""
|
|
}
|
|
stagingDir, err := createServerStagingDir(serverDir)
|
|
if err != nil {
|
|
jsonWrite(w, http.StatusInternalServerError, map[string]any{"ok": false, "error": "could not prepare reinstall staging; no server files were replaced"})
|
|
return ""
|
|
}
|
|
ready := false
|
|
defer func() {
|
|
if !ready {
|
|
_ = os.RemoveAll(stagingDir)
|
|
}
|
|
}()
|
|
if same, statErr := sameDevice(serverDir, stagingDir); (statErr != nil && !os.IsNotExist(statErr)) || (statErr == nil && !same) {
|
|
jsonWrite(w, http.StatusInternalServerError, map[string]any{"ok": false, "error": "reinstall staging is not on the server's filesystem; no server files were replaced"})
|
|
return ""
|
|
}
|
|
fork, _ := meta["fork"].(string)
|
|
version, _ := meta["version"].(string)
|
|
writeMinecraftScaffold(stagingDir, name, fork, version)
|
|
enforceServerProps(stagingDir)
|
|
minecraftRuntime, _ := meta["runtime"].(map[string]any)
|
|
hostPort, _ := parseStrictPortValue(meta["hostPort"])
|
|
_, dataDir := a.resolveStructuredBinds("minecraft", minecraftRuntime, serverDir, stagingDir)
|
|
command, _ := minecraftRuntime["command"].(string)
|
|
if !validateReinstallProcessCommand(w, "minecraft", command, dataDir, "server.jar", runtimeImageRef(minecraftRuntime), hostPort, meta) {
|
|
return ""
|
|
}
|
|
properties, err := os.Stat(filepath.Join(stagingDir, "server.properties"))
|
|
if err != nil || properties.Size() == 0 {
|
|
jsonWrite(w, http.StatusInternalServerError, map[string]any{"ok": false, "error": "could not stage Minecraft configuration; no server files were replaced"})
|
|
return ""
|
|
}
|
|
jarPath := filepath.Join(stagingDir, "server.jar")
|
|
downloader, downloadError := a.reinstallDownloader(serverDir, properties.Size())
|
|
if downloadError == nil {
|
|
resolveContext, resolveCancel := context.WithTimeout(ctx, 30*time.Second)
|
|
jarURL, resolveError := getMinecraftJarURL(resolveContext, a.dl, fork, version, a.debug)
|
|
resolveCancel()
|
|
if resolveError != nil {
|
|
fmt.Printf("[reinstall] Failed to resolve the Minecraft jar for %s: %v\n", name, resolveError)
|
|
jsonWrite(w, http.StatusInternalServerError, map[string]any{"ok": false, "error": "the Minecraft jar could not be resolved; no server files were replaced"})
|
|
return ""
|
|
}
|
|
downloadContext, downloadCancel := context.WithTimeout(ctx, 30*time.Minute)
|
|
downloadError = download(downloader, downloadContext, jarURL, jarPath)
|
|
downloadCancel()
|
|
if downloadError == nil {
|
|
if stat, err := os.Stat(jarPath); err != nil {
|
|
downloadError = err
|
|
} else if downloader.maxBytes > 0 && stat.Size() >= downloader.maxBytes {
|
|
downloadError = fmt.Errorf("download reached the configured byte limit")
|
|
} else {
|
|
downloadError = checkReinstallJar(jarPath)
|
|
}
|
|
}
|
|
}
|
|
if downloadError != nil {
|
|
if errors.Is(downloadError, errDownloadQuotaExceeded) {
|
|
jsonWrite(w, http.StatusInsufficientStorage, map[string]any{
|
|
"ok": false, "code": "reinstall_disk_limit_exceeded",
|
|
"error": "There is not enough temporary storage to stage the Minecraft rebuild. No server files were replaced.",
|
|
})
|
|
} else {
|
|
fmt.Printf("[reinstall] Failed to download the Minecraft jar for %s: %v\n", name, downloadError)
|
|
jsonWrite(w, http.StatusInternalServerError, map[string]any{
|
|
"ok": false, "code": "reinstall_download_failed",
|
|
"error": "The Minecraft jar could not be downloaded. No server files were replaced.",
|
|
})
|
|
}
|
|
return ""
|
|
}
|
|
// adpanel:reinstall-image-preflight - EULA gating defers startup, not
|
|
// checking that the new runtime can be prepared before replacing files.
|
|
if err := a.prepareReinstallImages(ctx, runtimeImageRef(minecraftRuntime)); err != nil {
|
|
fmt.Printf("[reinstall] Failed to prepare image for %s: %v\n", name, err)
|
|
jsonWrite(w, http.StatusInternalServerError, map[string]any{
|
|
"ok": false, "code": "reinstall_image_pull_failed",
|
|
"error": "The Minecraft runtime image could not be prepared. No server files were replaced.",
|
|
})
|
|
return ""
|
|
}
|
|
ready = true
|
|
return stagingDir
|
|
}
|
|
|
|
func checkReinstallJar(jarPath string) error {
|
|
file, err := os.Open(jarPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer file.Close()
|
|
info, err := file.Stat()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := preflightZipCentralDirectoryBounded(file, info.Size()); err != nil {
|
|
return err
|
|
}
|
|
archive, err := zip.NewReader(file, info.Size())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
remaining := int64(maxExtractSize)
|
|
hasManifest := false
|
|
for _, entry := range archive.File {
|
|
if entry.UncompressedSize64 > uint64(remaining) {
|
|
return fmt.Errorf("jar exceeds the uncompressed size limit")
|
|
}
|
|
contents, err := entry.Open()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
size, readErr := io.Copy(io.Discard, contents)
|
|
if err := errors.Join(readErr, contents.Close()); err != nil {
|
|
return fmt.Errorf("invalid jar entry %q: %w", entry.Name, err)
|
|
}
|
|
remaining -= size
|
|
hasManifest = hasManifest || (entry.Name == "META-INF/MANIFEST.MF" && !entry.FileInfo().IsDir())
|
|
}
|
|
if !hasManifest {
|
|
return fmt.Errorf("jar is missing its manifest")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func configureNonMinecraftReinstall(template string, meta, runtimeConfig map[string]any) {
|
|
startFile, _ := meta["start"].(string)
|
|
if command, ok := runtimeConfig["command"].(string); !ok || strings.TrimSpace(command) == "" {
|
|
if defaultCommand := defaultRuntimeCommandForType(template, startFile, defaultDataDirForType(template)); defaultCommand != "" {
|
|
runtimeConfig["command"] = defaultCommand
|
|
}
|
|
}
|
|
if _, configured := runtimeConfig["workdir"]; !configured && hasManagedRuntimeDefaults(template) {
|
|
runtimeConfig["workdir"] = defaultDataDirForType(template)
|
|
}
|
|
if len(runtimeConfig) > 0 {
|
|
meta["runtime"] = runtimeConfig
|
|
}
|
|
}
|
|
|
|
func validateReinstallProcessCommand(w http.ResponseWriter, template, command, dataDir, startFile, imageRef string, hostPort int, meta map[string]any, env ...map[string]string) bool {
|
|
if _, err := buildRenderedRuntimeProcessArgs(template, command, dataDir, startFile, imageRef, hostPort, resourceLimitsFromMeta(meta), meta, env...); err != nil {
|
|
jsonWrite(w, http.StatusBadRequest, map[string]any{
|
|
"ok": false, "error": "Invalid replacement startup command: " + err.Error() + ". No server files were replaced.",
|
|
})
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (a *Agent) validateReinstallMounts(template string, runtimeConfig map[string]any, serverDir, stagingDir string) error {
|
|
mounts := runtimeStringSlice(runtimeConfig["volumes"])
|
|
if len(mounts) == 0 {
|
|
return nil
|
|
}
|
|
binds, _, rejected := resolveStructuredBindsChecked(template, runtimeConfig, serverDir, stagingDir)
|
|
if rejected {
|
|
return fmt.Errorf("one or more mount sources are outside the server or missing from the staged files")
|
|
}
|
|
return validateReinstallBindSpecs(binds)
|
|
}
|
|
|
|
func validateReinstallBindSpecs(binds []string) error {
|
|
targets := make(map[string]bool, len(binds))
|
|
for _, bind := range binds {
|
|
fields := strings.Split(bind, ":")
|
|
if len(fields) < 2 || len(fields) > 3 || (len(fields) == 3 && fields[2] != "ro" && fields[2] != "rw") {
|
|
return fmt.Errorf("mounts must use a server-directory bind with an optional ro or rw mode")
|
|
}
|
|
target := parseVolumeSpecContainerPath(bind)
|
|
if !path.IsAbs(target) || path.Clean(target) == "/" {
|
|
return fmt.Errorf("invalid mount destination %q", target)
|
|
}
|
|
target = path.Clean(target)
|
|
if targets[target] {
|
|
return fmt.Errorf("duplicate mount destination %q", target)
|
|
}
|
|
targets[target] = true
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *Agent) installReinstallTemplate(w http.ResponseWriter, ctx context.Context, name, serverDir, stagingDir string, hostPort int, meta, runtimeConfig map[string]any) bool {
|
|
template, _ := meta["template"].(string)
|
|
resources := resourceLimitsFromMeta(meta)
|
|
containerPort := hostPort
|
|
var env map[string]string
|
|
if !isManagedProcessRuntime(template) {
|
|
env, containerPort = customRuntimeEnvironmentAndPort(name, template, startupTemplateFromRuntime(runtimeConfig), runtimeConfig, hostPort, resources)
|
|
}
|
|
install := installConfigFromRuntime(runtimeConfig)
|
|
if install != nil {
|
|
allowance := a.reinstallInstallerAllowance(name, serverDir, install.MinimumStorageMb)
|
|
if allowance <= 0 {
|
|
writeReinstallStageQuotaRefusal(w)
|
|
return false
|
|
}
|
|
if err := a.runTemplateInstall(ctx, name, stagingDir, install, runtimeConfig, containerPort, resources, allowance); err != nil {
|
|
if errors.Is(err, errReinstallInstallerBudget) {
|
|
writeReinstallStageQuotaRefusal(w)
|
|
return false
|
|
}
|
|
if ctx.Err() != nil {
|
|
jsonWrite(w, http.StatusRequestTimeout, map[string]any{"ok": false, "error": reinstallCanceledBeforeCommit})
|
|
return false
|
|
}
|
|
fmt.Printf("[reinstall] Template install failed: %v\n", err)
|
|
jsonWrite(w, http.StatusInternalServerError, map[string]any{
|
|
"ok": false, "code": "reinstall_install_failed", "reinstalled": false,
|
|
"error": "Template installation failed. No server files were replaced.", "detail": err.Error(),
|
|
})
|
|
return false
|
|
}
|
|
}
|
|
startFile, _ := meta["start"].(string)
|
|
imageRef := runtimeImageRef(runtimeConfig)
|
|
command := sanitizeRuntimeCommand(runtimeConfig["command"])
|
|
scaffoldErr := scaffoldReinstallFiles(template, stagingDir, name, startFile, hostPort)
|
|
if scaffoldErr == nil && isManagedProcessRuntime(template) {
|
|
_, dataDir := a.resolveStructuredBinds(template, runtimeConfig, serverDir, stagingDir)
|
|
workdir := normalizeContainerWorkdir(runtimeConfig["workdir"])
|
|
if workdir == "" {
|
|
workdir = dataDir
|
|
}
|
|
if command == "" {
|
|
command = defaultRuntimeCommandForType(template, startFile, dataDir)
|
|
}
|
|
if !validateReinstallProcessCommand(w, template, command, dataDir, startFile, imageRef, hostPort, meta) {
|
|
return false
|
|
}
|
|
scaffoldErr = ensureRuntimeEntrypointScaffold(ctx, stagingDir, template, command, dataDir, workdir, startFile, hostPort)
|
|
} else if scaffoldErr == nil && imageRef != "" && command != "" && startupTemplateFromRuntime(runtimeConfig) == "" {
|
|
normalizeCfxRuntimeLayout(template, runtimeConfig, stagingDir)
|
|
inspectCtx, cancel := context.WithTimeout(ctx, 6*time.Second)
|
|
imgCfg := a.docker.inspectImageConfig(inspectCtx, imageRef)
|
|
cancel()
|
|
if !shouldPreferImageDefaultRuntimeCommand(command, imgCfg) {
|
|
_, dataDir, _ := a.resolveCustomRuntimeLayout(template, runtimeConfig, serverDir, stagingDir, imageRef, imgCfg)
|
|
if !validateReinstallProcessCommand(w, template, command, dataDir, startFile, imageRef, containerPort, meta, env) {
|
|
return false
|
|
}
|
|
}
|
|
}
|
|
if scaffoldErr != nil {
|
|
fmt.Printf("[reinstall] Failed to scaffold replacement files for %s: %v\n", name, scaffoldErr)
|
|
jsonWrite(w, http.StatusInternalServerError, map[string]any{
|
|
"ok": false, "code": "reinstall_scaffold_failed",
|
|
"error": "Could not prepare the replacement entrypoint or runtime files. No server files were replaced.",
|
|
})
|
|
return false
|
|
}
|
|
if install != nil {
|
|
// adpanel:reinstall-installer-quota - the committed tree and backups
|
|
// must fit the server quota; per-disk usage already includes staging.
|
|
if limit := a.getServerDiskLimitBytes(serverDir); limit > 0 {
|
|
stagedBytes, err := getDirSizeBytes(stagingDir)
|
|
if err != nil {
|
|
jsonWrite(w, http.StatusInternalServerError, map[string]any{"ok": false, "error": "could not measure staged installer output; no server files were replaced"})
|
|
return false
|
|
}
|
|
if stagedBytes > limit-a.getServerBackupsUsage(name) {
|
|
writeReinstallStageQuotaRefusal(w)
|
|
return false
|
|
}
|
|
}
|
|
if a.checkDiskCapacityForPath(stagingDir, 0) != nil {
|
|
writeReinstallStageQuotaRefusal(w)
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func writeReinstallStageQuotaRefusal(w http.ResponseWriter) {
|
|
jsonWrite(w, http.StatusInsufficientStorage, map[string]any{
|
|
"ok": false, "code": "reinstall_disk_limit_exceeded",
|
|
"error": "There is not enough storage to stage the template files. No server files were replaced.",
|
|
})
|
|
}
|
|
|
|
func (a *Agent) inspectRuntimeLaunchImage(ctx context.Context, imageRef string) imageConfig {
|
|
if handoff, ok := ctx.Value(reinstallContainerContextKey{}).(*reinstallFileHandoff); ok && handoff.image.config.ID != "" {
|
|
return handoff.image.config
|
|
}
|
|
return a.inspectRuntimeImageConfig(ctx, imageRef)
|
|
}
|
|
|
|
func (a *Agent) prepareCustomRuntimeImage(ctx context.Context, imageRef, serverDir string, image imageConfig, binds []string, dataDir, workdir, command string, stagingBudget ...int64) (string, error) {
|
|
if _, ok := ctx.Value(reinstallContainerContextKey{}).(*reinstallFileHandoff); ok {
|
|
return "", nil
|
|
}
|
|
paths := []string{dataDir, workdir, image.Workdir}
|
|
for _, bind := range binds {
|
|
paths = append(paths, parseVolumeSpecContainerPath(bind))
|
|
}
|
|
paths = append(paths, commandReferencedContainerPaths(command, workdir, dataDir)...)
|
|
return a.prepareServerDirFromImage(ctx, imageRef, serverDir, image, paths, stagingBudget...)
|
|
}
|
|
|
|
func (a *Agent) stageReinstallRuntimeImage(ctx context.Context, name, template, serverDir, stagingDir string, runtimeConfig map[string]any) (reinstallRuntimeImage, error) {
|
|
imageRef := runtimeImageRef(runtimeConfig)
|
|
inspectCtx, cancel := context.WithTimeout(ctx, 6*time.Second)
|
|
image, err := a.docker.inspectImageConfigAPI(inspectCtx, imageRef)
|
|
cancel()
|
|
if err != nil {
|
|
return reinstallRuntimeImage{}, err
|
|
}
|
|
imageID, pinned := strings.CutPrefix(image.ID, "sha256:")
|
|
if !pinned || !validDockerContainerID(imageID) {
|
|
return reinstallRuntimeImage{}, fmt.Errorf("runtime image identity could not be verified")
|
|
}
|
|
prepared := reinstallRuntimeImage{config: image}
|
|
if template == "minecraft" || isManagedProcessRuntime(template) {
|
|
binds, _ := a.resolveStructuredBinds(template, runtimeConfig, serverDir, stagingDir)
|
|
hostConfig := buildStructuredHostConfigWithRuntime(binds, nil, nil, "", structuredRuntimeReadOnly(runtimeConfig, true), runtimeConfig)
|
|
return prepared, validateReinstallImageVolumes(image, hostConfig)
|
|
}
|
|
normalizeCfxRuntimeLayout(template, runtimeConfig, stagingDir)
|
|
binds, dataDir, workdir := a.resolveCustomRuntimeLayout(template, runtimeConfig, serverDir, stagingDir, imageRef, image)
|
|
if err := validateReinstallBindSpecs(binds); err != nil {
|
|
return prepared, fmt.Errorf("%w: %v", errReinstallInvalidMounts, err)
|
|
}
|
|
readOnly := structuredRuntimeReadOnly(runtimeConfig, false)
|
|
hostConfig := buildStructuredHostConfigWithRuntime(binds, nil, nil, "", readOnly, runtimeConfig)
|
|
if err := validateReinstallImageVolumes(image, hostConfig); err != nil {
|
|
return prepared, err
|
|
}
|
|
if !imageConfigHasRuntimeDefault(image) && sanitizeRuntimeCommand(runtimeConfig["command"]) == "" && startupTemplateFromRuntime(runtimeConfig) == "" {
|
|
return prepared, errReinstallMissingStartup
|
|
}
|
|
entries, err := os.ReadDir(stagingDir)
|
|
if err != nil {
|
|
return prepared, err
|
|
}
|
|
if len(entries) > 0 {
|
|
// adpanel:reinstall-installer-mount - installer output must be visible to the replacement, not just copied into the panel's file tree.
|
|
if installConfigFromRuntime(runtimeConfig) != nil {
|
|
configuredBinds, _ := a.resolveStructuredBinds(template, runtimeConfig, serverDir, stagingDir)
|
|
if len(binds) == 0 || (len(runtimeStringSlice(runtimeConfig["volumes"])) > 0 && len(binds) < len(configuredBinds)) {
|
|
return prepared, fmt.Errorf("%w: the image's default startup drops a configured installer output mount; configure a compatible server-directory bind", errReinstallUnmanagedVolume)
|
|
}
|
|
visible, err := reinstallInstallerFilesVisible(serverDir, stagingDir, binds)
|
|
if err != nil {
|
|
return prepared, err
|
|
}
|
|
if !visible {
|
|
return prepared, fmt.Errorf("%w: none of the staged installer files are visible through the runtime mounts", errReinstallUnmanagedVolume)
|
|
}
|
|
}
|
|
return prepared, nil
|
|
}
|
|
allowance := min(int64(maxExtractSize), a.reinstallStagingAllowance(name, serverDir))
|
|
if allowance <= 0 {
|
|
return prepared, errReinstallInstallerBudget
|
|
}
|
|
stageCtx, stageCancel := context.WithTimeout(ctx, 3*time.Minute)
|
|
defer stageCancel()
|
|
preparedPath, err := a.prepareCustomRuntimeImage(stageCtx, image.ID, stagingDir, image, binds, dataDir, workdir, sanitizeRuntimeCommand(runtimeConfig["command"]), allowance)
|
|
if err == nil && a.checkDiskCapacityForPath(stagingDir, 0) != nil {
|
|
err = errReinstallInstallerBudget
|
|
}
|
|
if err == nil && preparedPath != "" && len(binds) == 0 && !hasManagedRuntimeDefaults(template) {
|
|
runtimeConfig[runtimeImageSeedPathKey] = preparedPath
|
|
}
|
|
return prepared, err
|
|
}
|
|
|
|
func reinstallInstallerFilesVisible(serverDir, stagingDir string, binds []string) (bool, error) {
|
|
sources := make(map[string]struct{}, len(binds))
|
|
for _, bind := range binds {
|
|
source, _, _ := strings.Cut(bind, ":")
|
|
relative, err := filepath.Rel(serverDir, source)
|
|
if err != nil || !isUnder(serverDir, source) {
|
|
return false, fmt.Errorf("%w: invalid installer output mount source", errReinstallInvalidMounts)
|
|
}
|
|
stagedSource := filepath.Join(stagingDir, relative)
|
|
if relative == "." {
|
|
return true, nil
|
|
}
|
|
resolved, err := filepath.EvalSymlinks(stagedSource)
|
|
if err != nil || !isUnder(stagingDir, resolved) {
|
|
return false, fmt.Errorf("%w: installer output mount source is not in the staged files", errReinstallInvalidMounts)
|
|
}
|
|
sources[resolved] = struct{}{}
|
|
}
|
|
hasFiles, visible := false, false
|
|
err := filepath.WalkDir(stagingDir, func(filename string, entry fs.DirEntry, err error) error {
|
|
if err != nil || !entry.Type().IsRegular() {
|
|
return err
|
|
}
|
|
hasFiles = true
|
|
for source := filename; ; source = filepath.Dir(source) {
|
|
if _, mounted := sources[source]; mounted {
|
|
visible = true
|
|
return fs.SkipAll
|
|
}
|
|
if source == stagingDir {
|
|
return nil
|
|
}
|
|
}
|
|
})
|
|
return !hasFiles || visible, err
|
|
}
|
|
|
|
// adpanel:reinstall-image-volumes - a replacement must not silently move server data outside backup and rollback storage.
|
|
func validateReinstallImageVolumes(image imageConfig, hostConfig dockerHostConfig) error {
|
|
if image.DeclaresRootVolume {
|
|
return fmt.Errorf("%w at /; use an image without a root volume", errReinstallUnmanagedVolume)
|
|
}
|
|
for _, volume := range image.Volumes {
|
|
destination := path.Clean(volume)
|
|
if _, bounded := hostConfig.Tmpfs[destination]; bounded {
|
|
continue
|
|
}
|
|
matched := false
|
|
for _, bind := range hostConfig.Binds {
|
|
if path.Clean(parseVolumeSpecContainerPath(bind)) == destination {
|
|
matched = true
|
|
break
|
|
}
|
|
}
|
|
if !matched {
|
|
return fmt.Errorf("%w at %s; add a server-directory mount at this path", errReinstallUnmanagedVolume, destination)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *Agent) finishReinstallServer(w http.ResponseWriter, r *http.Request, name, serverDir, template string, hostPort int, meta, runtimeConfig map[string]any, retained ...*reinstallFileHandoff) {
|
|
var handoff *reinstallFileHandoff
|
|
if len(retained) != 0 {
|
|
handoff = retained[0]
|
|
}
|
|
startCtx, startCancel := context.WithTimeout(context.Background(), 240*time.Second)
|
|
if handoff != nil {
|
|
startCtx = context.WithValue(startCtx, reinstallContainerContextKey{}, handoff)
|
|
}
|
|
freshMeta := a.loadMeta(serverDir)
|
|
if len(freshMeta) == 0 {
|
|
freshMeta = meta
|
|
}
|
|
startResources := resourceLimitsFromMeta(freshMeta)
|
|
var startErr error
|
|
serverStopped := false
|
|
if template == "minecraft" {
|
|
startErr = a.startMinecraftContainer(startCtx, name, serverDir, hostPort, startResources, nil, false)
|
|
} else if isManagedProcessRuntime(template) {
|
|
startErr = a.startRuntimeContainer(startCtx, name, serverDir, freshMeta, hostPort, startResources, nil)
|
|
} else if image, ok := runtimeConfig["image"].(string); ok && strings.TrimSpace(image) != "" {
|
|
startErr = a.startCustomDockerContainer(startCtx, name, serverDir, freshMeta, hostPort, startResources)
|
|
} else {
|
|
serverStopped = true
|
|
fmt.Printf("[reinstall] No container image resolved for %s (template %s); skipping container start\n", name, template)
|
|
}
|
|
startCancel()
|
|
awaitingEula := errors.Is(startErr, errMinecraftEulaRequired)
|
|
serverRunning := false
|
|
var replacement dockerContainerInspectForStats
|
|
canRollback := false
|
|
startFailureCode := "reinstall_start_failed"
|
|
startFailureMessage := "server files reinstalled but container failed to start"
|
|
if !serverStopped && !awaitingEula {
|
|
if startErr == nil && handoff != nil {
|
|
if err := a.saveReinstallOutcome(serverDir, handoff, "running", false); err != nil {
|
|
fmt.Printf("[reinstall] Could not record acknowledged startup for %s: %v\n", name, err)
|
|
}
|
|
}
|
|
inspectCtx, inspectCancel := context.WithTimeout(context.Background(), reinstallRecoveryBudget)
|
|
inspected, exists, stable, inspectErr := a.inspectReinstallStartup(inspectCtx, name, handoff, startErr == nil)
|
|
inspectCancel()
|
|
if inspectErr != nil {
|
|
if startErr == nil {
|
|
startErr = fmt.Errorf("could not verify replacement container state: %w", inspectErr)
|
|
startFailureCode = "reinstall_start_unconfirmed"
|
|
startFailureMessage = "server files reinstalled but container startup could not be confirmed"
|
|
}
|
|
} else {
|
|
state := inspected.State
|
|
owned := exists && (handoff == nil || handoff.ownsContainer(inspected))
|
|
serverRunning = stable
|
|
serverStopped = !exists || reinstallContainerIsStopped(state)
|
|
canRollback = !exists
|
|
if owned && handoff != nil {
|
|
replacement = inspected
|
|
}
|
|
if startErr == nil && !serverRunning {
|
|
startErr = errors.New("container did not stay up after reinstall")
|
|
}
|
|
}
|
|
}
|
|
if startErr != nil && !awaitingEula {
|
|
fmt.Printf("[reinstall] Container start failed for %s: %v\n", name, startErr)
|
|
auditLog.Log("server_reinstall", getClientIP(r), "", name, "reinstall", "start-failed", map[string]any{"template": template, "error": startErr.Error()})
|
|
if handoff != nil {
|
|
if !canRollback && replacement.ID != "" {
|
|
removeCtx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
|
|
canRollback = a.discardReinstallContainer(removeCtx, handoff, replacement)
|
|
cancel()
|
|
}
|
|
if canRollback {
|
|
if err := a.rollbackFailedReinstall(serverDir, handoff); err == nil {
|
|
jsonWrite(w, http.StatusInternalServerError, map[string]any{
|
|
"ok": false, "code": "reinstall_start_rolled_back", "serverStopped": true,
|
|
"error": "The replacement could not start. The previous files and configuration were restored; the server is stopped.",
|
|
})
|
|
return
|
|
} else {
|
|
fmt.Printf("[reinstall] Could not restore previous files for %s: %v\n", name, err)
|
|
}
|
|
}
|
|
writeReinstallStartupPending(w)
|
|
return
|
|
}
|
|
// adpanel:reinstall-partial-commit - startup failed after rebuilt
|
|
// metadata committed; the panel must retain the new port and template.
|
|
jsonWrite(w, http.StatusInternalServerError, map[string]any{
|
|
"ok": false, "code": startFailureCode, "reinstalled": true, "serverStopped": serverStopped,
|
|
"error": startFailureMessage, "detail": startErr.Error(),
|
|
})
|
|
return
|
|
}
|
|
if awaitingEula {
|
|
serverStopped = true
|
|
}
|
|
if handoff != nil {
|
|
outcome := "stopped"
|
|
if awaitingEula {
|
|
outcome = "eula"
|
|
} else if serverRunning {
|
|
outcome = "running"
|
|
}
|
|
if err := a.saveReinstallOutcome(serverDir, handoff, outcome, true); err != nil {
|
|
fmt.Printf("[reinstall] Could not confirm replacement for %s: %v\n", name, err)
|
|
writeReinstallStartupPending(w)
|
|
return
|
|
}
|
|
if err := removeReinstallRollback(handoff.rollbackDir); err != nil {
|
|
fmt.Printf("[reinstall] Could not remove previous files for %s: %v\n", name, err)
|
|
jsonWrite(w, http.StatusInternalServerError, map[string]any{
|
|
"ok": false, "code": "reinstall_cleanup_failed", "reinstalled": true, "serverStopped": serverStopped,
|
|
"error": "Replacement files were committed but the previous files could not be fully removed.",
|
|
})
|
|
return
|
|
}
|
|
}
|
|
if awaitingEula {
|
|
a.broadcastDaemonLog(name, "Reinstall complete - accept the Minecraft EULA in the console to start the server.")
|
|
auditLog.Log("server_reinstall", getClientIP(r), "", name, "reinstall", "eula-required", map[string]any{"template": template})
|
|
jsonWrite(w, http.StatusConflict, map[string]any{
|
|
"ok": false, "error": "minecraft_eula_required", "code": "minecraft_eula_required",
|
|
"detail": "Server files reinstalled. Accept the Minecraft EULA in the console to start the server.",
|
|
})
|
|
return
|
|
}
|
|
a.ensureLiveLogs(name)
|
|
fmt.Printf("[reinstall] Server %s reinstalled successfully with template %s\n", name, template)
|
|
auditLog.Log("server_reinstall", getClientIP(r), "", name, "reinstall", "success", map[string]any{"template": template})
|
|
jsonWrite(w, http.StatusOK, map[string]any{
|
|
"ok": true, "name": name, "template": template, "meta": meta,
|
|
"serverStopped": serverStopped, "serverRunning": serverRunning,
|
|
})
|
|
}
|
|
|
|
func writeReinstallStartupPending(w http.ResponseWriter) {
|
|
jsonWrite(w, http.StatusServiceUnavailable, reinstallStartupPendingBody())
|
|
}
|
|
|
|
func reinstallStartupPendingBody() map[string]any {
|
|
return map[string]any{
|
|
"ok": false, "code": reinstallStartupPendingCode,
|
|
"error": "Replacement startup or rollback could not be confirmed. Previous files were retained for recovery. Contact an administrator before retrying.",
|
|
}
|
|
}
|