4270 lines
187 KiB
Go
4270 lines
187 KiB
Go
package main
|
|
|
|
// adpanel:backup-race regression tests. handleReinstallServer used to take no
|
|
// per-server op lock, so its RemoveAll(serverDir) + template rebuild raced a
|
|
// concurrent backup restore (two interleaved copyDir writers silently mixing
|
|
// files into serverDir) and a concurrent backup create (which persisted a
|
|
// torn, status:"complete" backup of the half-wiped tree). Reinstall now
|
|
// serializes on the same op lock as the backup handlers (non-blocking, 409 on
|
|
// conflict) and registers itself as a long op so power ops fail fast instead
|
|
// of queueing behind its potentially tens-of-minutes hold.
|
|
//
|
|
// The conflict tests simulate the in-flight holder exactly the way the real
|
|
// handlers do (op lock + beginLongOp) and then drive the REAL handlers
|
|
// end-to-end: the response must be a 409 and — the anti-corruption property —
|
|
// the server directory must be completely untouched, proving the wipe never
|
|
// started. The happy/failure-path tests prove the lock and the long-op marker
|
|
// are always released, on success and on every bail-out inside the critical
|
|
// section.
|
|
|
|
import (
|
|
"archive/tar"
|
|
"archive/zip"
|
|
"bytes"
|
|
"context"
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"mime/multipart"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strconv"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// newReinstallRaceTestAgent builds an agent whose docker paths are stubbed
|
|
// (engine API reports missing containers, CLI fails), so reinstall runs its
|
|
// filesystem course without a daemon and never reaches real containers. The
|
|
// "custom" template path never pulls an image nor starts a container.
|
|
func newReinstallRaceTestAgent(t *testing.T) *Agent {
|
|
t.Helper()
|
|
stubDockerEngineUnavailable(t)
|
|
stubDockerCLIToolchain(t)
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{}}
|
|
a, _ := newTestAgent(t)
|
|
a.uploadLimit = 32 << 20
|
|
a.panelHMAC = "test-panel-hmac-secret"
|
|
// killTail/ensureLiveLogs dereference a.logs; getOrCreate assigns into
|
|
// the tails map, so it must be non-nil. stoppingNow is written by
|
|
// handleStop before its first early return, so it needs the same.
|
|
a.logs = &logManager{tails: map[string]*logTail{}}
|
|
a.stoppingNow = map[string]time.Time{}
|
|
return a
|
|
}
|
|
|
|
// seedRaceServer creates the server directory with one irreplaceable file and
|
|
// a recognizable meta, so any wipe/rewrite by a wrongly-allowed reinstall is
|
|
// detectable.
|
|
func seedRaceServer(t *testing.T, a *Agent, name string) string {
|
|
t.Helper()
|
|
serverDir := a.serverDir(name)
|
|
if err := os.MkdirAll(serverDir, 0o750); err != nil {
|
|
t.Fatalf("mkdir server dir: %v", err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(serverDir, "world-data.txt"), []byte("precious"), 0o644); err != nil {
|
|
t.Fatalf("seed world file: %v", err)
|
|
}
|
|
if err := a.saveMeta(serverDir, map[string]any{"type": "seeded", "template": "seeded"}); err != nil {
|
|
t.Fatalf("seed meta: %v", err)
|
|
}
|
|
return serverDir
|
|
}
|
|
|
|
// signedReinstallRequest builds a POST request to handleReinstallServer with
|
|
// a valid nonce-less panel admin envelope (the test agent leaves
|
|
// panelRequireNonce at its zero value false, i.e. legacy envelopes accepted).
|
|
func signedReinstallRequest(t *testing.T, a *Agent, name, template string, payload any) (*http.Request, *httptest.ResponseRecorder) {
|
|
t.Helper()
|
|
body, err := json.Marshal(payload)
|
|
if err != nil {
|
|
t.Fatalf("marshal payload: %v", err)
|
|
}
|
|
req := httptest.NewRequest(http.MethodPost, "/v1/servers/"+name+"/reinstall", strings.NewReader(string(body)))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
ts := strconv.FormatInt(time.Now().UnixMilli(), 10)
|
|
base := strings.Join([]string{name, "reinstall", template, "admin", ts}, "|")
|
|
m := hmac.New(sha256.New, []byte(a.panelHMAC))
|
|
_, _ = m.Write([]byte(base))
|
|
req.Header.Set("x-panel-role", "admin")
|
|
req.Header.Set("x-panel-ts", ts)
|
|
req.Header.Set("x-panel-sign", hex.EncodeToString(m.Sum(nil)))
|
|
return req, httptest.NewRecorder()
|
|
}
|
|
|
|
// runReinstall drives the real handler in-process.
|
|
func runReinstall(t *testing.T, a *Agent, name, template string, payload any) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
req, rec := signedReinstallRequest(t, a, name, template, payload)
|
|
a.handleReinstallServer(rec, req, name)
|
|
return rec
|
|
}
|
|
|
|
func decodeResponse(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
|
|
t.Helper()
|
|
var body map[string]any
|
|
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
|
t.Fatalf("response not json (%d): %s", rec.Code, rec.Body.String())
|
|
}
|
|
return body
|
|
}
|
|
|
|
// assertServerDirUntouched verifies the anti-corruption property: neither the
|
|
// seeded file nor the meta was wiped or rewritten by a refused reinstall.
|
|
func assertServerDirUntouched(t *testing.T, a *Agent, name, serverDir string) {
|
|
t.Helper()
|
|
if data, err := os.ReadFile(filepath.Join(serverDir, "world-data.txt")); err != nil || string(data) != "precious" {
|
|
t.Fatalf("seeded world file must survive a refused reinstall: err=%v data=%q", err, string(data))
|
|
}
|
|
meta := a.loadMeta(serverDir)
|
|
if meta["template"] != "seeded" {
|
|
t.Fatalf("meta must survive a refused reinstall: got %v", meta)
|
|
}
|
|
}
|
|
|
|
// TestReinstallInvalidConfigPreservesServer tests that invalid configurations
|
|
// do not alter the server directory during a reinstall attempt.
|
|
func TestReinstallHTTPAuthorizationRefusalsPreserveServer(t *testing.T) {
|
|
for _, scenario := range []string{"missing bearer", "missing signature", "bad signature", "non-admin", "expired", "replayed nonce"} {
|
|
t.Run(scenario, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
agent.token = "synthetic-node-token"
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
request, response := signedReinstallRequest(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
request.Header.Set("X-Node-Token", agent.token)
|
|
expectedStatus := http.StatusForbidden
|
|
switch scenario {
|
|
case "missing bearer":
|
|
request.Header.Del("X-Node-Token")
|
|
expectedStatus = http.StatusUnauthorized
|
|
case "missing signature":
|
|
request.Header.Del("x-panel-sign")
|
|
case "bad signature":
|
|
request.Header.Set("x-panel-sign", "invalid")
|
|
case "non-admin":
|
|
request.Header.Set("x-panel-role", "user")
|
|
case "expired":
|
|
request.Header.Set("x-panel-ts", strconv.FormatInt(time.Now().Add(-10*time.Minute).UnixMilli(), 10))
|
|
case "replayed nonce":
|
|
nonce := "abcdef0123456789abcdef0123456789"
|
|
request.Header.Set("x-panel-nonce", nonce)
|
|
base := strings.Join([]string{serverName, "reinstall", "custom", "admin", request.Header.Get("x-panel-ts"), nonce}, "|")
|
|
signature := hmac.New(sha256.New, []byte(agent.panelHMAC))
|
|
_, _ = signature.Write([]byte(base))
|
|
request.Header.Set("x-panel-sign", hex.EncodeToString(signature.Sum(nil)))
|
|
if !agent.recordPanelNonce(nonce, time.Now().UnixMilli()) {
|
|
t.Fatal("test nonce must be fresh before it is marked consumed")
|
|
}
|
|
}
|
|
agent.ServeHTTP(response, request)
|
|
if response.Code != expectedStatus {
|
|
t.Fatalf("unauthorized reinstall must refuse before mutation: %d %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallInvalidConfigPreservesServer(t *testing.T) {
|
|
cases := []struct {
|
|
name string
|
|
payload map[string]any
|
|
}{
|
|
{"unsupported java", map[string]any{"templateId": "custom", "javaVersion": "999"}},
|
|
{"java on non-minecraft", map[string]any{"templateId": "custom", "javaVersion": "21"}},
|
|
{"unsupported docker java", map[string]any{"templateId": "custom", "docker": map[string]any{"javaVersion": "999"}}},
|
|
{"relative workdir", map[string]any{"templateId": "custom", "docker": map[string]any{"workdir": "relative/path"}}},
|
|
{"disallowed runtime image", map[string]any{"templateId": "custom", "docker": map[string]any{"image": "untrusted.invalid/runtime"}}},
|
|
{"invalid runtime image", map[string]any{"templateId": "custom", "docker": map[string]any{"image": "node invalid"}}},
|
|
{"invalid process command", map[string]any{"templateId": "custom", "docker": map[string]any{"command": "docker run node"}}},
|
|
{"invalid startup script", map[string]any{"templateId": "custom", "docker": map[string]any{"adpanelStartup": "docker run node"}}},
|
|
{"invalid installer script", map[string]any{"templateId": "custom", "docker": map[string]any{"install": map[string]any{"script": "docker run node"}}}},
|
|
{"disallowed installer image", map[string]any{"templateId": "custom", "docker": map[string]any{"install": map[string]any{"script": "echo ready", "image": "untrusted.invalid/installer"}}}},
|
|
}
|
|
for _, scenario := range cases {
|
|
t.Run(scenario.name, func(t *testing.T) {
|
|
t.Setenv("ADPANEL_ALLOWED_TEMPLATE_IMAGE_REGISTRIES", "docker.io,ghcr.io")
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
response := runReinstall(t, agent, serverName, "custom", scenario.payload)
|
|
if response.Code != http.StatusBadRequest {
|
|
t.Fatalf("invalid config must return 400, got %d: %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallRenderedCommandPreservesServer(t *testing.T) {
|
|
for _, scenario := range []struct{ template, command string }{
|
|
{"nodejs", "node /app/index.js --url {{env.SERVICE_URL}}"},
|
|
{"minecraft", "java -jar /data/server.jar --url {{env.SERVICE_URL}}"},
|
|
{"custom", "node /app/index.js --url {{env.SERVICE_URL}}"},
|
|
} {
|
|
t.Run(scenario.template, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const serverName = "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
|
|
imagesAvailable: true,
|
|
onRemoval: func() { t.Error("invalid rendered command must not reach container removal") },
|
|
}}
|
|
response := runReinstall(t, agent, serverName, scenario.template, map[string]any{
|
|
"templateId": scenario.template,
|
|
"docker": map[string]any{
|
|
"image": "node",
|
|
"command": scenario.command,
|
|
"env": map[string]string{"SERVICE_URL": "https://example.com/?region=eu&mode=preview"},
|
|
},
|
|
})
|
|
if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "shell control operator") {
|
|
t.Errorf("expected rendered command refusal before the wipe, got %d: %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallUsesConfigurationBodyLimit(t *testing.T) {
|
|
for _, scenario := range []struct {
|
|
name string
|
|
uploadLimit int64
|
|
configSize int
|
|
}{
|
|
{"default upload cap", 1 << 30, maxReinstallRequestBytes},
|
|
{"smaller configured cap", 1 << 20, 1 << 20},
|
|
} {
|
|
t.Run(scenario.name, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
agent.uploadLimit = scenario.uploadLimit
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{onRemoval: func() {
|
|
t.Fatal("oversized configuration must not reach container removal")
|
|
}}}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{
|
|
"templateId": "custom",
|
|
"docker": map[string]any{"env": map[string]string{"FIXTURE": strings.Repeat("x", scenario.configSize)}},
|
|
})
|
|
if response.Code != http.StatusRequestEntityTooLarge {
|
|
t.Fatalf("oversized configuration must return 413, got %d: %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallInvalidStoredStartupPreservesServer(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["type"] = "custom"
|
|
meta["runtime"] = map[string]any{"adpanelStartup": "docker run node"}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
if response.Code != http.StatusBadRequest {
|
|
t.Fatalf("invalid stored startup must return 400 before wiping files, got %d: %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
|
|
func TestResourceUpdatePreservesUnreadableMetadata(testCtx *testing.T) {
|
|
agent := newReinstallRaceTestAgent(testCtx)
|
|
const serverName = "alpha"
|
|
seedRaceServer(testCtx, agent, serverName)
|
|
metaPath := agent.metaPath(serverName)
|
|
const damagedMetadata = `{"runtime":`
|
|
if err := os.WriteFile(metaPath, []byte(damagedMetadata), 0o600); err != nil {
|
|
testCtx.Fatal(err)
|
|
}
|
|
response := httptest.NewRecorder()
|
|
request := httptest.NewRequest(http.MethodPatch, "/v1/servers/alpha/resources", strings.NewReader(`{"resources":{"ramMb":2048}}`))
|
|
agent.handleUpdateResources(response, request, serverName)
|
|
if response.Code != http.StatusInternalServerError {
|
|
testCtx.Fatalf("expected an error before replacing unreadable policy, got %d: %s", response.Code, response.Body)
|
|
}
|
|
if data, err := os.ReadFile(metaPath); err != nil || string(data) != damagedMetadata {
|
|
testCtx.Fatalf("resource update changed the damaged metadata: %q (%v)", data, err)
|
|
}
|
|
}
|
|
|
|
func TestResourceUpdateRefusesInProgressSetup(testCtx *testing.T) {
|
|
agent := newReinstallRaceTestAgent(testCtx)
|
|
const serverName = "alpha"
|
|
serverDir := seedRaceServer(testCtx, agent, serverName)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["setupStatus"] = "starting"
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
testCtx.Fatal(err)
|
|
}
|
|
metaPath := agent.metaPath(serverName)
|
|
original, err := os.ReadFile(metaPath)
|
|
if err != nil {
|
|
testCtx.Fatal(err)
|
|
}
|
|
response := httptest.NewRecorder()
|
|
request := httptest.NewRequest(http.MethodPatch, "/v1/servers/alpha/resources", strings.NewReader(`{"mainPort":30005}`))
|
|
agent.handleUpdateResources(response, request, serverName)
|
|
if response.Code != http.StatusConflict || decodeResponse(testCtx, response)["code"] != "server_installing" {
|
|
testCtx.Fatalf("expected setup conflict before changing ports, got %d: %s", response.Code, response.Body)
|
|
}
|
|
if saved, err := os.ReadFile(metaPath); err != nil || string(saved) != string(original) {
|
|
testCtx.Fatalf("resource update changed the installing server's metadata: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestResourceUpdateRejectsOccupiedRemappedUDPPort(testCtx *testing.T) {
|
|
listener, err := net.ListenPacket("udp4", "127.0.0.1:0")
|
|
if err != nil {
|
|
testCtx.Fatal(err)
|
|
}
|
|
defer listener.Close()
|
|
port := listener.LocalAddr().(*net.UDPAddr).Port
|
|
agent := newReinstallRaceTestAgent(testCtx)
|
|
const name = "alpha"
|
|
serverDir := seedRaceServer(testCtx, agent, name)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["type"] = "custom"
|
|
meta["hostPort"] = 30000
|
|
meta["bind_ip"] = "127.0.0.1"
|
|
meta["runtime"] = map[string]any{
|
|
"ports": []int{27015}, "portProtocols": map[string][]string{"27015": {"udp"}},
|
|
}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
testCtx.Fatal(err)
|
|
}
|
|
response := httptest.NewRecorder()
|
|
request := httptest.NewRequest(http.MethodPatch, "/v1/servers/alpha/resources", strings.NewReader(fmt.Sprintf(`{"mainPort":%d}`, port)))
|
|
agent.handleUpdateResources(response, request, name)
|
|
if response.Code != http.StatusConflict || decodeResponse(testCtx, response)["code"] != "port_in_use" {
|
|
testCtx.Fatalf("expected UDP conflict before saving, got %d: %s", response.Code, response.Body)
|
|
}
|
|
if saved := anyToInt(agent.loadMeta(serverDir)["hostPort"]); saved != 30000 {
|
|
testCtx.Fatalf("port changed despite the conflict: %d", saved)
|
|
}
|
|
}
|
|
|
|
func TestReinstallUnreadableMetadataPreservesServer(t *testing.T) {
|
|
for _, scenario := range []string{"invalid json", "null", "empty object", "array", "missing", "read error"} {
|
|
t.Run(scenario, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
metaPath := agent.metaPath(serverName)
|
|
switch scenario {
|
|
case "missing", "read error":
|
|
if err := os.Remove(metaPath); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if scenario == "read error" {
|
|
if err := os.Mkdir(metaPath, 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
default:
|
|
contents := map[string]string{"invalid json": "{", "null": "null", "empty object": "{}", "array": "[]"}[scenario]
|
|
if err := os.WriteFile(metaPath, []byte(contents), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom", "hostPort": 30005})
|
|
body := decodeResponse(t, response)
|
|
if response.Code != http.StatusInternalServerError || body["code"] != "reinstall_meta_read_failed" {
|
|
t.Fatalf("uncertain metadata must refuse before deleting files: %d %v", response.Code, body)
|
|
}
|
|
if data, err := os.ReadFile(filepath.Join(serverDir, "world-data.txt")); err != nil || string(data) != "precious" {
|
|
t.Fatalf("unreadable metadata must leave server files untouched: %q %v", data, err)
|
|
}
|
|
if operation := agent.tryLockServerOp(serverName); operation == nil {
|
|
t.Fatal("refused metadata lookup must release the operation lock")
|
|
} else {
|
|
operation.Unlock()
|
|
}
|
|
if agent.longOpKind(serverName) != "" {
|
|
t.Fatal("refused metadata lookup must release the long-operation marker")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallRefusesUnsafeLegacyMetadata(t *testing.T) {
|
|
for _, scenario := range []string{"symlink", "oversized"} {
|
|
t.Run(scenario, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
metaPath := agent.metaPath(serverName)
|
|
legacyPath := filepath.Join(serverDir, "adpanel.json")
|
|
if scenario == "symlink" {
|
|
fixture := filepath.Join(t.TempDir(), "metadata.json")
|
|
if err := os.Rename(metaPath, fixture); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.Symlink(fixture, legacyPath); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
} else {
|
|
if err := os.Rename(metaPath, legacyPath); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.Truncate(legacyPath, maxLegacyServerMetaBytes+1); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
if response.Code != http.StatusInternalServerError || decodeResponse(t, response)["code"] != "reinstall_meta_read_failed" {
|
|
t.Fatalf("unsafe metadata must refuse before the wipe: %d %s", response.Code, response.Body.String())
|
|
}
|
|
if contents, err := os.ReadFile(filepath.Join(serverDir, "world-data.txt")); err != nil || string(contents) != "precious" {
|
|
t.Fatalf("refusal must leave the existing server intact: %q %v", contents, err)
|
|
}
|
|
if _, err := os.Stat(metaPath); !os.IsNotExist(err) {
|
|
t.Fatalf("unsafe metadata must not be migrated: %v", err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallLegacyMetadataMigrationPreservesPolicy(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["type"], meta["template"] = "custom", "custom"
|
|
meta["bind_ip"] = "127.0.0.1"
|
|
meta["resources"] = map[string]any{"storageMb": 1, "ramMb": 1024}
|
|
metadataBytes, err := json.Marshal(meta)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(serverDir, "adpanel.json"), metadataBytes, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.Remove(agent.metaPath(serverName)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom", "hostPort": 30005})
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("valid legacy metadata must support reinstall: %d %s", response.Code, response.Body.String())
|
|
}
|
|
persisted := agent.loadMeta(serverDir)
|
|
if persisted["bind_ip"] != "127.0.0.1" || agent.getServerDiskLimitBytes(serverDir) != 1<<20 {
|
|
t.Fatalf("legacy migration must preserve binding and quota policy: %v", persisted)
|
|
}
|
|
}
|
|
|
|
func TestReinstallVerifiesSignatureBeforeMigratingLegacySetupState(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
agent.token = "synthetic-node-token"
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["setupStatus"] = "preparing"
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
metaPath := agent.metaPath(serverName)
|
|
legacyPath := filepath.Join(serverDir, "adpanel.json")
|
|
if err := os.Rename(metaPath, legacyPath); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
request, response := signedReinstallRequest(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
request.Header.Set("X-Node-Token", agent.token)
|
|
request.Header.Del("x-panel-sign")
|
|
agent.ServeHTTP(response, request)
|
|
if response.Code != http.StatusForbidden {
|
|
t.Fatalf("missing signature must refuse before reading setup state: %d %s", response.Code, response.Body.String())
|
|
}
|
|
if _, err := os.Stat(metaPath); !os.IsNotExist(err) {
|
|
t.Fatalf("refused request must not migrate metadata: %v", err)
|
|
}
|
|
if _, err := os.Stat(legacyPath); err != nil {
|
|
t.Fatalf("legacy metadata must survive refusal: %v", err)
|
|
}
|
|
request, response = signedReinstallRequest(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
request.Header.Set("X-Node-Token", agent.token)
|
|
agent.ServeHTTP(response, request)
|
|
if response.Code != http.StatusConflict || decodeResponse(t, response)["code"] != "server_installing" {
|
|
t.Fatalf("a signed request must still respect setup in progress: %d %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
|
|
func TestReinstallFailedLegacyMetadataMigrationPreservesServer(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
metadataBytes, err := os.ReadFile(agent.metaPath(serverName))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
legacyPath := filepath.Join(serverDir, "adpanel.json")
|
|
if err := os.WriteFile(legacyPath, metadataBytes, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.Remove(agent.metaPath(serverName)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.Remove(agent.metaDir()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(agent.metaDir(), []byte("blocked metadata directory"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
if response.Code != http.StatusInternalServerError || decodeResponse(t, response)["code"] != "reinstall_meta_read_failed" {
|
|
t.Fatalf("failed legacy migration must refuse before wiping files: %d %s", response.Code, response.Body.String())
|
|
}
|
|
if data, err := os.ReadFile(legacyPath); err != nil || !bytes.Equal(data, metadataBytes) {
|
|
t.Fatalf("failed migration must keep the legacy metadata: %q %v", data, err)
|
|
}
|
|
if data, err := os.ReadFile(filepath.Join(serverDir, "world-data.txt")); err != nil || string(data) != "precious" {
|
|
t.Fatalf("failed migration must leave server files untouched: %q %v", data, err)
|
|
}
|
|
}
|
|
|
|
func TestReinstallInheritedRuntimePolicyPreflight(t *testing.T) {
|
|
for _, template := range []string{"custom", "minecraft"} {
|
|
for _, runtimeConfig := range []map[string]any{
|
|
{"javaVersion": "999"},
|
|
{"image": "untrusted.invalid/runtime"},
|
|
} {
|
|
if template != "minecraft" && runtimeConfig["javaVersion"] != nil {
|
|
continue
|
|
}
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["type"] = template
|
|
meta["runtime"] = runtimeConfig
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
request, response := signedReinstallRequest(t, agent, serverName, template, nil)
|
|
agent.rebuildReinstallServer(response, request, serverName, serverDir, template, 30005, meta, nil, runtimeConfig, "", false,
|
|
func(Downloader, context.Context, string, string) error {
|
|
t.Fatal("invalid runtime must refuse before attempting a download")
|
|
return nil
|
|
})
|
|
if response.Code != http.StatusBadRequest {
|
|
t.Fatalf("invalid inherited runtime must be rejected before wiping %s: %d %s", template, response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestReinstallTemplateChangeDoesNotInheritOldRuntime(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["start"] = "previous-entry.js"
|
|
meta["runtime"] = map[string]any{
|
|
"command": "node /app/previous-entry.js", "env": map[string]any{"OLD_TEMPLATE_SECRET": "old"},
|
|
"adpanelStartup": "docker run node",
|
|
}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
payload := map[string]any{
|
|
"templateId": "custom", "operationId": strings.Repeat("a", 32),
|
|
"acceptUntil": time.Now().Add(time.Minute).UnixMilli(),
|
|
}
|
|
for _, runtimeType := range []string{"seeded", "custom"} {
|
|
meta["type"] = runtimeType
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
refused := runReinstall(t, agent, serverName, "custom", payload)
|
|
if refused.Code != http.StatusConflict || decodeResponse(t, refused)["code"] != "reinstall_template_mismatch" {
|
|
t.Fatalf("ordinary reinstall must refuse a different saved template, even with runtime type %s: %d %s", runtimeType, refused.Code, refused.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
payload["replaceRuntime"] = true
|
|
response := runReinstall(t, agent, serverName, "custom", payload)
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("replacing a different template must not inherit its invalid runtime: %d %s", response.Code, response.Body.String())
|
|
}
|
|
if runtimeConfig, _ := agent.loadMeta(serverDir)["runtime"].(map[string]any); len(runtimeConfig) != 0 {
|
|
t.Fatalf("new template must not inherit the previous command, startup or environment: %v", runtimeConfig)
|
|
}
|
|
}
|
|
|
|
func TestReinstallReappliesLatestDefinitionOfSameTemplate(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["start"] = "previous-entrypoint"
|
|
meta["runtime"] = map[string]any{
|
|
"install": map[string]any{"image": "docker.io/library/alpine:3.20", "script": "true"},
|
|
"env": map[string]any{"OLD_TEMPLATE_OPTION": "old"}, "readonlyRootfs": true,
|
|
}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := runReinstall(t, agent, serverName, "seeded", map[string]any{
|
|
"templateId": "seeded", "replaceRuntime": true,
|
|
"docker": map[string]any{"env": map[string]string{"NEW_TEMPLATE_OPTION": "new"}},
|
|
})
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("reapply should deploy the latest definition without the old installer: %d %s", response.Code, response.Body.String())
|
|
}
|
|
meta = agent.loadMeta(serverDir)
|
|
runtimeConfig, _ := meta["runtime"].(map[string]any)
|
|
env := runtimeEnvMap(runtimeConfig["env"])
|
|
if meta["start"] != nil || installConfigFromRuntime(runtimeConfig) != nil || env["OLD_TEMPLATE_OPTION"] != "" || env["NEW_TEMPLATE_OPTION"] != "new" || runtimeConfig["readonlyRootfs"] != true {
|
|
t.Fatalf("reapply must replace template execution settings but preserve server policy: %v", meta)
|
|
}
|
|
}
|
|
|
|
func TestReinstallResultDistinguishesBusyCompletedAndExpired(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverDir := seedRaceServer(t, agent, "alpha")
|
|
t.Cleanup(func() { agent.logs.killTail("alpha") })
|
|
operationID := strings.Repeat("a", 32)
|
|
acceptUntil := time.Now().Add(time.Minute).UnixMilli()
|
|
expired := time.Now().Add(-time.Minute).UnixMilli()
|
|
readResult := func(id string, until int64) map[string]any {
|
|
t.Helper()
|
|
response := httptest.NewRecorder()
|
|
request := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/v1/servers/alpha/reinstall-result?id=%s&acceptUntil=%d", id, until), nil)
|
|
agent.handleReinstallResult(response, request, "alpha")
|
|
body := decodeResponse(t, response)
|
|
if response.Code != http.StatusOK || body["operationId"] != id {
|
|
t.Fatalf("result must identify the requested operation: %d %v", response.Code, body)
|
|
}
|
|
return body
|
|
}
|
|
lock := agent.tryLockServerOp("alpha")
|
|
if lock == nil {
|
|
t.Fatal("could not acquire fixture server lock")
|
|
}
|
|
busy := readResult(operationID, expired)
|
|
lock.Unlock()
|
|
if busy["state"] != "pending" || readResult(operationID, acceptUntil)["state"] != "pending" {
|
|
t.Fatal("absence must require both an idle server and an expired admission window")
|
|
}
|
|
if body := readResult(operationID, expired); body["state"] != "absent" || body["powerState"] != "stopped" {
|
|
t.Fatalf("a missing container must resolve an expired operation as stopped: %v", body)
|
|
}
|
|
engine := dockerEngineHTTPClient
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(req *http.Request) (*http.Response, error) {
|
|
if req.Method == http.MethodGet && strings.HasSuffix(req.URL.Path, "/containers/alpha/json") {
|
|
body := `{"Id":"` + reinstallFixtureContainerID + `","Name":"/alpha","Config":{"Labels":{"adpanel.server":"alpha"}},"State":{"Running":true,"Status":"running"}}`
|
|
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
|
}
|
|
return engine.Transport.RoundTrip(req)
|
|
})}
|
|
if body := readResult(operationID, expired); body["state"] != "absent" || body["powerState"] != "running" {
|
|
t.Fatalf("an expired operation must not report a still-running container as stopped: %v", body)
|
|
}
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(*http.Request) (*http.Response, error) {
|
|
return nil, errors.New("Docker temporarily unavailable")
|
|
})}
|
|
if body := readResult(operationID, expired); body["state"] != "absent" || body["powerState"] != nil {
|
|
t.Fatalf("an unavailable Docker engine must not hide confirmed file absence or assert a power state: %v", body)
|
|
}
|
|
dockerEngineHTTPClient = engine
|
|
rollbackDir, err := os.MkdirTemp(filepath.Dir(agent.serverDir("alpha")), ".alpha"+reinstallRollbackMarker)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if body := readResult(operationID, expired); body["state"] != "pending" {
|
|
t.Fatalf("a swap without confirmed rollback must not report absence: %v", body)
|
|
}
|
|
if err := os.Remove(rollbackDir); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := runReinstall(t, agent, "alpha", "seeded", map[string]any{
|
|
"templateId": "seeded", "hostPort": 30005, "operationId": operationID, "acceptUntil": acceptUntil,
|
|
})
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("fixture reinstall did not complete: %d %s", response.Code, response.Body.String())
|
|
}
|
|
if body := readResult(operationID, expired); body["state"] != "completed" || body["outcome"] != "stopped" || body["template"] != "seeded" || body["hostPort"] != float64(30005) {
|
|
t.Fatalf("a matching completed result must survive expiration: %v", body)
|
|
}
|
|
meta := agent.loadMeta(serverDir)
|
|
meta[reinstallOutcomeMetadataKey] = "running"
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if body := readResult(operationID, expired); body["state"] != "completed" || body["outcome"] != "running" || body["powerState"] != "stopped" {
|
|
t.Fatalf("a completed reinstall must preserve its outcome but report the current Docker state: %v", body)
|
|
}
|
|
if body := readResult(strings.Repeat("b", 32), expired); body["state"] != "absent" || body["hostPort"] != nil {
|
|
t.Fatalf("an unrelated operation must not use the completed result: %v", body)
|
|
}
|
|
}
|
|
|
|
func TestReinstallInstallerScratchRejectsSharedFilesystem(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
shared := t.TempDir()
|
|
path, release, err := agent.acquireInstallerScratch(context.Background(), shared)
|
|
if err == nil || path != "" || release != nil || !strings.Contains(err.Error(), "not a separately mounted filesystem") {
|
|
t.Fatalf("an ordinary directory cannot be used for dedicated installer scratch: %q %v", path, err)
|
|
}
|
|
}
|
|
|
|
func TestReinstallInstallerMinimumStorageRefusesBeforeExecution(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverDir := seedRaceServer(t, agent, "alpha")
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["resources"] = map[string]any{"storageMb": 4}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := httptest.NewRecorder()
|
|
runtimeConfig := map[string]any{"install": map[string]any{
|
|
"image": "docker.io/library/alpine:3.20", "script": "true", "minimumStorageMb": 64,
|
|
}}
|
|
if agent.installReinstallTemplate(response, context.Background(), "alpha", serverDir, t.TempDir(), 30005, nil, runtimeConfig) ||
|
|
response.Code != http.StatusInsufficientStorage || decodeResponse(t, response)["code"] != "reinstall_disk_limit_exceeded" {
|
|
t.Fatalf("a template with an oversized minimum must fail before execution: %d %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, "alpha", serverDir)
|
|
}
|
|
|
|
type reinstallDockerRemovalTransport struct {
|
|
failRemoval bool
|
|
failRemovalAfterStop bool
|
|
onRemoval func()
|
|
onRemovalTarget func(string)
|
|
imagesAvailable bool
|
|
onImagePull func(context.Context) error
|
|
startedState string
|
|
startedLabels map[string]string
|
|
failStartedInspection func() bool
|
|
createConflict bool
|
|
containerOwner string
|
|
legacyMount string
|
|
}
|
|
|
|
func TestReinstallScaffoldPreservesCustomEntrypoint(t *testing.T) {
|
|
serverDir := t.TempDir()
|
|
startFile := "server.bin"
|
|
installed := []byte("installer-produced entrypoint")
|
|
if err := os.WriteFile(filepath.Join(serverDir, startFile), installed, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := scaffoldReinstallFiles("custom", serverDir, "alpha", startFile, 30005); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if actual, err := os.ReadFile(filepath.Join(serverDir, startFile)); err != nil || string(actual) != string(installed) {
|
|
t.Fatalf("reinstall scaffold must not truncate installed server files: %q %v", actual, err)
|
|
}
|
|
}
|
|
|
|
func TestReinstallScaffoldPreservesLargeManagedEntrypoint(t *testing.T) {
|
|
serverDir := t.TempDir()
|
|
startFile := "index.js"
|
|
entrypoint := filepath.Join(serverDir, startFile)
|
|
installed := []byte(`const express = require("express");` + "\n// Hello World from ADPanel!\n" + strings.Repeat("// installer output\n", 5000))
|
|
if err := os.WriteFile(entrypoint, installed, 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := scaffoldReinstallFiles("nodejs", serverDir, "alpha", startFile, 30005); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if actual, err := os.ReadFile(entrypoint); err != nil || !bytes.Equal(actual, installed) {
|
|
t.Fatalf("large installed entrypoint must survive legacy scaffold detection: got %d bytes, want %d: %v", len(actual), len(installed), err)
|
|
}
|
|
}
|
|
|
|
func TestReinstallRebuildRetainsAuthoritativePolicy(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["resources"] = map[string]any{"storageMb": 1, "ramMb": 1024}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("rebuild failed: %d %s", response.Code, response.Body.String())
|
|
}
|
|
if _, err := os.Stat(filepath.Join(serverDir, "world-data.txt")); !os.IsNotExist(err) {
|
|
t.Fatalf("successful rebuild must remove the original files: %v", err)
|
|
}
|
|
info, err := os.Stat(serverDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if info.Mode().Perm()&0o077 != 0 {
|
|
t.Fatalf("a replacement without a running container must stay private: %o", info.Mode().Perm())
|
|
}
|
|
if limit := agent.getServerDiskLimitBytes(serverDir); limit != 1<<20 {
|
|
t.Fatalf("rebuild must not erase the server's quota policy: got %d", limit)
|
|
}
|
|
resources := resourceLimitsFromMeta(agent.loadMeta(serverDir))
|
|
if resources == nil || resources.RamMb == nil || *resources.RamMb != 1024 {
|
|
t.Fatal("rebuild must retain resource limits in the replacement metadata")
|
|
}
|
|
}
|
|
|
|
func TestReinstallDownloadEnforcesSavedQuotaAndBackups(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["resources"] = map[string]any{"storageMb": 1}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
backupDir := agent.serverBackupsDir(serverName)
|
|
if err := os.MkdirAll(backupDir, 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(backupDir, "backup.data"), bytes.Repeat([]byte("b"), 512<<10), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
downloader, err := agent.reinstallDownloader(serverDir, 0)
|
|
if err != nil || downloader.quotaCheck == nil {
|
|
t.Fatalf("reinstall must arm the saved quota: %v", err)
|
|
}
|
|
remaining := int64(1<<20) - agent.getServerTotalUsage(serverDir)
|
|
if err := downloader.quotaCheck(remaining); err != nil {
|
|
t.Fatalf("the exact remaining allowance must fit: %v", err)
|
|
}
|
|
if err := downloader.quotaCheck(remaining + 1); !errors.Is(err, errDownloadQuotaExceeded) {
|
|
t.Fatalf("backups must reduce the reinstall download allowance: %v", err)
|
|
}
|
|
if err := downloader.writeDownloadToFile(bytes.NewReader(bytes.Repeat([]byte("j"), 1<<20)), filepath.Join(serverDir, "server.jar")); !errors.Is(err, errDownloadQuotaExceeded) {
|
|
t.Fatalf("oversized jar must abort during the copy: %v", err)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(serverDir, "server.jar")); !os.IsNotExist(err) {
|
|
t.Fatalf("an over-quota jar must not commit: %v", err)
|
|
}
|
|
if strays := strayTempFiles(t, serverDir, "server.jar"); len(strays) != 0 {
|
|
t.Fatalf("aborted reinstall download must remove its temporary files: %v", strays)
|
|
}
|
|
}
|
|
|
|
func TestReinstallSecondaryDiskPreservesBackupsAndRouting(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
disk := registerTestDisk(t, agent, t.TempDir(), 50)
|
|
agent.setServerDiskMapping(serverName, disk.ID)
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["type"] = "custom"
|
|
meta["__diskId"] = disk.ID
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
backupDir := agent.serverBackupsDir(serverName)
|
|
if err := os.MkdirAll(backupDir, 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
backupPath := filepath.Join(backupDir, "backup.data")
|
|
if err := os.WriteFile(backupPath, []byte("preserved backup"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("secondary-disk reinstall failed: %d %s", response.Code, response.Body.String())
|
|
}
|
|
agent.invalidateServerDiskCache(serverName)
|
|
if agent.serverDir(serverName) != serverDir || agent.serverBackupsDir(serverName) != backupDir {
|
|
t.Fatal("reinstall must retain the owning disk after a cold routing-cache lookup")
|
|
}
|
|
if actual, err := os.ReadFile(backupPath); err != nil || string(actual) != "preserved backup" {
|
|
t.Fatalf("existing backups must survive reinstall: %q %v", actual, err)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(serverDir, "world-data.txt")); !os.IsNotExist(err) {
|
|
t.Fatalf("the server tree itself must be rebuilt: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestReinstallPreservesRuntimeSecurityPolicy(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["type"] = "custom"
|
|
meta["runtime"] = map[string]any{"bind_ip": "127.0.0.1", "readonlyRootfs": true}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom", "hostPort": 30005})
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("reinstall failed: %d %s", response.Code, response.Body.String())
|
|
}
|
|
persisted := agent.loadMeta(serverDir)
|
|
runtimeConfig, _ := persisted["runtime"].(map[string]any)
|
|
if runtimeConfig["readonlyRootfs"] != true {
|
|
t.Fatalf("reinstall must preserve explicit read-only root filesystem policy: %v", runtimeConfig)
|
|
}
|
|
bindings, _ := agent.buildStructuredPortBindings(serverDir, persisted, 30005, 30005)
|
|
if len(bindings["30005/tcp"]) != 1 || bindings["30005/tcp"][0].HostIP != "127.0.0.1" {
|
|
t.Fatalf("reinstall must preserve runtime-level loopback binding: %v", bindings)
|
|
}
|
|
}
|
|
|
|
func TestReinstallAppliesRequestedReadOnlyPolicy(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
for _, requested := range []bool{true, false} {
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{
|
|
"templateId": "custom", "docker": map[string]any{"readonlyRootfs": requested},
|
|
})
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("reinstall must accept read-only policy: %d %s", response.Code, response.Body.String())
|
|
}
|
|
runtimeConfig, _ := agent.loadMeta(serverDir)["runtime"].(map[string]any)
|
|
if runtimeConfig["readonlyRootfs"] != true {
|
|
t.Fatalf("reinstall must apply and retain read-only policy: %v", runtimeConfig)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestReinstallTemplateChangePreservesPrivateRuntimeBinding(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["type"] = "python"
|
|
meta["template"] = "python"
|
|
meta["runtime"] = map[string]any{
|
|
"bind_ip": "127.0.0.1", "command": "python /app/main.py",
|
|
"env": map[string]any{"PREVIOUS_TEMPLATE_SECRET": "old"},
|
|
}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom", "hostPort": 30005})
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("template change failed: %d %s", response.Code, response.Body.String())
|
|
}
|
|
persisted := agent.loadMeta(serverDir)
|
|
runtimeConfig, _ := persisted["runtime"].(map[string]any)
|
|
if runtimeConfig["command"] != nil || runtimeConfig["env"] != nil {
|
|
t.Fatalf("previous template execution settings must not leak into the new template: %v", runtimeConfig)
|
|
}
|
|
bindings, _ := agent.buildStructuredPortBindings(serverDir, persisted, 30005, 30005)
|
|
if len(bindings["30005/tcp"]) != 1 || bindings["30005/tcp"][0].HostIP != "127.0.0.1" {
|
|
t.Fatalf("changing templates must not expose a private service on all interfaces: %v", bindings)
|
|
}
|
|
}
|
|
|
|
func TestReinstallTemplateChangePreservesReadOnlyPolicy(t *testing.T) {
|
|
for _, field := range []string{"readonlyRootfs", "readOnly"} {
|
|
t.Run(field, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["type"], meta["template"] = "python", "python"
|
|
meta["runtime"] = map[string]any{
|
|
field: true, "command": "python /app/main.py",
|
|
"env": map[string]any{"PREVIOUS_TEMPLATE_SECRET": "old"},
|
|
}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom", "hostPort": 30005})
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("template change failed: %d %s", response.Code, response.Body.String())
|
|
}
|
|
runtimeConfig, _ := agent.loadMeta(serverDir)["runtime"].(map[string]any)
|
|
if runtimeConfig[field] != true {
|
|
t.Fatalf("changing templates must preserve the saved read-only filesystem policy: %v", runtimeConfig)
|
|
}
|
|
if runtimeConfig["command"] != nil || runtimeConfig["env"] != nil {
|
|
t.Fatalf("preserving security policy must not inherit previous template execution settings: %v", runtimeConfig)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallReboundPortPreservesAllocationInterface(t *testing.T) {
|
|
for _, location := range []string{"metadata", "resources"} {
|
|
t.Run(location, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
oldMeta := agent.loadMeta(serverDir)
|
|
oldMeta["hostPort"] = 30001
|
|
allocations := []any{map[string]any{"port": 30001, "ip": "127.0.0.1"}, map[string]any{"port": 30006, "ip": "127.0.0.2"}}
|
|
oldMeta["resources"] = map[string]any{"ports": []any{30006}}
|
|
if location == "metadata" {
|
|
oldMeta["portAllocations"] = allocations
|
|
} else {
|
|
oldMeta["resources"].(map[string]any)["portAllocations"] = allocations
|
|
}
|
|
if err := agent.saveMeta(serverDir, oldMeta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
before, _ := agent.buildStructuredPortBindings(serverDir, agent.loadMeta(serverDir), 30001, 30001)
|
|
if before["30001/tcp"][0].HostIP != "127.0.0.1" {
|
|
t.Fatal("fixture must bind the original primary allocation privately")
|
|
}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom", "hostPort": 30005})
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("rebound reinstall failed: %d %s", response.Code, response.Body.String())
|
|
}
|
|
bindings, _ := agent.buildStructuredPortBindings(serverDir, agent.loadMeta(serverDir), 30005, 30005)
|
|
if bindings["30005/tcp"][0].HostIP != "127.0.0.1" {
|
|
t.Fatalf("moving the primary allocation must not expose a private service on all interfaces: %v", bindings)
|
|
}
|
|
if bindings["30006/tcp"][0].HostIP != "127.0.0.2" {
|
|
t.Fatalf("rebinding the primary port must not change additional interfaces: %v", bindings)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallReboundAllocationHonorsDestinationPolicy(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
for _, destinationIP := range []string{"127.0.0.3", "0.0.0.0"} {
|
|
oldMeta := map[string]any{
|
|
"hostPort": 30001,
|
|
"resources": map[string]any{"portAllocations": []any{
|
|
map[string]any{"port": 30001, "ip": "127.0.0.1"},
|
|
map[string]any{"port": 30005, "ip": destinationIP},
|
|
}},
|
|
"portAllocations": []any{map[string]any{"port": 30001, "ip": "127.0.0.2"}},
|
|
}
|
|
meta := buildReinstallMetadata("custom", 30005, oldMeta)
|
|
bindings, _ := agent.buildStructuredPortBindings("", meta, 30005, 30005)
|
|
if bindings["30005/tcp"][0].HostIP != destinationIP {
|
|
t.Fatalf("explicit destination allocation must win over the previous primary interface: %v", bindings)
|
|
}
|
|
if len(oldMeta["portAllocations"].([]any)) != 1 {
|
|
t.Fatal("building replacement metadata must not mutate the old allocation snapshot")
|
|
}
|
|
unchanged := buildReinstallMetadata("custom", 30001, oldMeta)
|
|
originalBindings, _ := agent.buildStructuredPortBindings("", unchanged, 30001, 30001)
|
|
if originalBindings["30001/tcp"][0].HostIP != "127.0.0.2" {
|
|
t.Fatalf("an unchanged port must retain top-level allocation precedence: %v", originalBindings)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestReinstallReboundPortKeepsPrimaryProtocol(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const oldPort, newPort, extraPort = 30001, 30005, 30006
|
|
for _, expected := range []string{"udp", "tcp"} {
|
|
t.Run(expected, func(t *testing.T) {
|
|
protocols := map[int][]string{oldPort: {"udp"}, extraPort: {"tcp"}}
|
|
other := "tcp"
|
|
if expected == "tcp" {
|
|
protocols[newPort] = []string{"tcp"}
|
|
other = "udp"
|
|
}
|
|
runtimeConfig := map[string]any{"portProtocols": protocols}
|
|
oldMeta := map[string]any{
|
|
"type": "nodejs", "hostPort": oldPort,
|
|
"resources": map[string]any{"ports": []any{extraPort}},
|
|
}
|
|
meta := buildReinstallMetadata("nodejs", newPort, oldMeta)
|
|
bindings := agent.reinstallPortBindings("alpha", "", "nodejs", newPort, meta, oldMeta, runtimeConfig)
|
|
if len(bindings["30005/"+expected]) != 1 || len(bindings["30005/"+other]) != 0 || len(bindings["30006/tcp"]) != 1 {
|
|
t.Fatalf("a rebound port must preserve policy and leave extra bindings alone: %v", bindings)
|
|
}
|
|
savedRuntime, _ := meta["runtime"].(map[string]any)
|
|
if savedProtocols := runtimePortProtocolMap(savedRuntime["portProtocols"]); strings.Join(savedProtocols[newPort], ",") != expected {
|
|
t.Fatalf("startup must see the same protocol as preflight: %v", savedProtocols)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallCustomTemplateRendersThePublishedContainerPort(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const name, template = "alpha", "custom"
|
|
const hostPort, internalPort = 30005, 8080
|
|
for _, scenario := range []struct {
|
|
name, startup string
|
|
port int
|
|
}{
|
|
{name: "fixed internal port", port: internalPort},
|
|
{name: "dynamic startup", startup: "./server --port {{SERVER_PORT}}", port: hostPort},
|
|
} {
|
|
t.Run(scenario.name, func(t *testing.T) {
|
|
runtimeConfig := map[string]any{
|
|
"image": "docker.io/example/game", "ports": []int{internalPort},
|
|
"env": map[string]any{"PORT": "12345", "STARTUP": "./different-command", "LISTEN": "tcp:{{SERVER_PORT}}"},
|
|
}
|
|
if scenario.startup != "" {
|
|
runtimeConfig["adpanelStartup"] = scenario.startup
|
|
}
|
|
meta := buildReinstallMetadata(template, hostPort, nil)
|
|
bindings := agent.reinstallPortBindings(name, "", template, hostPort, meta, nil, runtimeConfig)
|
|
port := strconv.Itoa(scenario.port)
|
|
if published := bindings[port+"/tcp"]; len(published) != 1 || published[0].HostPort != strconv.Itoa(hostPort) {
|
|
t.Fatalf("allocated host port must forward to %s: %v", port, bindings)
|
|
}
|
|
env, containerPort := customRuntimeEnvironmentAndPort(name, template, scenario.startup, runtimeConfig, hostPort, nil)
|
|
if containerPort != scenario.port || env["PORT"] != port || env["SERVER_PORT"] != port || env["LISTEN"] != "tcp:"+port {
|
|
t.Fatalf("environment must use the published container port: %d, %v", containerPort, env)
|
|
}
|
|
args, err := buildRenderedRuntimeProcessArgs(template, "./server --port {PORT} --default-port {{SERVER_PORT}} --listen {{LISTEN}}", "/app", "", runtimeImageRef(runtimeConfig), containerPort, nil, meta, env)
|
|
if err != nil || strings.Join(args, " ") != "./server --port "+port+" --default-port "+port+" --listen tcp:"+port {
|
|
t.Fatalf("startup command must use the published container port: %v, %v", args, err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallPolicySurvivesNextRuntimeSeed(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
disk := registerTestDisk(t, agent, t.TempDir(), 50)
|
|
agent.setServerDiskMapping(serverName, disk.ID)
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["type"], meta["template"] = "nodejs", "nodejs"
|
|
meta["__diskId"] = disk.ID
|
|
meta["hostPort"] = 30001
|
|
meta["runtime"] = map[string]any{
|
|
"image": "docker.io/library/node", "tag": "20-alpine",
|
|
"readonlyRootfs": true, "bind_ip": "127.0.0.1",
|
|
"portProtocols": map[string]any{"30001": []any{"udp"}},
|
|
}
|
|
meta["portAllocations"] = []any{map[string]any{"port": 30005, "ip": "127.0.0.2"}}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
setRunningReplacement := func() {
|
|
created := false
|
|
fixture := reinstallDockerRemovalTransport{imagesAvailable: true}
|
|
running := reinstallDockerRemovalTransport{imagesAvailable: true, startedState: "running"}
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(req *http.Request) (*http.Response, error) {
|
|
if strings.HasSuffix(req.URL.Path, "/containers/create") {
|
|
var create dockerContainerCreateRequest
|
|
if err := json.NewDecoder(req.Body).Decode(&create); err != nil {
|
|
return nil, err
|
|
}
|
|
running.startedLabels = create.Labels
|
|
created = true
|
|
}
|
|
if created {
|
|
return running.RoundTrip(req)
|
|
}
|
|
return fixture.RoundTrip(req)
|
|
})}
|
|
}
|
|
setRunningReplacement()
|
|
reinstallResponse := runReinstall(t, agent, serverName, "nodejs", map[string]any{"templateId": "nodejs", "hostPort": 30005})
|
|
if reinstallResponse.Code != http.StatusOK {
|
|
t.Fatalf("fixture must confirm startup before committing: %d %s", reinstallResponse.Code, reinstallResponse.Body.String())
|
|
}
|
|
setRunningReplacement()
|
|
operationID := strings.Repeat("a", 32)
|
|
acceptUntil := time.Now().Add(time.Minute).UnixMilli()
|
|
repeatedReinstall := runReinstall(t, agent, serverName, "nodejs", map[string]any{
|
|
"templateId": "nodejs", "hostPort": 30005,
|
|
"operationId": operationID, "acceptUntil": acceptUntil,
|
|
"docker": map[string]any{"portProtocols": map[string][]string{"30001": {"udp"}}},
|
|
})
|
|
if repeatedReinstall.Code != http.StatusOK {
|
|
t.Fatalf("repeat rebuild must also commit: %d %s", repeatedReinstall.Code, repeatedReinstall.Body.String())
|
|
}
|
|
request := httptest.NewRequest(http.MethodPost, "/v1/servers/alpha/runtime", strings.NewReader(`{"runtime":{"image":"docker.io/library/node","tag":"20-alpine","command":"node /app/index.js"},"template":"nodejs","start":"index.js","port":30005}`))
|
|
response := httptest.NewRecorder()
|
|
agent.handleRuntime(response, request, serverName)
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("next runtime seed failed: %d %s", response.Code, response.Body.String())
|
|
}
|
|
result := httptest.NewRecorder()
|
|
resultURL := fmt.Sprintf("/v1/servers/alpha/reinstall-result?id=%s&acceptUntil=%d", operationID, acceptUntil)
|
|
agent.handleReinstallResult(result, httptest.NewRequest(http.MethodGet, resultURL, nil), serverName)
|
|
if body := decodeResponse(t, result); result.Code != http.StatusOK || body["operationId"] != operationID || body["state"] != "completed" || body["hostPort"] != float64(30005) || body["template"] != "nodejs" {
|
|
t.Fatalf("runtime seed must retain the committed reinstall result: %d %v", result.Code, body)
|
|
}
|
|
persisted := agent.loadMeta(serverDir)
|
|
runtimeConfig, _ := persisted["runtime"].(map[string]any)
|
|
if runtimeConfig["readonlyRootfs"] != true || runtimeConfig["bind_ip"] != "127.0.0.1" {
|
|
t.Errorf("the next start must not erase reinstall's runtime security policy: %v", runtimeConfig)
|
|
}
|
|
bindings, _ := agent.buildStructuredPortBindings(serverDir, persisted, 30005, 30005)
|
|
if len(bindings["30005/udp"]) != 1 || len(bindings["30005/tcp"]) != 0 || bindings["30005/udp"][0].HostIP != "127.0.0.2" {
|
|
t.Errorf("the next start must retain the rebuilt allocation interface and UDP-only protocol: %v", bindings)
|
|
}
|
|
if persisted["__diskId"] != disk.ID {
|
|
t.Errorf("the next start must retain the rebuilt disk assignment: %v", persisted)
|
|
}
|
|
}
|
|
|
|
func TestReinstallMetadataRetainsBindingPrecedence(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
for _, field := range []string{"bind_ip", "host_ip", "ip"} {
|
|
oldMeta := map[string]any{
|
|
"type": "python", field: "127.0.0.1",
|
|
"runtime": map[string]any{"bind_ip": "0.0.0.0"},
|
|
}
|
|
meta := buildReinstallMetadata("custom", 30005, oldMeta)
|
|
bindings, _ := agent.buildStructuredPortBindings("", meta, 30005, 30005)
|
|
if len(bindings["30005/tcp"]) != 1 || bindings["30005/tcp"][0].HostIP != "127.0.0.1" {
|
|
t.Fatalf("rebuild must retain top-level %s precedence over runtime policy: %v", field, bindings)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestReinstallMetadataPreservesPrivateRuntimeWildcardOverride(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
for _, field := range []string{"bind_ip", "ip"} {
|
|
oldMeta := map[string]any{
|
|
"type": "python", "bind_ip": "0.0.0.0",
|
|
"runtime": map[string]any{field: "127.0.0.1"},
|
|
}
|
|
before, _ := agent.buildStructuredPortBindings("", oldMeta, 30005, 30005)
|
|
if len(before["30005/tcp"]) != 1 || before["30005/tcp"][0].HostIP != "127.0.0.1" {
|
|
t.Fatal("fixture must resolve the runtime-level private override")
|
|
}
|
|
meta := buildReinstallMetadata("custom", 30005, oldMeta)
|
|
after, _ := agent.buildStructuredPortBindings("", meta, 30005, 30005)
|
|
if len(after["30005/tcp"]) != 1 || after["30005/tcp"][0].HostIP != "127.0.0.1" {
|
|
t.Fatalf("template change must preserve the effective private wildcard override: %v", after)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestReinstallPreservesPrivateBindAddress(t *testing.T) {
|
|
for _, field := range []string{"bind_ip", "host_ip", "ip"} {
|
|
t.Run(field, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta[field] = "127.0.0.1"
|
|
meta["hostPort"] = 30005
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("reinstall failed: %d: %s", response.Code, response.Body.String())
|
|
}
|
|
bindings, _ := agent.buildStructuredPortBindings(serverDir, agent.loadMeta(serverDir), 30005, 30005)
|
|
if len(bindings["30005/tcp"]) != 1 || bindings["30005/tcp"][0].HostIP != "127.0.0.1" {
|
|
t.Fatalf("reinstall must not expose a loopback-only server on all interfaces: %v", bindings)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallExcludesConcurrentPolicyWrites(t *testing.T) {
|
|
for _, operation := range []string{"resources", "eula-accept"} {
|
|
t.Run(operation, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["type"] = "minecraft"
|
|
meta["resources"] = map[string]any{"ramMb": 1024}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(serverDir, "eula.txt"), []byte("eula=false\n"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
opMu := agent.getServerOpLock(serverName)
|
|
opMu.Lock()
|
|
defer opMu.Unlock()
|
|
agent.beginLongOp(serverName, longOpReinstall)
|
|
defer agent.endLongOp(serverName)
|
|
response := httptest.NewRecorder()
|
|
request := httptest.NewRequest(http.MethodPost, "/v1/servers/alpha/"+operation, strings.NewReader(`{"autostart":false}`))
|
|
if operation == "resources" {
|
|
request = httptest.NewRequest(http.MethodPatch, "/v1/servers/alpha/resources", strings.NewReader(`{"resources":{"ramMb":2048}}`))
|
|
agent.handleUpdateResources(response, request, serverName)
|
|
} else {
|
|
agent.handleEulaAccept(response, request, serverName)
|
|
}
|
|
if response.Code != http.StatusConflict || decodeResponse(t, response)["code"] != "reinstall_in_progress" {
|
|
t.Fatalf("policy writes must refuse during reinstall: %d: %s", response.Code, response.Body.String())
|
|
}
|
|
resources, _ := agent.loadMeta(serverDir)["resources"].(map[string]any)
|
|
if resources["ramMb"] != float64(1024) {
|
|
t.Fatalf("a refused resource update must not rewrite metadata: %v", resources)
|
|
}
|
|
if data, err := os.ReadFile(filepath.Join(serverDir, "eula.txt")); err != nil || string(data) != "eula=false\n" {
|
|
t.Fatalf("a refused EULA write must leave consent unchanged: %q %v", data, err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallExcludesConcurrentJarReplacement(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := applyVersionFixtureName
|
|
operation := agent.getServerOpLock(serverName)
|
|
operation.Lock()
|
|
defer operation.Unlock()
|
|
agent.beginLongOp(serverName, longOpReinstall)
|
|
defer agent.endLongOp(serverName)
|
|
|
|
request := applyVersionSignedRequest(t, agent, serverName+"|||"+applyVersionFixtureURL+"|", "")
|
|
request.Body = io.NopCloser(strings.NewReader(`{"url":` + strconv.Quote(applyVersionFixtureURL) + `,"destPath":"server.jar"}`))
|
|
response := httptest.NewRecorder()
|
|
agent.handleApplyVersion(response, request, serverName)
|
|
if response.Code != http.StatusConflict || decodeResponse(t, response)["code"] != "reinstall_in_progress" {
|
|
t.Fatalf("jar replacement must refuse before resolving the changing volume: %d %s", response.Code, response.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestReinstallMissingStartDoesNotCreateNilEntrypoint(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("reinstall failed: %d: %s", response.Code, response.Body.String())
|
|
}
|
|
meta := agent.loadMeta(serverDir)
|
|
if meta["start"] != nil {
|
|
t.Fatalf("a custom server without a start file must not gain a fabricated entrypoint: %v", meta)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(serverDir, "<nil>")); !os.IsNotExist(err) {
|
|
t.Fatalf("reinstall must not create a file literally named <nil>: %v", err)
|
|
}
|
|
}
|
|
|
|
const reinstallFixtureContainerID = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
|
|
|
type reinstallDockerTransportFunc func(*http.Request) (*http.Response, error)
|
|
|
|
func (transport reinstallDockerTransportFunc) RoundTrip(request *http.Request) (*http.Response, error) {
|
|
return transport(request)
|
|
}
|
|
|
|
func (transport reinstallDockerRemovalTransport) RoundTrip(request *http.Request) (*http.Response, error) {
|
|
if request.Method == http.MethodDelete {
|
|
if transport.onRemoval != nil {
|
|
transport.onRemoval()
|
|
}
|
|
if transport.onRemovalTarget != nil {
|
|
transport.onRemovalTarget(filepath.Base(request.URL.Path))
|
|
}
|
|
}
|
|
if (transport.containerOwner != "" || transport.legacyMount != "" || (transport.onRemoval != nil && transport.startedState == "")) && request.Method == http.MethodGet && strings.HasSuffix(request.URL.Path, "/containers/alpha/json") {
|
|
container := dockerContainerInspectForStats{ID: reinstallFixtureContainerID, Name: "/alpha"}
|
|
if transport.legacyMount != "" {
|
|
container.Mounts = []dockerContainerMount{{Type: "bind", Source: transport.legacyMount}}
|
|
} else {
|
|
owner := transport.containerOwner
|
|
if owner == "" {
|
|
owner = "alpha"
|
|
}
|
|
container.Labels = map[string]string{dockerServerOwnershipLabel: owner}
|
|
}
|
|
body, err := json.Marshal(container)
|
|
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(bytes.NewReader(body))}, err
|
|
}
|
|
if transport.imagesAvailable && request.Method == http.MethodPost && strings.HasSuffix(request.URL.Path, "/images/create") {
|
|
if transport.onImagePull != nil {
|
|
if err := transport.onImagePull(request.Context()); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"status":"Image ready"}`))}, nil
|
|
}
|
|
if transport.imagesAvailable && request.Method == http.MethodGet && strings.Contains(request.URL.Path, "/images/") && strings.HasSuffix(request.URL.Path, "/json") {
|
|
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"Id":"sha256:` + strings.Repeat("b", 64) + `","Config":{}}`))}, nil
|
|
}
|
|
if transport.createConflict && request.Method == http.MethodPost && strings.HasSuffix(request.URL.Path, "/containers/create") {
|
|
return &http.Response{StatusCode: http.StatusConflict, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"message":"Container name is already in use"}`))}, nil
|
|
}
|
|
if transport.startedState != "" {
|
|
status, body := 0, ""
|
|
switch {
|
|
case request.Method == http.MethodPost && strings.HasSuffix(request.URL.Path, "/containers/create"):
|
|
status, body = http.StatusCreated, `{"Id":`+strconv.Quote(reinstallFixtureContainerID)+`}`
|
|
case request.Method == http.MethodPost && strings.HasSuffix(request.URL.Path, "/containers/"+reinstallFixtureContainerID+"/start"):
|
|
status = http.StatusNoContent
|
|
case request.Method == http.MethodGet && strings.HasSuffix(request.URL.Path, "/containers/alpha/json"):
|
|
if transport.failStartedInspection != nil && transport.failStartedInspection() {
|
|
return &http.Response{StatusCode: http.StatusServiceUnavailable, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"message":"Docker inspection unavailable"}`))}, nil
|
|
}
|
|
container := dockerContainerInspectForStats{ID: reinstallFixtureContainerID, Name: "/alpha",
|
|
State: dockerContainerStateForStats{Status: transport.startedState, Running: transport.startedState == "running"},
|
|
Config: dockerContainerConfigLabels{Labels: transport.startedLabels},
|
|
}
|
|
encoded, err := json.Marshal(container)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
status, body = http.StatusOK, string(encoded)
|
|
}
|
|
if status != 0 {
|
|
return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
|
}
|
|
}
|
|
if !transport.failRemoval {
|
|
return &http.Response{StatusCode: http.StatusNotFound, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"message":"No such container"}`))}, nil
|
|
}
|
|
status := http.StatusInternalServerError
|
|
body := `{"message":"container removal failed"}`
|
|
if request.Method == http.MethodGet && strings.HasSuffix(request.URL.Path, "/json") {
|
|
status = http.StatusOK
|
|
body = `{"Id":` + strconv.Quote(reinstallFixtureContainerID) + `,"Name":"/alpha","State":{"Running":true},"Labels":{"adpanel.server":"alpha"}}`
|
|
if transport.failRemovalAfterStop && strings.HasSuffix(request.URL.Path, "/containers/"+reinstallFixtureContainerID+"/json") {
|
|
body = `{"Id":` + strconv.Quote(reinstallFixtureContainerID) + `,"Name":"/alpha","State":{"Running":false,"Status":"exited"},"Labels":{"adpanel.server":"alpha"}}`
|
|
}
|
|
}
|
|
return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
|
}
|
|
|
|
func TestReinstallReplacesRunningContainerAfterPortRelease(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const serverName = "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
listener, err := net.Listen("tcp4", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer listener.Close()
|
|
port := listener.Addr().(*net.TCPAddr).Port
|
|
previousFile := filepath.Join(serverDir, "world-data.txt")
|
|
oldID := strings.Repeat("a", 64)
|
|
binDir := t.TempDir()
|
|
stopTarget := filepath.Join(binDir, "stop-target")
|
|
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte("#!/bin/sh\nif [ \"$1\" = stop ]; then printf '%s' \"$4\" > \"$TEST_STOP_TARGET\"; else exit 1; fi\n"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
|
t.Setenv("TEST_STOP_TARGET", stopTarget)
|
|
removed, created, started := false, false, false
|
|
var createdLabels map[string]string
|
|
baseTransport := reinstallDockerRemovalTransport{imagesAvailable: true}
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(request *http.Request) (*http.Response, error) {
|
|
path := request.URL.Path
|
|
status, body := http.StatusNoContent, ""
|
|
switch {
|
|
case request.Method == http.MethodGet && strings.HasSuffix(path, "/containers/alpha/json") && (!removed || started):
|
|
container := dockerContainerInspectForStats{
|
|
ID: oldID, Name: "/alpha", Labels: map[string]string{dockerServerOwnershipLabel: serverName},
|
|
State: dockerContainerStateForStats{Running: true, Status: "running"},
|
|
}
|
|
if started {
|
|
container.ID = reinstallFixtureContainerID
|
|
container.Config.Labels = createdLabels
|
|
} else {
|
|
container.HostConfig.PortBindings = map[string][]dockerPortBinding{
|
|
strconv.Itoa(port) + "/tcp": {{HostIP: "0.0.0.0", HostPort: strconv.Itoa(port)}},
|
|
}
|
|
}
|
|
encoded, err := json.Marshal(container)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
status, body = http.StatusOK, string(encoded)
|
|
case request.Method == http.MethodDelete:
|
|
if !strings.HasSuffix(path, "/containers/"+oldID) || removed || request.URL.Query().Has("force") {
|
|
t.Fatalf("expected exactly one non-forced removal of the old Docker ID, got %s", request.URL)
|
|
}
|
|
if target, err := os.ReadFile(stopTarget); err != nil || string(target) != oldID {
|
|
t.Fatalf("expected graceful stop of the old Docker ID before removal, got %q: %v", target, err)
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
if err := listener.Close(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
removed = true
|
|
case request.Method == http.MethodPost && strings.HasSuffix(path, "/containers/create"):
|
|
if _, err := os.Stat(previousFile); !removed || !os.IsNotExist(err) {
|
|
t.Fatalf("Docker create must follow removal and file publication, removed=%t, stat=%v", removed, err)
|
|
}
|
|
var create dockerContainerCreateRequest
|
|
if err := json.NewDecoder(request.Body).Decode(&create); err != nil {
|
|
return nil, err
|
|
}
|
|
if create.Image != "sha256:"+strings.Repeat("b", 64) || reinstallRollbackServerName(create.Labels[reinstallContainerLabel]) != serverName {
|
|
t.Fatalf("replacement must use the inspected image and carry the handoff label: %s %v", create.Image, create.Labels)
|
|
}
|
|
createdLabels = create.Labels
|
|
created = true
|
|
status, body = http.StatusCreated, `{"Id":`+strconv.Quote(reinstallFixtureContainerID)+`}`
|
|
case request.Method == http.MethodPost && strings.HasSuffix(path, "/start"):
|
|
if !created || !strings.HasSuffix(path, "/containers/"+reinstallFixtureContainerID+"/start") {
|
|
t.Fatalf("expected Docker start of the replacement ID, got %s", path)
|
|
}
|
|
started = true
|
|
case request.Method == http.MethodPost && strings.HasSuffix(path, "/kill"):
|
|
t.Fatalf("reinstall must not hard-kill the original container: %s", path)
|
|
default:
|
|
return baseTransport.RoundTrip(request)
|
|
}
|
|
return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
|
})}
|
|
response := runReinstall(t, agent, serverName, "nodejs", map[string]any{"templateId": "nodejs", "hostPort": port})
|
|
if response.Code != http.StatusOK || decodeResponse(t, response)["serverRunning"] != true || !started {
|
|
t.Fatalf("expected a confirmed running replacement, got %d: %s", response.Code, response.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestReinstallFailedContainerRemovalPreservesServer(t *testing.T) {
|
|
for _, scenario := range []struct {
|
|
name string
|
|
stopped bool
|
|
}{{"graceful stop failed", false}, {"stopped but not removed", true}} {
|
|
t.Run(scenario.name, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
if scenario.stopped {
|
|
binDir := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte("#!/bin/sh\n[ \"$1\" = stop ]\n"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
|
}
|
|
var attemptedRemoval bool
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
|
|
failRemoval: true, failRemovalAfterStop: scenario.stopped,
|
|
onRemovalTarget: func(string) { attemptedRemoval = true },
|
|
}}
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
body := decodeResponse(t, response)
|
|
if response.Code != http.StatusInternalServerError || body["serverStopped"] != scenario.stopped || attemptedRemoval != scenario.stopped {
|
|
t.Fatalf("failed teardown must preserve the server and accurately report its state, got %d: %v (removal attempted: %t)", response.Code, body, attemptedRemoval)
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
if operation := agent.tryLockServerOp(serverName); operation == nil {
|
|
t.Fatal("failed removal must release the reinstall operation lock")
|
|
} else {
|
|
operation.Unlock()
|
|
}
|
|
if agent.longOpKind(serverName) != "" {
|
|
t.Fatal("failed removal must release the reinstall marker")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallRefusesContainerOwnedByDifferentServer(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
|
|
containerOwner: "other-server",
|
|
onRemoval: func() { t.Error("reinstall must not remove another server's container") },
|
|
}}
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
if response.Code != http.StatusServiceUnavailable || !strings.Contains(response.Body.String(), "ownership") {
|
|
t.Fatalf("expected ownership refusal for a rebuild without bindings: %d %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
|
|
func TestReinstallRefusesPendingServerStop(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
requestedAt := time.Now()
|
|
agent.stoppingNow[serverName] = requestedAt
|
|
removed := false
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
|
|
containerOwner: serverName,
|
|
onRemovalTarget: func(string) { removed = true },
|
|
}}
|
|
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
if response.Code != http.StatusConflict || decodeResponse(t, response)["code"] != "server_stop_in_progress" {
|
|
t.Fatalf("reinstall must wait for the pending stop: %d %s", response.Code, response.Body.String())
|
|
}
|
|
if removed || !agent.stoppingNow[serverName].Equal(requestedAt) {
|
|
t.Fatal("refused reinstall must not take over or clear the pending stop")
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
|
|
func TestReinstallRefusesUnmanagedDockerVolume(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const serverName = "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
var teardownAttempted bool
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(req *http.Request) (*http.Response, error) {
|
|
if req.Method == http.MethodDelete {
|
|
teardownAttempted = true
|
|
}
|
|
if req.Method == http.MethodGet && strings.HasSuffix(req.URL.Path, "/containers/alpha/json") {
|
|
body := `{"Id":"` + reinstallFixtureContainerID + `","Name":"/alpha","Config":{"Labels":{"adpanel.server":"alpha"}},"State":{"Running":false,"Status":"exited"},"Mounts":[{"Type":"volume"}]}`
|
|
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
|
}
|
|
return (reinstallDockerRemovalTransport{}).RoundTrip(req)
|
|
})}
|
|
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
if response.Code != http.StatusConflict || !strings.Contains(response.Body.String(), "Migrate their data") || teardownAttempted {
|
|
t.Fatalf("reinstall must preserve the container and unmanaged volume: %d %s (teardown attempted: %t)", response.Code, response.Body.String(), teardownAttempted)
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
|
|
func TestReinstallRemovesOnlyInspectedContainer(t *testing.T) {
|
|
for scenario, owner := range map[string]string{"verified": "alpha", "absent": ""} {
|
|
t.Run(scenario, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
seedRaceServer(t, agent, serverName)
|
|
oldConsole := &stdinConn{}
|
|
agent.stdinMgr = &stdinManager{conns: map[string]*stdinConn{serverName: oldConsole}}
|
|
var removed []string
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
|
|
containerOwner: owner,
|
|
onRemovalTarget: func(target string) {
|
|
removed = append(removed, target)
|
|
},
|
|
}}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("expected successful reinstall: %d %s", response.Code, response.Body.String())
|
|
}
|
|
if owner == "" && len(removed) != 0 || owner != "" && (len(removed) != 1 || removed[0] != reinstallFixtureContainerID) {
|
|
t.Fatalf("removal must use only the inspected Docker ID, or skip an absent container: %v", removed)
|
|
}
|
|
if !oldConsole.closed || agent.stdinMgr.conns[serverName] != nil {
|
|
t.Fatal("the replacement must not inherit the old console connection")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallLegacyContainerRequiresServerVolume(t *testing.T) {
|
|
for _, owned := range []bool{true, false} {
|
|
t.Run(strconv.FormatBool(owned), func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
source := t.TempDir()
|
|
if owned {
|
|
source = serverDir
|
|
}
|
|
removed := false
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
|
|
legacyMount: source, onRemovalTarget: func(string) { removed = true },
|
|
}}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
if owned {
|
|
if response.Code != http.StatusOK || !removed {
|
|
t.Fatalf("verified legacy storage must permit reinstall: %d %s", response.Code, response.Body.String())
|
|
}
|
|
} else {
|
|
if response.Code != http.StatusServiceUnavailable || removed {
|
|
t.Fatalf("a same-name container with unrelated storage must refuse the reinstall: %d %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallCanceledDuringContainerStopPreservesFiles(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const serverName = "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
request, response := signedReinstallRequest(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
ctx, cancel := context.WithCancel(request.Context())
|
|
defer cancel()
|
|
binDir := t.TempDir()
|
|
stopTarget := filepath.Join(binDir, "stop-target")
|
|
stopRelease := filepath.Join(binDir, "stop-release")
|
|
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte(`#!/bin/sh
|
|
[ "$1" = stop ] || exit 1
|
|
mkfifo "$REINSTALL_STOP_RELEASE" || exit 1
|
|
printf '%s\n' "$4" > "$REINSTALL_STOP_TARGET" || exit 1
|
|
read -r release < "$REINSTALL_STOP_RELEASE"
|
|
`), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
|
t.Setenv("REINSTALL_STOP_TARGET", stopTarget)
|
|
t.Setenv("REINSTALL_STOP_RELEASE", stopRelease)
|
|
removed := false
|
|
fixture := reinstallDockerRemovalTransport{onRemovalTarget: func(string) { removed = true }}
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(req *http.Request) (*http.Response, error) {
|
|
if req.Method == http.MethodGet && strings.HasSuffix(req.URL.Path, "/containers/alpha/json") {
|
|
body := `{"Id":"` + reinstallFixtureContainerID + `","Name":"/alpha","Config":{"Labels":{"adpanel.server":"alpha"}},"State":{"Running":true,"Status":"running"}}`
|
|
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
|
}
|
|
return fixture.RoundTrip(req)
|
|
})}
|
|
|
|
completed := make(chan struct{})
|
|
go func() {
|
|
agent.handleReinstallServer(response, request.WithContext(ctx), serverName)
|
|
close(completed)
|
|
}()
|
|
ready := time.NewTicker(10 * time.Millisecond)
|
|
defer ready.Stop()
|
|
deadline := time.NewTimer(3 * time.Second)
|
|
defer deadline.Stop()
|
|
for {
|
|
select {
|
|
case <-completed:
|
|
t.Fatalf("reinstall finished before stopping Docker: %d %s", response.Code, response.Body.String())
|
|
case <-deadline.C:
|
|
t.Fatal("Docker did not begin stopping the original container")
|
|
case <-ready.C:
|
|
}
|
|
if target, err := os.ReadFile(stopTarget); err == nil && strings.TrimSpace(string(target)) == reinstallFixtureContainerID {
|
|
break
|
|
}
|
|
}
|
|
release, err := os.OpenFile(stopRelease, os.O_RDWR, 0)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer release.Close()
|
|
cancel()
|
|
select {
|
|
case <-completed:
|
|
t.Fatal("reinstall released the server while Docker was still stopping it")
|
|
case <-time.After(50 * time.Millisecond):
|
|
}
|
|
if _, err := release.WriteString("done\n"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
select {
|
|
case <-completed:
|
|
case <-time.After(3 * time.Second):
|
|
t.Fatal("reinstall did not return after the Docker stop finished")
|
|
}
|
|
|
|
if body := decodeResponse(t, response); response.Code != http.StatusRequestTimeout || body["serverStopped"] != true || removed {
|
|
t.Fatalf("canceled reinstall must wait for Docker to stop without removing the container: %d %v (removed=%t)", response.Code, body, removed)
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
|
|
func TestReinstallCanceledDuringContainerRemovalPreservesFiles(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
request, response := signedReinstallRequest(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
ctx, cancel := context.WithCancel(request.Context())
|
|
defer cancel()
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{onRemoval: cancel}}
|
|
|
|
agent.handleReinstallServer(response, request.WithContext(ctx), serverName)
|
|
|
|
if response.Code != http.StatusRequestTimeout {
|
|
t.Fatalf("request canceled before the wipe must retain server files: %d %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
|
|
type reinstallStorageBarrierWriter struct {
|
|
*httptest.ResponseRecorder
|
|
started chan struct{}
|
|
}
|
|
|
|
func (writer *reinstallStorageBarrierWriter) SetWriteDeadline(time.Time) error {
|
|
close(writer.started)
|
|
return nil
|
|
}
|
|
|
|
func TestReinstallSerializesWithStorageWrites(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
releaseStorage := agent.lockUploadScope(agent.fsScopeRootFor(serverName, serverDir))
|
|
storageHeld := true
|
|
defer func() {
|
|
if storageHeld {
|
|
releaseStorage()
|
|
}
|
|
}()
|
|
request, recorder := signedReinstallRequest(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
writer := &reinstallStorageBarrierWriter{ResponseRecorder: recorder, started: make(chan struct{})}
|
|
completed := make(chan struct{})
|
|
go func() {
|
|
agent.handleReinstallServer(writer, request, serverName)
|
|
close(completed)
|
|
}()
|
|
<-writer.started
|
|
select {
|
|
case <-completed:
|
|
t.Fatal("reinstall completed while an upload or editor write held the server storage lock")
|
|
case <-time.After(100 * time.Millisecond):
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
releaseStorage()
|
|
storageHeld = false
|
|
select {
|
|
case <-completed:
|
|
case <-time.After(time.Second):
|
|
t.Fatal("reinstall did not resume after the storage writer completed")
|
|
}
|
|
if recorder.Code != http.StatusOK {
|
|
t.Fatalf("serialized reinstall failed: %d %s", recorder.Code, recorder.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestReinstallRejectsUploadWithOldDirectoryHandle(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const name = "alpha"
|
|
serverDir := seedRaceServer(t, agent, name)
|
|
root, err := safeOpenRoot(serverDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer root.Close()
|
|
stagingDir, err := createServerStagingDir(serverDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := agent.commitReinstallFiles(serverDir, stagingDir, buildReinstallMetadata("custom", 30005, nil)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var payload bytes.Buffer
|
|
form := multipart.NewWriter(&payload)
|
|
file, err := form.CreateFormFile("file", "new.txt")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := io.WriteString(file, "new data"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := form.Close(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
part, err := multipart.NewReader(&payload, form.Boundary()).NextPart()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
_, _, status, body := agent.storeStreamUploadPart(context.Background(), root, serverDir, ".", part, false)
|
|
if status != http.StatusConflict {
|
|
t.Fatalf("upload must not write through the original directory handle: %d %v", status, body)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(serverDir, "new.txt")); !os.IsNotExist(err) {
|
|
t.Fatalf("upload touched replacement files: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestReinstallCanceledWaitingForStorageReleasesClaim(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const serverName = "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
t.Cleanup(agent.lockUploadScope(serverDir))
|
|
request, recorder := signedReinstallRequest(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
ctx, cancel := context.WithCancel(request.Context())
|
|
defer cancel()
|
|
writer := &reinstallStorageBarrierWriter{ResponseRecorder: recorder, started: make(chan struct{})}
|
|
completed := make(chan struct{})
|
|
go func() {
|
|
defer close(completed)
|
|
agent.handleReinstallServer(writer, request.WithContext(ctx), serverName)
|
|
}()
|
|
select {
|
|
case <-writer.started:
|
|
cancel()
|
|
case <-time.After(2 * time.Second):
|
|
t.Fatal("reinstall did not acquire its operation lock")
|
|
}
|
|
select {
|
|
case <-completed:
|
|
case <-time.After(2 * time.Second):
|
|
t.Fatal("canceled reinstall kept waiting for the storage lock")
|
|
}
|
|
if recorder.Code != http.StatusRequestTimeout || agent.longOpKind(serverName) != "" {
|
|
t.Fatalf("expected a canceled reinstall with no marker, got %d: %s", recorder.Code, recorder.Body.String())
|
|
}
|
|
operation := agent.tryLockServerOp(serverName)
|
|
if operation == nil {
|
|
t.Fatal("canceled reinstall did not release its operation lock")
|
|
}
|
|
operation.Unlock()
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
|
|
func TestReinstallDockerHubImagePreflight(t *testing.T) {
|
|
t.Setenv("ADPANEL_ALLOWED_TEMPLATE_IMAGE_REGISTRIES", "docker.io,ghcr.io")
|
|
agent := newReinstallRaceTestAgent(t)
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{imagesAvailable: true}}
|
|
serverName := "alpha"
|
|
runtimeConfig := map[string]any{"image": "node", "tag": "20-alpine"}
|
|
status, reason := agent.preflightReinstallRuntime(context.Background(), serverName, "custom", runtimeConfig)
|
|
if status != http.StatusOK || reason != "" {
|
|
t.Fatalf("ordinary tagged Docker Hub image must pass preflight: %d %s", status, reason)
|
|
}
|
|
if reason := validateTemplateImageRef(runtimeImageRef(runtimeConfig)); reason != "" {
|
|
t.Fatalf("the image accepted before the wipe must remain accepted at container start: %s", reason)
|
|
}
|
|
}
|
|
|
|
func TestReinstallOccupiedUDPPortPreservesServer(t *testing.T) {
|
|
listener, err := net.ListenPacket("udp4", "0.0.0.0:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer listener.Close()
|
|
port := listener.LocalAddr().(*net.UDPAddr).Port
|
|
agent := newReinstallRaceTestAgent(t)
|
|
binDir := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte(`#!/bin/sh
|
|
case "$1" in
|
|
create|rm) exit 0 ;;
|
|
cp) printf '%s\n' 'Could not find the file in container' >&2 ;;
|
|
esac
|
|
exit 1
|
|
`), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
|
|
imagesAvailable: true,
|
|
onRemoval: func() { t.Error("a pre-existing port conflict must not remove the live container") },
|
|
}}
|
|
serverName := "alpha"
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{
|
|
"templateId": "custom", "hostPort": port,
|
|
"docker": map[string]any{"image": "node", "tag": "20-alpine", "command": "node index.js", "ports": []int{27015},
|
|
"portProtocols": map[string][]string{"27015": {"udp"}}},
|
|
})
|
|
if response.Code != http.StatusConflict || !strings.Contains(response.Body.String(), "no server files were replaced") {
|
|
t.Fatalf("an occupied UDP port must refuse the wipe: %d %s", response.Code, response.Body.String())
|
|
}
|
|
if body := decodeResponse(t, response); body["serverStopped"] != false || body["reinstalled"] != nil {
|
|
t.Fatalf("port refusal must leave the live container alone without claiming a rebuild: %v", body)
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
|
|
func TestReinstallPortPreflightHonorsBindingAddress(t *testing.T) {
|
|
listener, err := net.ListenPacket("udp4", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer listener.Close()
|
|
port := strconv.Itoa(listener.LocalAddr().(*net.UDPAddr).Port)
|
|
agent := newReinstallRaceTestAgent(t)
|
|
status, reason := agent.checkReinstallPortBindings(context.Background(), map[string][]dockerPortBinding{
|
|
"27015/udp": {{HostIP: "127.0.0.2", HostPort: port}},
|
|
}, "", nil)
|
|
if status != http.StatusOK || reason != "" {
|
|
t.Fatalf("an unrelated listening address cannot block a private binding: %d %s", status, reason)
|
|
}
|
|
}
|
|
|
|
func TestReinstallPortPreflightDefersOnlyCurrentContainerBindings(t *testing.T) {
|
|
currentListener, err := net.Listen("tcp4", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer currentListener.Close()
|
|
port := strconv.Itoa(currentListener.Addr().(*net.TCPAddr).Port)
|
|
otherListener, err := net.ListenPacket("udp4", net.JoinHostPort("127.0.0.1", port))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer otherListener.Close()
|
|
agent := newReinstallRaceTestAgent(t)
|
|
current := map[string][]dockerPortBinding{"80/tcp": {{HostIP: "0.0.0.0", HostPort: port}}}
|
|
replacement := map[string][]dockerPortBinding{"3000/tcp": {{HostIP: "127.0.0.1", HostPort: port}}}
|
|
status, reason := agent.checkReinstallPortBindings(context.Background(), replacement, "alpha", current)
|
|
if status != http.StatusOK || reason != "" {
|
|
t.Fatalf("a replacement can reuse a binding once its old container releases it: %d %s", status, reason)
|
|
}
|
|
replacement["3000/udp"] = replacement["3000/tcp"]
|
|
status, reason = agent.checkReinstallPortBindings(context.Background(), replacement, "alpha", current)
|
|
if status != http.StatusConflict || !strings.Contains(reason, port) {
|
|
t.Fatalf("the current TCP binding must not exempt a different protocol: %d %s", status, reason)
|
|
}
|
|
}
|
|
|
|
func TestReinstallUnavailableImagePreservesServer(t *testing.T) {
|
|
for _, scenario := range []struct {
|
|
name string
|
|
template string
|
|
docker map[string]any
|
|
}{
|
|
{name: "default runtime", template: "python"},
|
|
{name: "installer", template: "custom", docker: map[string]any{"install": map[string]any{
|
|
"image": "docker.io/library/alpine:3.20", "script": "echo fixture",
|
|
}}},
|
|
} {
|
|
t.Run(scenario.name, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{onRemoval: func() {
|
|
t.Fatal("image preparation failure must not remove the existing container")
|
|
}}}
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
response := runReinstall(t, agent, serverName, scenario.template, map[string]any{"templateId": scenario.template, "docker": scenario.docker})
|
|
if response.Code != http.StatusInternalServerError || !strings.Contains(response.Body.String(), "no server files were replaced") {
|
|
t.Fatalf("unavailable images must refuse before the wipe: %d %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallManagedRuntimeMissingImageUsesDefaults(t *testing.T) {
|
|
for _, template := range []string{"python", "nodejs", "discord-bot"} {
|
|
t.Run(template, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{imagesAvailable: true}}
|
|
serverName := "alpha"
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
runtimeConfig := map[string]any{}
|
|
if status, reason := agent.preflightReinstallRuntime(context.Background(), serverName, template, runtimeConfig); status != http.StatusOK || reason != "" {
|
|
t.Fatalf("managed preflight must resolve defaults: %d %s", status, reason)
|
|
}
|
|
wantImage, wantTag := "docker.io/library/node", "20-alpine"
|
|
if template == "python" {
|
|
wantImage, wantTag = "docker.io/library/python", "3.12-slim"
|
|
}
|
|
if runtimeConfig["image"] != wantImage || runtimeConfig["tag"] != wantTag {
|
|
t.Fatalf("a rebuild without stored image metadata must resolve its managed defaults: %v", runtimeConfig)
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallManagedDefaultImagePolicyPrecedesWipe(t *testing.T) {
|
|
t.Setenv("ADPANEL_ALLOWED_TEMPLATE_IMAGE_REGISTRIES", "ghcr.io")
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
response := runReinstall(t, agent, serverName, "python", map[string]any{"templateId": "python"})
|
|
if response.Code != http.StatusBadRequest {
|
|
t.Fatalf("a disallowed effective default image must be rejected before deletion: %d %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
|
|
func TestManagedRuntimeImagePreservesConfiguredImageAndTag(t *testing.T) {
|
|
image, tag := managedRuntimeImage("python", map[string]any{"image": "ghcr.io/example/runtime", "tag": "custom"})
|
|
if image != "ghcr.io/example/runtime" || tag != "custom" {
|
|
t.Fatalf("explicit image configuration must not be replaced by defaults: %s:%s", image, tag)
|
|
}
|
|
}
|
|
|
|
func TestReinstallMinecraftDefaultImagePreflight(t *testing.T) {
|
|
for _, javaVersion := range []string{"", "21"} {
|
|
runtimeConfig := map[string]any{"image": defaultMinecraftProcessImage, "tag": defaultMinecraftProcessTag}
|
|
if javaVersion != "" {
|
|
runtimeConfig["javaVersion"] = javaVersion
|
|
}
|
|
if err := configureMinecraftReinstall(buildReinstallMetadata("minecraft", 30005, nil), runtimeConfig); err != nil {
|
|
t.Fatalf("the stock Minecraft Java image must pass reinstall preflight: %v", err)
|
|
}
|
|
}
|
|
t.Setenv("ADPANEL_ALLOWED_TEMPLATE_IMAGE_REGISTRIES", "ghcr.io")
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
response := runReinstall(t, agent, serverName, "minecraft", map[string]any{"templateId": "minecraft"})
|
|
if response.Code != http.StatusBadRequest {
|
|
t.Fatalf("a disallowed effective default image must refuse before deletion: %d %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
|
|
func TestReinstallMetadataPreservesMinecraftSelection(t *testing.T) {
|
|
oldMeta := map[string]any{"type": "minecraft", "template": "minecraft", "fork": "purpur", "version": "1.20.6"}
|
|
meta := buildReinstallMetadata("minecraft", 30005, oldMeta)
|
|
if meta["fork"] != "purpur" || meta["version"] != "1.20.6" {
|
|
t.Fatalf("same-template reinstall must preserve the installed Minecraft fork and version: %v", meta)
|
|
}
|
|
}
|
|
|
|
func TestReinstallMinecraftPreparationPreservesSelection(t *testing.T) {
|
|
meta := buildReinstallMetadata("minecraft", 30005, map[string]any{"type": "minecraft", "fork": "vanilla", "version": "1.20.6"})
|
|
if err := configureMinecraftReinstall(meta, nil); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if meta["fork"] != "vanilla" || meta["version"] != "1.20.6" {
|
|
t.Fatalf("Minecraft preparation must use the installed selection, not fixed defaults: %v", meta)
|
|
}
|
|
}
|
|
|
|
func TestReinstallMinecraftQuotaFailurePreservesServer(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
disk := registerTestDisk(t, agent, t.TempDir(), 1)
|
|
agent.setServerDiskMapping(serverName, disk.ID)
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
backupDir := agent.serverBackupsDir(serverName)
|
|
if err := os.MkdirAll(backupDir, 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
backup, err := os.Create(filepath.Join(backupDir, "full-disk-backup"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := backup.Truncate(1 << 30); err != nil {
|
|
backup.Close()
|
|
t.Fatal(err)
|
|
}
|
|
if err := backup.Close(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := runReinstall(t, agent, serverName, "minecraft", map[string]any{"templateId": "minecraft", "hostPort": 30005})
|
|
body := decodeResponse(t, response)
|
|
if response.Code != http.StatusInsufficientStorage || body["code"] != "reinstall_disk_limit_exceeded" || body["reinstalled"] != nil || body["ok"] != false {
|
|
t.Fatalf("temporary quota failure must refuse before deleting files: %d %v", response.Code, body)
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
assertNoStagingSiblings(t, serverDir)
|
|
if _, err := os.Stat(filepath.Join(serverDir, "server.jar")); !os.IsNotExist(err) {
|
|
t.Fatalf("quota refusal must not create a jar: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestReinstallMinecraftDownloadFailurePreservesServer(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := buildReinstallMetadata("minecraft", 30005, agent.loadMeta(serverDir))
|
|
response := httptest.NewRecorder()
|
|
staging := agent.stageMinecraftReinstall(response, context.Background(), serverName, serverDir, meta, nil,
|
|
func(downloader Downloader, _ context.Context, _ string, destPath string) error {
|
|
return downloader.writeDownloadToFile(io.MultiReader(strings.NewReader("partial jar"), errReader{err: errors.New("download interrupted")}), destPath)
|
|
})
|
|
if staging != "" || response.Code != http.StatusInternalServerError || decodeResponse(t, response)["code"] != "reinstall_download_failed" {
|
|
t.Fatalf("interrupted staging must not admit the wipe: %q %d %s", staging, response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
assertNoStagingSiblings(t, serverDir)
|
|
}
|
|
|
|
func TestReinstallMinecraftOnlySwapsACompleteJar(t *testing.T) {
|
|
var jar bytes.Buffer
|
|
archive := zip.NewWriter(&jar)
|
|
manifest, err := archive.Create("META-INF/MANIFEST.MF")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := io.WriteString(manifest, "Manifest-Version: 1.0\n"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
class, err := archive.CreateHeader(&zip.FileHeader{Name: "Server.class", Method: zip.Store})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
const classPayload = "test-server-class-payload"
|
|
if _, err := io.WriteString(class, classPayload); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := archive.Close(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
corruptJar := bytes.Replace(jar.Bytes(), []byte(classPayload), []byte("bad!-server-class-payload"), 1)
|
|
if len(corruptJar) != jar.Len() || bytes.Equal(corruptJar, jar.Bytes()) {
|
|
t.Fatal("corruption must only modify the entry bytes")
|
|
}
|
|
for _, scenario := range []struct {
|
|
name string
|
|
payload []byte
|
|
limit int64
|
|
wantCode string
|
|
imageUnavailable bool
|
|
}{
|
|
{name: "valid jar", payload: jar.Bytes(), wantCode: "minecraft_eula_required"},
|
|
{name: "truncated jar", payload: jar.Bytes(), limit: int64(jar.Len() - 1), wantCode: "reinstall_download_failed"},
|
|
{name: "corrupt jar entry", payload: corruptJar, wantCode: "reinstall_download_failed"},
|
|
{name: "not a jar", payload: []byte("provider error response"), wantCode: "reinstall_download_failed"},
|
|
{name: "unavailable runtime image", payload: jar.Bytes(), wantCode: "reinstall_image_pull_failed", imageUnavailable: true},
|
|
} {
|
|
t.Run(scenario.name, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
|
|
imagesAvailable: !scenario.imageUnavailable,
|
|
onRemoval: func() {
|
|
if scenario.imageUnavailable {
|
|
t.Fatal("image preparation failure must not remove the existing container")
|
|
}
|
|
},
|
|
}}
|
|
agent.dl.maxBytes = scenario.limit
|
|
serverName := "alpha"
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
request, response := signedReinstallRequest(t, agent, serverName, "minecraft", nil)
|
|
agent.rebuildReinstallServer(response, request, serverName, serverDir, "minecraft", 30005, agent.loadMeta(serverDir), nil, nil, "", false,
|
|
func(downloader Downloader, _ context.Context, _ string, destPath string) error {
|
|
stagingName := filepath.Base(filepath.Dir(destPath))
|
|
if sanitizeName(stagingName) == stagingName {
|
|
t.Fatalf("staging must be outside the daemon server namespace: %q", stagingName)
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
return downloader.writeDownloadToFile(bytes.NewReader(scenario.payload), destPath)
|
|
})
|
|
if body := decodeResponse(t, response); body["code"] != scenario.wantCode {
|
|
t.Fatalf("unexpected staged rebuild outcome: %v", body)
|
|
}
|
|
assertNoStagingSiblings(t, serverDir)
|
|
if scenario.wantCode != "minecraft_eula_required" {
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
return
|
|
}
|
|
if _, err := os.Stat(filepath.Join(serverDir, "world-data.txt")); !os.IsNotExist(err) {
|
|
t.Fatalf("successful rebuild must remove the old files: %v", err)
|
|
}
|
|
if actual, err := os.ReadFile(filepath.Join(serverDir, "server.jar")); err != nil || !bytes.Equal(actual, jar.Bytes()) {
|
|
t.Fatalf("successful rebuild must commit the complete jar: %v", err)
|
|
}
|
|
if meta := agent.loadMeta(serverDir); meta["hostPort"] != float64(30005) || meta["type"] != "minecraft" {
|
|
t.Fatalf("successful rebuild must commit its new metadata: %v", meta)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallMinecraftSelection(t *testing.T) {
|
|
for _, scenario := range []struct {
|
|
name string
|
|
meta map[string]any
|
|
fork string
|
|
version string
|
|
}{
|
|
{"installed selection", map[string]any{"type": "minecraft", "fork": "purpur", "version": "1.20.6"}, "purpur", "1.20.6"},
|
|
{"legacy identifiers", map[string]any{"fork": "vanilla", "version": "24w14a"}, "vanilla", "24w14a"},
|
|
{"legacy alias", map[string]any{"template": "minecraft", "fork": "Spigot", "version": "1.21.8-pre1"}, "paper", "1.21.8-pre1"},
|
|
{"missing selection", nil, "paper", "1.21.8"},
|
|
{"different template", map[string]any{"type": "python", "fork": "invalid", "version": "../invalid"}, "paper", "1.21.8"},
|
|
} {
|
|
t.Run(scenario.name, func(t *testing.T) {
|
|
fork, version, err := reinstallMinecraftSelection(scenario.meta)
|
|
if err != nil || fork != scenario.fork || version != scenario.version {
|
|
t.Fatalf("unexpected reinstall selection: %s %s %v", fork, version, err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallMinecraftSelectionPreflightPreservesServer(t *testing.T) {
|
|
for _, selection := range []map[string]any{{"fork": "unsupported"}, {"version": "../invalid"}} {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["type"] = "minecraft"
|
|
for key, value := range selection {
|
|
meta[key] = value
|
|
}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := runReinstall(t, agent, serverName, "minecraft", map[string]any{"templateId": "minecraft"})
|
|
if response.Code != http.StatusBadRequest {
|
|
t.Fatalf("invalid installed selection must refuse before wiping files: %d %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
}
|
|
|
|
func TestReinstallMinecraftPreservesPortProtocolPolicy(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := buildReinstallMetadata("minecraft", 30005, map[string]any{
|
|
"type": "minecraft", "resources": map[string]any{"ports": []int{30006}},
|
|
})
|
|
runtimeConfig := map[string]any{
|
|
"ports": []int{25565, 30006},
|
|
"portProtocols": map[string][]string{
|
|
"25565": {"tcp"}, "30006": {"udp"},
|
|
},
|
|
}
|
|
|
|
if err := configureMinecraftReinstall(meta, runtimeConfig); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
bindings, _ := agent.buildStructuredPortBindings(serverDir, meta, 30005, 25565)
|
|
if len(bindings["25565/tcp"]) != 1 || len(bindings["25565/udp"]) != 0 {
|
|
t.Fatalf("reinstall must retain the main port's TCP-only policy: %v", bindings)
|
|
}
|
|
if len(bindings["30006/udp"]) != 1 || len(bindings["30006/tcp"]) != 0 {
|
|
t.Fatalf("reinstall must retain the additional port's UDP-only policy: %v", bindings)
|
|
}
|
|
}
|
|
|
|
func TestReinstallMetadataFailureDoesNotReportSuccess(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
worldPath := filepath.Join(serverDir, "world-data.txt")
|
|
oldWorld, err := os.ReadFile(worldPath)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
metaPath := agent.metaPath(serverName)
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{onRemoval: func() {
|
|
if _, err := os.Stat(filepath.Join(metaPath, "blocked")); err == nil {
|
|
return
|
|
}
|
|
if err := os.Remove(metaPath); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.Mkdir(metaPath, 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(metaPath, "blocked"), []byte("fixture"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}}}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
if response.Code != http.StatusInternalServerError {
|
|
t.Fatalf("failed metadata persistence must not report reinstall success, got %d: %s", response.Code, response.Body.String())
|
|
}
|
|
body := decodeResponse(t, response)
|
|
if body["code"] != "reinstall_meta_save_failed" || body["ok"] != false {
|
|
t.Fatalf("expected explicit failed rebuild metadata outcome, got %v", body)
|
|
}
|
|
if actual, err := os.ReadFile(worldPath); err != nil || !bytes.Equal(actual, oldWorld) {
|
|
t.Fatalf("failed metadata persistence must leave the old server files intact: %v", err)
|
|
}
|
|
assertNoStagingSiblings(t, serverDir)
|
|
if operation := agent.tryLockServerOp(serverName); operation == nil {
|
|
t.Fatal("metadata failure must release the reinstall operation lock")
|
|
} else {
|
|
operation.Unlock()
|
|
}
|
|
if agent.longOpKind(serverName) != "" {
|
|
t.Fatal("metadata failure must release the reinstall marker")
|
|
}
|
|
}
|
|
|
|
func TestReinstallFailedDirectoryHandoffRestoresOriginal(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
missingStagingDir := filepath.Join(filepath.Dir(serverDir), ".missing-replacement")
|
|
if code, err := agent.commitReinstallFiles(serverDir, missingStagingDir, buildReinstallMetadata("minecraft", 30005, nil)); err == nil || code != "reinstall_file_replace_failed" {
|
|
t.Fatalf("expected a directory handoff failure, got %s: %v", code, err)
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
if recoveryDirs, err := filepath.Glob(filepath.Join(filepath.Dir(serverDir), ".alpha.reinstall-rollback-*")); err != nil || len(recoveryDirs) != 0 {
|
|
t.Fatalf("successful rollback must not leave temporary directories: %v %v", recoveryDirs, err)
|
|
}
|
|
}
|
|
|
|
func TestReinstallRecoversInterruptedFileHandoff(t *testing.T) {
|
|
for _, phase := range []string{"prepared", "original moved", "replacement published", "original restored", "metadata committed", "unrelated live directory"} {
|
|
t.Run(phase, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverDir := seedRaceServer(t, agent, "alpha")
|
|
rollbackDir, err := os.MkdirTemp(filepath.Dir(serverDir), ".alpha"+reinstallRollbackMarker)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
staging, err := createServerStagingDir(serverDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
original, err := reinstallDirectoryInode(serverDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
replacement, err := reinstallDirectoryInode(staging)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := agent.recordReinstallRollbackMetadata(serverDir, rollbackDir, original, replacement); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
stagedPath := filepath.Join(rollbackDir, "replacement")
|
|
if err := os.Rename(staging, stagedPath); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if phase != "prepared" {
|
|
if err := os.Rename(serverDir, filepath.Join(rollbackDir, "previous")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if phase != "prepared" && phase != "original moved" {
|
|
if phase == "unrelated live directory" {
|
|
err = os.Mkdir(serverDir, 0o750)
|
|
} else {
|
|
err = os.Rename(stagedPath, serverDir)
|
|
}
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(serverDir, "replacement.txt"), []byte("new"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if phase == "original restored" {
|
|
if err := restoreReinstallFiles(serverDir, rollbackDir, replacement); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if phase == "metadata committed" {
|
|
if err := agent.saveMeta(serverDir, map[string]any{"template": "custom", reinstallCommitMetadataKey: filepath.Base(rollbackDir)}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
agent.recoverInterruptedServerOperations()
|
|
|
|
if phase == "unrelated live directory" {
|
|
for _, path := range []string{filepath.Join(serverDir, "replacement.txt"), filepath.Join(rollbackDir, "previous", "world-data.txt")} {
|
|
if _, err := os.Stat(path); err != nil {
|
|
t.Fatalf("ambiguous recovery must preserve both directories: %v", err)
|
|
}
|
|
}
|
|
return
|
|
}
|
|
if phase == "metadata committed" {
|
|
if data, err := os.ReadFile(filepath.Join(serverDir, "replacement.txt")); err != nil || string(data) != "new" || agent.loadMeta(serverDir)["template"] != "custom" {
|
|
t.Fatalf("recovery must keep the committed replacement, got %q: %v", data, err)
|
|
}
|
|
} else {
|
|
assertServerDirUntouched(t, agent, "alpha", serverDir)
|
|
if _, err := os.Lstat(filepath.Join(serverDir, "replacement.txt")); !os.IsNotExist(err) {
|
|
t.Fatalf("an uncommitted replacement must not remain live: %v", err)
|
|
}
|
|
}
|
|
if _, err := os.Lstat(rollbackDir); !os.IsNotExist(err) {
|
|
t.Fatalf("completed recovery must remove its private rollback directory: %v", err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallRecoveryRespectsAssignedDisk(t *testing.T) {
|
|
for _, matches := range []bool{true, false} {
|
|
t.Run(strconv.FormatBool(matches), func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
disk := registerTestDisk(t, agent, t.TempDir(), 50)
|
|
agent.setServerDiskMapping("alpha", disk.ID)
|
|
serverDir := seedRaceServer(t, agent, "alpha")
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["__diskId"] = primaryDiskID
|
|
if matches {
|
|
meta["__diskId"] = disk.ID
|
|
}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
stagingDir, err := createServerStagingDir(serverDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
original, err := reinstallDirectoryInode(serverDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
replacement, err := reinstallDirectoryInode(stagingDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rollbackDir, err := os.MkdirTemp(filepath.Dir(serverDir), ".alpha"+reinstallRollbackMarker)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := agent.recordReinstallRollbackMetadata(serverDir, rollbackDir, original, replacement); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
previous := filepath.Join(rollbackDir, "previous")
|
|
if err := os.Rename(serverDir, previous); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
agent.invalidateServerDiskCache("alpha")
|
|
agent.recoverInterruptedServerOperations()
|
|
if matches {
|
|
assertServerDirUntouched(t, agent, "alpha", serverDir)
|
|
if agent.serverDir("alpha") != serverDir {
|
|
t.Fatal("recovery must retain the assigned disk")
|
|
}
|
|
} else {
|
|
if _, err := os.Lstat(serverDir); !os.IsNotExist(err) {
|
|
t.Fatalf("recovery must not move files onto the wrong disk: %v", err)
|
|
}
|
|
if data, err := os.ReadFile(filepath.Join(previous, "world-data.txt")); err != nil || string(data) != "precious" {
|
|
t.Fatalf("disk mismatch must retain the original files for inspection: %v", err)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallMissingDirectoryDoesNotInitializeNewServer(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
|
|
onRemoval: func() { t.Error("missing server files must not remove the existing container") },
|
|
}}
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
if err := os.Rename(serverDir, filepath.Join(filepath.Dir(serverDir), ".previous")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom"})
|
|
if response.Code != http.StatusConflict || decodeResponse(t, response)["code"] != "reinstall_server_files_unavailable" {
|
|
t.Fatalf("expected an explicit missing-directory refusal: %d %s", response.Code, response.Body.String())
|
|
}
|
|
stagingDir, err := createServerStagingDir(serverDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if code, err := agent.commitReinstallFiles(serverDir, stagingDir, buildReinstallMetadata("custom", 30005, nil)); !os.IsNotExist(err) || code != "reinstall_file_replace_failed" {
|
|
t.Fatalf("handoff must also refuse an absent live directory: %s %v", code, err)
|
|
}
|
|
if _, err := os.Lstat(serverDir); !os.IsNotExist(err) || agent.loadMeta(serverDir)["type"] != "seeded" {
|
|
t.Fatalf("refused reinstall must not recreate the directory or repoint metadata: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestReinstallRefusesSuccessWhenPreviousTreeCannotBeRemoved(t *testing.T) {
|
|
if os.Geteuid() == 0 {
|
|
t.Skip("root bypasses directory write permission checks")
|
|
}
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
lockedDir := filepath.Join(serverDir, "locked")
|
|
if err := os.Mkdir(lockedDir, 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(lockedDir, "old-file"), []byte("original"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.Chmod(lockedDir, 0o500); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
pattern := filepath.Join(filepath.Dir(serverDir), ".alpha.reinstall-rollback-*", "previous", "locked")
|
|
t.Cleanup(func() {
|
|
_ = os.Chmod(lockedDir, 0o700)
|
|
residualDirs, _ := filepath.Glob(pattern)
|
|
for _, dir := range residualDirs {
|
|
_ = os.Chmod(dir, 0o700)
|
|
}
|
|
})
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{"templateId": "custom", "hostPort": 30005})
|
|
body := decodeResponse(t, response)
|
|
if response.Code != http.StatusInternalServerError || body["code"] != "reinstall_cleanup_failed" || body["reinstalled"] != true || body["serverStopped"] != true {
|
|
t.Fatalf("cleanup failure must report a committed but stopped rebuild: %d %v", response.Code, body)
|
|
}
|
|
if meta := agent.loadMeta(serverDir); meta["hostPort"] != float64(30005) || meta["type"] != "custom" {
|
|
t.Fatalf("cleanup failure must preserve the committed metadata: %v", meta)
|
|
}
|
|
}
|
|
|
|
func TestReinstallStartFailureReportsPersistedRebuild(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
meta := buildReinstallMetadata("nodejs", 30005, nil)
|
|
meta["runtime"] = map[string]any{"image": "node", "tag": "20-alpine"}
|
|
metaPath := agent.metaPath(serverName)
|
|
previous, err := os.Open(metaPath)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer previous.Close()
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatalf("valid metadata should persist: %v", err)
|
|
}
|
|
var previousMeta map[string]any
|
|
if err := json.NewDecoder(previous).Decode(&previousMeta); err != nil || previousMeta["type"] != "seeded" {
|
|
t.Fatalf("metadata publication must not truncate the previous file: %v %v", previousMeta, err)
|
|
}
|
|
committedAt := time.Unix(946684800, 0)
|
|
if err := os.Chtimes(metaPath, committedAt, committedAt); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := httptest.NewRecorder()
|
|
agent.finishReinstallServer(response, httptest.NewRequest(http.MethodPost, "/v1/servers/alpha/reinstall", nil), serverName, serverDir, "nodejs", 30005, meta, nil)
|
|
body := decodeResponse(t, response)
|
|
if response.Code != http.StatusInternalServerError || body["code"] != "reinstall_start_failed" || body["reinstalled"] != true || body["ok"] != false || body["serverStopped"] != true {
|
|
t.Fatalf("failed start after persisted runtime must report partial completion: %d %v", response.Code, body)
|
|
}
|
|
if saved := agent.loadMeta(serverDir); saved["type"] != "nodejs" || saved["hostPort"] != float64(30005) {
|
|
t.Fatalf("startup failure must retain rebuilt authoritative metadata: %v", saved)
|
|
}
|
|
info, err := os.Stat(metaPath)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !info.ModTime().Equal(committedAt) {
|
|
t.Fatalf("startup must not write the committed metadata again: %v", info.ModTime())
|
|
}
|
|
}
|
|
|
|
func TestReinstallConfirmsRuntimeStateAfterStart(t *testing.T) {
|
|
for _, state := range []string{"running", "exited", "created", "restarting", "inspect-unavailable"} {
|
|
t.Run(state, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
inspections := 0
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
|
|
imagesAvailable: true,
|
|
startedState: state,
|
|
failStartedInspection: func() bool {
|
|
inspections++
|
|
return state == "inspect-unavailable" && inspections > 1
|
|
},
|
|
}}
|
|
serverName := "alpha"
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := buildReinstallMetadata("nodejs", 30005, nil)
|
|
meta["runtime"] = map[string]any{"image": "node", "tag": "20-alpine"}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
binDir := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte("#!/bin/sh\n[ \"$1\" = inspect ] || exit 1\nprintf 'created 0\\n'\n"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
|
|
|
response := httptest.NewRecorder()
|
|
agent.finishReinstallServer(response, httptest.NewRequest(http.MethodPost, "/v1/servers/alpha/reinstall", nil), serverName, serverDir, "nodejs", 30005, meta, nil)
|
|
body := decodeResponse(t, response)
|
|
if state == "running" {
|
|
if response.Code != http.StatusOK || body["serverRunning"] != true || body["serverStopped"] != false {
|
|
t.Fatalf("running replacement must report its confirmed state: %d %v", response.Code, body)
|
|
}
|
|
} else {
|
|
expectedCode := "reinstall_start_failed"
|
|
if state == "inspect-unavailable" {
|
|
expectedCode = "reinstall_start_unconfirmed"
|
|
if body["error"] != "server files reinstalled but container startup could not be confirmed" {
|
|
t.Fatalf("unavailable inspection must not imply the container failed to start: %v", body)
|
|
}
|
|
}
|
|
if response.Code != http.StatusInternalServerError || body["code"] != expectedCode || body["reinstalled"] != true || body["serverStopped"] != (state == "created" || state == "exited") {
|
|
t.Fatalf("%s replacement must not report startup success or discard the rebuild: %d %v", state, response.Code, body)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallReplacementStartupHealth(t *testing.T) {
|
|
for _, outcome := range []string{"exited", "unhealthy", "healthy"} {
|
|
t.Run(outcome, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const name = "alpha"
|
|
serverDir := seedRaceServer(t, agent, name)
|
|
t.Cleanup(func() { agent.logs.killTail(name) })
|
|
binDir := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte(`#!/bin/sh
|
|
case "$1" in
|
|
inspect) printf 'running 0\n' ;;
|
|
stop) [ "$4" = "$REINSTALL_TEST_CONTAINER" ] ;;
|
|
*) exit 1 ;;
|
|
esac
|
|
`), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
|
t.Setenv("REINSTALL_TEST_CONTAINER", reinstallFixtureContainerID)
|
|
fixture := reinstallDockerRemovalTransport{imagesAvailable: true, startedState: "running"}
|
|
var labels map[string]string
|
|
var startedAt string
|
|
started, removed := false, false
|
|
inspections := 0
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(req *http.Request) (*http.Response, error) {
|
|
requestPath := req.URL.Path
|
|
switch {
|
|
case req.Method == http.MethodPost && strings.HasSuffix(requestPath, "/containers/create"):
|
|
var create dockerContainerCreateRequest
|
|
if err := json.NewDecoder(req.Body).Decode(&create); err != nil {
|
|
return nil, err
|
|
}
|
|
labels = create.Labels
|
|
case req.Method == http.MethodPost && strings.HasSuffix(requestPath, "/start"):
|
|
started = true
|
|
case req.Method == http.MethodGet && strings.HasSuffix(requestPath, "/containers/alpha/json"):
|
|
if !started {
|
|
return (reinstallDockerRemovalTransport{}).RoundTrip(req)
|
|
}
|
|
inspections++
|
|
if outcome == "healthy" && inspections == 3 {
|
|
meta, err := agent.loadMetaChecked(serverDir, true)
|
|
if err != nil || meta[reinstallOutcomeMetadataKey] != "running" || meta[reinstallPendingStartupKey] != true {
|
|
t.Fatalf("startup acknowledgement must survive an interruption during health observation without confirming the files: %v, %v", meta, err)
|
|
}
|
|
}
|
|
if inspections == 1 {
|
|
startedAt = time.Now().Add(-reinstallStartupObservation + 200*time.Millisecond).Format(time.RFC3339Nano)
|
|
}
|
|
state := map[string]any{"Status": "exited"}
|
|
if inspections == 1 || outcome != "exited" {
|
|
state = map[string]any{"Running": true, "Status": "running", "StartedAt": startedAt}
|
|
}
|
|
if outcome != "exited" {
|
|
health := "starting"
|
|
if inspections > 2 {
|
|
health = outcome
|
|
}
|
|
state["Health"] = map[string]string{"Status": health}
|
|
}
|
|
body, err := json.Marshal(map[string]any{"Id": reinstallFixtureContainerID, "Name": "/alpha", "State": state, "Config": dockerContainerConfigLabels{Labels: labels}})
|
|
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(bytes.NewReader(body))}, err
|
|
case req.Method == http.MethodDelete:
|
|
if !strings.HasSuffix(requestPath, "/containers/"+reinstallFixtureContainerID) || req.URL.Query().Has("force") {
|
|
t.Fatalf("rollback must remove only the owned replacement by ID: %s", req.URL)
|
|
}
|
|
removed = true
|
|
return &http.Response{StatusCode: http.StatusNoContent, Header: make(http.Header), Body: http.NoBody}, nil
|
|
}
|
|
return fixture.RoundTrip(req)
|
|
})}
|
|
response := runReinstall(t, agent, name, "nodejs", map[string]any{"templateId": "nodejs", "hostPort": 30005})
|
|
body := decodeResponse(t, response)
|
|
if outcome == "healthy" {
|
|
if response.Code != http.StatusOK || body["serverRunning"] != true || removed || inspections < 3 {
|
|
t.Fatalf("a healthy replacement must be committed only after its health check passes: %d %v", response.Code, body)
|
|
}
|
|
} else {
|
|
if response.Code != http.StatusInternalServerError || body["code"] != "reinstall_start_rolled_back" || !removed {
|
|
t.Fatalf("a %s replacement must roll back: %d %v, container removed: %t", outcome, response.Code, body, removed)
|
|
}
|
|
assertServerDirUntouched(t, agent, name, serverDir)
|
|
}
|
|
assertNoStagingSiblings(t, serverDir)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestDirectStartDoesNotReplaceRejectedCommandWithImageDefault(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const name = "alpha"
|
|
attempts := 0
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(request *http.Request) (*http.Response, error) {
|
|
status, body := http.StatusNotFound, `{"message":"fixture not found"}`
|
|
switch {
|
|
case request.Method == http.MethodPost && strings.HasSuffix(request.URL.Path, "/images/create"):
|
|
status, body = http.StatusOK, `{"status":"Image ready"}`
|
|
case request.Method == http.MethodGet && strings.Contains(request.URL.Path, "/images/"):
|
|
status, body = http.StatusOK, `{"Id":"sha256:`+strings.Repeat("b", 64)+`","Config":{"Cmd":["sleep","60"]}}`
|
|
case request.Method == http.MethodPost && strings.HasSuffix(request.URL.Path, "/containers/create"):
|
|
attempts++
|
|
status, body = http.StatusCreated, `{"Id":`+strconv.Quote(reinstallFixtureContainerID)+`}`
|
|
case request.Method == http.MethodPost && strings.HasSuffix(request.URL.Path, "/start"):
|
|
status, body = http.StatusInternalServerError, `{"message":"exec: executable file not found in PATH"}`
|
|
}
|
|
return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
|
})}
|
|
ctx := context.WithValue(t.Context(), confirmDockerStartKey{}, true)
|
|
request := dockerContainerCreateRequest{Image: "node:20-alpine", Cmd: []string{"configured-process"}}
|
|
err := agent.runStructuredContainerWithCompatUser(ctx, name, request)
|
|
if err == nil || !isMissingRuntimeExecutableStartError(err) || attempts != 1 {
|
|
t.Fatalf("expected one failed start with the configured command, got %d attempts (%v)", attempts, err)
|
|
}
|
|
}
|
|
|
|
func TestReinstallRollsBackInsteadOfStartingTheImageDefault(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const name = "alpha"
|
|
serverDir := seedRaceServer(t, agent, name)
|
|
var replacementLabels map[string]string
|
|
removed := false
|
|
fixture := reinstallDockerRemovalTransport{imagesAvailable: true}
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(req *http.Request) (*http.Response, error) {
|
|
requestPath := req.URL.Path
|
|
status, body := http.StatusOK, ""
|
|
switch {
|
|
case req.Method == http.MethodGet && strings.Contains(requestPath, "/images/"):
|
|
body = `{"Id":"sha256:` + strings.Repeat("b", 64) + `","Config":{"Cmd":["sleep","60"]}}`
|
|
case req.Method == http.MethodPost && strings.HasSuffix(requestPath, "/containers/create"):
|
|
if replacementLabels != nil {
|
|
t.Fatal("reinstall must not replace a rejected startup command with the image default")
|
|
}
|
|
var create dockerContainerCreateRequest
|
|
if err := json.NewDecoder(req.Body).Decode(&create); err != nil {
|
|
return nil, err
|
|
}
|
|
replacementLabels = create.Labels
|
|
status, body = http.StatusCreated, `{"Id":`+strconv.Quote(reinstallFixtureContainerID)+`}`
|
|
case req.Method == http.MethodPost && strings.HasSuffix(requestPath, "/start"):
|
|
status, body = http.StatusInternalServerError, `{"message":"exec: executable file not found in PATH"}`
|
|
case req.Method == http.MethodGet && strings.HasSuffix(requestPath, "/containers/alpha/json") && replacementLabels != nil && !removed:
|
|
container := dockerContainerInspectForStats{ID: reinstallFixtureContainerID, Name: "/alpha", Config: dockerContainerConfigLabels{Labels: replacementLabels}, State: dockerContainerStateForStats{Status: "created"}}
|
|
encoded, err := json.Marshal(container)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
body = string(encoded)
|
|
case req.Method == http.MethodDelete:
|
|
if !strings.HasSuffix(requestPath, "/containers/"+reinstallFixtureContainerID) || req.URL.Query().Has("force") {
|
|
t.Fatalf("expected rollback to remove only the stopped replacement by ID: %s", req.URL)
|
|
}
|
|
removed = true
|
|
status = http.StatusNoContent
|
|
default:
|
|
return fixture.RoundTrip(req)
|
|
}
|
|
return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
|
})}
|
|
response := runReinstall(t, agent, name, "nodejs", map[string]any{"templateId": "nodejs", "hostPort": 30005})
|
|
if body := decodeResponse(t, response); response.Code != http.StatusInternalServerError || body["code"] != "reinstall_start_rolled_back" || !removed {
|
|
t.Fatalf("a rejected startup command must roll back: %d %v", response.Code, body)
|
|
}
|
|
assertServerDirUntouched(t, agent, name, serverDir)
|
|
}
|
|
|
|
func TestReinstallDoesNotGenerateMissingCustomAppAfterHandoff(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const name = "alpha"
|
|
serverDir := seedRaceServer(t, agent, name)
|
|
stagingDir, err := createServerStagingDir(serverDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
meta := buildReinstallMetadata("custom", 30005, agent.loadMeta(serverDir))
|
|
runtimeConfig := map[string]any{
|
|
"image": "docker.io/library/node", "tag": "20-alpine", "command": "node /app/service.js",
|
|
"volumes": []string{"{SERVER_DIR}:/app"}, "workdir": "/app",
|
|
}
|
|
meta["runtime"] = runtimeConfig
|
|
var handoff reinstallFileHandoff
|
|
if code, err := agent.commitReinstallFiles(serverDir, stagingDir, meta, &handoff); err != nil {
|
|
t.Fatalf("commit staged files: %s: %v", code, err)
|
|
}
|
|
agent.beginLongOp(name, longOpReinstall)
|
|
defer agent.endLongOp(name)
|
|
handoff.image.config.ID = "sha256:" + strings.Repeat("b", 64)
|
|
createAttempted := false
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(req *http.Request) (*http.Response, error) {
|
|
if req.Method == http.MethodPost && strings.HasSuffix(req.URL.Path, "/containers/create") {
|
|
createAttempted = true
|
|
if _, err := os.Lstat(filepath.Join(serverDir, "service.js")); !os.IsNotExist(err) {
|
|
t.Errorf("a reinstall must not generate a demo in place of the custom app: %v", err)
|
|
}
|
|
return &http.Response{StatusCode: http.StatusInternalServerError, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"message":"fixture entrypoint missing"}`))}, nil
|
|
}
|
|
return (reinstallDockerRemovalTransport{}).RoundTrip(req)
|
|
})}
|
|
response := httptest.NewRecorder()
|
|
agent.finishReinstallServer(response, httptest.NewRequest(http.MethodPost, "/v1/servers/alpha/reinstall", nil), name, serverDir, "custom", 30005, meta, runtimeConfig, &handoff)
|
|
if body := decodeResponse(t, response); !createAttempted || body["code"] != "reinstall_start_rolled_back" {
|
|
t.Fatalf("a missing replacement app must not commit the rebuild: %d %v", response.Code, body)
|
|
}
|
|
assertServerDirUntouched(t, agent, name, serverDir)
|
|
assertNoStagingSiblings(t, serverDir)
|
|
}
|
|
|
|
func TestReinstallCustomManagedStartupOverridesImageCmdWithoutEntrypoint(t *testing.T) {
|
|
for _, hasEntrypoint := range []bool{false, true} {
|
|
t.Run(strconv.FormatBool(hasEntrypoint), func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const name, script = "alpha", "./service --port {{SERVER_PORT}}"
|
|
serverDir := seedRaceServer(t, agent, name)
|
|
meta := buildReinstallMetadata("custom", 30005, agent.loadMeta(serverDir))
|
|
meta["runtime"] = map[string]any{
|
|
"image": "docker.io/library/alpine", "adpanelStartup": script,
|
|
"workdir": "/app", "volumes": []string{"{SERVER_DIR}:/app"},
|
|
}
|
|
image := imageConfig{ID: "sha256:" + strings.Repeat("b", 64), Workdir: "/app", Cmd: []string{"sleep", "60"}}
|
|
if hasEntrypoint {
|
|
image.Entrypoint = []string{"/entrypoint.sh"}
|
|
}
|
|
handoff := &reinstallFileHandoff{image: reinstallRuntimeImage{config: image}}
|
|
ctx := context.WithValue(context.Background(), reinstallContainerContextKey{}, handoff)
|
|
agent.beginLongOp(name, longOpReinstall)
|
|
defer agent.endLongOp(name)
|
|
var create dockerContainerCreateRequest
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(req *http.Request) (*http.Response, error) {
|
|
if req.Method == http.MethodPost && strings.HasSuffix(req.URL.Path, "/containers/create") {
|
|
if err := json.NewDecoder(req.Body).Decode(&create); err != nil {
|
|
return nil, err
|
|
}
|
|
return &http.Response{StatusCode: http.StatusConflict, Header: make(http.Header), Body: http.NoBody}, nil
|
|
}
|
|
return (reinstallDockerRemovalTransport{}).RoundTrip(req)
|
|
})}
|
|
_ = agent.startCustomDockerContainer(ctx, name, serverDir, meta, 30005, nil)
|
|
|
|
const rendered = "./service --port ${SERVER_PORT}"
|
|
if !strings.Contains(strings.Join(create.Env, "\n"), "STARTUP="+rendered) {
|
|
t.Fatalf("the rendered startup must be present in the runtime environment: %v", create.Env)
|
|
}
|
|
if binds := create.HostConfig.Binds; len(binds) != 1 || binds[0] != serverDir+":/app" {
|
|
t.Fatalf("the explicit startup needs access to the server files at the image workdir: %v", binds)
|
|
}
|
|
if hasEntrypoint {
|
|
if len(create.Cmd) != 0 || len(create.Entrypoint) != 0 {
|
|
t.Fatalf("the image entrypoint must keep its own invocation: %v %v", create.Entrypoint, create.Cmd)
|
|
}
|
|
} else if len(create.Cmd) != 3 || create.Cmd[0] != "sh" || create.Cmd[1] != "-lc" || create.Cmd[2] != rendered {
|
|
t.Fatalf("managed startup must replace the image default CMD: %v", create.Cmd)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallRollsBackInsteadOfChangingTheContainerUser(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const name = "alpha"
|
|
serverDir := seedRaceServer(t, agent, name)
|
|
binDir := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte("#!/bin/sh\ncase \"$1\" in\n inspect) printf 'exited 1\\n' ;;\n logs) printf 'permission denied\\n' ;;\n *) exit 1 ;;\nesac\n"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
|
fixture := reinstallDockerRemovalTransport{imagesAvailable: true}
|
|
removed := false
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(req *http.Request) (*http.Response, error) {
|
|
if req.Method == http.MethodPost && strings.HasSuffix(req.URL.Path, "/containers/create") {
|
|
var create dockerContainerCreateRequest
|
|
if err := json.NewDecoder(req.Body).Decode(&create); err != nil {
|
|
return nil, err
|
|
}
|
|
if fixture.startedLabels != nil || create.User == "" {
|
|
t.Fatal("reinstall must create the replacement only with its selected user")
|
|
}
|
|
fixture.startedLabels = create.Labels
|
|
fixture.startedState = "exited"
|
|
}
|
|
if req.Method == http.MethodDelete {
|
|
if !strings.HasSuffix(req.URL.Path, "/containers/"+reinstallFixtureContainerID) || req.URL.Query().Has("force") {
|
|
t.Fatalf("rollback must remove only the stopped replacement by ID: %s", req.URL)
|
|
}
|
|
removed = true
|
|
}
|
|
return fixture.RoundTrip(req)
|
|
})}
|
|
response := runReinstall(t, agent, name, "nodejs", map[string]any{"templateId": "nodejs", "hostPort": 30005})
|
|
if body := decodeResponse(t, response); response.Code != http.StatusInternalServerError || body["code"] != "reinstall_start_rolled_back" || !removed {
|
|
t.Fatalf("a permission failure must roll back: %d %v", response.Code, body)
|
|
}
|
|
assertServerDirUntouched(t, agent, name, serverDir)
|
|
}
|
|
|
|
func TestDelayedFileRecoveryCannotCrossReinstall(t *testing.T) {
|
|
for _, scenario := range []string{"original", "reinstall active", "replacement"} {
|
|
t.Run(scenario, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const serverName = "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
if err := os.Remove(filepath.Join(serverDir, "world-data.txt")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
original := dockerContainerInspectForStats{ID: reinstallFixtureContainerID}
|
|
currentID := original.ID
|
|
if scenario == "replacement" {
|
|
currentID = strings.Repeat("a", 64)
|
|
}
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(request *http.Request) (*http.Response, error) {
|
|
body := `{"Id":` + strconv.Quote(currentID) + `,"Name":"/alpha","State":{"Running":true}}`
|
|
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
|
})}
|
|
binDir := t.TempDir()
|
|
copySource := filepath.Join(binDir, "copy-source")
|
|
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte("#!/bin/sh\ncase \"$1\" in\ndiff) printf 'A /data/world/example.txt\\n' ;;\ncp) printf '%s' \"$2\" > \"$TEST_COPY_SOURCE\" ;;\n*) exit 1 ;;\nesac\n"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
|
t.Setenv("TEST_COPY_SOURCE", copySource)
|
|
if scenario == "reinstall active" {
|
|
operation := agent.getServerOpLock(serverName)
|
|
operation.Lock()
|
|
defer operation.Unlock()
|
|
}
|
|
|
|
agent.recoverMisplacedFiles(serverName, serverDir, original)
|
|
copiedFrom, copyErr := os.ReadFile(copySource)
|
|
meta := agent.loadMeta(serverDir)
|
|
if scenario == "original" {
|
|
if copyErr != nil || string(copiedFrom) != original.ID+":/data/world/." || meta["runtime"] == nil {
|
|
t.Fatalf("current container recovery did not copy by ID and save the mount: %q, %v, %v", copiedFrom, copyErr, meta)
|
|
}
|
|
} else if !os.IsNotExist(copyErr) || meta["runtime"] != nil {
|
|
t.Fatalf("stale or busy recovery touched Docker or metadata: %q, %v, %v", copiedFrom, copyErr, meta)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallStartupLeavesNameConflictUntouched(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
|
|
imagesAvailable: true,
|
|
createConflict: true,
|
|
onRemovalTarget: func(target string) { t.Errorf("startup tried to remove %s by name", target) },
|
|
}}
|
|
binDir := t.TempDir()
|
|
cliRemoval := filepath.Join(binDir, "removed")
|
|
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte("#!/bin/sh\n[ \"$1\" != rm ] || printf '%s\\n' \"$*\" >> \"$REINSTALL_FIXTURE_REMOVED\"\nexit 1\n"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
|
t.Setenv("REINSTALL_FIXTURE_REMOVED", cliRemoval)
|
|
response := runReinstall(t, agent, serverName, "nodejs", map[string]any{"templateId": "nodejs", "hostPort": 30005})
|
|
body := decodeResponse(t, response)
|
|
if response.Code != http.StatusInternalServerError || body["code"] != "reinstall_start_rolled_back" || body["reinstalled"] == true || body["serverStopped"] != true {
|
|
t.Fatalf("startup name conflict must report a rolled-back rebuild: %d %v", response.Code, body)
|
|
}
|
|
if _, err := os.Stat(cliRemoval); !os.IsNotExist(err) {
|
|
t.Fatalf("startup must not remove a conflicting container via the CLI: %v", err)
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
assertNoStagingSiblings(t, serverDir)
|
|
}
|
|
|
|
func TestReinstallUnconfirmedStartupRetainsOriginalTree(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverDir := seedRaceServer(t, agent, "alpha")
|
|
fixture := reinstallDockerRemovalTransport{imagesAvailable: true}
|
|
created := false
|
|
inspectionUnavailable := true
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(req *http.Request) (*http.Response, error) {
|
|
if strings.HasSuffix(req.URL.Path, "/containers/create") {
|
|
created = true
|
|
fixture.createConflict = true
|
|
}
|
|
if created && inspectionUnavailable && req.Method == http.MethodGet && strings.Contains(req.URL.Path, "/containers/") {
|
|
return nil, errors.New("fixture inspection unavailable")
|
|
}
|
|
return fixture.RoundTrip(req)
|
|
})}
|
|
operationID := strings.Repeat("a", 32)
|
|
acceptUntil := time.Now().Add(time.Minute).UnixMilli()
|
|
payload := map[string]any{"templateId": "nodejs", "replaceRuntime": true, "hostPort": 30005, "operationId": operationID, "acceptUntil": acceptUntil}
|
|
response := runReinstall(t, agent, "alpha", "nodejs", payload)
|
|
if response.Code != http.StatusServiceUnavailable || decodeResponse(t, response)["code"] != "reinstall_startup_pending" {
|
|
t.Fatalf("expected a pending startup response: %d %s", response.Code, response.Body.String())
|
|
}
|
|
agent.recoverInterruptedServerOperations()
|
|
meta := agent.loadMeta(serverDir)
|
|
rollback, _ := meta[reinstallCommitMetadataKey].(string)
|
|
if data, err := os.ReadFile(filepath.Join(filepath.Dir(serverDir), rollback, "previous", "world-data.txt")); err != nil || string(data) != "precious" {
|
|
t.Fatalf("uncertain startup must retain the original files: %q %v", data, err)
|
|
}
|
|
response = runReinstall(t, agent, "alpha", "nodejs", payload)
|
|
if response.Code != http.StatusServiceUnavailable || decodeResponse(t, response)["code"] != "reinstall_startup_pending" {
|
|
t.Fatalf("a second reinstall must not overwrite the pending handoff: %d %s", response.Code, response.Body.String())
|
|
}
|
|
for _, operation := range []struct {
|
|
path string
|
|
body string
|
|
handler func(http.ResponseWriter, *http.Request, string)
|
|
}{
|
|
{"start", `{}`, agent.handleStart},
|
|
{"restart", `{}`, agent.handleRestart},
|
|
{"runtime", `{"runtime":{"image":"node"},"template":"nodejs"}`, agent.handleRuntime},
|
|
} {
|
|
response := httptest.NewRecorder()
|
|
request := httptest.NewRequest(http.MethodPost, "/v1/servers/alpha/"+operation.path, strings.NewReader(operation.body))
|
|
operation.handler(response, request, "alpha")
|
|
if response.Code != http.StatusServiceUnavailable || decodeResponse(t, response)["code"] != "reinstall_startup_pending" {
|
|
t.Fatalf("%s must not disturb the pending handoff: %d %s", operation.path, response.Code, response.Body.String())
|
|
}
|
|
}
|
|
writeResponse := httptest.NewRecorder()
|
|
writeBody := fmt.Sprintf(`{"server":"alpha","path":%q,"content":"new data"}`, filepath.Join(serverDir, "new.txt"))
|
|
agent.handleFSWrite(writeResponse, httptest.NewRequest(http.MethodPost, "/v1/fs/write", strings.NewReader(writeBody)))
|
|
if writeResponse.Code != http.StatusServiceUnavailable || decodeResponse(t, writeResponse)["code"] != "reinstall_startup_pending" {
|
|
t.Fatalf("editor write must not be acknowledged on a pending replacement: %d %s", writeResponse.Code, writeResponse.Body.String())
|
|
}
|
|
|
|
inspectionUnavailable = false
|
|
result := httptest.NewRecorder()
|
|
request := httptest.NewRequest(http.MethodGet, "/v1/servers/alpha/reinstall-result?id="+operationID+"&acceptUntil="+strconv.FormatInt(acceptUntil, 10), nil)
|
|
agent.handleReinstallResult(result, request, "alpha")
|
|
if result.Code != http.StatusOK {
|
|
t.Fatalf("unexpected recovery response: %d %s", result.Code, result.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, "alpha", serverDir)
|
|
assertNoStagingSiblings(t, serverDir)
|
|
}
|
|
|
|
func TestReinstallResultFinishesInterruptedRollback(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const name = "alpha"
|
|
serverDir := seedRaceServer(t, agent, name)
|
|
operationID := strings.Repeat("b", 32)
|
|
meta := buildReinstallMetadata("custom", 30005, nil)
|
|
meta[reinstallOperationMetadataKey] = operationID
|
|
stagingDir, err := createServerStagingDir(serverDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var handoff reinstallFileHandoff
|
|
if _, err := agent.commitReinstallFiles(serverDir, stagingDir, meta, &handoff); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := restoreReinstallFiles(serverDir, handoff.rollbackDir, handoff.replacement); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{}}
|
|
result := httptest.NewRecorder()
|
|
resultURL := fmt.Sprintf("/v1/servers/alpha/reinstall-result?id=%s&acceptUntil=%d", operationID, time.Now().Add(-time.Minute).UnixMilli())
|
|
agent.handleReinstallResult(result, httptest.NewRequest(http.MethodGet, resultURL, nil), name)
|
|
if body := decodeResponse(t, result); result.Code != http.StatusOK || body["state"] != "absent" || body["powerState"] != "stopped" {
|
|
t.Fatalf("polling must finish interrupted rollback: %d %v", result.Code, body)
|
|
}
|
|
assertServerDirUntouched(t, agent, name, serverDir)
|
|
assertNoStagingSiblings(t, serverDir)
|
|
}
|
|
|
|
func TestReinstallRecoversOnlyVerifiedRunningAttempt(t *testing.T) {
|
|
for _, scenario := range []struct {
|
|
name string
|
|
startupProof bool
|
|
owned bool
|
|
health string
|
|
wantState string
|
|
}{
|
|
{"verified", true, true, "", "completed"},
|
|
{"different attempt", true, false, "", "pending"},
|
|
{"startup not verified", false, true, "", "absent"},
|
|
{"health check pending", true, true, "starting", "pending"},
|
|
{"health check failed", true, true, "unhealthy", "absent"},
|
|
} {
|
|
t.Run(scenario.name, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const name = "alpha"
|
|
serverDir := seedRaceServer(t, agent, name)
|
|
t.Cleanup(func() { agent.logs.killTail(name) })
|
|
operationID := strings.Repeat("b", 32)
|
|
meta := buildReinstallMetadata("custom", 30005, nil)
|
|
meta[reinstallOperationMetadataKey] = operationID
|
|
stagingDir, err := createServerStagingDir(serverDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var handoff reinstallFileHandoff
|
|
if _, err := agent.commitReinstallFiles(serverDir, stagingDir, meta, &handoff); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if scenario.startupProof {
|
|
if err := agent.saveReinstallOutcome(serverDir, &handoff, "running", false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
container := dockerContainerInspectForStats{
|
|
ID: reinstallFixtureContainerID, Name: "/alpha",
|
|
State: dockerContainerStateForStats{Running: true, Status: "running", StartedAt: time.Now().Add(-time.Minute).Format(time.RFC3339Nano)},
|
|
Config: dockerContainerConfigLabels{Labels: map[string]string{dockerServerOwnershipLabel: name}},
|
|
}
|
|
container.State.Health.Status = scenario.health
|
|
if scenario.owned {
|
|
container.Config.Labels[reinstallContainerLabel] = handoff.containerLabel()
|
|
}
|
|
binDir := t.TempDir()
|
|
stopTarget := filepath.Join(binDir, "stop-target")
|
|
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte("#!/bin/sh\n[ \"$1\" = stop ] || exit 1\nprintf '%s' \"$4\" > \"$REINSTALL_FIXTURE_STOP_TARGET\"\n"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
|
t.Setenv("REINSTALL_FIXTURE_STOP_TARGET", stopTarget)
|
|
body, err := json.Marshal(container)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(req *http.Request) (*http.Response, error) {
|
|
if req.Method == http.MethodGet && strings.HasSuffix(req.URL.Path, "/containers/alpha/json") {
|
|
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(bytes.NewReader(body))}, nil
|
|
}
|
|
if req.Method == http.MethodDelete {
|
|
if scenario.wantState != "absent" || !strings.HasSuffix(req.URL.Path, "/containers/"+container.ID) || req.URL.Query().Has("force") {
|
|
t.Fatalf("only the unverified attempt may be removed during recovery: %s", req.URL)
|
|
}
|
|
if data, err := os.ReadFile(stopTarget); err != nil || string(data) != container.ID {
|
|
t.Fatalf("the exact replacement must be stopped before recovery removes it: %q %v", data, err)
|
|
}
|
|
return &http.Response{StatusCode: http.StatusNoContent, Header: make(http.Header), Body: http.NoBody}, nil
|
|
}
|
|
return (reinstallDockerRemovalTransport{}).RoundTrip(req)
|
|
})}
|
|
result := httptest.NewRecorder()
|
|
resultURL := fmt.Sprintf("/v1/servers/alpha/reinstall-result?id=%s&acceptUntil=%d", operationID, time.Now().Add(-time.Minute).UnixMilli())
|
|
request := httptest.NewRequest(http.MethodGet, resultURL, nil)
|
|
if scenario.health == "starting" {
|
|
ctx, cancel := context.WithTimeout(request.Context(), 200*time.Millisecond)
|
|
defer cancel()
|
|
request = request.WithContext(ctx)
|
|
}
|
|
agent.handleReinstallResult(result, request, name)
|
|
if body := decodeResponse(t, result); result.Code != http.StatusOK || body["state"] != scenario.wantState {
|
|
t.Fatalf("unexpected reinstall recovery result: %d %v", result.Code, body)
|
|
}
|
|
if scenario.wantState == "absent" {
|
|
assertServerDirUntouched(t, agent, name, serverDir)
|
|
}
|
|
if scenario.wantState != "pending" {
|
|
assertNoStagingSiblings(t, serverDir)
|
|
} else {
|
|
if _, err := os.Stat(stopTarget); !os.IsNotExist(err) {
|
|
t.Fatalf("pending recovery must not stop this container: %v", err)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(handoff.rollbackDir, "previous", "world-data.txt")); err != nil {
|
|
t.Fatalf("unverified replacement must retain previous files: %v", err)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallRejectsUnsupportedStoredMounts(t *testing.T) {
|
|
for _, volumes := range [][]string{{"game-data:/data"}, {"/data"}, {"{SERVER_DIR}:/data:invalid"}, {"{BOT_DIR}:/data", "{SERVER_DIR}:/game/../data/"}} {
|
|
t.Run(strings.Join(volumes, ","), func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverDir := seedRaceServer(t, agent, "alpha")
|
|
response := runReinstall(t, agent, "alpha", "seeded", map[string]any{
|
|
"templateId": "seeded", "docker": map[string]any{"volumes": volumes},
|
|
})
|
|
if response.Code != http.StatusBadRequest || decodeResponse(t, response)["code"] != "reinstall_invalid_mounts" {
|
|
t.Fatalf("mount refusal must precede the file swap: %d %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, "alpha", serverDir)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallInstallerFailurePreservesServer(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
|
|
imagesAvailable: true,
|
|
onRemoval: func() {
|
|
t.Fatal("a failing installer must not remove the existing container")
|
|
},
|
|
}}
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["hostPort"] = 30001
|
|
meta["resources"] = map[string]any{"storageMb": 1, "ramMb": 1024}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{
|
|
"templateId": "custom", "hostPort": 30005,
|
|
"docker": map[string]any{"install": map[string]any{
|
|
"image": "docker.io/library/alpine:3.20", "script": "echo preparing server",
|
|
}},
|
|
})
|
|
body := decodeResponse(t, response)
|
|
if response.Code != http.StatusInternalServerError || body["code"] != "reinstall_install_failed" || body["reinstalled"] != false || body["ok"] != false {
|
|
t.Fatalf("installer failure must report no committed rebuild: %d %v", response.Code, body)
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
assertNoStagingSiblings(t, serverDir)
|
|
if saved := agent.loadMeta(serverDir); saved["hostPort"] != float64(30001) {
|
|
t.Fatalf("installer failure must retain the original host port: %v", saved)
|
|
}
|
|
if limit := agent.getServerDiskLimitBytes(serverDir); limit != 1<<20 {
|
|
t.Fatalf("installer failure must retain the server disk limit: %d", limit)
|
|
}
|
|
if operation := agent.tryLockServerOp(serverName); operation == nil {
|
|
t.Fatal("installer failure must release the reinstall operation lock")
|
|
} else {
|
|
operation.Unlock()
|
|
}
|
|
if agent.longOpKind(serverName) != "" {
|
|
t.Fatal("installer failure must release the reinstall marker")
|
|
}
|
|
}
|
|
|
|
func TestReinstallCancelsStagedInstallerBeforeWipe(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
request, response := signedReinstallRequest(t, agent, serverName, "custom", map[string]any{
|
|
"templateId": "custom",
|
|
"docker": map[string]any{"install": map[string]any{
|
|
"image": "docker.io/library/alpine:3.20", "script": "echo installer fixture",
|
|
}},
|
|
})
|
|
requestCtx, cancel := context.WithCancel(request.Context())
|
|
defer cancel()
|
|
pulls := 0
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
|
|
imagesAvailable: true,
|
|
onImagePull: func(ctx context.Context) error {
|
|
pulls++
|
|
if pulls == 2 {
|
|
cancel()
|
|
if !errors.Is(ctx.Err(), context.Canceled) {
|
|
t.Fatal("staged installer image preparation must inherit request cancellation")
|
|
}
|
|
}
|
|
return ctx.Err()
|
|
},
|
|
onRemoval: func() { t.Fatal("canceled installer must not remove the live container") },
|
|
}}
|
|
|
|
agent.handleReinstallServer(response, request.WithContext(requestCtx), serverName)
|
|
if response.Code != http.StatusRequestTimeout || pulls != 2 {
|
|
t.Fatalf("staging cancellation must return before the wipe: %d %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
assertNoStagingSiblings(t, serverDir)
|
|
}
|
|
|
|
func TestReinstallRejectsUncoveredImageVolume(t *testing.T) {
|
|
for _, template := range []string{"custom", "nodejs"} {
|
|
t.Run(template, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const name = "alpha"
|
|
serverDir := seedRaceServer(t, agent, name)
|
|
fixture := reinstallDockerRemovalTransport{imagesAvailable: true, onRemoval: func() {
|
|
t.Error("uncovered image volume must be refused before teardown")
|
|
}}
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(req *http.Request) (*http.Response, error) {
|
|
if req.Method == http.MethodGet && strings.Contains(req.URL.Path, "/images/") {
|
|
body := `{"Id":"sha256:` + strings.Repeat("b", 64) + `","Config":{"Volumes":{"/data":{},"/cache":{}}}}`
|
|
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
|
}
|
|
return fixture.RoundTrip(req)
|
|
})}
|
|
response := runReinstall(t, agent, name, template, map[string]any{
|
|
"templateId": template, "docker": map[string]any{
|
|
"image": "docker.io/library/node", "volumes": []string{"{SERVER_DIR}:/data"},
|
|
},
|
|
})
|
|
body := decodeResponse(t, response)
|
|
if response.Code != http.StatusBadRequest || body["code"] != "reinstall_invalid_mounts" || !strings.Contains(response.Body.String(), "/cache") {
|
|
t.Fatalf("uncovered image volume must refuse reinstall: %d %v", response.Code, body)
|
|
}
|
|
assertServerDirUntouched(t, agent, name, serverDir)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReinstallRefusesCustomImageWithoutStartup(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const name = "alpha"
|
|
serverDir := seedRaceServer(t, agent, name)
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
|
|
imagesAvailable: true, containerOwner: name,
|
|
onRemoval: func() { t.Error("missing startup must be refused before removing the existing container") },
|
|
}}
|
|
response := runReinstall(t, agent, name, "custom", map[string]any{
|
|
"templateId": "custom", "docker": map[string]any{"image": "docker.io/example/game"},
|
|
})
|
|
if body := decodeResponse(t, response); response.Code != http.StatusBadRequest || body["code"] != "reinstall_missing_startup" {
|
|
t.Fatalf("missing startup must be refused before teardown: %d %v", response.Code, body)
|
|
}
|
|
assertServerDirUntouched(t, agent, name, serverDir)
|
|
assertNoStagingSiblings(t, serverDir)
|
|
}
|
|
|
|
func TestReinstallCustomImageCannotExceedStagingQuota(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const serverName = "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["resources"] = map[string]any{"storageMb": 1}
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
binDir := t.TempDir()
|
|
archivePath := filepath.Join(binDir, "image.tar")
|
|
archive, err := os.Create(archivePath)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
tarWriter := tar.NewWriter(archive)
|
|
if err := tarWriter.WriteHeader(&tar.Header{Name: "seed.bin", Mode: 0o644, Size: 2 << 20}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := tarWriter.Write(make([]byte, 2<<20)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := errors.Join(tarWriter.Close(), archive.Close()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte(`#!/bin/sh
|
|
case "$1" in
|
|
create) exit 0 ;;
|
|
cp) [ "$3" = - ] && exec cat "$REINSTALL_IMAGE_ARCHIVE" ;;
|
|
rm) exit 0 ;;
|
|
esac
|
|
exit 1
|
|
`), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
|
t.Setenv("REINSTALL_IMAGE_ARCHIVE", archivePath)
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
|
|
imagesAvailable: true, containerOwner: serverName,
|
|
onRemoval: func() { t.Error("quota refusal must happen before removing the existing container") },
|
|
}}
|
|
|
|
response := runReinstall(t, agent, serverName, "custom", map[string]any{
|
|
"templateId": "custom", "docker": map[string]any{"image": "docker.io/library/alpine", "command": "sh"},
|
|
})
|
|
if response.Code != http.StatusInsufficientStorage || decodeResponse(t, response)["code"] != "reinstall_disk_limit_exceeded" {
|
|
t.Fatalf("oversized image seed must fail before teardown: %d %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
assertNoStagingSiblings(t, serverDir)
|
|
}
|
|
|
|
func TestReinstallPersistsInferredCustomImageMount(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const name, template, imagePath = "alpha", "custom", "/opt/game"
|
|
serverDir := seedRaceServer(t, agent, name)
|
|
stagingDir, err := createServerStagingDir(serverDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer os.RemoveAll(stagingDir)
|
|
binDir := t.TempDir()
|
|
seedDir := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(seedDir, "world.cfg"), []byte("fresh"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte(`#!/bin/sh
|
|
case "$1" in
|
|
create|rm) exit 0 ;;
|
|
cp) exec tar -C "$REINSTALL_SEED_DIR" -cf - . ;;
|
|
esac
|
|
exit 1
|
|
`), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
|
t.Setenv("REINSTALL_SEED_DIR", seedDir)
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerTransportFunc(func(request *http.Request) (*http.Response, error) {
|
|
if request.Method == http.MethodGet && strings.Contains(request.URL.Path, "/images/") {
|
|
body := `{"Id":"sha256:` + strings.Repeat("b", 64) + `","Config":{"WorkingDir":"` + imagePath + `","Cmd":["./launch"]}}`
|
|
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
|
}
|
|
return (reinstallDockerRemovalTransport{}).RoundTrip(request)
|
|
})}
|
|
runtimeConfig := map[string]any{"image": "docker.io/example/game", "tag": "latest"}
|
|
prepared, err := agent.stageReinstallRuntimeImage(context.Background(), name, template, serverDir, stagingDir, runtimeConfig)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(stagingDir, "world.cfg")); err != nil {
|
|
t.Fatalf("image data was not staged: %v", err)
|
|
}
|
|
meta := buildReinstallMetadata(template, 30005, agent.loadMeta(serverDir))
|
|
meta["runtime"] = runtimeConfig
|
|
if code, err := agent.commitReinstallFiles(serverDir, stagingDir, meta); err != nil {
|
|
t.Fatalf("commit failed: %s: %v", code, err)
|
|
}
|
|
savedRuntime, _ := agent.loadMeta(serverDir)["runtime"].(map[string]any)
|
|
binds, dataDir, workdir := agent.resolveCustomRuntimeLayout(template, savedRuntime, serverDir, serverDir, runtimeImageRef(savedRuntime), prepared.config)
|
|
if len(binds) != 1 || binds[0] != serverDir+":"+imagePath || dataDir != imagePath || workdir != imagePath {
|
|
t.Fatalf("the next start must mount the staged data at the same path: %v, %q, %q", binds, dataDir, workdir)
|
|
}
|
|
|
|
installerStage, err := createServerStagingDir(serverDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer os.RemoveAll(installerStage)
|
|
if err := os.WriteFile(filepath.Join(installerStage, "installed.cfg"), []byte("installed"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.Mkdir(filepath.Join(installerStage, "config"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
runtimeConfig = map[string]any{
|
|
"image": "docker.io/example/game", "tag": "latest",
|
|
"volumes": []string{"{SERVER_DIR}:" + imagePath},
|
|
"install": &templateInstallConfig{Script: "echo installed", RuntimePath: imagePath},
|
|
}
|
|
if _, err := agent.stageReinstallRuntimeImage(context.Background(), name, template, serverDir, installerStage, runtimeConfig); !errors.Is(err, errReinstallUnmanagedVolume) {
|
|
t.Fatalf("an image layout that drops the only installer mount must fail before teardown: %v", err)
|
|
}
|
|
runtimeConfig["volumes"] = []string{"{SERVER_DIR}:" + imagePath, "{SERVER_DIR}/config:/config"}
|
|
if _, err := agent.stageReinstallRuntimeImage(context.Background(), name, template, serverDir, installerStage, runtimeConfig); !errors.Is(err, errReinstallUnmanagedVolume) {
|
|
t.Fatalf("an unrelated config mount must not hide the loss of the installer output mount: %v", err)
|
|
}
|
|
runtimeConfig["volumes"] = []string{"{SERVER_DIR}/config:/config"}
|
|
if _, err := agent.stageReinstallRuntimeImage(context.Background(), name, template, serverDir, installerStage, runtimeConfig); !errors.Is(err, errReinstallUnmanagedVolume) {
|
|
t.Fatalf("a retained but empty config mount must not hide all installer output: %v", err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(installerStage, "config", "game.cfg"), []byte("config"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := agent.stageReinstallRuntimeImage(context.Background(), name, template, serverDir, installerStage, runtimeConfig); err != nil {
|
|
t.Fatalf("a configured subdirectory containing installer output must be supported: %v", err)
|
|
}
|
|
runtimeConfig["volumes"] = []string{"{SERVER_DIR}:" + imagePath, "{SERVER_DIR}/config:/config"}
|
|
runtimeConfig["image"] = "docker.io/example/valheim"
|
|
if _, err := agent.stageReinstallRuntimeImage(context.Background(), name, template, serverDir, installerStage, runtimeConfig); err == nil || !strings.Contains(err.Error(), "duplicate mount destination") {
|
|
t.Fatalf("a remapped image bind must not collide with another configured mount: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestReinstallPublishesSuccessfulStagedInstaller(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
backupPath := filepath.Join(agent.serverBackupsDir(serverName), "existing.txt")
|
|
if err := os.MkdirAll(filepath.Dir(backupPath), 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(backupPath, []byte("backup"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
meta := agent.loadMeta(serverDir)
|
|
meta["resources"] = map[string]any{"storageMb": 1, "ramMb": 256, "swapMb": -1, "cpuCores": 0.5, "pidsLimit": 128}
|
|
meta["start"] = "server.bin"
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
binDir := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte(`#!/bin/sh
|
|
if [ "$1" = rm ]; then
|
|
printf '%s\n' "$4" >> "$REINSTALL_FIXTURE_REMOVED"
|
|
exit 0
|
|
fi
|
|
[ "$1" = run ] || exit 1
|
|
printf '%s\n' "$@" > "$REINSTALL_FIXTURE_ARGS" || exit 1
|
|
if [ "$REINSTALL_FIXTURE_CREATE_FAIL" = 1 ]; then
|
|
exit 1
|
|
fi
|
|
while [ "$#" -gt 1 ]; do
|
|
if [ "$1" = --cidfile ]; then
|
|
printf '%s\n' "$REINSTALL_FIXTURE_CONTAINER_ID" > "$2" || exit 1
|
|
fi
|
|
shift
|
|
done
|
|
scratch=$(mktemp -d) || exit 1
|
|
trap 'rm -rf "$scratch"' EXIT
|
|
if [ -n "$REINSTALL_FIXTURE_ENTRYPOINT_DIR" ]; then
|
|
mkdir -p "$scratch/$REINSTALL_FIXTURE_ENTRYPOINT_DIR" || exit 1
|
|
elif [ "$REINSTALL_FIXTURE_OVER_QUOTA" = 1 ]; then
|
|
truncate -s 1M "$scratch/installed.txt" || exit 1
|
|
else
|
|
printf installed > "$scratch/installed.txt" || exit 1
|
|
chmod +x "$scratch/installed.txt" || exit 1
|
|
fi
|
|
tar -C "$scratch" -cf - .
|
|
`), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
|
containerID := strings.Repeat("a", 64)
|
|
removedFile := filepath.Join(binDir, "removed")
|
|
argsFile := filepath.Join(binDir, "args")
|
|
t.Setenv("REINSTALL_FIXTURE_CONTAINER_ID", containerID)
|
|
t.Setenv("REINSTALL_FIXTURE_REMOVED", removedFile)
|
|
t.Setenv("REINSTALL_FIXTURE_ARGS", argsFile)
|
|
removals := 0
|
|
dockerEngineHTTPClient = &http.Client{Transport: reinstallDockerRemovalTransport{
|
|
imagesAvailable: true,
|
|
onRemoval: func() {
|
|
removals++
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
staged, err := filepath.Glob(filepath.Join(filepath.Dir(serverDir), ".alpha.restore-staging-*", "installed.txt"))
|
|
if err != nil || len(staged) != 1 {
|
|
t.Fatalf("installer output must be staged before removing the container: %v %v", staged, err)
|
|
}
|
|
},
|
|
}}
|
|
payload := map[string]any{
|
|
"templateId": "seeded", "hostPort": 30005,
|
|
"docker": map[string]any{"install": map[string]any{
|
|
"image": "docker.io/library/alpine:3.20", "script": "echo installer fixture",
|
|
}},
|
|
}
|
|
t.Setenv("REINSTALL_FIXTURE_CREATE_FAIL", "1")
|
|
failed := runReinstall(t, agent, serverName, "seeded", payload)
|
|
if failed.Code != http.StatusInternalServerError || decodeResponse(t, failed)["code"] != "reinstall_install_failed" || removals != 0 {
|
|
t.Fatalf("failed installer creation must not stop the live server: %d %s", failed.Code, failed.Body.String())
|
|
}
|
|
args, err := os.ReadFile(argsFile)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, flag := range []string{"--memory=268435456", "--memory-swap=268435456", "--cpu-period=100000", "--cpu-quota=50000", "--pids-limit=128", "--read-only", "--pull=never", "--log-driver=none", "sha256:" + strings.Repeat("b", 64), "/mnt/server:rw,exec,nodev,nosuid,mode=1777,size=1048570,nr_inodes=100000"} {
|
|
if !strings.Contains(string(args), "\n"+flag+"\n") {
|
|
t.Errorf("installer Docker command did not enforce %s", flag)
|
|
}
|
|
}
|
|
if strings.Contains(string(args), "\n-v\n") || strings.Contains(string(args), filepath.Dir(serverDir)) {
|
|
t.Fatal("the installer must not be given a writable host staging path")
|
|
}
|
|
if _, err := os.Stat(removedFile); !os.IsNotExist(err) {
|
|
t.Fatalf("cleanup must not remove anything without an installer ID: %v", err)
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
assertNoStagingSiblings(t, serverDir)
|
|
|
|
t.Setenv("REINSTALL_FIXTURE_CREATE_FAIL", "0")
|
|
t.Setenv("REINSTALL_FIXTURE_OVER_QUOTA", "1")
|
|
refused := runReinstall(t, agent, serverName, "seeded", payload)
|
|
if refused.Code != http.StatusInsufficientStorage || decodeResponse(t, refused)["code"] != "reinstall_disk_limit_exceeded" || removals != 0 {
|
|
t.Fatalf("over-budget installer output must be refused before removal: %d %s", refused.Code, refused.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
assertNoStagingSiblings(t, serverDir)
|
|
|
|
t.Setenv("REINSTALL_FIXTURE_OVER_QUOTA", "0")
|
|
t.Setenv("REINSTALL_FIXTURE_ENTRYPOINT_DIR", "server.bin")
|
|
invalid := runReinstall(t, agent, serverName, "seeded", payload)
|
|
if invalid.Code != http.StatusInternalServerError || decodeResponse(t, invalid)["code"] != "reinstall_scaffold_failed" || removals != 0 {
|
|
t.Fatalf("unusable staged entrypoint must be refused before removal: %d %s", invalid.Code, invalid.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
assertNoStagingSiblings(t, serverDir)
|
|
|
|
t.Setenv("REINSTALL_FIXTURE_ENTRYPOINT_DIR", "service/index.js")
|
|
managed := runReinstall(t, agent, serverName, "nodejs", map[string]any{
|
|
"templateId": "nodejs", "hostPort": 30005,
|
|
"docker": map[string]any{
|
|
"command": "node /app/service/index.js",
|
|
"install": payload["docker"].(map[string]any)["install"],
|
|
},
|
|
})
|
|
if managed.Code != http.StatusInternalServerError || decodeResponse(t, managed)["code"] != "reinstall_scaffold_failed" || removals != 0 {
|
|
t.Fatalf("unusable managed command entrypoint must be refused before removal: %d %s", managed.Code, managed.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
assertNoStagingSiblings(t, serverDir)
|
|
|
|
t.Setenv("REINSTALL_FIXTURE_ENTRYPOINT_DIR", "")
|
|
t.Setenv("ADPANEL_REINSTALL_INSTALLER_MAX_MB", "1")
|
|
meta["resources"].(map[string]any)["storageMb"] = 4
|
|
if err := agent.saveMeta(serverDir, meta); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
payload["docker"].(map[string]any)["install"].(map[string]any)["minimumStorageMb"] = 2
|
|
response := runReinstall(t, agent, serverName, "seeded", payload)
|
|
if response.Code != http.StatusOK || decodeResponse(t, response)["ok"] != true {
|
|
t.Fatalf("a template's disk minimum may exceed its bounded installer output: %d %s", response.Code, response.Body.String())
|
|
}
|
|
for path, expected := range map[string]string{filepath.Join(serverDir, "installed.txt"): "installed", backupPath: "backup"} {
|
|
if data, err := os.ReadFile(path); err != nil || string(data) != expected {
|
|
t.Fatalf("read %s: got %q, err=%v", path, data, err)
|
|
}
|
|
}
|
|
if _, err := os.Stat(filepath.Join(serverDir, "world-data.txt")); !os.IsNotExist(err) {
|
|
t.Fatalf("committed reinstall must replace the original files: %v", err)
|
|
}
|
|
if removed, err := os.ReadFile(removedFile); err != nil || string(removed) != strings.Repeat(containerID+"\n", 4) {
|
|
t.Fatalf("cleanup must use only the Docker-issued installer ID: got %q, err=%v", removed, err)
|
|
}
|
|
assertNoStagingSiblings(t, serverDir)
|
|
}
|
|
|
|
func TestReinstallVolumePermissionsStayWithinServer(t *testing.T) {
|
|
root := t.TempDir()
|
|
if err := os.Chmod(root, 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
serverDir := filepath.Join(root, "server")
|
|
nested := filepath.Join(serverDir, "nested")
|
|
if err := os.MkdirAll(nested, 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
outside := filepath.Join(root, "outside.txt")
|
|
dataFile := filepath.Join(nested, "data.txt")
|
|
executable := filepath.Join(nested, "run")
|
|
for path, mode := range map[string]os.FileMode{outside: 0o600, dataFile: 0o600, executable: 0o700} {
|
|
if err := os.WriteFile(path, nil, mode); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if err := os.Symlink(outside, filepath.Join(nested, "reference")); err != nil {
|
|
t.Skipf("symlinks unsupported: %v", err)
|
|
}
|
|
rootAlias := filepath.Join(root, "alias")
|
|
if err := os.Symlink(root, rootAlias); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if runtime.GOOS == "linux" {
|
|
for _, path := range []string{dataFile, nested} {
|
|
if err := os.Chmod(path, 0); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
ensureVolumeWritable(serverDir)
|
|
ensureVolumeWritable(rootAlias)
|
|
|
|
for path, mode := range map[string]os.FileMode{root: 0o700, outside: 0o600, nested: 0o777, dataFile: 0o666, executable: 0o777} {
|
|
info, err := os.Stat(path)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if info.Mode().Perm() != mode {
|
|
t.Errorf("%s has permissions %o, want %o", path, info.Mode().Perm(), mode)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestReinstallDeadlineCoversMaximumInstallerRuntime(t *testing.T) {
|
|
install := normalizeTemplateInstallConfig(&templateInstallConfig{Script: "echo fixture", TimeoutSeconds: 24 * 60 * 60})
|
|
remaining := reinstallCallerWaitBudget - time.Duration(install.TimeoutSeconds)*time.Second
|
|
if remaining <= 14*time.Minute {
|
|
t.Fatalf("a maximum-length installer must leave time for image pull and startup, got %v", remaining)
|
|
}
|
|
}
|
|
|
|
func TestReinstallPersistsMetadataForEveryTemplate(t *testing.T) {
|
|
for _, template := range []string{"custom", "minecraft"} {
|
|
t.Run(template, func(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
meta := map[string]any{"type": template, "hostPort": 30005, "__diskId": "secondary"}
|
|
stagingDir, err := createServerStagingDir(serverDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := agent.commitReinstallFiles(serverDir, stagingDir, meta); err != nil {
|
|
t.Fatalf("valid metadata should persist: %v", err)
|
|
}
|
|
persisted := agent.loadMeta(serverDir)
|
|
if persisted["type"] != template || persisted["hostPort"] != float64(30005) || persisted["__diskId"] != "secondary" {
|
|
t.Fatalf("runtime and disk identity must persist: %v", persisted)
|
|
}
|
|
metaPath := agent.metaPath(serverName)
|
|
if err := os.Remove(metaPath); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.Mkdir(metaPath, 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
stagingDir, err = createServerStagingDir(serverDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if code, err := agent.commitReinstallFiles(serverDir, stagingDir, meta); code != "reinstall_meta_save_failed" || err == nil {
|
|
t.Fatalf("failed metadata save must not report a commit: %s %v", code, err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestReinstallRefusedWhileRestoreInFlight reproduces the reported race: a
|
|
// backup restore holds the op lock (mid copyDir into serverDir) while the
|
|
// reinstall request arrives. The reinstall must 409 with backup_in_progress
|
|
// and must not touch the server directory — the old code RemoveAll'd it and
|
|
// extracted the template straight into the restore's target.
|
|
func TestReinstallRefusedWhileRestoreInFlight(t *testing.T) {
|
|
a := newReinstallRaceTestAgent(t)
|
|
name := "alpha"
|
|
serverDir := seedRaceServer(t, a, name)
|
|
|
|
opMu := a.getServerOpLock(name)
|
|
opMu.Lock()
|
|
t.Cleanup(opMu.Unlock)
|
|
a.beginLongOp(name, longOpBackup)
|
|
t.Cleanup(func() { a.endLongOp(name) })
|
|
|
|
rec := runReinstall(t, a, name, "custom", map[string]any{"templateId": "custom"})
|
|
if rec.Code != http.StatusConflict {
|
|
t.Fatalf("expected 409 while restore in flight, got %d: %s", rec.Code, rec.Body.String())
|
|
}
|
|
body := decodeResponse(t, rec)
|
|
if body["code"] != "backup_in_progress" {
|
|
t.Fatalf("expected code backup_in_progress, got: %v", body)
|
|
}
|
|
if body["ok"] != false {
|
|
t.Fatalf("expected ok=false, got: %v", body)
|
|
}
|
|
assertServerDirUntouched(t, a, name, serverDir)
|
|
}
|
|
|
|
// TestReinstallRefusedWhileShortOpHoldsLock: a power op (start/stop/...) holds
|
|
// the op lock without a long-op marker. The reinstall must still 409 (never
|
|
// race), but with the quick-retry server_op_in_progress response rather than
|
|
// a long-op conflict.
|
|
func TestReinstallRefusedWhileShortOpHoldsLock(t *testing.T) {
|
|
a := newReinstallRaceTestAgent(t)
|
|
name := "alpha"
|
|
serverDir := seedRaceServer(t, a, name)
|
|
|
|
opMu := a.getServerOpLock(name)
|
|
opMu.Lock()
|
|
t.Cleanup(opMu.Unlock)
|
|
|
|
rec := runReinstall(t, a, name, "custom", map[string]any{"templateId": "custom"})
|
|
if rec.Code != http.StatusConflict {
|
|
t.Fatalf("expected 409 while op lock held, got %d: %s", rec.Code, rec.Body.String())
|
|
}
|
|
body := decodeResponse(t, rec)
|
|
if body["code"] != "server_op_in_progress" {
|
|
t.Fatalf("expected code server_op_in_progress, got: %v", body)
|
|
}
|
|
assertServerDirUntouched(t, a, name, serverDir)
|
|
}
|
|
|
|
// TestBackupCreateRefusedWhileReinstallInFlight is the mirror direction: a
|
|
// reinstall holds the op lock (mid wipe/extract, potentially for many
|
|
// minutes) while a backup create arrives. The create must 409 instead of
|
|
// walking and copying the half-wiped tree into a status:"complete" backup.
|
|
func TestBackupCreateRefusedWhileReinstallInFlight(t *testing.T) {
|
|
a := newReinstallRaceTestAgent(t)
|
|
name := "alpha"
|
|
seedRaceServer(t, a, name)
|
|
|
|
opMu := a.getServerOpLock(name)
|
|
opMu.Lock()
|
|
t.Cleanup(opMu.Unlock)
|
|
a.beginLongOp(name, longOpReinstall)
|
|
t.Cleanup(func() { a.endLongOp(name) })
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "/v1/servers/"+name+"/backups", strings.NewReader(`{"name":"during reinstall"}`))
|
|
rec := httptest.NewRecorder()
|
|
a.handleBackupsCreate(rec, req, name)
|
|
|
|
if rec.Code != http.StatusConflict {
|
|
t.Fatalf("expected 409 while reinstall in flight, got %d: %s", rec.Code, rec.Body.String())
|
|
}
|
|
body := decodeResponse(t, rec)
|
|
// The 409 must name the actual holder (reinstall), not the legacy
|
|
// backup-text: a user asking for a backup during a reinstall must not be
|
|
// told a backup is running.
|
|
if body["error"] != "reinstall operation already in progress" || body["code"] != "reinstall_in_progress" {
|
|
t.Fatalf("expected reinstall-holder refusal body, got: %v", body)
|
|
}
|
|
// No backup directory may have been created for the refused create.
|
|
entries, err := os.ReadDir(a.serverBackupsDir(name))
|
|
if err == nil && len(entries) != 0 {
|
|
t.Fatalf("refused create must not leave backup entries: %v", entries)
|
|
}
|
|
}
|
|
|
|
// TestBackupCreateRefusedWhileBackupHoldsLock pins the byte-compat of the
|
|
// backup refusal for the pre-existing holder combinations (another backup, or
|
|
// any short op that leaves no marker): the exact legacy body, unchanged.
|
|
func TestBackupCreateRefusedWhileBackupHoldsLock(t *testing.T) {
|
|
a := newReinstallRaceTestAgent(t)
|
|
name := "alpha"
|
|
seedRaceServer(t, a, name)
|
|
|
|
opMu := a.getServerOpLock(name)
|
|
opMu.Lock()
|
|
t.Cleanup(opMu.Unlock)
|
|
a.beginLongOp(name, longOpBackup)
|
|
t.Cleanup(func() { a.endLongOp(name) })
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "/v1/servers/"+name+"/backups", strings.NewReader(`{"name":"dup"}`))
|
|
rec := httptest.NewRecorder()
|
|
a.handleBackupsCreate(rec, req, name)
|
|
|
|
if rec.Code != http.StatusConflict {
|
|
t.Fatalf("expected 409 while backup in flight, got %d: %s", rec.Code, rec.Body.String())
|
|
}
|
|
var body map[string]any
|
|
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
|
t.Fatalf("response not json: %s", rec.Body.String())
|
|
}
|
|
if body["ok"] != false || body["error"] != "backup operation already in progress" {
|
|
t.Fatalf("legacy backup refusal body must be preserved, got: %v", body)
|
|
}
|
|
// The compat contract is also the ABSENCE of extra fields: relays pass the
|
|
// body through and any consumer may match on the exact shape.
|
|
if len(body) != 2 {
|
|
t.Fatalf("legacy backup refusal body must not gain fields, got %d: %v", len(body), body)
|
|
}
|
|
}
|
|
|
|
// TestBackupRestoreRefusedWhileReinstallInFlight: the same exclusion for the
|
|
// restore handler, whose copyDir writer is the other half of the reported
|
|
// interleaving corruption.
|
|
func TestBackupRestoreRefusedWhileReinstallInFlight(t *testing.T) {
|
|
a := newReinstallRaceTestAgent(t)
|
|
name := "alpha"
|
|
serverDir := seedRaceServer(t, a, name)
|
|
|
|
// A plausible backup to restore.
|
|
backupID := "1700000000_abcdef012345"
|
|
dataDir := filepath.Join(a.serverBackupsDir(name), backupID, "data")
|
|
if err := os.MkdirAll(dataDir, 0o750); err != nil {
|
|
t.Fatalf("mkdir backup data: %v", err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(dataDir, "restored.txt"), []byte("backup"), 0o644); err != nil {
|
|
t.Fatalf("seed backup file: %v", err)
|
|
}
|
|
|
|
opMu := a.getServerOpLock(name)
|
|
opMu.Lock()
|
|
t.Cleanup(opMu.Unlock)
|
|
a.beginLongOp(name, longOpReinstall)
|
|
t.Cleanup(func() { a.endLongOp(name) })
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "/v1/servers/"+name+"/backups/"+backupID+"/restore", strings.NewReader(`{"deleteOldFiles":true}`))
|
|
rec := httptest.NewRecorder()
|
|
a.handleBackupsRestore(rec, req, name, backupID)
|
|
|
|
if rec.Code != http.StatusConflict {
|
|
t.Fatalf("expected 409 while reinstall in flight, got %d: %s", rec.Code, rec.Body.String())
|
|
}
|
|
// The server dir must be exactly as seeded: no wipe, no restore copy.
|
|
assertServerDirUntouched(t, a, name, serverDir)
|
|
}
|
|
|
|
func TestExportRefusedWhileReinstallInFlight(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
operation := agent.getServerOpLock(serverName)
|
|
operation.Lock()
|
|
defer operation.Unlock()
|
|
agent.beginLongOp(serverName, longOpReinstall)
|
|
defer agent.endLongOp(serverName)
|
|
response := httptest.NewRecorder()
|
|
agent.handleExportServer(response, httptest.NewRequest(http.MethodGet, "/v1/servers/alpha/export", nil), serverName)
|
|
if response.Code != http.StatusConflict || decodeResponse(t, response)["code"] != "reinstall_in_progress" {
|
|
t.Fatalf("export must not snapshot a tree being rebuilt: %d %s", response.Code, response.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
}
|
|
|
|
func TestExportReleasesOperationLock(t *testing.T) {
|
|
for _, present := range []bool{false, true} {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
serverName := "alpha"
|
|
if present {
|
|
seedRaceServer(t, agent, serverName)
|
|
}
|
|
response := httptest.NewRecorder()
|
|
agent.handleExportServer(response, httptest.NewRequest(http.MethodGet, "/v1/servers/alpha/export", nil), serverName)
|
|
expectedStatus := http.StatusNotFound
|
|
if present {
|
|
expectedStatus = http.StatusOK
|
|
}
|
|
if response.Code != expectedStatus {
|
|
t.Fatalf("unexpected export status: %d", response.Code)
|
|
}
|
|
if operation := agent.tryLockServerOp(serverName); operation == nil {
|
|
t.Fatal("export must release its operation lock on success and early refusal")
|
|
} else {
|
|
operation.Unlock()
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestPowerOpsFailFastDuringReinstall: with reinstall registered as the long
|
|
// op (as the real handler does while it holds the lock), every power op must
|
|
// fail fast with 409 reinstall_in_progress — never queue behind the
|
|
// reinstall's potentially tens-of-minutes hold and execute later as a
|
|
// phantom action after the panel relay gave up.
|
|
func TestPowerOpsFailFastDuringReinstall(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const serverName = "alpha"
|
|
serverDir := seedRaceServer(t, agent, serverName)
|
|
t.Cleanup(func() { agent.logs.killTail(serverName) })
|
|
releaseStorage := agent.lockUploadScope(serverDir)
|
|
storageHeld := true
|
|
payload := map[string]any{"templateId": "custom"}
|
|
request, recorder := signedReinstallRequest(t, agent, serverName, "custom", payload)
|
|
writer := &reinstallStorageBarrierWriter{ResponseRecorder: recorder, started: make(chan struct{})}
|
|
completed := make(chan struct{})
|
|
go func() {
|
|
defer close(completed)
|
|
agent.handleReinstallServer(writer, request, serverName)
|
|
}()
|
|
defer func() {
|
|
if storageHeld {
|
|
releaseStorage()
|
|
}
|
|
<-completed
|
|
}()
|
|
select {
|
|
case <-writer.started:
|
|
case <-time.After(2 * time.Second):
|
|
t.Fatal("reinstall did not acquire its operation lock")
|
|
}
|
|
|
|
powerHandlers := []struct {
|
|
action string
|
|
handle func(http.ResponseWriter, *http.Request, string)
|
|
}{
|
|
{"start", agent.handleStart},
|
|
{"stop", agent.handleStop},
|
|
{"restart", agent.handleRestart},
|
|
{"kill", agent.handleKill},
|
|
}
|
|
for _, handler := range powerHandlers {
|
|
response := httptest.NewRecorder()
|
|
handler.handle(response, httptest.NewRequest(http.MethodPost, "/v1/servers/"+serverName+"/"+handler.action, nil), serverName)
|
|
if response.Code != http.StatusConflict || decodeResponse(t, response)["code"] != "reinstall_in_progress" {
|
|
t.Fatalf("%s: expected reinstall conflict, got %d: %s", handler.action, response.Code, response.Body.String())
|
|
}
|
|
}
|
|
duplicate := runReinstall(t, agent, serverName, "custom", payload)
|
|
if duplicate.Code != http.StatusConflict || decodeResponse(t, duplicate)["code"] != "reinstall_in_progress" {
|
|
t.Fatalf("duplicate reinstall must be refused, got %d: %s", duplicate.Code, duplicate.Body.String())
|
|
}
|
|
assertServerDirUntouched(t, agent, serverName, serverDir)
|
|
releaseStorage()
|
|
storageHeld = false
|
|
<-completed
|
|
if recorder.Code != http.StatusOK || agent.longOpKind(serverName) != "" {
|
|
t.Fatalf("reinstall must complete and release its marker, got %d: %s", recorder.Code, recorder.Body.String())
|
|
}
|
|
}
|
|
|
|
// TestPowerOpsFailFastDuringBackup keeps the pre-existing backup half of the
|
|
// fail-fast contract honest after the marker generalization: a backup marker
|
|
// still yields 409 backup_in_progress (and performServerStart still maps to
|
|
// errBackupOpInProgress).
|
|
func TestPowerOpsFailFastDuringBackup(t *testing.T) {
|
|
a := newReinstallRaceTestAgent(t)
|
|
name := "alpha"
|
|
seedRaceServer(t, a, name)
|
|
|
|
a.beginLongOp(name, longOpBackup)
|
|
t.Cleanup(func() { a.endLongOp(name) })
|
|
|
|
if _, err := a.performServerStart(context.Background(), name, 0, nil); !errors.Is(err, errBackupOpInProgress) {
|
|
t.Fatalf("performServerStart must fail fast with errBackupOpInProgress, got %v", err)
|
|
}
|
|
|
|
rec := httptest.NewRecorder()
|
|
a.handleStop(rec, httptest.NewRequest(http.MethodPost, "/v1/servers/"+name+"/stop", nil), name)
|
|
if rec.Code != http.StatusConflict {
|
|
t.Fatalf("expected 409 during backup, got %d: %s", rec.Code, rec.Body.String())
|
|
}
|
|
if body := decodeResponse(t, rec); body["code"] != "backup_in_progress" {
|
|
t.Fatalf("expected code backup_in_progress, got: %v", body)
|
|
}
|
|
}
|
|
|
|
// TestReinstallHappyPathReleasesLockAndMarker runs a full reinstall (custom
|
|
// template: no image, no container start) and asserts the op lock and the
|
|
// long-op marker are released afterwards, the wipe+rebuild actually happened
|
|
// (proving the test really exercised the critical section), and the rebuilt
|
|
// meta records the new template.
|
|
func TestReinstallHappyPathReleasesLockAndMarker(t *testing.T) {
|
|
a := newReinstallRaceTestAgent(t)
|
|
name := "alpha"
|
|
serverDir := seedRaceServer(t, a, name)
|
|
t.Cleanup(func() { a.logs.killTail(name) })
|
|
|
|
rec := runReinstall(t, a, name, "custom", map[string]any{"templateId": "custom"})
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("expected 200 reinstall, got %d: %s", rec.Code, rec.Body.String())
|
|
}
|
|
if body := decodeResponse(t, rec); body["ok"] != true || body["serverStopped"] != true {
|
|
t.Fatalf("a completed reinstall without an image must report a stopped server: %v", body)
|
|
}
|
|
|
|
// The critical section really ran: the seeded file is gone and the meta
|
|
// was rebuilt with the new template.
|
|
if _, err := os.Stat(filepath.Join(serverDir, "world-data.txt")); !os.IsNotExist(err) {
|
|
t.Fatalf("seeded world file must be wiped by the reinstall (err=%v)", err)
|
|
}
|
|
if meta := a.loadMeta(serverDir); meta["template"] != "custom" {
|
|
t.Fatalf("meta must record the reinstalled template, got: %v", meta)
|
|
}
|
|
|
|
// Lock and marker must be free again — a leaked lock would wedge every
|
|
// future op on this server; a leaked marker would 409 them all.
|
|
if opMu := a.tryLockServerOp(name); opMu == nil {
|
|
t.Fatal("op lock must be released after a successful reinstall")
|
|
} else {
|
|
opMu.Unlock()
|
|
}
|
|
if kind := a.longOpKind(name); kind != "" {
|
|
t.Fatalf("long-op marker must be withdrawn after a successful reinstall, got %q", kind)
|
|
}
|
|
}
|
|
|
|
// TestReinstallFailureInsideCriticalSectionReleasesLockAndMarker forces a
|
|
// validation failure that fires INSIDE the critical section (invalid docker
|
|
// workdir is rejected before the wipe) and asserts the deferred release
|
|
// still runs on the bail-out path.
|
|
func TestReinstallFailureInsideCriticalSectionReleasesLockAndMarker(t *testing.T) {
|
|
a := newReinstallRaceTestAgent(t)
|
|
name := "alpha"
|
|
seedRaceServer(t, a, name)
|
|
|
|
rec := runReinstall(t, a, name, "custom", map[string]any{
|
|
"templateId": "custom",
|
|
"docker": map[string]any{"workdir": "relative/not/absolute"},
|
|
})
|
|
if rec.Code != http.StatusBadRequest {
|
|
t.Fatalf("expected 400 for invalid workdir, got %d: %s", rec.Code, rec.Body.String())
|
|
}
|
|
|
|
if opMu := a.tryLockServerOp(name); opMu == nil {
|
|
t.Fatal("op lock must be released after a failed reinstall")
|
|
} else {
|
|
opMu.Unlock()
|
|
}
|
|
if kind := a.longOpKind(name); kind != "" {
|
|
t.Fatalf("long-op marker must be withdrawn after a failed reinstall, got %q", kind)
|
|
}
|
|
}
|
|
|
|
// TestLongOpConflictContract pins the marker vocabulary: unset yields no
|
|
// conflict, and each kind maps to its 409 code and a detail that names the
|
|
// actual holder.
|
|
func TestLongOpConflictContract(t *testing.T) {
|
|
a := newReinstallRaceTestAgent(t)
|
|
name := "alpha"
|
|
|
|
if _, _, _, busy := a.longOpConflict(name); busy {
|
|
t.Fatal("no conflict expected when no long op is registered")
|
|
}
|
|
a.beginLongOp(name, longOpBackup)
|
|
code, message, _, busy := a.longOpConflict(name)
|
|
if !busy || code != "backup_in_progress" || message != "backup operation in progress" {
|
|
t.Fatalf("backup marker mismatch: code=%q message=%q busy=%v", code, message, busy)
|
|
}
|
|
a.endLongOp(name)
|
|
a.beginLongOp(name, longOpReinstall)
|
|
code, message, _, busy = a.longOpConflict(name)
|
|
if !busy || code != "reinstall_in_progress" || message != "reinstall operation in progress" {
|
|
t.Fatalf("reinstall marker mismatch: code=%q message=%q busy=%v", code, message, busy)
|
|
}
|
|
a.endLongOp(name)
|
|
a.beginLongOp(name, longOpRuntimeSeed)
|
|
code, message, _, busy = a.longOpConflict(name)
|
|
if !busy || code != "runtime_seed_in_progress" || message != "runtime seed operation in progress" {
|
|
t.Fatalf("runtime-seed marker mismatch: code=%q message=%q busy=%v", code, message, busy)
|
|
}
|
|
a.endLongOp(name)
|
|
if kind := a.longOpKind(name); kind != "" {
|
|
t.Fatalf("marker must be withdrawn by endLongOp, got %q", kind)
|
|
}
|
|
}
|
|
|
|
// runRuntimeSeed drives the real /runtime handler in-process (panel-side
|
|
// seeding shape: template + runtime + start + port).
|
|
func runRuntimeSeed(t *testing.T, a *Agent, name string, payload map[string]any) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
body, err := json.Marshal(payload)
|
|
if err != nil {
|
|
t.Fatalf("marshal payload: %v", err)
|
|
}
|
|
req := httptest.NewRequest(http.MethodPost, "/v1/servers/"+name+"/runtime", strings.NewReader(string(body)))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
rec := httptest.NewRecorder()
|
|
a.handleRuntime(rec, req, name)
|
|
return rec
|
|
}
|
|
|
|
// TestRuntimeSeedRefusedWhileBackupHoldsOpLock: the runtime seed's legacy
|
|
// migration path RemoveAll's serverDir; while a backup create/restore holds
|
|
// the op lock the seed must 409 and leave the directory untouched, closing
|
|
// the same wipe-vs-copy corruption class reinstall had.
|
|
func TestRuntimeSeedRefusedWhileBackupHoldsOpLock(t *testing.T) {
|
|
a := newReinstallRaceTestAgent(t)
|
|
name := "alpha"
|
|
serverDir := seedRaceServer(t, a, name)
|
|
|
|
opMu := a.getServerOpLock(name)
|
|
opMu.Lock()
|
|
t.Cleanup(opMu.Unlock)
|
|
a.beginLongOp(name, longOpBackup)
|
|
t.Cleanup(func() { a.endLongOp(name) })
|
|
|
|
rec := runRuntimeSeed(t, a, name, map[string]any{
|
|
"runtime": map[string]any{"providerId": "nodejs"},
|
|
"template": "nodejs",
|
|
"start": "index.js",
|
|
"port": 3001,
|
|
})
|
|
if rec.Code != http.StatusConflict {
|
|
t.Fatalf("expected 409 while backup in flight, got %d: %s", rec.Code, rec.Body.String())
|
|
}
|
|
body := decodeResponse(t, rec)
|
|
if body["code"] != "backup_in_progress" || body["ok"] != false {
|
|
t.Fatalf("expected backup_in_progress refusal, got: %v", body)
|
|
}
|
|
assertServerDirUntouched(t, a, name, serverDir)
|
|
}
|
|
|
|
// TestRuntimeSeedHappyPathWipesRebuildsAndReleases: a legacy server (meta
|
|
// without structured runtime) is seeded end-to-end — the wipe must happen
|
|
// (proving the test exercises the critical section), the rebuilt meta carries
|
|
// the structured runtime, and lock and marker must be free again afterwards.
|
|
func TestRuntimeSeedHappyPathWipesRebuildsAndReleases(t *testing.T) {
|
|
a := newReinstallRaceTestAgent(t)
|
|
name := "alpha"
|
|
serverDir := seedRaceServer(t, a, name)
|
|
// Legacy meta: no "runtime" key, so the seed takes the wipe path.
|
|
if meta := a.loadMeta(serverDir); meta["runtime"] != nil {
|
|
t.Fatalf("test premise: seeded meta must not carry a runtime, got %v", meta)
|
|
}
|
|
|
|
rec := runRuntimeSeed(t, a, name, map[string]any{
|
|
"runtime": map[string]any{"providerId": "nodejs", "image": "node", "tag": "20-alpine"},
|
|
"template": "nodejs",
|
|
"start": "index.js",
|
|
"port": 3001,
|
|
})
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("expected 200 seed, got %d: %s", rec.Code, rec.Body.String())
|
|
}
|
|
|
|
if _, err := os.Stat(filepath.Join(serverDir, "world-data.txt")); !os.IsNotExist(err) {
|
|
t.Fatalf("legacy wipe must have removed the seeded file (err=%v)", err)
|
|
}
|
|
meta := a.loadMeta(serverDir)
|
|
if rt, ok := meta["runtime"].(map[string]any); !ok || len(rt) == 0 {
|
|
t.Fatalf("seeded meta must carry a structured runtime, got: %v", meta)
|
|
}
|
|
|
|
if opMu := a.tryLockServerOp(name); opMu == nil {
|
|
t.Fatal("op lock must be released after a successful runtime seed")
|
|
} else {
|
|
opMu.Unlock()
|
|
}
|
|
if kind := a.longOpKind(name); kind != "" {
|
|
t.Fatalf("long-op marker must be withdrawn after a successful runtime seed, got %q", kind)
|
|
}
|
|
}
|
|
|
|
// TestPowerOpsFailFastDuringRuntimeSeed: while a runtime seed holds the
|
|
// marker, start returns the runtime-seed sentinel (mapped to 409
|
|
// runtime_seed_in_progress) and the direct power handlers 409 with the same
|
|
// code — never queue behind the seed's minutes-long hold.
|
|
func TestPowerOpsFailFastDuringRuntimeSeed(t *testing.T) {
|
|
a := newReinstallRaceTestAgent(t)
|
|
name := "alpha"
|
|
seedRaceServer(t, a, name)
|
|
|
|
a.beginLongOp(name, longOpRuntimeSeed)
|
|
t.Cleanup(func() { a.endLongOp(name) })
|
|
|
|
if _, err := a.performServerStart(context.Background(), name, 0, nil); !errors.Is(err, errRuntimeSeedOpInProgress) {
|
|
t.Fatalf("performServerStart must fail fast with errRuntimeSeedOpInProgress, got %v", err)
|
|
}
|
|
|
|
rec := httptest.NewRecorder()
|
|
a.handleStop(rec, httptest.NewRequest(http.MethodPost, "/v1/servers/"+name+"/stop", nil), name)
|
|
if rec.Code != http.StatusConflict {
|
|
t.Fatalf("expected 409 during runtime seed, got %d: %s", rec.Code, rec.Body.String())
|
|
}
|
|
if body := decodeResponse(t, rec); body["code"] != "runtime_seed_in_progress" {
|
|
t.Fatalf("expected code runtime_seed_in_progress, got: %v", body)
|
|
}
|
|
}
|