"use strict"; const { nodeConnectionState } = require("./node-http"); const { resolveServerCreateBindAddress, renderServerCreateOutcome, scanNodeStorageCollisions } = require("./server-create"); const { serverEntryAssignedHostPorts } = require("../utils/server-host-ports"); function computeTransferEffectiveResources(serverResources, sourceNode, destNode) { const inRes = (serverResources && typeof serverResources === "object") ? serverResources : {}; const out = { ...inRes }; const srcRam = Number(sourceNode?.ram_mb || 0); const dstRam = Number(destNode?.ram_mb || 0); const srcDisk = Number(sourceNode?.disk_gb || 0); const dstDisk = Number(destNode?.disk_gb || 0); const srcCores = Number(sourceNode?.buildConfig?.cpu_cores || sourceNode?.buildConfig?.cpuCores || 0); const dstCores = Number(destNode?.buildConfig?.cpu_cores || destNode?.buildConfig?.cpuCores || 0); const coerceInt = (value) => { const number = Number(value); return Number.isFinite(number) ? Math.trunc(number) : null; }; const coerceFloat = (value) => { const number = Number(value); return Number.isFinite(number) ? number : null; }; const isUnlimitedOrNodeMaxInt = (value, srcMax) => { if (value == null) return true; const number = coerceInt(value); if (number == null || number <= 0) return true; return srcMax > 0 && number === Math.trunc(srcMax); }; const isUnlimitedOrNodeMaxFloat = (value, srcMax) => { if (value == null) return true; const number = coerceFloat(value); if (number == null || number <= 0) return true; return srcMax > 0 && Math.abs(number - srcMax) < 0.0001; }; if (dstRam > 0) { const current = coerceInt(inRes.ramMb); if (isUnlimitedOrNodeMaxInt(inRes.ramMb, srcRam)) out.ramMb = Math.trunc(dstRam); else if (current != null && current > Math.trunc(dstRam)) out.ramMb = Math.trunc(dstRam); } const storageField = inRes.storageMb != null ? "storageMb" : "storageGb"; const storageSrcMax = storageField === "storageMb" ? srcDisk * 1024 : srcDisk; const storageDstMax = storageField === "storageMb" ? dstDisk * 1024 : dstDisk; if (storageDstMax > 0) { const current = coerceInt(inRes[storageField]); if (isUnlimitedOrNodeMaxInt(inRes[storageField], storageSrcMax)) out[storageField] = Math.trunc(storageDstMax); else if (current != null && current > Math.trunc(storageDstMax)) out[storageField] = Math.trunc(storageDstMax); } if (dstCores > 0) { const current = coerceFloat(inRes.cpuCores); if (isUnlimitedOrNodeMaxFloat(inRes.cpuCores, srcCores)) out.cpuCores = dstCores; else if (current != null && current > dstCores) out.cpuCores = dstCores; } return out; } async function checkTransferDestinationPorts({ checkDestinationNodePort, loadServersIndexIncludingDeleting }, node, entry) { const ports = serverEntryAssignedHostPorts({ ...entry, runtime: null }); const assignedEntries = ports.length ? await loadServersIndexIncludingDeleting(node) : []; const allocations = []; const deadline = Date.now() + 20_000; const runtime = entry.runtime || entry.docker || null; const minecraft = String(entry.type || entry.template || "").toLowerCase() === "minecraft"; const defaultProtocols = minecraft || [runtime?.providerId, runtime?.id].includes("minecraft") ? ["tcp", "udp"] : ["tcp"]; for (const port of ports) { const outcome = await checkDestinationNodePort(node, port, { excludeName: entry.name, docker: runtime, assignedEntries, checkLive: true, deadline, containerPort: minecraft && port === Number(entry.port) ? 25565 : port, defaultProtocols, }); if (!outcome.ok) return outcome; const binding = resolveServerCreateBindAddress(node, port); if (binding.error) { const { status, body } = renderServerCreateOutcome(binding.error, "panel"); return { ok: false, statusCode: status, error: body.error }; } allocations.push({ port, ip: binding.address }); } return { ok: true, allocations }; } async function checkTransferAdmission(deps, sourceNode, destNode, entry) { // adpanel:transfer-storage-ownership - both the source cleanup and destination import must have an unambiguous storage owner. for (const [node, excludeName] of [[sourceNode, entry.name], [destNode, ""]]) { const conflict = await scanNodeStorageCollisions(deps, node, entry.name, { uuidFallbackId: true, excludeName }); if (conflict) { return { ok: false, statusCode: 409, error: `Transfer refused: server storage on ${node === sourceNode ? "the source" : "the destination"} is also claimed by "${conflict.data.collidingName}".` }; } } return checkTransferDestinationPorts(deps, destNode, entry); } async function finishTransferSource(deps, node, name, transferId, { cleanup = false } = {}) { if (typeof transferId !== "string" || !/^[a-f0-9]{32}$/.test(transferId)) throw new Error("Missing transfer identity"); const baseUrl = deps.buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, deps.nodeUnderCloudflare(node)); if (!baseUrl) throw new Error("invalid source node address"); const params = new URLSearchParams({ transferId, ...(cleanup ? { cleanup: "true" } : {}) }); const response = await deps.httpRequestJson( `${baseUrl}/v1/servers/${encodeURIComponent(name)}/export?${params}`, "DELETE", deps.nodeAuthHeadersFor(node, true), null, 30_000 ); if (!cleanup && response.status === 404) return; if (response.status !== 200 || response.json?.ok !== true || response.json.transferId !== transferId) { throw new Error(response.json?.error || `source transfer could not be settled (${response.status})`); } } async function finalizeTransferDestination(deps, { sourceNode, destNode, serverEntry, sourceMeta, defaultBackupsMax }) { // adpanel:transfer-port-claim - pool removal and competing claims must wait until the destination assignment is durable. return deps.withKeyedLock(`node-ports:${destNode.id}`, async () => { const current = await deps.findNodeByIdOrName(destNode.id); if (!current || current.id !== destNode.id) throw new Error("destination node no longer exists"); if (nodeConnectionState(current) !== nodeConnectionState(destNode)) { throw new Error("destination node connection changed while transferring"); } const resources = computeTransferEffectiveResources(serverEntry.resources, sourceNode, current); if (resources.backupsMax == null) resources.backupsMax = defaultBackupsMax; const primaryPort = deps.validatePort(serverEntry.port) || deps.validatePort(sourceMeta?.hostPort); const portless = sourceMeta?.runtime != null && ["python", "nodejs", "discord-bot", "runtime"].includes(String(sourceMeta.type).toLowerCase()) && (sourceMeta.hostPort == null || sourceMeta.hostPort === 0 || sourceMeta.hostPort === "0"); if (!primaryPort && !portless) throw new Error("cannot verify the source server's main port"); const additionalPorts = Array.isArray(resources.ports) ? resources.ports : sourceMeta?.resources?.ports; if (!sourceMeta && !Array.isArray(additionalPorts)) throw new Error("cannot verify the source server's additional ports"); resources.ports = Array.isArray(additionalPorts) ? additionalPorts.map(deps.validatePort) : []; if (resources.ports.includes(null)) throw new Error("the source server has an invalid additional port"); const outcome = await checkTransferDestinationPorts(deps, current, { ...serverEntry, type: sourceMeta?.type, runtime: sourceMeta?.runtime || serverEntry.runtime, port: primaryPort, resources, }); if (!outcome.ok) throw new Error(outcome.error); const primaryAddress = outcome.allocations.find(({ port }) => port === primaryPort)?.ip || current.address; resources.portAllocations = outcome.allocations; const baseUrl = deps.buildNodeBaseUrl(current.address, current.api_port || 8080, current.ssl_enabled, deps.nodeUnderCloudflare(current)); if (!baseUrl) throw new Error("invalid destination node address"); const patch = await deps.httpRequestJson( `${baseUrl}/v1/servers/${encodeURIComponent(serverEntry.name)}/resources`, "PATCH", deps.nodeAuthHeadersFor(current, true), { resources, ...(primaryPort ? { mainPort: primaryPort, bind_ip: primaryAddress, ip: primaryAddress } : {}), }, 30_000 ); if (patch.status !== 200 || !patch.json?.ok) { throw new Error(patch.json?.error || patch.json?.detail || `failed to apply resources (${patch.status})`); } await deps.startServerOnNode(current, serverEntry.name, primaryPort); const status = "online"; const saved = await deps.db.query( "UPDATE servers SET node_id = ?, ip = ?, port = ?, resources = ?, status = ? WHERE id = ? AND name = ? AND node_id = ? AND status = 'transferring' AND suspended = 0", [current.id, primaryAddress || null, primaryPort || null, JSON.stringify(resources), status, serverEntry.rowId, serverEntry.name, serverEntry.nodeId] ); if (saved?.affectedRows !== 1) throw new Error("transfer assignment is no longer pending"); return { node: current, status }; }); } module.exports = { checkTransferAdmission, finalizeTransferDestination, finishTransferSource };