Files
Kelx/transfer_import_multidisk_test.go
T
2026-06-10 17:04:11 +00:00

234 lines
8.7 KiB
Go

package main
import (
"archive/tar"
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"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)
}
}
// 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)
}
}