Files
Kelx/utils/transfer-recovery.js
T
2026-11-30 16:32:37 +00:00

578 lines
23 KiB
JavaScript

"use strict";
// F6 crash-safety for server transfers.
//
// A transfer flags servers.status = 'transferring' in the DB, runs from an
// in-process async job, and only clears the flag once the move settles. If
// the panel process dies mid-transfer (crash, SIGKILL, power loss), nothing
// cleared the flag: the server stayed "transferring" indefinitely, new
// transfers were refused via the already-running check, and the server page
// was stuck on the transfer splash. This module is the recovery path.
//
// Ownership model: the process running a transfer renews a short-TTL Redis
// key (the "heartbeat"). Any panel worker — cluster deployments share Redis
// and the DB — can therefore distinguish a live transfer from one orphaned by
// a dead process. A missing heartbeat means the transfer is dead and the flag
// plus any partial node state can be rolled back; a Redis outage is treated
// as "unknown" and skips the round, because skipping recovery is always safe
// while rolling back a live transfer is not.
//
// This module is policy-only: DB access, Redis, node HTTP operations and job
// bookkeeping are injected via deps (same pattern as utils/server-delete.js)
// so the panel keeps a single source of truth and the behaviour is unit
// testable.
const DEFAULT_OWNER_TTL_SEC = 45;
const DEFAULT_OWNER_RENEW_MS = 15_000;
const DEFAULT_SWEEP_INTERVAL_MS = 60_000;
const DEFAULT_CLAIM_TTL_SEC = 300;
// Status values that can be put back into servers.status after an aborted
// transfer. Anything else (null, unknown, another flow's flag such as
// "deleting") falls back to "stopped" — the only status the panel can assert
// for a container it just made sure is not running. Mirrors the restore rule
// in the suspension flow.
const RESTORABLE_STATUSES = new Set(["online", "running", "stopped", "installing"]);
function transferOwnerAliveKey(name) {
return `transferOwnerAlive:${String(name || "").trim()}`;
}
function transferRecoveryClaimKey(name) {
return `transferRecoveryClaim:${String(name || "").trim()}`;
}
function normalizeServerName(name) {
return String(name || "").trim();
}
function isSuspendedEntry(entry) {
return !!(entry && (entry.suspended === true || entry.suspended === 1 || String(entry.suspended) === "1"));
}
// deleteServerOnNode throws for any non-200, but a 404/410 during cleanup
// means the partial copy is already gone — that is success for recovery.
function isAlreadyGoneError(err) {
const raw = String(err?.message || err || "");
return /\b404\b|\b410\b/i.test(raw) || /not found|not exist|no such/i.test(raw);
}
// ---------------------------------------------------------------------------
// Ownership heartbeat
// ---------------------------------------------------------------------------
function startTransferOwnerHeartbeat(deps, name) {
const key = normalizeServerName(name);
if (!key) return;
const timers = deps.ownerTimers;
if (!timers || timers.has(key)) return;
const redis = deps.redis();
if (!redis) return; // no Redis = single-process deployment; recovery falls back to the in-memory job map
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(transferOwnerAliveKey(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 stopTransferOwnerHeartbeat(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 live transfer in another worker must keep its heartbeat. The delete is
// conditional on the stored bootId, so a caller whose heartbeat never owned
// the key cannot blind-delete it.
const redis = deps.redis();
if (redis) {
(async () => {
try {
const current = await redis.get(transferOwnerAliveKey(key));
if (current === deps.bootId) {
await redis.del(transferOwnerAliveKey(key));
}
} catch { }
})();
}
}
// True only when a live transfer in SOME worker is provably renewing
// ownership. An unfinished in-memory job always means this process owns it.
// Redis errors return true (unknown): skipping a recovery round is always
// safe, rolling back a live transfer is not. Without Redis the deployment is
// single-process, so a live transfer can only ever be local.
async function hasLiveTransferOwner(deps, name) {
const key = normalizeServerName(name);
if (!key) return true;
const localJob = typeof deps.getMemoryJob === "function" ? deps.getMemoryJob(key) : null;
if (localJob && !localJob.finishedAt) return true;
const redis = deps.redis();
if (!redis) return false;
try {
const owner = await redis.get(transferOwnerAliveKey(key));
return owner != null;
} catch {
return true;
}
}
// ---------------------------------------------------------------------------
// Rollback
// ---------------------------------------------------------------------------
function transferRollbackStatus(prevStatus, entry) {
if (isSuspendedEntry(entry)) return "stopped";
const candidate = String(prevStatus || "").trim().toLowerCase();
if (candidate && RESTORABLE_STATUSES.has(candidate)) return candidate;
return "stopped";
}
// Shared rollback for a transfer that will not complete on the destination
// node: the live job's error path and post-crash recovery both end here.
//
// Ordering matters: node-side cleanup runs FIRST, while this flow still owns
// the 'transferring' flag — the flag is the durable interlock that refuses
// new transfers, so a destination delete can never race a fresh import. The
// status restore is the final step; every node call is best-effort so an
// unreachable node cannot wedge the flag again (the sweeper re-runs this
// rollback idempotently until the restore lands). With
// expectTransferringFlag set, ownership is verified with a conditional
// UPDATE — a lost race means another flow owns the status column now.
async function rollbackAbortedTransfer(deps, {
name,
entry = null,
sourceNode = null,
destNode = null,
transferId = null,
prevStatus = null,
expectTransferringFlag = true,
} = {}) {
const log = deps.log || console;
const serverName = normalizeServerName(entry?.name || name);
if (!serverName) return { restored: false, status: null, destCleanupDone: true };
const restoreStatus = transferRollbackStatus(prevStatus, entry);
// adpanel:transfer-rollback-owner - a replaced or moved row does not authorize a stale job to touch either node.
const rowId = entry?.rowId;
if (expectTransferringFlag && rowId != null) {
try {
const current = await deps.findServer(serverName);
if (current?.rowId !== rowId || current.nodeId !== entry.nodeId ||
normalizeServerName(current.status).toLowerCase() !== "transferring") {
return { restored: false, status: restoreStatus, destCleanupDone: false };
}
} catch (err) {
log.warn(`[transfer-recovery] ${serverName}: could not verify rollback ownership:`, err?.message || err);
return { restored: false, status: restoreStatus, destCleanupDone: false };
}
}
// End the container in a state that matches the restored status. For
// "installing" leave power state alone — the install poller owns it.
let sourceReleased = true;
if (sourceNode && transferId) {
try {
await deps.finishTransferSource(sourceNode, serverName, transferId);
} catch (error) {
sourceReleased = false;
log.warn(`[transfer-recovery] ${serverName}: source transfer hold could not be released:`, error?.message || error);
}
}
if (sourceNode && sourceReleased && !isSuspendedEntry(entry)) {
if (restoreStatus === "online" || restoreStatus === "running") {
try {
await deps.startServerOnNode(sourceNode, serverName, entry?.port != null ? entry.port : undefined);
} catch (err) {
log.warn(`[transfer-recovery] ${serverName}: could not restart server on its source node:`, err?.message || err);
}
} else if (restoreStatus !== "installing") {
// Best-effort stop so a container cannot outlive the restored "stopped"
// status (e.g. the crash landed mid "stopping" phase).
try {
await deps.stopServerOnNode(sourceNode, serverName);
} catch { }
}
}
// Remove the partially-imported copy from the destination node. Skipped
// when the crashed job never recorded where it was going.
let destCleanupDone = true;
if (destNode && transferId) {
try {
await deps.deleteServerOnNode(destNode, serverName, { transferId });
} catch (err) {
if (isAlreadyGoneError(err)) {
log.info?.(`[transfer-recovery] ${serverName}: destination copy already gone`);
} else {
destCleanupDone = false;
log.warn(`[transfer-recovery] ${serverName}: could not remove partial copy from destination node:`, err?.message || err);
}
}
}
let restored = false;
if (!sourceReleased) return { restored, status: restoreStatus, destCleanupDone };
try {
if (expectTransferringFlag) {
const identity = rowId == null ? [] : [rowId, entry.nodeId];
const result = await deps.db.query(
`UPDATE servers SET status = ? WHERE name = ? AND status = ?${identity.length ? " AND id = ? AND node_id <=> ?" : ""}`,
[restoreStatus, serverName, "transferring", ...identity]
);
restored = Number(result?.affectedRows || 0) === 1;
} else {
await deps.db.query("UPDATE servers SET status = ? WHERE name = ?", [restoreStatus, serverName]);
restored = true;
}
} catch (err) {
log.error(`[transfer-recovery] ${serverName}: could not restore server status:`, err?.message || err);
return { restored: false, status: restoreStatus, destCleanupDone };
}
if (!restored) {
return { restored: false, status: restoreStatus, destCleanupDone };
}
try {
if (typeof deps.onStatusRestored === "function") {
await deps.onStatusRestored({ name: serverName, status: restoreStatus, nodeId: entry?.nodeId || null });
}
} catch { }
log.warn(`[transfer-recovery] ${serverName}: aborted transfer rolled back; status restored to '${restoreStatus}'`);
return { restored: true, status: restoreStatus, destCleanupDone };
}
// ---------------------------------------------------------------------------
// Recovery sweeps
// ---------------------------------------------------------------------------
async function acquireRecoveryClaim(deps, name) {
const redis = deps.redis();
if (!redis) return true; // single-process: nothing to race against
try {
const result = await redis.set(
transferRecoveryClaimKey(name),
deps.bootId,
{ NX: true, EX: Math.max(30, Number(deps.claimTtlSec) || DEFAULT_CLAIM_TTL_SEC) }
);
return result === "OK" || (result && result.ok === "OK");
} catch {
return false; // unknown state — skip this round, the sweeper retries
}
}
async function releaseRecoveryClaim(deps, name) {
const redis = deps.redis();
if (!redis) return;
try { await redis.del(transferRecoveryClaimKey(name)); } catch { }
}
// One DB row still flagged 'transferring' with no live owner is a transfer
// that died with a previous panel process. Roll it back to the source node.
async function recoverStaleServerFlag(deps, name, trigger) {
const log = deps.log || console;
if (await hasLiveTransferOwner(deps, name)) {
return { skipped: "live-owner" };
}
if (!(await acquireRecoveryClaim(deps, name))) {
return { skipped: "claim" };
}
try {
// Re-check under the claim: a transfer may have started between the first
// check and the claim (heartbeat lands before the flag write, so a live
// transfer is never rolled back).
if (await hasLiveTransferOwner(deps, name)) {
return { skipped: "live-owner" };
}
const entry = await deps.findServer(name);
if (!entry) {
// Row vanished mid-sweep (server deleted); drop stale job bookkeeping.
deps.clearJobArtifacts(name);
return { skipped: "server-gone" };
}
const job = await deps.getJobRecord(name);
if (String(entry.status || "").trim().toLowerCase() !== "transferring") {
// The flag is gone (an earlier recovery pass restored it, or a live
// flow finished). If the pass died between the status restore and the
// job cleanup, a dead owner's unfinished job record would still gate
// new transfers via the already-running check — drop it.
if (job && !job.finishedAt && !(await hasLiveTransferOwner(deps, name))) {
deps.clearJobArtifacts(name);
}
return { skipped: "flag-gone" };
}
const sourceNode = await deps.findNodeByIdOrName(entry.nodeId);
if (!sourceNode) {
log.warn(`[transfer-recovery] ${entry.name}: source node for stale transfer not found; restoring status only`);
}
// adpanel:transfer-cleanup-owner - old job records cannot authorize a destructive guess.
let destNode = null;
const destId = normalizeServerName(job?.destNodeId);
const sourceId = normalizeServerName(entry.nodeId);
if (job?.transferId && destId && (!sourceId || destId.toLowerCase() !== sourceId.toLowerCase())) {
destNode = await deps.findNodeByIdOrName(destId) || null;
}
const outcome = await deps.rollbackAbortedTransfer({
entry,
sourceNode,
destNode,
transferId: job?.transferId,
prevStatus: job?.prevStatus,
expectTransferringFlag: true,
});
if (!outcome.restored) {
// Lost the flag or the DB failed; the sweeper retries on a later pass.
return { skipped: "not-restored" };
}
if (outcome.destCleanupDone) {
deps.clearJobArtifacts(name);
} else if (destNode) {
// Keep the record so a later sweep retries the destination cleanup; the
// job TTL bounds how long retries continue.
deps.setJobPatch(name, {
...job,
status: "error",
percent: 0,
message: "Transfer interrupted by panel restart; rolled back to source node, destination cleanup pending",
error: "transfer interrupted by panel restart; rolled back to source node",
finishedAt: Date.now(),
destCleanupNodeId: destId,
});
}
return { recovered: true, status: outcome.status };
} finally {
// Released on completion so a NEW crash recovers immediately; if the
// rollback itself dies, the TTL keeps the dedup guarantee alive.
await releaseRecoveryClaim(deps, name);
}
}
// A flag younger than two heartbeat TTLs cannot be a crash orphan: its owner
// (if any) either registered liveness in the event-loop turn right after the
// claim, or died within that same instant and is recovered on a later pass.
// Age-gating the selection keeps a sweeper pass whose owner-check raced ahead
// of a just-landed claim from rolling back a live transfer.
function flagMinAgeSeconds(deps) {
return Math.max(60, (Number(deps.ownerTtlSec) || DEFAULT_OWNER_TTL_SEC) * 2);
}
async function recoverStaleTransfers(deps, trigger = "startup") {
const log = deps.log || console;
let rows;
try {
rows = await deps.db.query(
"SELECT name FROM servers WHERE status = ? AND updated_at < DATE_SUB(NOW(), INTERVAL ? SECOND)",
["transferring", flagMinAgeSeconds(deps)]
);
} catch (err) {
// Older deployments may lack servers.updated_at; degrade to the unguarded
// listing rather than never recovering — the per-server owner checks still
// gate every rollback.
try {
rows = await deps.db.query("SELECT name FROM servers WHERE status = ?", ["transferring"]);
} catch (err2) {
log.warn("[transfer-recovery] could not list servers flagged 'transferring':", err2?.message || err2);
return { scanned: 0 };
}
}
const names = (Array.isArray(rows) ? rows : [])
.map((row) => normalizeServerName(row?.name))
.filter(Boolean);
let recovered = 0;
for (const name of names) {
try {
const outcome = await recoverStaleServerFlag(deps, name, trigger);
if (outcome && outcome.recovered) recovered += 1;
} catch (err) {
log.error(`[transfer-recovery] ${name}: rollback attempt failed:`, err?.message || err);
}
}
return { scanned: names.length, recovered };
}
// Sweep finished/orphaned job records for the follow-up work a crash can
// leave behind:
// - a transfer that died AFTER the DB commit (server already lives on the
// destination): delete its leftover files from the source node;
// - a rolled-back transfer whose destination cleanup kept failing: retry it;
// - a dead owner's unfinished, un-committed record with no flag left to
// roll back: drop it so new transfers are not blocked.
async function recoverStaleTransferJobs(deps, trigger = "startup") {
const log = deps.log || console;
let entries;
try {
entries = await deps.listJobEntries();
} catch (err) {
log.warn("[transfer-recovery] could not list transfer job records:", err?.message || err);
return { scanned: 0 };
}
let cleaned = 0;
for (const { name, job } of entries) {
if (!name || !job || typeof job !== "object") continue;
try {
// Live transfer in some worker (including one that started after the
// listing above): hands off the name entirely, so a stale retry record
// can never delete from a destination a new transfer is importing to.
if (await hasLiveTransferOwner(deps, name)) continue;
if (job.destCleanupNodeId) {
// finished record with a pending destination cleanup retry
const destNode = await deps.findNodeByIdOrName(job.destCleanupNodeId);
if (!destNode || !job.transferId) {
deps.clearJobArtifacts(name);
continue;
}
try {
await deps.deleteServerOnNode(destNode, name, { transferId: job.transferId });
} catch (err) {
if (isAlreadyGoneError(err)) {
deps.clearJobArtifacts(name);
cleaned += 1;
} else {
log.warn(`[transfer-recovery] ${name}: destination cleanup retry failed:`, err?.message || err);
}
continue;
}
deps.clearJobArtifacts(name);
cleaned += 1;
continue;
}
let committed = job.dbCommitted === true;
if (!committed && job.transferId && Number.isSafeInteger(job.serverRowId)) {
// adpanel:transfer-commit-recovery - the row can commit before the worker records completion in Redis.
const current = await deps.findServer(name);
if (current?.name === name && current.rowId === job.serverRowId) {
if (normalizeServerName(current.status).toLowerCase() === "transferring") continue;
committed = job.importStarted === true && !!job.sourceNodeId && !!job.destNodeId &&
job.sourceNodeId !== job.destNodeId && current.nodeId === job.destNodeId;
}
}
if (committed && (!job.dbCommitted || !job.finishedAt || job.sourceCleanupPending)) {
// DB already points at the destination; finish the interrupted
// cleanup tail by removing the leftover copy from the source node.
const sourceNode = job.sourceNodeId ? await deps.findNodeByIdOrName(job.sourceNodeId) : null;
if (!sourceNode || !job.transferId || (job.serverRowId != null && sourceNode.id !== job.sourceNodeId)) {
deps.clearJobArtifacts(name);
continue;
}
try {
await deps.finishTransferSource(sourceNode, name, job.transferId, { cleanup: true });
} catch (err) {
if (isAlreadyGoneError(err)) {
deps.clearJobArtifacts(name);
cleaned += 1;
} else {
log.warn(`[transfer-recovery] ${name}: source-node cleanup after committed transfer failed:`, err?.message || err);
}
continue;
}
// No done-marker needed: the transfer itself completed before the
// crash (the DB already points at the destination), so the record's
// only purpose was this cleanup bookkeeping.
deps.clearJobArtifacts(name);
cleaned += 1;
log.warn(`[transfer-recovery] ${name}: committed transfer completed on destination; removed leftover source files`);
continue;
}
if (job.finishedAt) continue;
// Unfinished, un-committed, no live owner, no flag to roll back (the
// flag sweep owns that case) — dead bookkeeping; drop it. A heartbeat
// could only be missing here if the owner is gone, but require the
// record itself to be stale as well so a just-created record belonging
// to a worker whose heartbeat has not landed yet is never dropped.
const staleAfterMs = Math.max(10, Number(deps.ownerTtlSec) || DEFAULT_OWNER_TTL_SEC) * 1000;
const updatedAt = Number(job.updatedAt || 0);
if (!updatedAt || Date.now() - updatedAt > staleAfterMs) {
deps.clearJobArtifacts(name);
}
} catch (err) {
log.error(`[transfer-recovery] ${name}: job record recovery failed:`, err?.message || err);
}
}
return { scanned: entries.length, cleaned };
}
async function sweepTransferRecovery(deps, trigger = "sweep") {
const flagOutcome = await recoverStaleTransfers(deps, trigger);
const jobOutcome = await recoverStaleTransferJobs(deps, trigger);
return { flagOutcome, jobOutcome };
}
// 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 startTransferRecoverySweeper(deps) {
const log = deps.log || console;
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 sweepTransferRecovery(deps, trigger);
} catch (err) {
log.warn("[transfer-recovery] sweep failed:", err?.message || err);
} finally {
running = false;
}
};
const timer = setInterval(() => run("sweep"), intervalMs);
if (typeof timer.unref === "function") timer.unref();
run("startup").catch(() => { });
return () => clearInterval(timer);
}
module.exports = {
RESTORABLE_STATUSES,
transferOwnerAliveKey,
transferRecoveryClaimKey,
startTransferOwnerHeartbeat,
stopTransferOwnerHeartbeat,
hasLiveTransferOwner,
transferRollbackStatus,
rollbackAbortedTransfer,
recoverStaleServerFlag,
recoverStaleTransfers,
recoverStaleTransferJobs,
sweepTransferRecovery,
startTransferRecoverySweeper,
};