384 lines
16 KiB
Go
384 lines
16 KiB
Go
package main
|
|
|
|
import (
|
|
"archive/tar"
|
|
"bytes"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
// buildTransferTar produces a tarball in the exact shape handleExportServer
|
|
// emits: server files at the root, backups under ".adpanel_backups/", and the
|
|
// server meta under ".adpanel_meta/<name>.json". The meta deliberately carries a
|
|
// SOURCE-node __diskId to simulate a server that lived on the source's secondary
|
|
// disk, which must be stripped by the destination on import.
|
|
func buildTransferTar(t *testing.T, name string, sourceMeta map[string]any) []byte {
|
|
t.Helper()
|
|
var buf bytes.Buffer
|
|
tw := tar.NewWriter(&buf)
|
|
|
|
writeFile := func(tarName string, data []byte) {
|
|
hdr := &tar.Header{Name: tarName, Mode: 0o644, Size: int64(len(data)), Typeflag: tar.TypeReg}
|
|
if err := tw.WriteHeader(hdr); err != nil {
|
|
t.Fatalf("write header %s: %v", tarName, err)
|
|
}
|
|
if _, err := tw.Write(data); err != nil {
|
|
t.Fatalf("write body %s: %v", tarName, err)
|
|
}
|
|
}
|
|
|
|
// Server payload file.
|
|
writeFile("server.properties", []byte("level-name=world\n"))
|
|
// A backup artifact.
|
|
writeFile(".adpanel_backups/backup-1.tar.gz", []byte("fake-backup-bytes"))
|
|
// Source meta with a stale disk identity.
|
|
metaBytes, err := json.Marshal(sourceMeta)
|
|
if err != nil {
|
|
t.Fatalf("marshal source meta: %v", err)
|
|
}
|
|
writeFile(".adpanel_meta/"+sanitizeName(name)+".json", metaBytes)
|
|
|
|
if err := tw.Close(); err != nil {
|
|
t.Fatalf("close tar: %v", err)
|
|
}
|
|
return buf.Bytes()
|
|
}
|
|
|
|
func doImportTar(t *testing.T, a *Agent, name, diskID string, body []byte) (*httptest.ResponseRecorder, map[string]any) {
|
|
t.Helper()
|
|
url := "/v1/servers/" + name + "/import-tar"
|
|
if diskID != "" {
|
|
url += "?diskId=" + diskID
|
|
}
|
|
req := httptest.NewRequest(http.MethodPost, url, bytes.NewReader(body))
|
|
rr := httptest.NewRecorder()
|
|
a.handleImportTar(rr, req, name)
|
|
|
|
var parsed map[string]any
|
|
_ = json.Unmarshal(rr.Body.Bytes(), &parsed)
|
|
return rr, parsed
|
|
}
|
|
|
|
// TestImportTarToDestinationPrimaryStripsSourceDiskId covers the user's first
|
|
// scenario: a server is transferred to another node and lands on that node's
|
|
// PRIMARY disk. The source's __diskId must be discarded so the server resolves to
|
|
// the destination's default volumes/backups roots, not a phantom disk.
|
|
func TestImportTarToDestinationPrimaryStripsSourceDiskId(t *testing.T) {
|
|
a, vol := newTestAgent(t)
|
|
name := "alpha"
|
|
|
|
// Source meta pretends the server lived on a secondary disk that does NOT
|
|
// exist on this destination node.
|
|
sourceMeta := map[string]any{
|
|
"type": "custom",
|
|
"template": "custom",
|
|
"__diskId": "disk-source-secondary",
|
|
"resources": map[string]any{
|
|
"ramMb": float64(2048),
|
|
},
|
|
}
|
|
tarBytes := buildTransferTar(t, name, sourceMeta)
|
|
|
|
rr, resp := doImportTar(t, a, name, "", tarBytes)
|
|
if rr.Code != 200 {
|
|
t.Fatalf("import-tar status: got %d body=%s", rr.Code, rr.Body.String())
|
|
}
|
|
if ok, _ := resp["ok"].(bool); !ok {
|
|
t.Fatalf("import-tar not ok: %v", resp)
|
|
}
|
|
|
|
// Files must live on the primary disk.
|
|
wantServerDir := filepath.Join(vol, name)
|
|
if _, err := os.Stat(filepath.Join(wantServerDir, "server.properties")); err != nil {
|
|
t.Fatalf("server file not on primary disk: %v", err)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(a.backupsDir(), name, "backup-1.tar.gz")); err != nil {
|
|
t.Fatalf("backup file not on primary backups root: %v", err)
|
|
}
|
|
|
|
// Meta must have the stale __diskId stripped and NOT re-added for primary.
|
|
a.invalidateServerDiskCache(name)
|
|
persisted := a.loadMeta(wantServerDir)
|
|
if _, present := persisted["__diskId"]; present {
|
|
t.Fatalf("__diskId must be absent for a primary-disk import, got %v", persisted["__diskId"])
|
|
}
|
|
// Non-routing meta must be preserved.
|
|
if persisted["template"] != "custom" {
|
|
t.Fatalf("template meta not preserved: %v", persisted["template"])
|
|
}
|
|
|
|
// Routing must resolve to the primary disk across a cold cache.
|
|
if got := a.diskForServer(name); !(got.Primary || got.ID == primaryDiskID) {
|
|
t.Fatalf("server mis-routed after import: got disk %q", got.ID)
|
|
}
|
|
if got := a.serverDir(name); got != wantServerDir {
|
|
t.Fatalf("serverDir after import: got %q want %q", got, wantServerDir)
|
|
}
|
|
}
|
|
|
|
// TestImportTarToDestinationSecondaryStampsCorrectDiskId covers the user's second
|
|
// scenario: a server (regardless of which disk it lived on at the source) is
|
|
// placed on a SECONDARY disk of the destination node. The destination must stamp
|
|
// ITS OWN disk id so the panel/node know the server is at
|
|
// "<mountPath>/adpanel/volumes/<name>" with backups at
|
|
// "<mountPath>/adpanel/backups/<name>".
|
|
func TestImportTarToDestinationSecondaryStampsCorrectDiskId(t *testing.T) {
|
|
a, _ := newTestAgent(t)
|
|
mount := t.TempDir()
|
|
dest := registerTestDisk(t, a, mount, 50)
|
|
name := "beta"
|
|
|
|
sourceMeta := map[string]any{
|
|
"type": "custom",
|
|
"template": "custom",
|
|
// A different, source-only disk id that must be replaced.
|
|
"__diskId": "disk-source-foreign",
|
|
}
|
|
tarBytes := buildTransferTar(t, name, sourceMeta)
|
|
|
|
rr, resp := doImportTar(t, a, name, dest.ID, tarBytes)
|
|
if rr.Code != 200 {
|
|
t.Fatalf("import-tar status: got %d body=%s", rr.Code, rr.Body.String())
|
|
}
|
|
if resp["diskId"] != dest.ID {
|
|
t.Fatalf("import-tar reported diskId %v want %q", resp["diskId"], dest.ID)
|
|
}
|
|
|
|
// Files must live under the destination secondary disk's layout.
|
|
wantServerDir := filepath.Join(a.diskLayoutVolumes(mount), name)
|
|
if _, err := os.Stat(filepath.Join(wantServerDir, "server.properties")); err != nil {
|
|
t.Fatalf("server file not on secondary disk volumes root: %v", err)
|
|
}
|
|
wantBackupDir := filepath.Join(a.diskLayoutBackups(mount), name)
|
|
if _, err := os.Stat(filepath.Join(wantBackupDir, "backup-1.tar.gz")); err != nil {
|
|
t.Fatalf("backup file not on secondary disk backups root: %v", err)
|
|
}
|
|
|
|
// Meta must record the DESTINATION disk id, never the source's.
|
|
persisted := a.loadMeta(wantServerDir)
|
|
if id, _ := persisted["__diskId"].(string); id != dest.ID {
|
|
t.Fatalf("__diskId after import: got %q want %q (must not keep source id)", id, dest.ID)
|
|
}
|
|
|
|
// Routing must resolve to the destination secondary disk across a cold cache.
|
|
a.invalidateServerDiskCache(name)
|
|
if got := a.diskForServer(name); got.ID != dest.ID {
|
|
t.Fatalf("server mis-routed after import: got disk %q want %q", got.ID, dest.ID)
|
|
}
|
|
if got := a.serverDir(name); got != wantServerDir {
|
|
t.Fatalf("serverDir after import: got %q want %q", got, wantServerDir)
|
|
}
|
|
if got := a.serverBackupsDir(name); got != wantBackupDir {
|
|
t.Fatalf("serverBackupsDir after import: got %q want %q", got, wantBackupDir)
|
|
}
|
|
}
|
|
|
|
// TestImportTarRejectsUnknownDiskId ensures a transfer that targets a disk this
|
|
// node does not own fails fast instead of silently extracting to the wrong place.
|
|
func TestImportTarRejectsUnknownDiskId(t *testing.T) {
|
|
a, _ := newTestAgent(t)
|
|
name := "gamma"
|
|
tarBytes := buildTransferTar(t, name, map[string]any{"type": "custom"})
|
|
|
|
rr, resp := doImportTar(t, a, name, "disk-does-not-exist", tarBytes)
|
|
if rr.Code != 400 {
|
|
t.Fatalf("expected 400 for unknown diskId, got %d body=%s", rr.Code, rr.Body.String())
|
|
}
|
|
if ok, _ := resp["ok"].(bool); ok {
|
|
t.Fatalf("expected ok=false for unknown diskId, got %v", resp)
|
|
}
|
|
}
|
|
|
|
func TestTransferExportProtectsWritesAndCleansOnlyItsSource(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const name = "alpha"
|
|
const transferID = "1234567890abcdef1234567890abcdef"
|
|
serverDir := seedRaceServer(t, agent, name)
|
|
containerPresent := true
|
|
var removedContainer string
|
|
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.MethodGet && strings.HasSuffix(request.URL.Path, "/containers/alpha/json") && containerPresent:
|
|
status = http.StatusOK
|
|
body = `{"Id":"` + reinstallFixtureContainerID + `","Name":"/alpha","State":{"Status":"exited"}}`
|
|
case request.Method == http.MethodDelete:
|
|
removedContainer = filepath.Base(request.URL.Path)
|
|
containerPresent = false
|
|
status, body = http.StatusNoContent, ""
|
|
}
|
|
return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
|
})}
|
|
endpoint := "/v1/servers/alpha/export?transferId="
|
|
export := func() {
|
|
t.Helper()
|
|
response := httptest.NewRecorder()
|
|
agent.handleExportServer(response, httptest.NewRequest(http.MethodGet, endpoint+transferID, nil), name)
|
|
if response.Code != http.StatusOK || response.Header().Get("X-ADPanel-Transfer-Id") != transferID {
|
|
t.Fatalf("protected export: got %d %s", response.Code, response.Body.String())
|
|
}
|
|
}
|
|
finish := func(query string) *httptest.ResponseRecorder {
|
|
response := httptest.NewRecorder()
|
|
agent.handleFinishTransferExport(response, httptest.NewRequest(http.MethodDelete, endpoint+query, nil), name)
|
|
return response
|
|
}
|
|
write := func() *httptest.ResponseRecorder {
|
|
return fsPost(t, agent.handleFSWrite, "/v1/fs/write", map[string]any{
|
|
"path": filepath.Join(serverDir, "world-data.txt"), "server": name, "content": "updated",
|
|
})
|
|
}
|
|
|
|
export()
|
|
if response := write(); response.Code != http.StatusConflict || !strings.Contains(response.Body.String(), "transfer_in_progress") {
|
|
t.Fatalf("file write was not fenced: %d %s", response.Code, response.Body.String())
|
|
}
|
|
startReply := httptest.NewRecorder()
|
|
agent.handleStart(startReply, httptest.NewRequest(http.MethodPost, "/v1/servers/alpha/start", nil), name)
|
|
if startReply.Code != http.StatusConflict || !strings.Contains(startReply.Body.String(), "transfer_in_progress") {
|
|
t.Fatalf("start was not fenced: %d %s", startReply.Code, startReply.Body.String())
|
|
}
|
|
if response := finish(strings.Repeat("a", 32) + "&cleanup=true"); response.Code != http.StatusConflict || removedContainer != "" {
|
|
t.Fatalf("unowned cleanup changed the source: %d %s", response.Code, response.Body.String())
|
|
}
|
|
if response := finish(transferID); response.Code != http.StatusOK {
|
|
t.Fatalf("rollback could not release the hold: %d %s", response.Code, response.Body.String())
|
|
}
|
|
if response := write(); response.Code != http.StatusOK {
|
|
t.Fatalf("write was not restored after rollback: %d %s", response.Code, response.Body.String())
|
|
}
|
|
export()
|
|
if response := finish(transferID + "&cleanup=true"); response.Code != http.StatusOK || removedContainer != reinstallFixtureContainerID {
|
|
t.Fatalf("owned cleanup did not remove the original container: %d %s, removed %q", response.Code, response.Body.String(), removedContainer)
|
|
}
|
|
if response := finish(transferID + "&cleanup=true"); response.Code != http.StatusOK {
|
|
t.Fatalf("completed cleanup must be retryable: %d %s", response.Code, response.Body.String())
|
|
}
|
|
if err := os.MkdirAll(serverDir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if response := finish(transferID + "&cleanup=true"); response.Code != http.StatusConflict {
|
|
t.Fatalf("stale cleanup accepted replacement data: %d %s", response.Code, response.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestTransferImportDoesNotReplaceOrCleanUnownedDestination(t *testing.T) {
|
|
agent, _ := newTestAgent(t)
|
|
name := "fixture"
|
|
disk := registerTestDisk(t, agent, t.TempDir(), 0)
|
|
destination := filepath.Join(agent.diskLayoutVolumes(disk.MountPath), name)
|
|
if err := os.MkdirAll(destination, 0o750); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
sentinel := filepath.Join(destination, "existing.txt")
|
|
if err := os.WriteFile(sentinel, []byte("original"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
url := "/v1/servers/fixture/import-tar?transferId=1234567890abcdef1234567890abcdef"
|
|
importReply := httptest.NewRecorder()
|
|
agent.handleImportTar(importReply, httptest.NewRequest(http.MethodPut, url, bytes.NewReader(buildTransferTar(t, name, nil))), name)
|
|
if importReply.Code != http.StatusConflict {
|
|
t.Fatalf("occupied import: got %d %s", importReply.Code, importReply.Body.String())
|
|
}
|
|
if err := agent.saveMeta(destination, map[string]any{transferImportOwnerKey: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
cleanupReply := httptest.NewRecorder()
|
|
agent.handleDeleteTransferImport(cleanupReply, httptest.NewRequest(http.MethodDelete, url, nil), name)
|
|
if cleanupReply.Code != http.StatusNotFound {
|
|
t.Fatalf("unowned cleanup: got %d %s", cleanupReply.Code, cleanupReply.Body.String())
|
|
}
|
|
if data, err := os.ReadFile(sentinel); err != nil || string(data) != "original" {
|
|
t.Fatalf("unowned destination changed: %q, %v", data, err)
|
|
}
|
|
}
|
|
|
|
func TestTransferImportRefusesBusyServerWithoutQueueing(t *testing.T) {
|
|
agent, _ := newTestAgent(t)
|
|
opLock := agent.getServerOpLock("fixture")
|
|
opLock.Lock()
|
|
defer opLock.Unlock()
|
|
url := "/v1/servers/fixture/import-tar?transferId=1234567890abcdef1234567890abcdef"
|
|
reply := httptest.NewRecorder()
|
|
agent.handleImportTar(reply, httptest.NewRequest(http.MethodPut, url, nil), "fixture")
|
|
if reply.Code != http.StatusConflict {
|
|
t.Fatalf("busy protected import: got %d %s", reply.Code, reply.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestTransferImportConfirmsAndCleansOwnedCopy(t *testing.T) {
|
|
agent := newReinstallRaceTestAgent(t)
|
|
const name = "fixture"
|
|
const transferID = "1234567890abcdef1234567890abcdef"
|
|
url := "/v1/servers/fixture/import-tar?transferId=" + transferID
|
|
archive := buildTransferTar(t, name, map[string]any{"type": "custom", transferImportOwnerKey: "old-import"})
|
|
reply := httptest.NewRecorder()
|
|
agent.handleImportTar(reply, httptest.NewRequest(http.MethodPut, url, bytes.NewReader(archive)), name)
|
|
var receipt map[string]any
|
|
if err := json.Unmarshal(reply.Body.Bytes(), &receipt); err != nil || reply.Code != http.StatusOK || receipt["transferId"] != transferID {
|
|
t.Fatalf("protected import: got %d %s (%v)", reply.Code, reply.Body.String(), err)
|
|
}
|
|
serverDir := agent.serverDir(name)
|
|
if err := agent.requireTransferImportOwner(name, transferID); err != nil {
|
|
t.Fatalf("import ownership not recorded: %v", err)
|
|
}
|
|
if contents, err := os.ReadFile(filepath.Join(serverDir, "server.properties")); err != nil || string(contents) != "level-name=world\n" {
|
|
t.Fatalf("imported payload: %q, %v", contents, err)
|
|
}
|
|
reply = httptest.NewRecorder()
|
|
agent.handleDeleteTransferImport(reply, httptest.NewRequest(http.MethodDelete, url, nil), name)
|
|
if reply.Code != http.StatusOK {
|
|
t.Fatalf("owned cleanup: got %d %s", reply.Code, reply.Body.String())
|
|
}
|
|
for _, path := range []string{serverDir, agent.serverBackupsDir(name), agent.metaPath(name)} {
|
|
if _, err := os.Lstat(path); !os.IsNotExist(err) {
|
|
t.Fatalf("owned cleanup left %s: %v", path, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestImportTarReimportClearsStaleSecondaryRouting guards a re-transfer: a server
|
|
// previously routed to a secondary disk that is then re-imported onto the primary
|
|
// disk must not retain the old secondary __diskId.
|
|
func TestImportTarReimportClearsStaleSecondaryRouting(t *testing.T) {
|
|
a, vol := newTestAgent(t)
|
|
mount := t.TempDir()
|
|
dest := registerTestDisk(t, a, mount, 50)
|
|
name := "delta"
|
|
|
|
// First import onto the secondary disk.
|
|
first := buildTransferTar(t, name, map[string]any{"type": "custom", "__diskId": "disk-source"})
|
|
if rr, _ := doImportTar(t, a, name, dest.ID, first); rr.Code != 200 {
|
|
t.Fatalf("first import failed: %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
if got := a.diskForServer(name); got.ID != dest.ID {
|
|
t.Fatalf("after first import expected secondary disk, got %q", got.ID)
|
|
}
|
|
|
|
// Re-import onto the primary disk; routing/meta must follow the new target.
|
|
second := buildTransferTar(t, name, map[string]any{"type": "custom", "__diskId": dest.ID})
|
|
if rr, _ := doImportTar(t, a, name, "", second); rr.Code != 200 {
|
|
t.Fatalf("second import failed: %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
|
|
wantServerDir := filepath.Join(vol, name)
|
|
a.invalidateServerDiskCache(name)
|
|
if got := a.serverDir(name); got != wantServerDir {
|
|
t.Fatalf("serverDir after re-import to primary: got %q want %q", got, wantServerDir)
|
|
}
|
|
persisted := a.loadMeta(wantServerDir)
|
|
if _, present := persisted["__diskId"]; present {
|
|
t.Fatalf("__diskId must be cleared on re-import to primary, got %v", persisted["__diskId"])
|
|
}
|
|
// The secondary-disk copy must no longer be the routing target.
|
|
if got := a.diskForServer(name); !(got.Primary || got.ID == primaryDiskID) {
|
|
t.Fatalf("re-import did not re-route to primary, got %q", got.ID)
|
|
}
|
|
}
|