"use strict"; // F5: cross-operation state guards for the three long-running, mutually // exclusive server operations — transfer, delete and reinstall (admin // template change + user reinstall). // // Before this module the operations did not check each other's in-flight // state: a delete or a template change could run while a transfer was live // (the transfer only flagged servers.status = 'transferring' and nothing // revalidated it), and a transfer could start while a reinstall was wiping // the server directory on the node. Every overlap produced a partial state — // a reinstall starting on the source node mid-export, or the index row being // deleted while the transfer job was still writing to the destination node. // // The servers.status column is the durable interlock (same rule the transfer // flow already documents: Redis job records alone cannot be trusted across // restarts). Each guarded operation "claims" the row with a conditional // UPDATE that can only land while no OTHER guarded marker owns it, so at // most one of the three operations can hold a server at any time — across // workers, because the database arbitrates, and without a check-then-write // race, because the check IS the write: // // transferring — claimed/released by the transfer flow (utils/transfer-recovery.js // owns crash recovery for this marker), // deleting — claimed by the delete flow; terminal (the row is removed), // reinstalling — claimed by panel-initiated reinstalls; released by CAS // restore of the previous status. // // Guarded markers must never be clobbered by unrelated status writers (node // status polls, suspension, EULA autostart): those writers either condition // on the marker or — for suspension — deliberately keep it. A panel crash // mid-reinstall would otherwise wedge the row: like transfer recovery, a // short-TTL Redis heartbeat (plus an in-process set for single-process // deployments) marks a live owner, and a periodic sweeper restores orphaned // 'reinstalling' flags to 'stopped' once the owner is provably gone. // // This module is policy-only: DB access, Redis and entry lookups are // injected via deps (same pattern as utils/server-delete.js and // utils/transfer-recovery.js) so the panel keeps a single source of truth // and the behaviour is unit-testable. const { createHash } = require("node:crypto"); const path = require("node:path"); const { createCrossProcessOperationMutex } = require("./cross-process-mutex"); const { isServerSuspended, suspendedServerBody } = require("../services/node-fs-relay"); const GUARDED_STATUSES = ["transferring", "deleting", "reinstalling"]; // Statuses that may be put back into servers.status when a marker is // released. Anything else (null, unknown, another flow's flag) falls back to // "stopped" — the only status the panel can assert for a container whose // real power state is unknown. Mirrors RESTORABLE_STATUSES in // utils/transfer-recovery.js. const RESTORABLE_STATUSES = new Set(["online", "running", "stopped", "installing"]); const DEFAULT_OWNER_TTL_SEC = 45; const DEFAULT_OWNER_RENEW_MS = 15_000; const DEFAULT_SWEEP_INTERVAL_MS = 60_000; // User-facing reasons keyed by the marker that owns the row. const BLOCKED_REASON = { transferring: "server is being transferred to another node (or a crashed transfer is awaiting recovery); try again once it settles", deleting: "server is being deleted", reinstalling: "server is being reinstalled", }; function normalizeServerName(name) { return String(name || "").trim(); } function normalizeStatus(value) { const raw = value === undefined || value === null ? "" : String(value).trim().toLowerCase(); return raw || null; } // adpanel:server-settings-target - a stale editor or confirmation cannot follow a name onto a replacement row. function requireServerSettingsTarget(req, res, entry) { const expected = req.body?.expectedTargetId; if (Number.isSafeInteger(expected) && expected > 0 && expected === entry?.rowId) return true; res.status(409).json({ error: "Server changed. Reload its settings and try again.", code: "server-target-changed" }); return false; } // adpanel:reinstall-suspension - lifecycle operations that can start a container and suspension share the canonical lock. async function withReinstallSuspensionLock(name, busyResult, operation) { const key = createHash("sha256").update(normalizeServerName(name).toLowerCase()).digest("hex"); const release = createCrossProcessOperationMutex({ label: "[reinstall-suspension]", lockFilePath: path.join(__dirname, "..", `.reinstall-suspension-${key}.lock`), respectLiveOwner: true, }).tryAcquire(); if (!release) return busyResult; try { return await operation(); } finally { release(); } } async function withSuspensionAgainstReinstall({ findServer }, requested, operation, expectedRow = null) { const target = expectedRow || await findServer(requested); if (!target?.name) return { ok: false, statusCode: 404, error: "server not found" }; const busy = { ok: false, statusCode: 409, error: "Another operation is in progress for this server. Try again after it finishes." }; return withReinstallSuspensionLock(target.name, busy, async () => { const entry = await findServer(target.name); if (!entry || entry.name !== target.name || entry.rowId !== target.rowId || entry.nodeId !== target.nodeId) { return { ok: false, statusCode: 409, error: "server state changed; reload servers and try again" }; } const status = normalizeStatus(entry.status); if (isGuardedServerStatus(status)) return { ...busy, error: BLOCKED_REASON[status] }; return operation(entry); }); } // Single predicate for "does this servers.status value hold a guarded marker?" // Unrelated status writers (node status polls, console-room watchers, socket // run/stop, suspension) check this before touching the status column, so a // marker owned by a live transfer/delete/reinstall is never clobbered back to // a power-state label. The SQL writers additionally enforce the same rule // atomically (status = IF(LOWER(status) IN (...), status, VALUES(status)) in // the index upserts), closing the read-then-write window this predicate has. function isGuardedServerStatus(value) { const normalized = normalizeStatus(value); return normalized != null && GUARDED_STATUSES.includes(normalized); } // adpanel:agent-transfer-fence - the transfer claim updates this same row before copying any files. async function withServerFileDispatch(pool, target, operation) { const connection = await pool.getConnection(); let usable = true; try { await connection.query({ sql: "START TRANSACTION", timeout: 2000 }); const [[row]] = await connection.execute({ sql: `SELECT id, legacy_id, name, node_id, status, suspended FROM servers WHERE name = ? LIMIT 1 FOR UPDATE`, timeout: 2000 }, [target.serverName]); if (!row || row.name !== target.serverName || String(row.legacy_id || row.id) !== String(target.serverId) || String(row.node_id) !== target.nodeId || Number(row.suspended) || isGuardedServerStatus(row.status)) return null; return await operation(); } catch (err) { if (err.code !== "PROTOCOL_SEQUENCE_TIMEOUT") throw err; usable = false; connection.destroy(); return null; } finally { if (usable) { try { await connection.query({ sql: "ROLLBACK", timeout: 2000 }); connection.release(); } catch { connection.destroy(); } } } } // adpanel:reinstall-power-admission - the panel claim outlives the Docker // operation, until the rebuilt server's port and template are published. function getReinstallPowerConflict(server) { if (normalizeStatus(server?.status) !== "reinstalling") return null; return { status: 409, body: { ok: false, code: "reinstall_in_progress", error: BLOCKED_REASON.reinstalling, detail: "Wait for reinstall to complete before retrying the power action.", } }; } // adpanel:suspension-power-dispatch - a start admitted before the force-stop must not reach the node after suspension commits. async function withServerPowerStart({ findServer }, expected, dispatch) { const conflict = { status: 409, body: { ok: false, code: "server_operation_in_progress", error: "server_operation_in_progress", detail: "Another operation is in progress for this server. Try again after it finishes.", } }; return withReinstallSuspensionLock(expected.name, { conflict }, async () => { const server = await findServer(expected.name); if (!server || server.name !== expected.name || server.nodeId !== expected.nodeId || String(server.rowId ?? server.id) !== String(expected.rowId ?? expected.id)) { return { conflict: { status: 409, body: { ok: false, error: "Server state changed. Retry the power action." } } }; } if (isServerSuspended(server)) return { conflict: { status: 423, body: suspendedServerBody(server) } }; const reinstall = getReinstallPowerConflict(server); if (reinstall) return { conflict: reinstall }; const status = normalizeStatus(server.status); if (isGuardedServerStatus(status)) return { conflict: { ...conflict, body: { ...conflict.body, detail: BLOCKED_REASON[status] } } }; return { result: await dispatch(server) }; }); } // The statuses a claim of `marker` must refuse. A marker never blocks itself // (re-claiming your own marker stays idempotent — e.g. a retried delete). function forbiddenFor(marker) { const normalized = normalizeStatus(marker); return GUARDED_STATUSES.filter((status) => status !== normalized); } function reinstallOwnerAliveKey(name) { return `reinstallOwnerAlive:${normalizeServerName(name)}`; } function placeholders(values) { return values.map(() => "?").join(", "); } async function readServerStatus(deps, name, identity = []) { const rows = await deps.db.query( `SELECT status FROM servers WHERE name = ?${identity.length ? " AND id = ? AND node_id <=> ?" : ""}`, [normalizeServerName(name), ...identity] ); const row = Array.isArray(rows) ? rows[0] : null; if (!row) return { missing: true, status: null }; return { missing: false, status: normalizeStatus(row.status) }; } // Atomically claim `marker` on the server row. Returns: // { ok: true, prevStatus, alreadyOwned? } — the caller owns the row now, // { ok: false, missing: true } — the row is gone, // { ok: false, blockedBy } — another guarded operation owns // the row (or the state changed // in a way we cannot classify — // fail closed and let the caller // retry). // // adpanel:reinstall-claim-cas - mysql2 enables FOUND_ROWS by default: a // matched no-op UPDATE is not ownership. Non-idempotent claims exclude // their own marker in SQL so only one concurrent request can win. async function claimServerOperationStatus(deps, { name, marker, expectedRow = null }) { const serverName = normalizeServerName(name); const normalizedMarker = normalizeStatus(marker); if (!serverName || !normalizedMarker) { return { ok: false, blockedBy: null, invalid: true }; } if (!GUARDED_STATUSES.includes(normalizedMarker)) { return { ok: false, blockedBy: null, invalid: true }; } const forbidden = forbiddenFor(normalizedMarker); const claimForbidden = normalizedMarker === "deleting" ? forbidden : GUARDED_STATUSES; const identity = expectedRow?.rowId == null ? [] : [expectedRow.rowId, expectedRow.nodeId ?? null]; const before = await readServerStatus(deps, serverName, identity); if (before.missing) return { ok: false, missing: true }; if (forbidden.includes(before.status)) { return { ok: false, blockedBy: before.status }; } const result = await deps.db.query( `UPDATE servers SET status = ? WHERE name = ? AND (status IS NULL OR LOWER(status) NOT IN (${placeholders(claimForbidden)}))${identity.length ? " AND id = ? AND node_id <=> ?" : ""}`, [normalizedMarker, serverName, ...claimForbidden, ...identity] ); if (Number(result?.affectedRows || 0) > 0) { return { ok: true, prevStatus: before.status, ...(before.status === normalizedMarker ? { alreadyOwned: true } : {}) }; } // Lost the race (or re-claimed our own marker). Classify from the row. const after = await readServerStatus(deps, serverName, identity); if (after.missing) return { ok: false, missing: true }; if (after.status === normalizedMarker) { // Re-claiming a marker that is already ours. Only 'deleting' tolerates // this: delete is idempotent (a retried delete of a half-deleted server // must keep going). A second transfer or reinstall arriving while the // first still owns the row must be refused, not allowed to pile on. if (normalizedMarker === "deleting") { return { ok: true, prevStatus: before.status, alreadyOwned: true }; } return { ok: false, blockedBy: after.status, alreadyOwned: true }; } if (forbidden.includes(after.status)) { return { ok: false, blockedBy: after.status }; } // Not a guarded marker and not ours: another writer moved the row between // our read and the UPDATE. Refuse — the caller re-reads and retries. return { ok: false, blockedBy: null }; } // Release a claimed marker, restoring `restoreStatus` (or the only status // the panel can assert when none is given). The restore is conditional on // the marker still being ours, so a writer that legitimately replaced the // status meanwhile (e.g. suspension force-stop) is never overwritten. A // server suspended while the marker was held always restores to "stopped" — // suspension guarantees the container is not running. async function releaseServerOperationStatus(deps, { name, marker, restoreStatus = null }) { const serverName = normalizeServerName(name); const normalizedMarker = normalizeStatus(marker); if (!serverName || !normalizedMarker) return { restored: false }; let next = normalizeStatus(restoreStatus); if (!next || !RESTORABLE_STATUSES.has(next)) next = "stopped"; if (typeof deps.findServer === "function") { let entry = null; try { entry = await deps.findServer(serverName); } catch { entry = null; } const suspended = !!(entry && (entry.suspended === true || entry.suspended === 1 || String(entry.suspended) === "1")); if (suspended) next = "stopped"; } try { const pending = normalizedMarker === "reinstalling" && typeof deps.recoverPendingReinstall === "function" ? " AND NOT EXISTS (SELECT 1 FROM server_reinstall_dispatch WHERE server_id = servers.id)" : ""; const result = await deps.db.query( `UPDATE servers SET status = ? WHERE name = ? AND LOWER(status) = ?${pending}`, [next, serverName, normalizedMarker] ); const restored = Number(result?.affectedRows || 0) > 0; if (restored && typeof deps.onStatusRestored === "function") { try { await deps.onStatusRestored({ name: serverName, status: next }); } catch { } } return { restored, status: next }; } catch (err) { (deps.log || console).warn(`[server-op-guard] ${serverName}: could not release '${normalizedMarker}' marker:`, err?.message || err); return { restored: false, status: next }; } } // --------------------------------------------------------------------------- // Reinstall liveness (crash-orphaned 'reinstalling' flags) // --------------------------------------------------------------------------- // // Mirrors the transfer ownership model: the process running a reinstall // renews a short-TTL Redis key, and additionally keeps the name in an // in-process set (sufficient for single-process deployments without Redis). // A missing heartbeat means the reinstall died with its panel process and // the sweeper may restore the flag; a Redis error is "unknown" and skips the // round — skipping recovery is always safe, clearing a live guard is not. function startReinstallOwnerHeartbeat(deps, name) { const key = normalizeServerName(name); if (!key) return; const timers = deps.ownerTimers; if (!timers || timers.has(key)) return; const redis = deps.redis ? deps.redis() : null; if (!redis) return; // single-process deployment; the in-process set covers liveness const ttlSec = Math.max(10, Number(deps.ownerTtlSec) || DEFAULT_OWNER_TTL_SEC); const renewMs = Math.max(2_000, Math.min(Number(deps.ownerRenewMs) || DEFAULT_OWNER_RENEW_MS, (ttlSec * 1000) / 2)); const renew = () => { try { redis.set(reinstallOwnerAliveKey(key), deps.bootId, { EX: ttlSec }).catch(() => { }); } catch { } }; renew(); const timer = setInterval(renew, renewMs); if (typeof timer.unref === "function") timer.unref(); timers.set(key, timer); } function stopReinstallOwnerHeartbeat(deps, name) { const key = normalizeServerName(name); if (!key) return; const timers = deps.ownerTimers; const timer = timers ? timers.get(key) : null; if (timer) { clearInterval(timer); timers.delete(key); } // Only this process's owner may remove the Redis liveness key: in a cluster // a stopped-but-live reinstall in another worker must keep its heartbeat. // The delete is conditional on the stored bootId, so a caller whose heartbeat // never owned the key (or whose key was taken over) cannot blind-delete it. const redis = deps.redis ? deps.redis() : null; if (redis) { (async () => { try { const current = await redis.get(reinstallOwnerAliveKey(key)); if (current === deps.bootId) { await redis.del(reinstallOwnerAliveKey(key)); } } catch { } })(); } } // True only when a reinstall in SOME worker is provably live: this process // (in-process set) or any worker renewing the Redis heartbeat. Redis errors // return true (unknown → hands off the row). async function hasLiveReinstallOwner(deps, name) { const key = normalizeServerName(name); if (!key) return true; if (typeof deps.isReinstallActive === "function" && deps.isReinstallActive(key)) return true; const redis = deps.redis ? deps.redis() : null; if (!redis) return false; try { const owner = await redis.get(reinstallOwnerAliveKey(key)); return owner != null; } catch { return true; } } // Restore 'reinstalling' rows whose owner is provably gone to 'stopped' — // the only status the panel can assert for a server whose reinstall died // with its process; the node status poller reconciles from there. // // Two gates protect a freshly claimed flag from being swept: // 1. the liveness check (in-process set + Redis heartbeat, registered by // the claim winner immediately after its DB claim), and // 2. a flag-age floor of two heartbeat TTLs: claims register liveness in // the same event-loop turn that follows the DB claim, but a sweeper // pass whose owner-check raced ahead of the claim could still land its // restore after it. Age-gating the selection makes that impossible — // a row younger than the floor is never a crash orphan, so it is not // even considered. The floor also keeps a row whose claimant died in // the microsecond between its DB claim and liveness registration from // being wedged forever (it sweeps on a later pass). async function sweepStaleReinstallingFlags(deps) { const log = deps.log || console; const minAgeSec = Math.max(60, (Number(deps.ownerTtlSec) || DEFAULT_OWNER_TTL_SEC) * 2); let rows; try { rows = await deps.db.query( "SELECT name FROM servers WHERE LOWER(status) = ? AND updated_at < DATE_SUB(NOW(), INTERVAL ? SECOND)", ["reinstalling", minAgeSec] ); } catch (err) { // adpanel:reinstall-recovery-cas - without claim age, an orphan snapshot // can release a newly acquired operation before its heartbeat is visible. log.warn("[server-op-guard] could not safely list aged reinstall claims:", err?.message || err); return { scanned: 0, restored: 0 }; } const names = (Array.isArray(rows) ? rows : []) .map((row) => normalizeServerName(row?.name)) .filter(Boolean); let restored = 0; for (const name of names) { try { if (await hasLiveReinstallOwner(deps, name)) continue; if (typeof deps.recoverPendingReinstall === "function" && await deps.recoverPendingReinstall(name)) continue; const pending = typeof deps.recoverPendingReinstall === "function" ? " AND NOT EXISTS (SELECT 1 FROM server_reinstall_dispatch WHERE server_id = servers.id)" : ""; const result = await deps.db.query( `UPDATE servers SET status = ? WHERE name = ? AND LOWER(status) = ? AND updated_at < DATE_SUB(NOW(), INTERVAL ? SECOND)${pending}`, ["stopped", name, "reinstalling", minAgeSec] ); if (Number(result?.affectedRows || 0) > 0) { restored += 1; log.warn(`[server-op-guard] ${name}: orphaned 'reinstalling' flag restored to 'stopped' (owner process is gone)`); if (typeof deps.onStatusRestored === "function") { try { await deps.onStatusRestored({ name, status: "stopped" }); } catch { } } } } catch (err) { log.error(`[server-op-guard] ${name}: 'reinstalling' recovery failed:`, err?.message || err); } } return { scanned: names.length, restored }; } // Boot hook: one immediate pass, then a periodic sweep. The interval never // keeps the event loop alive and ticks are skipped while a pass is running. function startReinstallFlagSweeper(deps) { const intervalMs = Math.max(15_000, Number(deps.sweepIntervalMs) || DEFAULT_SWEEP_INTERVAL_MS); let running = false; const run = async (trigger) => { if (running) return; running = true; try { await sweepStaleReinstallingFlags(deps); } catch { // individual per-server errors are already logged } finally { running = false; } }; const timer = setInterval(() => run("sweep"), intervalMs); if (typeof timer.unref === "function") timer.unref(); run("startup").catch(() => { }); return () => clearInterval(timer); } module.exports = { withServerFileDispatch, getReinstallPowerConflict, withServerPowerStart, GUARDED_STATUSES, BLOCKED_REASON, isGuardedServerStatus, requireServerSettingsTarget, reinstallOwnerAliveKey, withReinstallSuspensionLock, withSuspensionAgainstReinstall, claimServerOperationStatus, releaseServerOperationStatus, startReinstallOwnerHeartbeat, stopReinstallOwnerHeartbeat, hasLiveReinstallOwner, sweepStaleReinstallingFlags, startReinstallFlagSweeper, };