Files
Kelx/docker_engine_test.go
2026-11-30 16:32:37 +00:00

555 lines
21 KiB
Go

package main
import (
"context"
"errors"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestShellConsoleCommandBoundsOutput(t *testing.T) {
binDir := t.TempDir()
stub := "#!/bin/sh\n" +
"[ \"$1\" = exec ] || exit 1\n" +
"printf 'earliest stdout\\n%200000s latest stdout\\n' x\n" +
"printf 'earliest stderr\\n%200000s latest stderr\\n' x >&2\n"
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte(stub), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
tail := &logTail{recentN: logTailRecentMaxLines}
a := &Agent{logs: &logManager{tails: map[string]*logTail{"fixture": tail}}}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if code, err := a.executeShellConsoleCommand(ctx, "fixture", "fixture command"); err != nil || code != 0 {
t.Fatalf("command failed: exit=%d, err=%v", code, err)
}
output := strings.Join(tail.snapshotRecent(10), "\n")
for _, expected := range []string{"command output truncated", "latest stdout", "latest stderr"} {
if !strings.Contains(output, expected) {
t.Errorf("missing %q from captured output", expected)
}
}
if strings.Contains(output, "earliest") || len(output) > 2*consoleExecOutputLimit+128 {
t.Errorf("captured output did not retain only the bounded tail (%d bytes)", len(output))
}
}
func TestShellConsoleCommandOnlyRetriesMissingShell(t *testing.T) {
for _, scenario := range []struct {
name string
diagnostic string
wantShells string
wantExit int
}{
{"command exited", "sh: 1: example-command: not found", "sh\n", 127},
{"shell missing", `OCI runtime exec failed: exec failed: unable to start container process: exec: "sh": executable file not found in $PATH: unknown`, "sh\n/bin/sh\n", 0},
} {
t.Run(scenario.name, func(t *testing.T) {
binDir := t.TempDir()
trace := filepath.Join(binDir, "calls")
stub := "#!/bin/sh\nprintf '%s\\n' \"$3\" >> \"$CONSOLE_TEST_TRACE\"\n" +
"[ \"$3\" = sh ] || exit 0\nprintf '%s\\n' \"$CONSOLE_TEST_STDERR\" >&2\nexit 127\n"
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte(stub), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("CONSOLE_TEST_TRACE", trace)
t.Setenv("CONSOLE_TEST_STDERR", scenario.diagnostic)
a := &Agent{logs: &logManager{tails: map[string]*logTail{"fixture": {recentN: logTailRecentMaxLines}}}}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if code, err := a.executeShellConsoleCommand(ctx, "fixture", "fixture command"); err != nil || code != scenario.wantExit {
t.Fatalf("exit=%d, err=%v; want exit=%d", code, err, scenario.wantExit)
}
if got, err := os.ReadFile(trace); err != nil || string(got) != scenario.wantShells {
t.Fatalf("shell attempts = %q (%v); want %q", got, err, scenario.wantShells)
}
})
}
}
func TestIsTransientDockerPullError(t *testing.T) {
transient := []string{
`failed to pull image eclipse-temurin:17-jre: failed to copy: httpReadSeeker: failed open: failed to do request: local error: tls: bad record MAC`,
`unexpected EOF`,
`Get "https://registry-1.docker.io/v2/": net/http: TLS handshake timeout`,
`received unexpected HTTP status: 503 Service Unavailable`,
}
for _, msg := range transient {
if !isTransientDockerPullError(errors.New(msg)) {
t.Fatalf("expected transient pull error for %q", msg)
}
}
permanent := []string{
`manifest unknown`,
`pull access denied, repository does not exist or may require authorization`,
`unauthorized: authentication required`,
`invalid reference format`,
}
for _, msg := range permanent {
if isTransientDockerPullError(errors.New(msg)) {
t.Fatalf("expected permanent pull error for %q", msg)
}
}
}
func TestPreferDockerAPIConsoleTransportByDefault(t *testing.T) {
t.Setenv("ADPANEL_DOCKER_STREAM_TRANSPORT", "")
if preferDockerCLIConsoleTransport() {
t.Fatalf("expected Docker API attach transport by default")
}
}
func TestPreferDockerCLIConsoleTransportOverride(t *testing.T) {
t.Setenv("ADPANEL_DOCKER_STREAM_TRANSPORT", "cli")
if !preferDockerCLIConsoleTransport() {
t.Fatalf("expected Docker CLI transport override to be honored")
}
t.Setenv("ADPANEL_DOCKER_STREAM_TRANSPORT", "docker-api")
if preferDockerCLIConsoleTransport() {
t.Fatalf("expected Docker API transport override to be honored")
}
}
func TestEnterpriseLinuxOSReleaseDetection(t *testing.T) {
if !isEnterpriseLinuxOSRelease("ID=rocky\nID_LIKE=\"rhel centos fedora\"\n") {
t.Fatalf("expected Rocky Linux to prefer enterprise Linux stdin fallback")
}
if !isEnterpriseLinuxOSRelease("ID=almalinux\nID_LIKE=\"rhel centos fedora\"\n") {
t.Fatalf("expected AlmaLinux to prefer enterprise Linux stdin fallback")
}
if isEnterpriseLinuxOSRelease("ID=ubuntu\nID_LIKE=debian\n") {
t.Fatalf("did not expect Ubuntu to prefer enterprise Linux stdin fallback")
}
}
func TestPreferDockerCLIPTYStdinTransportOverride(t *testing.T) {
t.Setenv("ADPANEL_DOCKER_STDIN_TRANSPORT", "pty")
if !preferDockerCLIPTYStdinTransport() {
t.Fatalf("expected Docker CLI PTY stdin override to be honored")
}
t.Setenv("ADPANEL_DOCKER_STDIN_TRANSPORT", "docker-api")
if preferDockerCLIPTYStdinTransport() {
t.Fatalf("expected Docker API stdin override to be honored")
}
}
func TestParseDockerLogSnapshotEntriesKeepsTimestamps(t *testing.T) {
raw := "2026-05-14T19:20:01.123456789Z server starting\n" +
"2026-05-14T19:20:02Z Done (3.2s)! For help, type \"help\"\n"
entries := parseDockerLogSnapshotEntries(raw, 10)
if len(entries) != 2 {
t.Fatalf("expected 2 entries, got %#v", entries)
}
if entries[0].line != "server starting" {
t.Fatalf("expected timestamp prefix to be removed, got %q", entries[0].line)
}
if entries[0].ts != 1778786401123 {
t.Fatalf("expected nanosecond timestamp to be parsed as ms, got %d", entries[0].ts)
}
if entries[1].line != `Done (3.2s)! For help, type "help"` {
t.Fatalf("unexpected second line: %q", entries[1].line)
}
if entries[1].ts != 1778786402000 {
t.Fatalf("expected whole-second timestamp to be parsed as ms, got %d", entries[1].ts)
}
}
func TestConsoleHistoryBoundsPersistedBytes(t *testing.T) {
filePath := filepath.Join(t.TempDir(), "fixture.log")
oldLine := strings.Repeat("x", consolePersistMaxBytes+32)
if err := os.WriteFile(filePath, []byte(oldLine+"\nlatest saved line\n"), 0o600); err != nil {
t.Fatal(err)
}
tail := &logTail{persistPath: filePath, persistLines: 2, persistLineTotal: 2}
if got, end := tail.readPersistedSnapshot(5000); len(got) != 1 || got[0] != "latest saved line" || end != 2 {
t.Fatalf("bounded snapshot: got %d lines, want the most recent complete line", len(got))
}
tail.appendPersistedLines([]string{"new output"})
info, err := os.Stat(filePath)
if err != nil || info.Size() > consolePersistMaxBytes {
t.Fatalf("persisted log was not rotated within its byte budget: %v (%v)", info, err)
}
lines, end := tail.readPersistedSnapshot(5000)
if got := strings.Join(lines, "\n"); got != "latest saved line\nnew output" {
t.Fatalf("persisted snapshot after rotation does not contain the two newest lines (got %d bytes)", len(got))
}
if end != 3 {
t.Fatalf("rotation reused a persisted line position: got %d, want 3", end)
}
}
func TestConsoleHistoryBoundsDockerBackfill(t *testing.T) {
binDir := t.TempDir()
stub := "#!/bin/sh\n" +
"[ \"$1\" = logs ] && [ \"$2\" = --timestamps ] && [ \"$3\" = --tail ] || exit 1\n" +
"printf '%1100000s\\nlatest stdout\\n' x\n" +
"printf '%1100000s\\nlatest stderr\\n' x >&2\n"
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte(stub), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
stdout, stderr := collectDockerLogTail(ctx, "fixture", 100, true)
if stdout != "latest stdout\n" || stderr != "latest stderr\n" {
t.Fatalf("backfill did not keep the newest complete lines: stdout=%d bytes, stderr=%d bytes", len(stdout), len(stderr))
}
}
func TestConsoleLogStreamClosesWhenTailRetires(t *testing.T) {
const serverName = "fixture"
tail := &logTail{name: serverName, clients: map[chan string]struct{}{}, stopCh: make(chan struct{})}
agent := &Agent{logs: &logManager{tails: map[string]*logTail{serverName: tail}}}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
response := httptest.NewRecorder()
request := httptest.NewRequest("GET", "/v1/servers/fixture/logs?tail=0", nil).WithContext(ctx)
done := make(chan struct{})
go func() {
defer close(done)
agent.handleLogsSSE(response, request, serverName)
}()
tick := time.NewTicker(time.Millisecond)
defer tick.Stop()
for {
tail.mu.Lock()
subscribed := len(tail.clients) == 1
tail.mu.Unlock()
if subscribed {
break
}
select {
case <-tick.C:
case <-ctx.Done():
t.Fatal("Console stream did not subscribe")
}
}
agent.logs.killTail(serverName)
select {
case <-done:
if ctx.Err() != nil || !strings.Contains(response.Body.String(), "event: hello") {
t.Fatal("Console stream did not close on retirement")
}
case <-ctx.Done():
t.Fatal("retired log tail kept the Console stream open")
}
}
func TestPterodactylRustKeepsHomeContainerVolume(t *testing.T) {
cfg := imageConfig{
Entrypoint: []string{"/bin/bash", "/entrypoint.sh"},
Workdir: "/home/container",
Env: map[string]string{},
}
binds, dataDir := sanitizeCustomImageDefaultBinds(
"ghcr.io/pterodactyl/games:rust",
cfg,
[]string{"/srv/adpanel/rust:/home/container"},
"/home/container",
)
if len(binds) != 1 || binds[0] != "/srv/adpanel/rust:/home/container" {
t.Fatalf("expected /home/container bind to be preserved, got %#v", binds)
}
if dataDir != "/home/container" {
t.Fatalf("expected dataDir /home/container, got %q", dataDir)
}
}
func TestImageWorkdirBindIsKeptWhenItIsKnownGameDataPath(t *testing.T) {
cfg := imageConfig{
Entrypoint: []string{"/entrypoint.sh"},
Workdir: "/steamcmd/rust",
Env: map[string]string{},
}
binds, dataDir := sanitizeCustomImageDefaultBinds(
"didstopia/rust-server:full",
cfg,
[]string{"/srv/adpanel/rust:/steamcmd/rust"},
"/steamcmd/rust",
)
if len(binds) != 1 || binds[0] != "/srv/adpanel/rust:/steamcmd/rust" {
t.Fatalf("expected known data-path bind to be preserved, got %#v", binds)
}
if dataDir != "/steamcmd/rust" {
t.Fatalf("expected dataDir /steamcmd/rust, got %q", dataDir)
}
}
func TestRustRestartRecreatesContainer(t *testing.T) {
if !shouldRecreateContainerOnRestart(map[string]any{"type": "rust"}) {
t.Fatalf("expected rust template restart to recreate the container")
}
if !shouldRecreateContainerOnRestart(map[string]any{
"type": "custom",
"runtime": map[string]any{
"image": "ghcr.io/pterodactyl/games",
"tag": "rust",
},
}) {
t.Fatalf("expected pterodactyl rust image restart to recreate the container")
}
if shouldRecreateContainerOnRestart(map[string]any{"type": "minecraft"}) {
t.Fatalf("did not expect minecraft restart to use rust recreate path")
}
}
func TestContainerStartupConfirmation(t *testing.T) {
binDir := t.TempDir()
stub := `#!/bin/sh
[ "$1" = inspect ] || exit 1
printf '%s\n' "$ADPANEL_TEST_DOCKER_STATUS"
exit "$ADPANEL_TEST_DOCKER_EXIT_CODE"
`
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte(stub), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
for _, testCase := range []struct {
name string
status string
exitCode string
wantErr string
}{
{name: "running", status: "running 0", exitCode: "0"},
{name: "stuck in created", status: "created 0", exitCode: "0", wantErr: "status: created"},
{name: "failed inspection", status: "running 0", exitCode: "1", wantErr: "could not be confirmed"},
} {
t.Run(testCase.name, func(t *testing.T) {
t.Setenv("ADPANEL_TEST_DOCKER_STATUS", testCase.status)
t.Setenv("ADPANEL_TEST_DOCKER_EXIT_CODE", testCase.exitCode)
ctx := context.WithValue(t.Context(), confirmDockerStartKey{}, true)
err := (&Agent{}).verifyContainerHealthyAfterStart(ctx, "fixture")
if testCase.wantErr == "" {
if err != nil {
t.Fatal(err)
}
} else if err == nil || !strings.Contains(err.Error(), testCase.wantErr) {
t.Fatalf("got %v, want error containing %q", err, testCase.wantErr)
}
})
}
}
func TestContainerResourceMinimums(testCtx *testing.T) {
for _, testCase := range []struct {
ramMb int
cpu float64
invalid bool
}{
{ramMb: 0, cpu: 0},
{ramMb: 5, cpu: 1, invalid: true},
{ramMb: 6, cpu: 0.005, invalid: true},
{ramMb: 6, cpu: 0.01},
} {
limits := &resourceLimits{RamMb: &testCase.ramMb, CpuCores: &testCase.cpu}
if reason := validateResourcePerformanceLimits(limits); (reason != "") != testCase.invalid {
testCtx.Fatalf("RAM %d, CPU %g: got %q, invalid=%v", testCase.ramMb, testCase.cpu, reason, testCase.invalid)
}
if testCase.invalid || testCase.ramMb == 0 {
continue
}
host := buildStructuredHostConfig(nil, nil, limits, "no", false)
if host.Memory != 6*1024*1024 || host.MemoryReservation != host.Memory || host.CpuQuota != 1000 {
testCtx.Fatalf("invalid Docker limits at minimums: %+v", host)
}
}
}
func TestServerNetworkQuotaSurvivesContainerRestartAndIdleCleanup(t *testing.T) {
cache := newServerResourceStatsCache(0, 0)
agent := &Agent{resourceStats: cache}
meta := map[string]any{"resources": map[string]any{"networkInboundLimitMb": 1, "networkResetMinutes": 60}}
entry := cache.get("fixture")
now := time.Now()
started := now.Add(-30 * time.Minute)
entry.touchedAt = started
entry.updateNetworkCounters("original", 1024*1024-1, 0, started, time.Hour)
if err := agent.prepareServerResourceStart("fixture", meta); err != nil {
t.Fatalf("restart before exhaustion refused: %v", err)
}
entry.updateNetworkCounters("replacement", 1, 0, started.Add(time.Minute), time.Hour)
cache.cleanup(10 * time.Minute)
if err := agent.prepareServerResourceStart("fixture", meta); !errors.Is(err, errNetworkQuotaExceeded) {
t.Fatalf("restart after exhaustion: got %v, want %v", err, errNetworkQuotaExceeded)
}
if err := agent.verifyServerNetworkQuota("fixture", meta, started.Add(time.Hour)); err != nil {
t.Fatalf("start after quota expiry refused: %v", err)
}
cache.forget("fixture")
if err := agent.prepareServerResourceStart("fixture", meta); err != nil {
t.Fatalf("new server inherited deleted server's quota: %v", err)
}
}
func TestRustGetsDefaultHighFileLimit(t *testing.T) {
resources := withRuntimeDefaultFileLimit(nil, "rust", "ghcr.io/pterodactyl/games:rust")
if resources == nil || resources.FileLimit == nil || *resources.FileLimit != maxFileLimit {
t.Fatalf("expected rust to default to max file limit, got %#v", resources)
}
customLimit := 65535
resources = withRuntimeDefaultFileLimit(&resourceLimits{FileLimit: &customLimit}, "rust", "ghcr.io/pterodactyl/games:rust")
if resources == nil || resources.FileLimit == nil || *resources.FileLimit != customLimit {
t.Fatalf("expected explicit file limit to be preserved, got %#v", resources)
}
if got := withRuntimeDefaultFileLimit(nil, "minecraft", "eclipse-temurin:21-jre"); got != nil {
t.Fatalf("did not expect non-rust runtime defaults, got %#v", got)
}
}
func TestCfxRuntimeLayoutStaysInsideMountedServerDir(t *testing.T) {
newFixture := func(t *testing.T) (string, map[string]any) {
t.Helper()
serverDir := t.TempDir()
if err := ensureDir(filepath.Join(serverDir, "serverfiles")); err != nil {
t.Fatalf("failed to create nested legacy dir: %v", err)
}
if err := writeFileNoFollow(filepath.Join(serverDir, "serverfiles", "server.cfg"), []byte("sv_maxclients 32\n"), 0o644); err != nil {
t.Fatalf("failed to create legacy cfg: %v", err)
}
runtimeObj := map[string]any{
"volumes": []any{"{BOT_DIR}:/serverdata"},
"workdir": "/serverdata",
"install": map[string]any{
"runtimePath": "/serverdata",
},
"env": map[string]any{
"DATA_DIR": "/serverdata",
"SERVER_DIR": "/serverdata/serverfiles",
"DATA_PERM": "770",
"SERVER_KEY": "keep-me",
"START_VARS": "+set gamename rdr3",
"GAME_CONFIG": "old.cfg",
},
}
return serverDir, runtimeObj
}
t.Run("default denies template root", func(t *testing.T) {
serverDir, runtimeObj := newFixture(t)
if !normalizeCfxRuntimeLayout("redm", runtimeObj, serverDir) {
t.Fatalf("expected legacy CFX runtime to be normalized")
}
volumes := runtimeObj["volumes"].([]any)
if len(volumes) != 1 || volumes[0] != "{BOT_DIR}:/serverdata/serverfiles" {
t.Fatalf("expected server root to be mounted directly to CFX server dir, got %#v", volumes)
}
if runtimeObj["workdir"] != "/serverdata/serverfiles" {
t.Fatalf("expected CFX workdir inside mounted server dir, got %#v", runtimeObj["workdir"])
}
if runtimeObj["runAsRoot"] != nil {
t.Fatalf("expected CFX layout normalization to stop granting root by default, got %#v", runtimeObj["runAsRoot"])
}
env := runtimeObj["env"].(map[string]string)
for key, want := range map[string]string{
"DATA_DIR": "/serverdata/serverfiles",
"SERVER_DIR": "/serverdata/serverfiles",
"HOME": "/serverdata/serverfiles",
"DATA_PERM": "777",
"GAME_CONFIG": "server.cfg",
} {
if got := env[key]; got != want {
t.Fatalf("expected env %s=%q, got %q", key, want, got)
}
}
if env["SERVER_KEY"] != "keep-me" || env["START_VARS"] != "+set gamename rdr3" {
t.Fatalf("expected CFX-specific user env to be preserved, got %#v", env)
}
install := runtimeObj["install"].(map[string]any)
if install["runtimePath"] != "/serverdata/serverfiles" || install["mountPath"] != "/mnt/server" {
t.Fatalf("expected CFX install paths to stay aligned to mounted dir, got %#v", install)
}
if !pathExists(filepath.Join(serverDir, "server.cfg")) {
t.Fatalf("expected nested legacy serverfiles content to be migrated into server root")
}
if _, err := os.Lstat(filepath.Join(serverDir, "serverfiles")); !os.IsNotExist(err) {
t.Fatalf("expected empty legacy directory to be removed: %v", err)
}
})
t.Run("linked legacy directory is not migrated", func(t *testing.T) {
serverDir, otherDir := t.TempDir(), t.TempDir()
otherFile := filepath.Join(otherDir, "fixture.txt")
if err := os.WriteFile(otherFile, []byte("unrelated"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.Symlink(otherDir, filepath.Join(serverDir, "serverfiles")); err != nil {
t.Fatal(err)
}
normalizeCfxRuntimeLayout("redm", map[string]any{}, serverDir)
if data, err := os.ReadFile(otherFile); err != nil || string(data) != "unrelated" {
t.Fatalf("migration must leave the unrelated directory untouched, got %q: %v", data, err)
}
if _, err := os.Lstat(filepath.Join(serverDir, "fixture.txt")); !os.IsNotExist(err) {
t.Fatalf("migration must not copy files from a linked legacy directory: %v", err)
}
})
t.Run("operator opt-in keeps legacy root bootstrap", func(t *testing.T) {
t.Setenv("ADPANEL_ALLOW_TEMPLATE_ROOT", "1")
serverDir, runtimeObj := newFixture(t)
if !normalizeCfxRuntimeLayout("redm", runtimeObj, serverDir) {
t.Fatalf("expected legacy CFX runtime to be normalized")
}
if runtimeObj["runAsRoot"] != true {
t.Fatalf("expected image root bootstrap to be kept under ADPANEL_ALLOW_TEMPLATE_ROOT=1, got %#v", runtimeObj["runAsRoot"])
}
})
}
func TestLegacyRustRuntimeMigratesToPterodactyl(t *testing.T) {
meta := map[string]any{
"type": "rust",
"template": "rust",
"runtime": map[string]any{
"image": "didstopia/rust-server",
"tag": "full",
"volumes": []any{"{BOT_DIR}:/steamcmd/rust"},
"workdir": "/",
"env": map[string]any{
"RUST_SERVER_NAME": "Legacy Rust",
"RUST_RCON_PASSWORD": "secret",
"RUST_SERVER_QUERYPORT": "28016",
},
},
}
if !normalizeRustRuntimeForPterodactyl(meta) {
t.Fatalf("expected legacy rust metadata to be migrated")
}
runtimeObj := meta["runtime"].(map[string]any)
if runtimeObj["image"] != "ghcr.io/pterodactyl/games" || runtimeObj["tag"] != "rust" {
t.Fatalf("expected pterodactyl rust runtime, got %#v:%#v", runtimeObj["image"], runtimeObj["tag"])
}
env := runtimeObj["env"].(map[string]string)
if env["SERVER_NAME"] != "Legacy Rust" || env["RCON_PASS"] != "secret" {
t.Fatalf("expected legacy env values to be preserved, got %#v", env)
}
volumes := runtimeObj["volumes"].([]any)
if len(volumes) != 1 || volumes[0] != "{BOT_DIR}:/home/container" {
t.Fatalf("expected home/container volume, got %#v", volumes)
}
}
func TestRustMigrationPreservesCustomTemplate(t *testing.T) {
for _, template := range []string{"rust-custom", ""} {
runtime := map[string]any{"image": "didstopia/rust-server", "tag": "full", "workdir": "/custom"}
meta := map[string]any{"type": "rust-custom", "template": template, "runtime": runtime}
if normalizeRustRuntimeForPterodactyl(meta) || meta["type"] != "rust-custom" || meta["template"] != template ||
runtime["image"] != "didstopia/rust-server" || runtime["workdir"] != "/custom" {
t.Fatalf("a shared image must not replace an installed custom runtime: %v", meta)
}
}
}