362 lines
14 KiB
Go
362 lines
14 KiB
Go
package main
|
|
|
|
import (
|
|
"archive/tar"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"os/exec"
|
|
"path"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
var errReinstallInstallerBudget = errors.New("staged installer exceeds its storage allowance")
|
|
var errImageSeedPathMissing = errors.New("runtime image path does not exist")
|
|
|
|
func (a *Agent) reinstallInstallerAllowance(name, serverDir string, minimumStorageMb int) int64 {
|
|
allowance := a.reinstallStagingAllowance(name, serverDir)
|
|
if allowance>>20 < int64(minimumStorageMb) {
|
|
return 0
|
|
}
|
|
maxScratchMb := int64(1024)
|
|
if strings.TrimSpace(os.Getenv("ADPANEL_REINSTALL_INSTALLER_SCRATCH")) != "" {
|
|
maxScratchMb = 128 * 1024
|
|
}
|
|
if configured, err := strconv.ParseInt(os.Getenv("ADPANEL_REINSTALL_INSTALLER_MAX_MB"), 10, 32); err == nil && configured > 0 {
|
|
maxScratchMb = configured
|
|
}
|
|
return min(allowance, maxScratchMb<<20)
|
|
}
|
|
|
|
func (a *Agent) reinstallStagingAllowance(name, serverDir string) int64 {
|
|
allowance := (freeDiskMb(serverDir) - 64) << 20
|
|
if limit := a.getServerDiskLimitBytes(serverDir); limit > 0 {
|
|
allowance = min(allowance, limit-a.getServerBackupsUsage(name))
|
|
}
|
|
remaining, _, _, limited, _ := a.diskCapacityAllowanceForPath(serverDir)
|
|
if limited {
|
|
allowance = min(allowance, remaining)
|
|
}
|
|
return allowance
|
|
}
|
|
|
|
// adpanel:reinstall-scratch-device - never turn a missing dedicated mount
|
|
// into an unrestricted writer on the node's shared filesystems.
|
|
func (a *Agent) acquireInstallerScratch(ctx context.Context, configured string) (string, func(bool), error) {
|
|
root := filepath.Clean(configured)
|
|
resolved, err := filepath.EvalSymlinks(root)
|
|
if err != nil || !filepath.IsAbs(root) || root == "/" || resolved != root || strings.ContainsAny(root, ",:\r\n") {
|
|
return "", nil, fmt.Errorf("installer scratch must be an absolute, dedicated mount without symlinks")
|
|
}
|
|
if same, err := sameDevice(root, filepath.Dir(root)); err != nil || same {
|
|
return "", nil, fmt.Errorf("installer scratch is not a separately mounted filesystem")
|
|
}
|
|
body, status, err := a.docker.engineRequest(ctx, http.MethodGet, "/info", nil, nil)
|
|
var dockerInfo struct{ DockerRootDir string }
|
|
if err != nil || status != http.StatusOK || json.Unmarshal(body, &dockerInfo) != nil || !filepath.IsAbs(dockerInfo.DockerRootDir) {
|
|
return "", nil, fmt.Errorf("Docker data storage could not be verified for installer scratch")
|
|
}
|
|
protected := []string{"/", a.dataRoot, dockerInfo.DockerRootDir}
|
|
for _, disk := range a.registeredDisks() {
|
|
protected = append(protected, disk.MountPath)
|
|
}
|
|
for _, location := range protected {
|
|
if same, err := sameDevice(root, location); err != nil || same {
|
|
return "", nil, fmt.Errorf("installer scratch is not isolated from %s", location)
|
|
}
|
|
}
|
|
var filesystem syscall.Statfs_t
|
|
if err := syscall.Statfs(root, &filesystem); err != nil || filesystem.Flags&(syscall.MS_NODEV|syscall.MS_NOSUID) != syscall.MS_NODEV|syscall.MS_NOSUID {
|
|
return "", nil, fmt.Errorf("installer scratch must be mounted with nodev and nosuid")
|
|
}
|
|
directory, err := safeOpenRoot(root)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
if err := syscall.Flock(int(directory.file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
|
|
directory.Close()
|
|
return "", nil, fmt.Errorf("dedicated installer scratch is busy")
|
|
}
|
|
entries, err := directory.file.ReadDir(3)
|
|
if err != nil && !errors.Is(err, io.EOF) {
|
|
directory.Close()
|
|
return "", nil, err
|
|
}
|
|
for _, entry := range entries {
|
|
if entry.Name() != "lost+found" || !entry.IsDir() {
|
|
directory.Close()
|
|
return "", nil, fmt.Errorf("dedicated installer scratch is not empty; check previous installer cleanup")
|
|
}
|
|
}
|
|
scratch, err := os.MkdirTemp(root, "installer-")
|
|
if err != nil {
|
|
directory.Close()
|
|
return "", nil, err
|
|
}
|
|
release := func(remove bool) {
|
|
defer directory.Close()
|
|
if remove {
|
|
if err := os.RemoveAll(scratch); err != nil {
|
|
fmt.Printf("[installer] Could not remove dedicated scratch: %v\n", err)
|
|
}
|
|
}
|
|
}
|
|
if err := os.Chmod(scratch, 0o777); err != nil {
|
|
release(true)
|
|
return "", nil, err
|
|
}
|
|
return scratch, release, nil
|
|
}
|
|
|
|
// adpanel:reinstall-installer-storage - only the bounded scratch paths may be
|
|
// writable, including mounts the installer image declares itself.
|
|
func boundedInstallerArgs(args []string, install *templateInstallConfig, image imageConfig, command []string, byteLimit int64, scratch string) ([]string, error) {
|
|
imageID, pinned := strings.CutPrefix(image.ID, "sha256:")
|
|
if !pinned || !validDockerContainerID(imageID) || image.DeclaresRootVolume {
|
|
return nil, fmt.Errorf("installer image identity or writable volumes could not be verified")
|
|
}
|
|
mountPath := path.Clean(install.MountPath)
|
|
if mountPath == "/" || strings.ContainsAny(mountPath, ":,") || mountPath == "/dev" || strings.HasPrefix(mountPath, "/dev/") {
|
|
return nil, fmt.Errorf("unsupported installer mount path: %s", install.MountPath)
|
|
}
|
|
for _, volume := range image.Volumes {
|
|
if volume = path.Clean(volume); volume != mountPath && volume != "/tmp" {
|
|
return nil, fmt.Errorf("installer image requires an unbounded writable volume at %s", volume)
|
|
}
|
|
}
|
|
const tmpfs = ":rw,exec,nodev,nosuid,mode=1777"
|
|
args = append(args, "--read-only", "--pull=never", "--log-driver=none", "--entrypoint", "/bin/sh")
|
|
if scratch != "" {
|
|
args = append(args, "--mount", fmt.Sprintf("type=bind,source=%s,target=%s,bind-recursive=disabled", scratch, mountPath))
|
|
} else {
|
|
args = append(args, "--tmpfs", fmt.Sprintf("%s%s,size=%d,nr_inodes=%d", mountPath, tmpfs, byteLimit, maxExtractFiles))
|
|
}
|
|
if mountPath != "/tmp" {
|
|
args = append(args, "--tmpfs", "/tmp"+tmpfs+",size=67108864,nr_inodes=8192")
|
|
}
|
|
args = append(args, image.ID, "-c", `install_dir=$1; shift; "$@" >&2 || exit "$?"; exec tar -C "$install_dir" -cf - .`, "adpanel-installer", mountPath)
|
|
args = append(args, trimRuntimeProcessArgs(image.Entrypoint)...)
|
|
return append(args, command...), nil
|
|
}
|
|
|
|
func stageRegularArchive(cmd *exec.Cmd, serverDir string, limit int64) error {
|
|
stream, err := cmd.StdoutPipe()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer stream.Close()
|
|
if err := cmd.Start(); err != nil {
|
|
return err
|
|
}
|
|
_, extractErr := extractTarSafe(tar.NewReader(stream), serverDir, limit, false, true)
|
|
if extractErr != nil {
|
|
_ = stream.Close()
|
|
_ = cmd.Process.Kill()
|
|
} else {
|
|
_, extractErr = io.Copy(io.Discard, stream)
|
|
}
|
|
waitErr := cmd.Wait()
|
|
if extractErr != nil {
|
|
return extractErr
|
|
}
|
|
return waitErr
|
|
}
|
|
|
|
func extractStagedImageFiles(ctx context.Context, source, stagingDir string, limit int64) error {
|
|
logs := newBoundedLogWriter(8 << 10)
|
|
cmd := exec.CommandContext(ctx, "docker", rewriteDockerCLIArgs([]string{"cp", source, "-"})...)
|
|
cmd.WaitDelay = 5 * time.Second
|
|
cmd.Stderr = logs
|
|
if err := stageRegularArchive(cmd, stagingDir, limit); err != nil {
|
|
var exitErr *exec.ExitError
|
|
if errors.As(err, &exitErr) && strings.Contains(strings.ToLower(logs.String()), "could not find the file") {
|
|
return errImageSeedPathMissing
|
|
}
|
|
return fmt.Errorf("copy staged image archive: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *Agent) prepareServerDirFromImage(ctx context.Context, imageRef, serverDir string, image imageConfig, paths []string, stagingBudget ...int64) (string, error) {
|
|
if serverDirVisibleFileCount(serverDir) > 0 {
|
|
return "", nil
|
|
}
|
|
for _, candidate := range imageExtractCandidates(paths, image) {
|
|
// Failed copies can leave partial files; only count the current attempt's output.
|
|
before := serverDirVisibleFileCount(serverDir)
|
|
extractCtx, cancel := context.WithTimeout(ctx, imageExtractAttemptBudget)
|
|
err := a.docker.extractImageFiles(extractCtx, imageRef, serverDir, candidate.Path, stagingBudget...)
|
|
cancel()
|
|
if len(stagingBudget) != 0 {
|
|
entries, readErr := os.ReadDir(serverDir)
|
|
if readErr != nil {
|
|
return "", readErr
|
|
}
|
|
if err != nil && (!errors.Is(err, errImageSeedPathMissing) || len(entries) != 0) {
|
|
return "", err
|
|
}
|
|
if err == nil && len(entries) != 0 && serverDirVisibleFileCount(serverDir) == 0 {
|
|
return "", nil
|
|
}
|
|
}
|
|
if err != nil {
|
|
continue
|
|
}
|
|
if serverDirVisibleFileCount(serverDir) > before {
|
|
_ = sanitizeExtractedTree(serverDir)
|
|
ensureVolumeWritable(serverDir)
|
|
fmt.Printf("[docker] prepared server directory from image %s:%s\n", imageRef, candidate.Path)
|
|
return candidate.Path, nil
|
|
}
|
|
}
|
|
return "", nil
|
|
}
|
|
|
|
func (a *Agent) runTemplateInstall(parentCtx context.Context, name, serverDir string, install *templateInstallConfig, runtimeObj map[string]any, hostPort int, resources *resourceLimits, stagingBytes int64) error {
|
|
install = normalizeTemplateInstallConfig(install)
|
|
if install == nil {
|
|
return nil
|
|
}
|
|
if err := parentCtx.Err(); err != nil {
|
|
return err
|
|
}
|
|
if err := ensureDir(serverDir); err != nil {
|
|
return err
|
|
}
|
|
ensureVolumeWritable(serverDir)
|
|
|
|
startup := startupTemplateFromRuntime(runtimeObj)
|
|
env := adpanelStartupDefaultEnv(name, hostPort, resources, startup)
|
|
env = mergeStringEnv(env, runtimeEnvMap(runtimeObj["env"]))
|
|
env = mergeStringEnv(env, install.Env)
|
|
tpl := strings.ToLower(strings.TrimSpace(fmt.Sprint(runtimeObj["providerId"])))
|
|
applyRuntimeHostPortEnv(tpl, env, hostPort)
|
|
renderRuntimeEnvTemplates(tpl, env, hostPort)
|
|
if startup != "" {
|
|
env["STARTUP"] = renderADPanelStartupTemplate(startup, env, hostPort)
|
|
}
|
|
if err := a.checkTemplateInstallPreflight(name, serverDir, install); err != nil {
|
|
return err
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(parentCtx, time.Duration(install.TimeoutSeconds)*time.Second)
|
|
defer cancel()
|
|
|
|
a.emitSetupLog(name, "stdout", "Preparing template installer")
|
|
if err := a.docker.ensureImageAvailableAPI(ctx, install.Image); err != nil {
|
|
return fmt.Errorf("installer image pull failed: %w", err)
|
|
}
|
|
a.emitSetupLog(name, "stdout", "Running template installer in "+install.Image)
|
|
var imgCfg imageConfig
|
|
if stagingBytes > 0 {
|
|
var err error
|
|
imgCfg, err = a.docker.inspectImageConfigAPI(ctx, install.Image)
|
|
if err != nil {
|
|
return fmt.Errorf("cannot verify staged installer image configuration: %w", err)
|
|
}
|
|
} else {
|
|
imgCfg = a.inspectRuntimeImageConfig(ctx, install.Image)
|
|
}
|
|
installerCmdArgs := installerDefaultCommandArgs(imgCfg.Entrypoint, install.Script)
|
|
|
|
installRunDir, err := os.MkdirTemp("", "adpanel-installer-")
|
|
if err != nil {
|
|
return fmt.Errorf("prepare installer container tracking: %w", err)
|
|
}
|
|
defer os.RemoveAll(installRunDir)
|
|
containerIDFile := filepath.Join(installRunDir, "container.id")
|
|
scratch := ""
|
|
var releaseScratch func(bool)
|
|
if configured := strings.TrimSpace(os.Getenv("ADPANEL_REINSTALL_INSTALLER_SCRATCH")); stagingBytes > 0 && configured != "" {
|
|
scratch, releaseScratch, err = a.acquireInstallerScratch(ctx, configured)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
defer func() {
|
|
// adpanel:installer-cleanup-owner - remove only the ID this run created.
|
|
data, readErr := os.ReadFile(containerIDFile)
|
|
containerID := strings.TrimSpace(string(data))
|
|
if releaseScratch != nil {
|
|
if os.IsNotExist(readErr) {
|
|
releaseScratch(true)
|
|
return
|
|
}
|
|
if readErr != nil || !validDockerContainerID(containerID) {
|
|
releaseScratch(false)
|
|
return
|
|
}
|
|
cleanupCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
releaseScratch(a.docker.removeContainerAPI(cleanupCtx, containerID, true) == nil)
|
|
return
|
|
}
|
|
if readErr != nil || !validDockerContainerID(containerID) {
|
|
return
|
|
}
|
|
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cleanupCancel()
|
|
a.docker.rmForce(cleanupCtx, containerID)
|
|
}()
|
|
if scratch != "" && freeDiskMb(scratch) <= 0 {
|
|
return errReinstallInstallerBudget
|
|
}
|
|
|
|
args := []string{"run", "--rm", "--name", safeInstallerContainerName(name), "--cidfile", containerIDFile, "--cap-drop=ALL"}
|
|
args = append(args, panelSafeCaps()...)
|
|
args = append(appendInstallerResourceArgs(args, resources, stagingBytes > 0), "--security-opt=no-new-privileges", "-w", install.MountPath)
|
|
if installNetwork := strings.TrimSpace(os.Getenv("ADPANEL_TEMPLATE_INSTALL_NETWORK")); installNetwork != "" {
|
|
args = append(args, "--network", installNetwork)
|
|
}
|
|
args = append(args, dockerEnvArgs(env)...)
|
|
if stagingBytes > 0 {
|
|
args, err = boundedInstallerArgs(args, install, imgCfg, installerCmdArgs, stagingBytes, scratch)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
args = append(args, "-v", fmt.Sprintf("%s:%s", serverDir, install.MountPath), install.Image)
|
|
args = append(args, installerCmdArgs...)
|
|
}
|
|
|
|
logs := newBoundedLogWriter(96 * 1024)
|
|
cmd := exec.CommandContext(ctx, "docker", args...)
|
|
cmd.WaitDelay = 5 * time.Second
|
|
if stagingBytes > 0 {
|
|
cmd.Stderr = logs
|
|
err = stageRegularArchive(cmd, serverDir, stagingBytes)
|
|
} else {
|
|
stdoutLog := newSetupConsoleWriter(a, name, "stdout")
|
|
stderrLog := newSetupConsoleWriter(a, name, "stderr")
|
|
cmd.Stdout = io.MultiWriter(logs, stdoutLog)
|
|
cmd.Stderr = io.MultiWriter(logs, stderrLog)
|
|
err = cmd.Run()
|
|
stdoutLog.Flush()
|
|
stderrLog.Flush()
|
|
}
|
|
if err != nil {
|
|
if ctx.Err() == context.DeadlineExceeded {
|
|
return fmt.Errorf("template installer timed out after %ds; last logs: %s", install.TimeoutSeconds, summarizeStartupLogs(logs.String(), 2400))
|
|
}
|
|
return fmt.Errorf("template installer failed: %w; last logs: %s", err, summarizeStartupLogs(logs.String(), 2400))
|
|
}
|
|
|
|
ensureVolumeWritable(serverDir)
|
|
if count := serverDirVisibleFileCount(serverDir); count == 0 && !install.AllowEmpty {
|
|
return fmt.Errorf("template installer completed but did not create any visible server files in %s; last logs: %s", install.MountPath, summarizeStartupLogs(logs.String(), 2400))
|
|
} else if count == 0 {
|
|
a.emitSetupLog(name, "stdout", "Installer completed without visible files; continuing because allowEmpty is enabled")
|
|
}
|
|
a.emitSetupLog(name, "stdout", "Template installer completed")
|
|
fmt.Printf("[installer] template install completed for %s using %s into %s\n", name, install.Image, install.MountPath)
|
|
return nil
|
|
}
|