1153 lines
53 KiB
JavaScript
1153 lines
53 KiB
JavaScript
"use strict";
|
|
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
const crypto = require("node:crypto");
|
|
const { fork } = require("node:child_process");
|
|
const { setTimeout: delay } = require("node:timers/promises");
|
|
const { atomicWriteFileSync, createAtomicWriteTempPath } = require("../utils/atomic-file");
|
|
const { createCrossProcessOperationMutex, getProcessStartTicks } = require("../utils/cross-process-mutex");
|
|
|
|
const INFO_FILE = "panel-information.json";
|
|
const JOURNAL_FILE = ".update-journal";
|
|
const CONFIRM_PENDING_FILE = ".confirm-pending.json";
|
|
const CONFIRM_PROVISIONAL_FILE = ".confirm-provisional.json";
|
|
const CONFIRM_COMPLETE_FILE = ".confirm-complete.json";
|
|
const PREFLIGHT_FAILURE_FILE = ".preflight-failure.json";
|
|
const PREFLIGHT_DISCARDING_FILE = ".preflight-discarding.json";
|
|
const PREFLIGHT_SPACE_FILE = ".preflight-space-reserve";
|
|
const PREFLIGHT_SPACE_BYTES = 128 * 1024;
|
|
const RELEASE_DIGEST = /^[a-f0-9]{64}$/;
|
|
const STORAGE_FAILURE_FILE = ".storage-failure.json";
|
|
const STORAGE_RESTORING_FILE = ".storage-restoring.json";
|
|
const RECOVERY_ERROR_FILE = ".recovery-error.json";
|
|
const RECOVERY_ERROR_RESERVE = ".recovery-error-reserve.json";
|
|
const RESTORE_TEMP_FILE = ".update-restore.tmp";
|
|
const RESTORE_PATH_FILE = ".update-restore-path.json";
|
|
const SHARED_SNAPSHOT_FILE = ".backup-may-share-live-files";
|
|
const SHARED_SNAPSHOT_RESERVE = ".shared-snapshot-reserve";
|
|
const UNUSED_SNAPSHOT_FILE = ".snapshot-unused";
|
|
const STAGED_RELEASE_PREFIX = ".staged-";
|
|
const STAGED_MANIFEST_FILE = ".release-files.json";
|
|
const BACKUP_ID = /^\d{8}-\d{6}-[a-f0-9]{16}$/;
|
|
const RETAINED_BACKUP_NAME = /^\d{8}-\d{6}(?:-[A-Za-z0-9]{6}|-[a-f0-9]{16})?$/;
|
|
const DISCARDED_BACKUP_PREFIX = ".discarded-";
|
|
const BACKUPS_TO_KEEP = 5;
|
|
const STARTUP_TIMEOUT_MS = 120_000;
|
|
const STARTUP_SETTLE_MS = 5_000;
|
|
const WATCHDOG_ARM_TIMEOUT_MS = 5_000;
|
|
const AGENT_DRAIN_TIMEOUT_MS = 10_000;
|
|
const RESTART_RECOVERY_MS = 120_000;
|
|
const TRIAL_POLL_MS = 250;
|
|
const READY_REFRESH_MS = 1_000;
|
|
const READY_MAX_AGE_MS = 3_000;
|
|
const RECOVERY_STORAGE_CODES = new Set(["ENOSPC", "EDQUOT"]);
|
|
const BOOT_ID = (() => {
|
|
try { return fs.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(); } catch { return undefined; }
|
|
})();
|
|
let launcherActive = false;
|
|
let loadedUpdateId;
|
|
let startupTrial;
|
|
|
|
function createPanelUpdateMutex(panelInfoFile, acquireTimeoutMs) {
|
|
return createCrossProcessOperationMutex({
|
|
label: "[panel-update]",
|
|
lockDirectoryPath: path.dirname(panelInfoFile),
|
|
acquireTimeoutMs,
|
|
});
|
|
}
|
|
|
|
function createPanelWorkerLease(panelRoot, sharedDirectoryLock = false) {
|
|
return createCrossProcessOperationMutex({
|
|
label: "[panel-update-worker]",
|
|
lockDirectoryPath: path.join(panelRoot, "scripts"),
|
|
sharedDirectoryLock,
|
|
});
|
|
}
|
|
|
|
function generationHasDrained(generationLock) {
|
|
if (!generationLock) return true;
|
|
const release = generationLock.tryAcquire();
|
|
if (!release) return false;
|
|
release();
|
|
return true;
|
|
}
|
|
|
|
function createPanelScaleMutex(panelInfoFile) {
|
|
return createCrossProcessOperationMutex({
|
|
label: "[panel-autoscale]",
|
|
lockDirectoryPath: path.join(path.dirname(panelInfoFile), "utils"),
|
|
});
|
|
}
|
|
|
|
function canAutoscale(panelRoot) {
|
|
const panelInfoFile = path.join(panelRoot, INFO_FILE);
|
|
const release = createPanelUpdateMutex(panelInfoFile).tryAcquire();
|
|
if (!release) return false;
|
|
try {
|
|
return !createPanelUpdateState(panelInfoFile).read().pending;
|
|
} finally {
|
|
release();
|
|
}
|
|
}
|
|
|
|
function panelWorkerIdentity(pid) {
|
|
if (!Number.isSafeInteger(pid) || pid <= 0) return null;
|
|
const info = getProcessStartTicks(pid);
|
|
return info && info.state !== "Z" ? { pid, startTicks: info.startTicks, bootId: BOOT_ID } : null;
|
|
}
|
|
|
|
function isWorkerIdentity(worker) {
|
|
return worker && Number.isSafeInteger(worker.pid) && worker.pid > 0 &&
|
|
Number.isSafeInteger(worker.startTicks) && worker.startTicks >= 0;
|
|
}
|
|
|
|
function samePanelProcess(first, second) {
|
|
return first.pid === second.pid && first.startTicks === second.startTicks && first.bootId === second.bootId;
|
|
}
|
|
|
|
function isPanelWorkerAlive(worker) {
|
|
if (worker.bootId && BOOT_ID && worker.bootId !== BOOT_ID) return false;
|
|
const info = getProcessStartTicks(worker.pid);
|
|
if (info) return info.state !== "Z" && info.startTicks === worker.startTicks;
|
|
try { process.kill(worker.pid, 0); } catch (err) { return err.code !== "ESRCH"; }
|
|
return true;
|
|
}
|
|
|
|
function isManagedPanelProcess() {
|
|
return process.connected === true && process.env.pm_exec_path === __filename && /^\d+$/.test(process.env.pm_id || "");
|
|
}
|
|
|
|
function identifyTrialWorker(cohort) {
|
|
const worker = panelWorkerIdentity(process.pid);
|
|
if (!worker) throw new Error("Cannot identify this panel trial process");
|
|
if (!cohort?.appName) return worker;
|
|
if (!isManagedPanelProcess() || process.env.name !== cohort.appName) {
|
|
throw new Error("The staged panel must start through its managed PM2 app");
|
|
}
|
|
const supervisor = panelWorkerIdentity(process.ppid);
|
|
if (!supervisor) throw new Error("Cannot identify the PM2 trial supervisor");
|
|
const sameSupervisor = samePanelProcess(supervisor, cohort.supervisor);
|
|
const slot = Number(process.env.pm_id);
|
|
const expected = sameSupervisor ? cohort.expected : Number(process.env.instances ?? 1);
|
|
if (!Number.isSafeInteger(expected) || expected < 1) throw new Error("Invalid PM2 trial worker count");
|
|
if (!Number.isSafeInteger(slot) || (sameSupervisor && cohort.slots && !cohort.slots.includes(slot))) {
|
|
throw new Error("The PM2 trial slot was not in the captured panel group");
|
|
}
|
|
return { ...worker, slot, supervisor, expected };
|
|
}
|
|
|
|
function wasInterruptedByReboot(pending) {
|
|
const previousBootId = pending?.cohort?.supervisor?.bootId;
|
|
return !!(BOOT_ID && previousBootId && previousBootId !== BOOT_ID);
|
|
}
|
|
|
|
function getRestartRecoveryReason(pending, now = Date.now()) {
|
|
if (wasInterruptedByReboot(pending) || (pending.cohort?.appName && (!BOOT_ID || !pending.cohort.supervisor.bootId))) return "interrupted";
|
|
if (now - (pending.phaseAt || 0) >= RESTART_RECOVERY_MS) return "restart";
|
|
}
|
|
|
|
function isUnpublishedUpdate(pending) {
|
|
return pending?.phase === "preparing" || (pending?.phase === "restart" && pending.staged === true);
|
|
}
|
|
|
|
function trialHasFailed(pending) {
|
|
return !Number.isSafeInteger(pending.deadlineAt) || !pending.workers?.length ||
|
|
Date.now() >= pending.deadlineAt || pending.workers.some(worker => !isPanelWorkerAlive(worker));
|
|
}
|
|
|
|
function trialIsReady(pending) {
|
|
const now = Date.now();
|
|
return !trialHasFailed(pending) && pending.workers.length === pending.expectedWorkers &&
|
|
pending.workers.every(worker => Number.isSafeInteger(worker.readyAt) && worker.readyAt <= now && now - worker.readyAt <= READY_MAX_AGE_MS) &&
|
|
!pending.cohort?.previous.some(isPanelWorkerAlive);
|
|
}
|
|
|
|
function updateTargetType(targetPath) {
|
|
const existing = fs.lstatSync(targetPath, { throwIfNoEntry: false });
|
|
if (existing && !existing.isFile()) {
|
|
throw Object.assign(new Error("Update target is not a regular file"), { code: "EUPDATEFILETYPE", statusCode: 409 });
|
|
}
|
|
return existing;
|
|
}
|
|
|
|
// adpanel:update-atomic-replace - the final rename does not follow target symlinks.
|
|
function writePanelUpdateFileNoFollow(targetPath, data, options) {
|
|
const existing = updateTargetType(targetPath);
|
|
atomicWriteFileSync(targetPath, data, { ...options, mode: existing ? existing.mode & 0o777 : 0o644, durable: true });
|
|
}
|
|
|
|
function writePanelUpdateInfo(panelInfoFile, fields, options) {
|
|
const existing = updateTargetType(panelInfoFile);
|
|
const data = existing ? JSON.parse(fs.readFileSync(panelInfoFile, "utf8")) : [{}];
|
|
const entries = Array.isArray(data) ? data : [data];
|
|
const info = entries[0] && typeof entries[0] === "object" ? entries[0] : {};
|
|
entries[0] = { ...info, ...fields };
|
|
writePanelUpdateFileNoFollow(panelInfoFile, JSON.stringify(entries, null, 2), options);
|
|
}
|
|
|
|
function syncPath(targetPath) {
|
|
const fd = fs.openSync(targetPath, "r");
|
|
try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
}
|
|
|
|
function checkPanelUpdateParent(root, filePath, create = false, beforeCreate) {
|
|
const relative = path.relative(root, path.dirname(filePath));
|
|
if (path.isAbsolute(relative) || relative === ".." || relative.startsWith(`..${path.sep}`)) {
|
|
throw new Error("Panel update path escapes its root");
|
|
}
|
|
let parent = root;
|
|
let complete = true;
|
|
for (const component of relative ? relative.split(path.sep) : []) {
|
|
const next = path.join(parent, component);
|
|
const existing = fs.lstatSync(next, { throwIfNoEntry: false });
|
|
if (!existing) {
|
|
if (!create && !beforeCreate) return false;
|
|
beforeCreate?.(path.relative(root, next));
|
|
if (create) {
|
|
fs.mkdirSync(next);
|
|
syncPath(parent);
|
|
} else {
|
|
complete = false;
|
|
}
|
|
} else if (!existing.isDirectory()) {
|
|
throw Object.assign(new Error("Cannot update a panel path through a symlink or non-directory parent"), {
|
|
code: existing.isSymbolicLink() ? "EUPDATEFILETYPE" : "ENOTDIR", statusCode: 409,
|
|
});
|
|
}
|
|
parent = next;
|
|
}
|
|
return complete;
|
|
}
|
|
|
|
function restoreSnapshot(backupPath, targetPath, temporary, { beforeExternalCopy, beforeSharedRestore, withStorageReserve = operation => operation() }) {
|
|
const saved = updateTargetType(backupPath);
|
|
if (!saved) throw new Error("Panel update snapshot is missing");
|
|
const existing = updateTargetType(targetPath);
|
|
const targetDirectory = path.dirname(targetPath);
|
|
const backupDirectory = path.dirname(temporary);
|
|
const sameDevice = fs.statSync(targetDirectory).dev === saved.dev;
|
|
const copy = scratch => {
|
|
try {
|
|
fs.copyFileSync(backupPath, scratch, fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE);
|
|
fs.utimesSync(scratch, saved.atime, saved.mtime);
|
|
syncPath(scratch);
|
|
fs.renameSync(scratch, targetPath);
|
|
} finally {
|
|
fs.rmSync(scratch, { force: true });
|
|
}
|
|
};
|
|
const copyAcrossDevices = () => {
|
|
const scratch = path.join(targetDirectory, `.update-restore-${crypto.randomUUID()}.tmp`);
|
|
withStorageReserve(() => beforeExternalCopy?.(scratch));
|
|
try { withStorageReserve(() => copy(scratch)); } finally { withStorageReserve(() => syncPath(targetDirectory)); }
|
|
};
|
|
let shared = false;
|
|
if (sameDevice) {
|
|
try {
|
|
withStorageReserve(() => copy(temporary));
|
|
} catch (err) {
|
|
if (err.code === "EXDEV") {
|
|
copyAcrossDevices();
|
|
} else if (RECOVERY_STORAGE_CODES.has(err.code)) {
|
|
// adpanel:update-restore - a shared inode is an emergency restore, not an independent retained snapshot.
|
|
beforeSharedRestore?.();
|
|
if (existing?.ino !== saved.ino || existing.dev !== saved.dev) {
|
|
fs.linkSync(backupPath, temporary);
|
|
try { fs.renameSync(temporary, targetPath); } finally { fs.rmSync(temporary, { force: true }); }
|
|
}
|
|
shared = true;
|
|
} else {
|
|
throw err;
|
|
}
|
|
}
|
|
} else {
|
|
copyAcrossDevices();
|
|
}
|
|
withStorageReserve(() => syncPath(targetDirectory));
|
|
if (backupDirectory !== targetDirectory) withStorageReserve(() => syncPath(backupDirectory));
|
|
return shared;
|
|
}
|
|
|
|
function rollbackPanelUpdateFiles(writtenFiles, backupDir, logger = console, panelRoot = null, restoreHooks = {}) {
|
|
const withStorageReserve = restoreHooks.withStorageReserve || (operation => operation());
|
|
const temporary = path.join(backupDir, RESTORE_TEMP_FILE);
|
|
if (updateTargetType(temporary)) withStorageReserve(() => fs.unlinkSync(temporary));
|
|
withStorageReserve(() => syncPath(backupDir));
|
|
let failed = 0;
|
|
for (const item of [...writtenFiles].reverse()) {
|
|
try {
|
|
if (panelRoot && !checkPanelUpdateParent(panelRoot, item.target) && !item.existedBefore) continue;
|
|
if (item.directory) {
|
|
const directory = fs.lstatSync(item.target, { throwIfNoEntry: false });
|
|
if (directory && !directory.isDirectory()) throw new Error("Panel update directory has changed type");
|
|
if (directory) {
|
|
try {
|
|
withStorageReserve(() => fs.rmdirSync(item.target));
|
|
} catch (err) {
|
|
if (err.code !== "ENOTEMPTY" && err.code !== "EEXIST") throw err;
|
|
}
|
|
}
|
|
withStorageReserve(() => syncPath(path.dirname(item.target)));
|
|
} else if (item.existedBefore) {
|
|
const snapshot = path.join(backupDir, item.relative);
|
|
checkPanelUpdateParent(backupDir, snapshot);
|
|
const current = updateTargetType(item.target);
|
|
if (item.original && current?.dev === item.original.dev && current.ino === item.original.ino) {
|
|
withStorageReserve(() => syncPath(path.dirname(item.target)));
|
|
} else {
|
|
restoreHooks.beforeRestore?.(item);
|
|
if (restoreSnapshot(snapshot, item.target, temporary, restoreHooks)) {
|
|
logger.warn?.(`[panel-update] Restored ${item.relative} using a hard link; its retained backup is not independent.`);
|
|
}
|
|
}
|
|
} else {
|
|
if (updateTargetType(item.target)) {
|
|
restoreHooks.beforeRestore?.(item);
|
|
withStorageReserve(() => fs.unlinkSync(item.target));
|
|
}
|
|
withStorageReserve(() => syncPath(path.dirname(item.target)));
|
|
}
|
|
} catch (err) {
|
|
failed++;
|
|
logger.error(`[panel-update] Rollback failed for ${item.relative}:`, err?.message || err);
|
|
}
|
|
}
|
|
return failed;
|
|
}
|
|
|
|
function createPanelUpdateState(panelInfoFile, logger = console) {
|
|
const panelRoot = path.dirname(panelInfoFile);
|
|
const backupRoot = path.join(panelRoot, ".update-backups");
|
|
const stateFile = path.join(backupRoot, "update-state.json");
|
|
const confirmPendingFile = path.join(backupRoot, CONFIRM_PENDING_FILE);
|
|
const recoveryErrorFile = path.join(backupRoot, RECOVERY_ERROR_FILE);
|
|
const recoveryErrorReserve = path.join(backupRoot, RECOVERY_ERROR_RESERVE);
|
|
const preflightSpaceFile = path.join(backupRoot, PREFLIGHT_SPACE_FILE);
|
|
|
|
function checkBackupRoot(create = false) {
|
|
if (create) fs.mkdirSync(backupRoot, { recursive: true, mode: 0o700 });
|
|
const stat = fs.lstatSync(backupRoot, { throwIfNoEntry: false });
|
|
if (stat && !stat.isDirectory()) throw new Error("Invalid panel update backup directory");
|
|
}
|
|
|
|
function readRecord(file) {
|
|
try {
|
|
if (!updateTargetType(file)) return null;
|
|
const record = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
if (!record || typeof record !== "object" || Array.isArray(record)) throw new Error("Invalid panel update state");
|
|
return record;
|
|
} catch (err) {
|
|
if (err.code === "ENOENT") return null;
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
function readConfirmation(primary) {
|
|
const active = readRecord(confirmPendingFile);
|
|
const id = primary?.verified?.id;
|
|
if (active || primary?.pending || !id || !BACKUP_ID.test(id)) return active;
|
|
const directory = path.join(backupRoot, id);
|
|
const archive = path.join(directory, CONFIRM_PENDING_FILE);
|
|
if (!checkPanelUpdateParent(backupRoot, archive)) return null;
|
|
const record = readRecord(archive) || readRecord(path.join(directory, CONFIRM_PROVISIONAL_FILE));
|
|
return record?.pending?.id === id && record.pending.receiptRequired ? record : null;
|
|
}
|
|
|
|
function read() {
|
|
checkBackupRoot();
|
|
const primary = readRecord(stateFile);
|
|
const confirmation = readConfirmation(primary);
|
|
if (confirmation && (confirmation.pending?.phase !== "committing" ||
|
|
(primary?.pending && primary.pending.id !== confirmation.pending.id))) {
|
|
throw new Error("Invalid panel update confirmation record");
|
|
}
|
|
const state = confirmation && (!primary?.pending || primary.pending.phase === "starting") ? confirmation : (primary || {});
|
|
const { pending } = state;
|
|
const cohort = pending?.cohort;
|
|
if (pending && (!BACKUP_ID.test(pending.id) || typeof pending.version !== "string" ||
|
|
!["preparing", "applying", "restart", "starting", "committing", "restoring"].includes(pending.phase) ||
|
|
(pending.staged && !RELEASE_DIGEST.test(pending.stageDigest)) ||
|
|
(cohort && (!Number.isSafeInteger(cohort.expected) || cohort.expected < 1 ||
|
|
!Array.isArray(cohort.previous) || !cohort.previous.every(isWorkerIdentity) ||
|
|
(cohort.slots && (!Array.isArray(cohort.slots) || new Set(cohort.slots).size !== cohort.expected ||
|
|
cohort.slots.length !== cohort.expected || !cohort.slots.every(slot => Number.isSafeInteger(slot) && slot >= 0))) ||
|
|
(cohort.appName && (typeof cohort.appName !== "string" || !isWorkerIdentity(cohort.supervisor))))) ||
|
|
(pending.workers && (!Array.isArray(pending.workers) || !pending.workers.every(isWorkerIdentity))))) {
|
|
throw new Error("Invalid pending panel update");
|
|
}
|
|
return state;
|
|
}
|
|
|
|
function write(state) {
|
|
checkBackupRoot(true);
|
|
atomicWriteFileSync(stateFile, JSON.stringify(state), { mode: 0o600, durable: true });
|
|
}
|
|
|
|
function publishReservedRecord(reservation, destination = stateFile) {
|
|
const sourceDirectory = path.dirname(reservation);
|
|
withStorageReserve(() => fs.renameSync(reservation, destination));
|
|
withStorageReserve(() => syncPath(backupRoot));
|
|
if (sourceDirectory !== backupRoot) withStorageReserve(() => syncPath(sourceDirectory));
|
|
}
|
|
|
|
function reservePreflightSpace() {
|
|
checkBackupRoot(true);
|
|
if (updateTargetType(preflightSpaceFile)?.size === PREFLIGHT_SPACE_BYTES) return;
|
|
syncPath(panelRoot);
|
|
atomicWriteFileSync(preflightSpaceFile, crypto.randomBytes(PREFLIGHT_SPACE_BYTES), { mode: 0o600, durable: true });
|
|
}
|
|
|
|
function releasePreflightSpace() {
|
|
if (!updateTargetType(preflightSpaceFile)) return false;
|
|
fs.unlinkSync(preflightSpaceFile);
|
|
syncPath(backupRoot);
|
|
return true;
|
|
}
|
|
|
|
function withStorageReserve(operation) {
|
|
try {
|
|
return operation();
|
|
} catch (err) {
|
|
if (!RECOVERY_STORAGE_CODES.has(err.code) || !releasePreflightSpace()) throw err;
|
|
return operation();
|
|
}
|
|
}
|
|
|
|
function retireConfirmation(id, verifyReady) {
|
|
const confirmation = readRecord(confirmPendingFile);
|
|
if (!confirmation && !verifyReady) return;
|
|
if (confirmation?.pending?.id !== id) throw new Error("Panel update confirmation changed");
|
|
if (!verifyReady) {
|
|
fs.unlinkSync(confirmPendingFile);
|
|
syncPath(backupRoot);
|
|
return;
|
|
}
|
|
const directory = getBackupDir(id);
|
|
const archivedGuard = path.join(directory, CONFIRM_PENDING_FILE);
|
|
const provisionalGuard = path.join(directory, CONFIRM_PROVISIONAL_FILE);
|
|
const completedGuard = path.join(directory, CONFIRM_COMPLETE_FILE);
|
|
fs.linkSync(confirmPendingFile, archivedGuard);
|
|
syncPath(directory);
|
|
verifyReady();
|
|
fs.unlinkSync(confirmPendingFile);
|
|
syncPath(backupRoot);
|
|
verifyReady();
|
|
fs.renameSync(archivedGuard, provisionalGuard);
|
|
syncPath(directory);
|
|
verifyReady();
|
|
// adpanel:update-confirm - after a crash the durable provisional receipt still requires rollback.
|
|
fs.renameSync(provisionalGuard, completedGuard);
|
|
fs.promises.open(directory, "r").then(async handle => {
|
|
try { await handle.sync(); } finally { await handle.close(); }
|
|
}).catch(err => logger.warn("[panel-update] Could not flush the completion receipt; recovery may run after a reboot:", err));
|
|
}
|
|
|
|
function getBackupDir(id) {
|
|
if (!BACKUP_ID.test(id)) throw new Error("Invalid panel update backup ID");
|
|
checkBackupRoot();
|
|
const backupDir = path.join(backupRoot, id);
|
|
if (!fs.lstatSync(backupDir).isDirectory()) throw new Error("Invalid panel update snapshot directory");
|
|
return backupDir;
|
|
}
|
|
|
|
function resolveTarget(relative) {
|
|
if (typeof relative !== "string" || !relative || path.isAbsolute(relative) || relative !== path.normalize(relative) ||
|
|
relative === "." || relative === ".." || relative.startsWith(`..${path.sep}`) ||
|
|
relative.split(path.sep)[0] === ".update-backups") {
|
|
throw new Error("Invalid panel update journal path");
|
|
}
|
|
return path.join(panelRoot, relative);
|
|
}
|
|
|
|
function snapshot(id, relative, existedBefore, directory = false, temporary = false) {
|
|
const backupDir = getBackupDir(id);
|
|
const target = resolveTarget(relative);
|
|
if (!checkPanelUpdateParent(panelRoot, target) && existedBefore) throw new Error("Panel update target directory is missing");
|
|
let original;
|
|
if (existedBefore) {
|
|
const existing = updateTargetType(target);
|
|
if (!existing) throw new Error("Panel update target disappeared before snapshot");
|
|
original = { dev: existing.dev, ino: existing.ino };
|
|
const backupPath = path.join(backupDir, relative);
|
|
checkPanelUpdateParent(backupDir, backupPath, true);
|
|
fs.copyFileSync(target, backupPath, fs.constants.COPYFILE_EXCL);
|
|
fs.utimesSync(backupPath, existing.atime, existing.mtime);
|
|
syncPath(backupPath);
|
|
syncPath(path.dirname(backupPath));
|
|
}
|
|
const journal = fs.openSync(path.join(backupDir, JOURNAL_FILE), "a", 0o600);
|
|
try {
|
|
fs.writeFileSync(journal, `${JSON.stringify({ relative, existedBefore, directory, original, ...(temporary && { temporary }) })}\n`);
|
|
fs.fsyncSync(journal);
|
|
} finally {
|
|
fs.closeSync(journal);
|
|
}
|
|
syncPath(backupDir);
|
|
}
|
|
|
|
function markSnapshotUsed(backupDir) {
|
|
const unused = path.join(backupDir, UNUSED_SNAPSHOT_FILE);
|
|
if (updateTargetType(unused)) fs.unlinkSync(unused);
|
|
syncPath(backupDir);
|
|
}
|
|
|
|
function pruneBackups(activeId) {
|
|
try {
|
|
const names = fs.readdirSync(backupRoot, { withFileTypes: true })
|
|
.filter(entry => entry.isDirectory()).map(entry => entry.name).sort().reverse();
|
|
let remaining = BACKUPS_TO_KEEP - (activeId ? 1 : 0);
|
|
for (const name of names) {
|
|
const directory = path.join(backupRoot, name);
|
|
if (name.startsWith(STAGED_RELEASE_PREFIX) && BACKUP_ID.test(name.slice(STAGED_RELEASE_PREFIX.length))) {
|
|
tryDiscardStage(name.slice(STAGED_RELEASE_PREFIX.length));
|
|
} else if (name.startsWith(DISCARDED_BACKUP_PREFIX) && RETAINED_BACKUP_NAME.test(name.slice(DISCARDED_BACKUP_PREFIX.length))) {
|
|
syncPath(backupRoot);
|
|
fs.rmSync(directory, { recursive: true, force: true });
|
|
} else if (name !== activeId && RETAINED_BACKUP_NAME.test(name)) {
|
|
if (remaining > 0 && !updateTargetType(path.join(directory, UNUSED_SNAPSHOT_FILE))) {
|
|
remaining--;
|
|
continue;
|
|
}
|
|
// adpanel:update-retention - an interrupted recursive removal must not leave a partial retained backup.
|
|
const discarded = path.join(backupRoot, DISCARDED_BACKUP_PREFIX + name);
|
|
fs.renameSync(directory, discarded);
|
|
syncPath(backupRoot);
|
|
fs.rmSync(discarded, { recursive: true, force: true });
|
|
}
|
|
}
|
|
} catch (err) {
|
|
logger.warn("[panel-update] Could not prune old update backups:", err?.message || err);
|
|
}
|
|
}
|
|
|
|
function prepare(version, ignoredThrough = version, keepFailure = false, cohort) {
|
|
const state = { ...read(), checkFailed: undefined };
|
|
if (state.pending) throw Object.assign(new Error("A panel update is awaiting recovery or restart"), { statusCode: 409 });
|
|
const previousId = state.verified?.id;
|
|
if (typeof previousId === "string" && BACKUP_ID.test(previousId)) {
|
|
const receipt = path.join(backupRoot, previousId, CONFIRM_COMPLETE_FILE);
|
|
// adpanel:update-confirm - a later journal must not rely on an unflushed completion receipt.
|
|
if (checkPanelUpdateParent(backupRoot, receipt) && updateTargetType(receipt)) syncPath(path.dirname(receipt));
|
|
}
|
|
const stamp = new Date().toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-");
|
|
const id = `${stamp}-${crypto.randomBytes(8).toString("hex")}`;
|
|
const reservation = path.join(backupRoot, PREFLIGHT_FAILURE_FILE);
|
|
const pending = { id, version, ignoredThrough, keepFailure, phase: "preparing", cohort };
|
|
const storageFailure = {
|
|
...state, ignoredThrough, failure: { version, at: new Date().toISOString(), reason: "storage", restored: null },
|
|
};
|
|
let reservationReady = false;
|
|
try {
|
|
checkBackupRoot(true);
|
|
syncPath(panelRoot);
|
|
reservePreflightSpace();
|
|
atomicWriteFileSync(reservation, JSON.stringify(storageFailure), { mode: 0o600, durable: true });
|
|
reservationReady = true;
|
|
atomicWriteFileSync(path.join(backupRoot, PREFLIGHT_DISCARDING_FILE), JSON.stringify({
|
|
...state, pending: { ...pending, reason: "storage" },
|
|
}), { mode: 0o600, durable: true });
|
|
// adpanel:update-status - preallocate both names so a full disk cannot hide a failed rollback from other workers.
|
|
atomicWriteFileSync(recoveryErrorFile, "{}", { mode: 0o600, durable: true });
|
|
atomicWriteFileSync(recoveryErrorReserve, JSON.stringify({ id, reason: "storage" }), { mode: 0o600, durable: true });
|
|
write({ ...state, pending });
|
|
} catch (err) {
|
|
if (RECOVERY_STORAGE_CODES.has(err.code)) {
|
|
try {
|
|
if (!reservationReady) throw err;
|
|
publishReservedRecord(reservation);
|
|
} catch (statusErr) {
|
|
if (!RECOVERY_STORAGE_CODES.has(statusErr.code) || !releasePreflightSpace()) throw statusErr;
|
|
write(storageFailure);
|
|
}
|
|
err.panelUpdateFailureSaved = true;
|
|
}
|
|
throw err;
|
|
}
|
|
return id;
|
|
}
|
|
|
|
function openStage(id) {
|
|
const { pending } = read();
|
|
if (pending?.id !== id || pending.phase !== "preparing") throw new Error("No panel update is being prepared");
|
|
const directory = path.join(backupRoot, STAGED_RELEASE_PREFIX + id);
|
|
fs.mkdirSync(directory, { mode: 0o700 });
|
|
syncPath(backupRoot);
|
|
const files = new Map();
|
|
return {
|
|
write(relative, data) {
|
|
const live = resolveTarget(relative);
|
|
if (relative === INFO_FILE || relative === STAGED_MANIFEST_FILE || files.has(relative)) throw new Error("Duplicate or reserved panel update entry");
|
|
if (checkPanelUpdateParent(panelRoot, live)) updateTargetType(live);
|
|
const target = path.join(directory, relative);
|
|
checkPanelUpdateParent(directory, target, true);
|
|
writePanelUpdateFileNoFollow(target, data);
|
|
files.set(relative, crypto.createHash("sha256").update(data).digest("hex"));
|
|
},
|
|
seal() {
|
|
const state = read();
|
|
if (state.pending?.id !== id || state.pending.phase !== "preparing" || !files.size) {
|
|
throw new Error("No prepared panel release to seal");
|
|
}
|
|
const manifest = JSON.stringify([...files]);
|
|
const stageDigest = crypto.createHash("sha256").update(manifest).digest("hex");
|
|
atomicWriteFileSync(path.join(directory, STAGED_MANIFEST_FILE), manifest, { mode: 0o600, durable: true });
|
|
write({ ...state, pending: { ...state.pending, phase: "restart", phaseAt: Date.now(), staged: true, stageDigest } });
|
|
},
|
|
};
|
|
}
|
|
|
|
function discardStage(id) {
|
|
fs.rmSync(path.join(backupRoot, STAGED_RELEASE_PREFIX + id), { recursive: true, force: true });
|
|
syncPath(backupRoot);
|
|
}
|
|
|
|
function tryDiscardStage(id, cleanup = discardStage) {
|
|
try { cleanup(id); } catch (err) { logger.warn?.("[panel-update] Could not clean up the staged release:", err.message); }
|
|
}
|
|
|
|
function publishStagedRelease(id, worker, deadlineAt) {
|
|
const state = read();
|
|
const pending = state.pending;
|
|
if (pending?.id !== id || pending.phase !== "restart" || !pending.staged) throw new Error("No staged panel release to publish");
|
|
const directory = path.join(backupRoot, STAGED_RELEASE_PREFIX + id);
|
|
const manifest = path.join(directory, STAGED_MANIFEST_FILE);
|
|
if (!checkPanelUpdateParent(backupRoot, manifest) || !updateTargetType(manifest)) throw new Error("Missing staged panel release manifest");
|
|
const contents = fs.readFileSync(manifest);
|
|
if (crypto.createHash("sha256").update(contents).digest("hex") !== pending.stageDigest) {
|
|
throw Object.assign(new Error("Staged panel release manifest no longer matches the journal"), { code: "PANEL_UPDATE_INTEGRITY_FAILED" });
|
|
}
|
|
const files = JSON.parse(contents.toString("utf8"));
|
|
if (!Array.isArray(files) || !files.length) throw new Error("Invalid staged panel release manifest");
|
|
const seen = new Set();
|
|
const targets = files.map(item => {
|
|
if (!Array.isArray(item) || item.length !== 2) throw new Error("Invalid staged panel release entry");
|
|
const [relative, hash] = item;
|
|
if (relative === INFO_FILE || relative === STAGED_MANIFEST_FILE || seen.has(relative) || typeof hash !== "string" || !RELEASE_DIGEST.test(hash)) {
|
|
throw new Error("Invalid staged panel release entry");
|
|
}
|
|
seen.add(relative);
|
|
const target = resolveTarget(relative);
|
|
return { relative, hash, target, temporaryPath: createAtomicWriteTempPath(target) };
|
|
});
|
|
const metadataTemporary = createAtomicWriteTempPath(panelInfoFile);
|
|
const snapshotTemporary = temporaryPath => {
|
|
if (seen.has(path.relative(panelRoot, temporaryPath)) ||
|
|
(checkPanelUpdateParent(panelRoot, temporaryPath) && fs.lstatSync(temporaryPath, { throwIfNoEntry: false }))) {
|
|
throw new Error("A panel update temporary path is already in use");
|
|
}
|
|
snapshot(id, path.relative(panelRoot, temporaryPath), false, false, true);
|
|
};
|
|
write({ ...state, pending: { ...pending, phase: "preparing" } });
|
|
const directories = new Set();
|
|
// adpanel:update-snapshot - flush the complete undo journal before publication; never append to it while replacing files.
|
|
begin(id, () => {
|
|
for (const { relative, target, temporaryPath } of targets) {
|
|
const parentExists = checkPanelUpdateParent(panelRoot, target, false, parent => {
|
|
if (directories.has(parent)) return;
|
|
snapshot(id, parent, false, true);
|
|
directories.add(parent);
|
|
});
|
|
snapshot(id, relative, parentExists && !!updateTargetType(target));
|
|
snapshotTemporary(temporaryPath);
|
|
}
|
|
snapshotTemporary(metadataTemporary);
|
|
});
|
|
for (const { relative, hash, target, temporaryPath } of targets) {
|
|
const source = path.join(directory, relative);
|
|
if (!checkPanelUpdateParent(directory, source) || !updateTargetType(source)) throw new Error("Missing staged panel release file");
|
|
const data = fs.readFileSync(source);
|
|
if (crypto.createHash("sha256").update(data).digest("hex") !== hash) {
|
|
throw Object.assign(new Error("Staged panel release file no longer matches the archive"), { code: "PANEL_UPDATE_INTEGRITY_FAILED" });
|
|
}
|
|
checkPanelUpdateParent(panelRoot, target, true, parent => {
|
|
if (!directories.has(parent)) throw new Error("Panel update target parent changed after snapshot");
|
|
});
|
|
writePanelUpdateFileNoFollow(target, data, { temporaryPath });
|
|
fs.unlinkSync(source);
|
|
}
|
|
writePanelUpdateInfo(panelInfoFile, { "panel-version": pending.version, "panel-last-update-at": new Date().toISOString() }, { temporaryPath: metadataTemporary });
|
|
markSnapshotUsed(getBackupDir(id));
|
|
if (!enrollTrial(id, worker, deadlineAt, true)) throw new Error("Could not enroll the panel worker that published the release");
|
|
pruneBackups(id);
|
|
}
|
|
|
|
function begin(id, snapshotSources) {
|
|
const state = read();
|
|
if (state.pending?.id !== id || state.pending.phase !== "preparing") throw new Error("No panel update is being prepared");
|
|
checkBackupRoot(true);
|
|
fs.mkdirSync(path.join(backupRoot, id), { mode: 0o700 });
|
|
snapshot(id, INFO_FILE, !!updateTargetType(panelInfoFile));
|
|
snapshotSources?.();
|
|
const backupDir = getBackupDir(id);
|
|
const pending = { ...state.pending, phase: "applying" };
|
|
const { version, ignoredThrough } = pending;
|
|
const failure = { version, at: new Date().toISOString(), reason: "storage", restored: true, backupMayShareLiveFiles: true };
|
|
atomicWriteFileSync(path.join(backupDir, STORAGE_FAILURE_FILE), JSON.stringify({ ...state, pending: undefined, ignoredThrough, failure }), { mode: 0o600, durable: true });
|
|
atomicWriteFileSync(path.join(backupDir, STORAGE_RESTORING_FILE), JSON.stringify({
|
|
...state, pending: { ...pending, phase: "restoring", reason: "storage" },
|
|
}), { mode: 0o600, durable: true });
|
|
atomicWriteFileSync(path.join(backupDir, SHARED_SNAPSHOT_RESERVE), "", { mode: 0o600, durable: true });
|
|
atomicWriteFileSync(path.join(backupDir, UNUSED_SNAPSHOT_FILE), "", { mode: 0o600, durable: true });
|
|
syncPath(backupRoot);
|
|
write({ ...state, pending });
|
|
}
|
|
|
|
function setPhase(id, phase) {
|
|
const state = read();
|
|
if (state.pending?.id !== id) throw new Error("Panel update transaction changed");
|
|
if (phase === "restart") markSnapshotUsed(getBackupDir(id));
|
|
write({ ...state, pending: { ...state.pending, staged: undefined, stageDigest: undefined, phase, phaseAt: Date.now() } });
|
|
if (phase === "restart") pruneBackups(id);
|
|
}
|
|
|
|
function recordRestartAttempt(id, nextAt) {
|
|
const state = read();
|
|
const pending = state.pending;
|
|
if (pending?.id !== id || pending.phase !== "restart") throw new Error("No panel restart is pending");
|
|
pending.restartAttempts = (pending.restartAttempts || 0) + 1;
|
|
pending.restartNextAt = nextAt;
|
|
write(state);
|
|
return pending.restartAttempts;
|
|
}
|
|
|
|
function enrollTrial(id, worker, deadlineAt, publishing = false) {
|
|
const state = read();
|
|
const pending = state.pending;
|
|
if (pending?.id !== id || (publishing ? pending.phase !== "applying" || !pending.staged
|
|
: pending.staged || !["restart", "starting"].includes(pending.phase))) throw new Error("No panel trial to join");
|
|
const expected = pending.expectedWorkers || worker.expected || pending.cohort?.expected || 1;
|
|
const workers = pending.workers || [];
|
|
if (workers.length >= expected) return false;
|
|
if (pending.cohort?.appName && (worker.expected !== expected || workers.some(entry =>
|
|
!samePanelProcess(entry.supervisor, worker.supervisor) || entry.slot === worker.slot))) return false;
|
|
const deadline = pending.deadlineAt || deadlineAt;
|
|
if (!Number.isSafeInteger(deadline) || Date.now() >= deadline) throw new Error("The panel trial deadline expired before enrollment");
|
|
write({ ...state, pending: { ...pending, staged: undefined, stageDigest: undefined, phase: "starting", deadlineAt: deadline, expectedWorkers: expected, workers: [...workers, worker] } });
|
|
return true;
|
|
}
|
|
|
|
function joinTrial(id, worker, timeoutMs, deadlineAt = Date.now() + timeoutMs) {
|
|
return enrollTrial(id, worker, deadlineAt);
|
|
}
|
|
|
|
function readyTrial(id, worker) {
|
|
const state = read();
|
|
const pending = state.pending;
|
|
if (pending?.id !== id || pending.phase !== "starting" || trialHasFailed(pending)) return false;
|
|
const joined = pending.workers.find(entry => samePanelProcess(entry, worker));
|
|
if (!joined) return false;
|
|
const now = Date.now();
|
|
if (!joined.readyAt || now - joined.readyAt >= READY_REFRESH_MS) {
|
|
joined.readyAt = now;
|
|
write(state);
|
|
}
|
|
if (!trialIsReady(pending)) return false;
|
|
confirm(id);
|
|
return true;
|
|
}
|
|
|
|
function recover(id, reason) {
|
|
const state = read();
|
|
if (state.pending?.id !== id) return false;
|
|
try {
|
|
return replay(state, reason);
|
|
} catch (err) {
|
|
// adpanel:update-status - retain the attempted failure even if replacing the primary journal failed.
|
|
try {
|
|
try {
|
|
atomicWriteFileSync(recoveryErrorFile, JSON.stringify({ id, reason }), { mode: 0o600, durable: true });
|
|
} catch (statusErr) {
|
|
if (!RECOVERY_STORAGE_CODES.has(statusErr.code)) throw statusErr;
|
|
if (readRecord(recoveryErrorReserve)?.id === id) {
|
|
publishReservedRecord(recoveryErrorReserve, recoveryErrorFile);
|
|
} else if (readRecoveryError(id)) {
|
|
syncPath(backupRoot);
|
|
} else {
|
|
throw statusErr;
|
|
}
|
|
}
|
|
} catch (statusErr) {
|
|
logger.error("[panel-update] Could not record the failed recovery attempt:", statusErr);
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
function readRecoveryError(id) {
|
|
const failure = readRecord(recoveryErrorFile);
|
|
return failure?.id === id ? failure : undefined;
|
|
}
|
|
|
|
function replay(state, reason) {
|
|
const { id, version, ignoredThrough } = state.pending;
|
|
const failure = { version, at: new Date().toISOString(), reason, restored: null };
|
|
if (isUnpublishedUpdate(state.pending)) {
|
|
const reservation = path.join(backupRoot, PREFLIGHT_FAILURE_FILE);
|
|
if (state.pending.phase === "restart") {
|
|
// adpanel:update-abandon - an interrupted cleanup must not leave the stage eligible for trial.
|
|
try {
|
|
write({ ...state, pending: { ...state.pending, phase: "preparing", reason } });
|
|
} catch (err) {
|
|
if (!RECOVERY_STORAGE_CODES.has(err.code)) throw err;
|
|
publishReservedRecord(path.join(backupRoot, PREFLIGHT_DISCARDING_FILE));
|
|
}
|
|
}
|
|
withStorageReserve(() => {
|
|
discardStage(id);
|
|
fs.rmSync(path.join(backupRoot, id), { recursive: true, force: true });
|
|
syncPath(backupRoot);
|
|
});
|
|
try {
|
|
write({ ...state, pending: undefined, ignoredThrough, failure });
|
|
} catch (err) {
|
|
if (!RECOVERY_STORAGE_CODES.has(err.code)) throw err;
|
|
publishReservedRecord(reservation);
|
|
}
|
|
return true;
|
|
}
|
|
if (state.pending.workers?.some(isPanelWorkerAlive)) return null;
|
|
tryDiscardStage(id, stageId => withStorageReserve(() => discardStage(stageId)));
|
|
const backupDir = getBackupDir(id);
|
|
const restoring = { ...state.pending, phase: "restoring", reason };
|
|
if (state.pending.phase !== "restoring") {
|
|
try {
|
|
write({ ...state, pending: restoring });
|
|
} catch (err) {
|
|
if (!RECOVERY_STORAGE_CODES.has(err.code)) throw err;
|
|
publishReservedRecord(path.join(backupDir, STORAGE_RESTORING_FILE));
|
|
}
|
|
} else {
|
|
withStorageReserve(() => syncPath(backupRoot));
|
|
}
|
|
const journal = fs.readFileSync(path.join(backupDir, JOURNAL_FILE), "utf8");
|
|
const items = journal.split("\n").slice(0, -1).map((line) => {
|
|
const item = JSON.parse(line);
|
|
if (typeof item.existedBefore !== "boolean" || (item.directory && item.existedBefore)) {
|
|
throw new Error("Invalid panel update journal entry");
|
|
}
|
|
return { ...item, target: resolveTarget(item.relative) };
|
|
});
|
|
if (items[0]?.relative !== INFO_FILE) throw new Error("Panel update journal is missing its metadata snapshot");
|
|
const restorePathFile = path.join(backupDir, RESTORE_PATH_FILE);
|
|
const sharedSnapshot = path.join(backupDir, SHARED_SNAPSHOT_FILE);
|
|
const cleanExternalRestore = () => {
|
|
const previousRestore = readRecord(restorePathFile);
|
|
if (!previousRestore) return;
|
|
const temporary = resolveTarget(previousRestore.relative);
|
|
if (!/^\.update-restore-[a-f0-9-]{36}\.tmp$/.test(path.basename(temporary))) throw new Error("Invalid panel restore temporary");
|
|
if (checkPanelUpdateParent(panelRoot, temporary)) {
|
|
if (updateTargetType(temporary)) withStorageReserve(() => fs.unlinkSync(temporary));
|
|
withStorageReserve(() => syncPath(path.dirname(temporary)));
|
|
}
|
|
};
|
|
cleanExternalRestore();
|
|
let snapshotUsed = !updateTargetType(path.join(backupDir, UNUSED_SNAPSHOT_FILE));
|
|
const failed = rollbackPanelUpdateFiles(items, backupDir, logger, panelRoot, {
|
|
withStorageReserve,
|
|
beforeRestore: item => {
|
|
if (snapshotUsed || item.temporary) return;
|
|
// adpanel:update-retention - record a real replacement before replay can erase the evidence.
|
|
withStorageReserve(() => markSnapshotUsed(backupDir));
|
|
snapshotUsed = true;
|
|
},
|
|
beforeExternalCopy: temporary => {
|
|
cleanExternalRestore();
|
|
atomicWriteFileSync(restorePathFile, JSON.stringify({ relative: path.relative(panelRoot, temporary) }), { mode: 0o600, durable: true });
|
|
},
|
|
beforeSharedRestore: () => {
|
|
withStorageReserve(() => {
|
|
if (!updateTargetType(sharedSnapshot)) {
|
|
const reserve = path.join(backupDir, SHARED_SNAPSHOT_RESERVE);
|
|
if (updateTargetType(reserve)) fs.renameSync(reserve, sharedSnapshot);
|
|
else atomicWriteFileSync(sharedSnapshot, "", { mode: 0o600, durable: true });
|
|
}
|
|
syncPath(backupDir);
|
|
});
|
|
},
|
|
});
|
|
if (updateTargetType(sharedSnapshot)) failure.backupMayShareLiveFiles = true;
|
|
failure.restored = !failed;
|
|
if (!failed) withStorageReserve(() => retireConfirmation(id));
|
|
try {
|
|
write({ ...state, pending: failed ? { ...restoring, needsOperator: true } : undefined,
|
|
ignoredThrough: state.pending.ignoredThrough, failure });
|
|
} catch (err) {
|
|
if (failed || !RECOVERY_STORAGE_CODES.has(err.code)) throw err;
|
|
publishReservedRecord(path.join(backupDir, STORAGE_FAILURE_FILE));
|
|
}
|
|
if (!failed) pruneBackups(snapshotUsed ? id : undefined);
|
|
return !failed;
|
|
}
|
|
|
|
function confirm(id) {
|
|
const state = read();
|
|
if (state.pending?.id !== id || state.pending.phase !== "starting") throw new Error("No panel update is being verified");
|
|
const confirmation = {
|
|
...state, pending: { ...state.pending, phase: "committing", reason: "commit", receiptRequired: true },
|
|
};
|
|
atomicWriteFileSync(confirmPendingFile, JSON.stringify(confirmation), { mode: 0o600, durable: true });
|
|
write(confirmation);
|
|
const checkReady = () => {
|
|
if (!trialIsReady(state.pending)) throw new Error("The panel worker set did not stay ready through the commit");
|
|
};
|
|
checkReady();
|
|
// adpanel:update-confirm - the active record wins over a provisional verified state after a crash.
|
|
write({ ...state, pending: undefined, verified: { id, version: state.pending.version }, failure: state.pending.keepFailure ? state.failure : undefined,
|
|
ignoredThrough: state.pending.keepFailure ? state.ignoredThrough : undefined });
|
|
retireConfirmation(id, checkReady);
|
|
}
|
|
|
|
return { read, write, reservePreflightSpace, prepare, openStage, publishStagedRelease, begin, snapshot, setPhase, recordRestartAttempt, recover, readRecoveryError, joinTrial, readyTrial };
|
|
}
|
|
|
|
function failStartup(err) {
|
|
console.error("[panel-update] Panel startup failed:", err);
|
|
process.exit(1);
|
|
}
|
|
|
|
function disarmStartupWatchdog(trial) {
|
|
if (startupTrial !== trial) return;
|
|
startupTrial = undefined;
|
|
if (trial.watchdog?.connected) trial.watchdog.disconnect();
|
|
}
|
|
|
|
function armStartupWatchdog(trial, panelInfoFile, deadlineAt, beforeRestartTransition) {
|
|
const remainingMs = deadlineAt - Date.now();
|
|
if (remainingMs <= 0) throw new Error("Panel startup deadline expired before arming the watchdog");
|
|
const watchdog = fork(__filename, ["--watch-panel-startup", panelInfoFile, trial.id, String(deadlineAt), beforeRestartTransition ? "publish" : "trial"], {
|
|
stdio: ["ignore", "inherit", "inherit", "ipc"], execArgv: [],
|
|
});
|
|
trial.watchdog = watchdog;
|
|
// adpanel:update-watchdog - synchronous candidate startup must not run until the deadline is armed outside this worker.
|
|
return new Promise((resolve, reject) => {
|
|
let armed = false;
|
|
const fail = err => {
|
|
if (startupTrial !== trial) return;
|
|
clearTimeout(timer);
|
|
if (armed) return failStartup(err);
|
|
disarmStartupWatchdog(trial);
|
|
reject(err);
|
|
};
|
|
const timer = setTimeout(() => fail(new Error("Panel startup watchdog did not arm in time")), Math.min(remainingMs, WATCHDOG_ARM_TIMEOUT_MS));
|
|
watchdog.on("error", fail);
|
|
watchdog.once("exit", () => fail(new Error("Panel startup watchdog exited before verification")));
|
|
watchdog.once("disconnect", () => fail(new Error("Panel startup watchdog disconnected before verification")));
|
|
watchdog.once("message", message => {
|
|
if (startupTrial !== trial) return;
|
|
if (message !== "armed" || Date.now() >= deadlineAt) return fail(new Error("Panel startup watchdog did not arm in time"));
|
|
clearTimeout(timer);
|
|
armed = true;
|
|
resolve();
|
|
});
|
|
});
|
|
}
|
|
|
|
function markPanelUpdateReady(httpServer, httpsServer) {
|
|
const trial = startupTrial;
|
|
const listening = () => httpServer.listening && (!httpsServer || httpsServer.listening);
|
|
if (!trial || trial.timer || !listening()) return;
|
|
const checkReady = () => {
|
|
if (!listening()) return failStartup(new Error("Updated panel stopped listening during startup"));
|
|
let release;
|
|
try {
|
|
release = trial.mutex.tryAcquire();
|
|
if (release) {
|
|
const { verified } = trial.state.read();
|
|
if (verified?.id === trial.id || trial.state.readyTrial(trial.id, trial.worker)) {
|
|
disarmStartupWatchdog(trial);
|
|
return;
|
|
}
|
|
}
|
|
} catch (err) {
|
|
failStartup(err);
|
|
} finally {
|
|
release?.();
|
|
}
|
|
trial.timer = setTimeout(checkReady, TRIAL_POLL_MS);
|
|
};
|
|
trial.timer = setTimeout(checkReady, trial.settleMs);
|
|
}
|
|
|
|
async function launchPanel({
|
|
panelRoot = path.dirname(__dirname), timeoutMs = STARTUP_TIMEOUT_MS, settleMs = STARTUP_SETTLE_MS, recoverBeforeService = false,
|
|
} = {}) {
|
|
// adpanel:update-cohort - PM2 may respawn a parked reload slot before retiring it.
|
|
if (process.connected && process.env.pm_exec_path === __filename && /^_old_\d+$/.test(process.env.pm_id || "")) return;
|
|
const panelInfoFile = path.join(panelRoot, INFO_FILE);
|
|
const state = createPanelUpdateState(panelInfoFile);
|
|
const mutex = createPanelUpdateMutex(panelInfoFile, STARTUP_TIMEOUT_MS + 30_000);
|
|
const installedLauncher = panelRoot === path.dirname(__dirname);
|
|
const workerLease = installedLauncher ? createPanelWorkerLease(panelRoot, true) : null;
|
|
const generationLock = installedLauncher ? createPanelWorkerLease(panelRoot) : null;
|
|
for (;;) {
|
|
const release = await mutex.acquire();
|
|
let waiting = true;
|
|
try {
|
|
const { pending, verified } = state.read();
|
|
if (installedLauncher && !pending && !recoverBeforeService) {
|
|
try { state.reservePreflightSpace(); } catch (err) { console.warn("[panel-update] Could not reserve update recovery space:", err.message); }
|
|
}
|
|
const interruptedByReboot = wasInterruptedByReboot(pending);
|
|
const restartFailure = pending?.phase === "restart" && (getRestartRecoveryReason(pending) || state.readRecoveryError(pending.id)?.reason);
|
|
const trialEligible = pending && !interruptedByReboot && ((pending.phase === "restart" && !restartFailure) ||
|
|
(pending.phase === "starting" && !trialHasFailed(pending)));
|
|
if (recoverBeforeService && (!pending || trialEligible || pending.workers?.some(isPanelWorkerAlive))) return;
|
|
if (!pending) {
|
|
if (verified) syncPath(path.join(panelRoot, ".update-backups"));
|
|
waiting = false;
|
|
} else if (pending.phase === "restart" && !pending.cohort && isManagedPanelProcess()) {
|
|
if (!state.recover(pending.id, "interrupted")) throw new Error("Could not restore the pre-upgrade panel update");
|
|
waiting = false;
|
|
} else if (trialEligible && (pending.cohort?.previous.some(isPanelWorkerAlive) ||
|
|
(pending.phase === "restart" && !generationHasDrained(generationLock)))) {
|
|
// adpanel:update-cohort - PM2 omits parked reload workers, but their leases remain until exit.
|
|
} else if (trialEligible) {
|
|
let trial;
|
|
try {
|
|
const worker = identifyTrialWorker(pending.cohort);
|
|
const deadlineAt = pending.deadlineAt || Date.now() + timeoutMs;
|
|
trial = { id: pending.id, state, mutex, worker, settleMs };
|
|
const releaseGeneration = pending.staged ? generationLock?.tryAcquire() : null;
|
|
if (pending.staged && !releaseGeneration) throw new Error("The old panel generation has not drained");
|
|
try {
|
|
startupTrial = trial;
|
|
await armStartupWatchdog(trial, panelInfoFile, deadlineAt, pending.phase === "restart");
|
|
if (pending.staged) {
|
|
state.publishStagedRelease(pending.id, worker, deadlineAt);
|
|
waiting = false;
|
|
} else if (state.joinTrial(pending.id, worker, timeoutMs, deadlineAt)) {
|
|
waiting = false;
|
|
} else {
|
|
disarmStartupWatchdog(trial);
|
|
}
|
|
} finally {
|
|
releaseGeneration?.();
|
|
}
|
|
} catch (err) {
|
|
if (trial) disarmStartupWatchdog(trial);
|
|
console.error("[panel-update] Could not publish or enroll a panel trial worker:", err);
|
|
const reason = RECOVERY_STORAGE_CODES.has(err.code) ? "storage"
|
|
: err.code === "PANEL_UPDATE_INTEGRITY_FAILED" ? "integrity" : "startup";
|
|
const restored = state.recover(pending.id, reason);
|
|
if (restored === false || (restored === null && state.read().pending?.workers?.some(entry => entry.pid === process.pid))) throw err;
|
|
waiting = restored === null;
|
|
}
|
|
} else {
|
|
const reason = pending.reason || restartFailure || (pending.phase === "starting" ? "startup" : "interrupted");
|
|
const restored = state.recover(pending.id, reason);
|
|
if (restored === false) throw new Error("Panel update recovery could not restore all files");
|
|
waiting = restored === null;
|
|
}
|
|
if (!waiting) {
|
|
if (recoverBeforeService) return;
|
|
loadedUpdateId = startupTrial?.id || state.read().verified?.id || null;
|
|
const releaseWorker = workerLease?.tryAcquire();
|
|
if (workerLease && !releaseWorker) throw new Error("Could not register the panel worker's startup generation");
|
|
try {
|
|
launcherActive = true;
|
|
require(path.join(panelRoot, "index.js"));
|
|
return;
|
|
} catch (err) {
|
|
launcherActive = false;
|
|
releaseWorker?.();
|
|
throw err;
|
|
}
|
|
}
|
|
} finally {
|
|
release();
|
|
}
|
|
await delay(TRIAL_POLL_MS);
|
|
}
|
|
}
|
|
|
|
async function launchPanelAgent(panelRoot = path.dirname(__dirname)) {
|
|
const info = path.join(panelRoot, INFO_FILE);
|
|
const state = createPanelUpdateState(info);
|
|
const mutex = createPanelUpdateMutex(info, STARTUP_TIMEOUT_MS + 30_000);
|
|
const workerLease = createPanelWorkerLease(panelRoot, true);
|
|
for (;;) {
|
|
const release = await mutex.acquire();
|
|
try {
|
|
if (!state.read().pending) {
|
|
const releaseWorker = workerLease.tryAcquire();
|
|
if (!releaseWorker) throw new Error("Could not register the Agent worker's startup generation");
|
|
const shutdown = new AbortController();
|
|
const monitor = setInterval(() => {
|
|
try {
|
|
const { pending } = state.read();
|
|
if (!pending?.staged || pending.phase !== "restart") return;
|
|
} catch (err) {
|
|
console.error("[panel-update] Agent could not read the update record:", err);
|
|
return;
|
|
}
|
|
clearInterval(monitor);
|
|
// adpanel:update-cohort - the lease must survive until process exit, even if Agent does not finish stopping.
|
|
setTimeout(() => failStartup(new Error("Agent did not stop for the panel update")), AGENT_DRAIN_TIMEOUT_MS).unref();
|
|
shutdown.abort();
|
|
}, TRIAL_POLL_MS).unref();
|
|
try {
|
|
if (!require(path.join(panelRoot, "AgentWorker/feature-config.js")).readAgentFeatureConfig().enabled) {
|
|
clearInterval(monitor);
|
|
releaseWorker();
|
|
return;
|
|
}
|
|
return require(path.join(panelRoot, "AgentWorker/worker.js")).main({ updateSignal: shutdown.signal });
|
|
} catch (err) {
|
|
clearInterval(monitor);
|
|
releaseWorker();
|
|
throw err;
|
|
}
|
|
}
|
|
} finally {
|
|
release();
|
|
}
|
|
await delay(TRIAL_POLL_MS);
|
|
}
|
|
}
|
|
|
|
function watchPanelStartup(panelInfoFile, id, deadlineAt, publishing) {
|
|
const remainingMs = deadlineAt - Date.now();
|
|
if (!process.connected || !BACKUP_ID.test(id) || !Number.isSafeInteger(deadlineAt) || remainingMs <= 0) return;
|
|
const parentPid = process.ppid;
|
|
const state = createPanelUpdateState(panelInfoFile);
|
|
const stopIfFailed = (expired = false) => {
|
|
if (!process.connected || process.ppid !== parentPid) return;
|
|
try {
|
|
const { pending } = state.read();
|
|
if (pending?.id !== id) return;
|
|
if (!expired && publishing && ["preparing", "applying", "restart"].includes(pending.phase)) return;
|
|
if (!expired && ["starting", "committing"].includes(pending.phase) && !trialHasFailed(pending)) return;
|
|
if (state.read().pending?.id !== id) return;
|
|
} catch (err) {
|
|
console.error("[panel-update] Could not read the trial state:", err);
|
|
}
|
|
console.error("[panel-update] Stopping an unverified panel worker so recovery can proceed.");
|
|
try {
|
|
process.kill(parentPid, "SIGKILL");
|
|
} catch (err) {
|
|
if (err.code !== "ESRCH") throw err;
|
|
}
|
|
};
|
|
const watcher = setInterval(stopIfFailed, TRIAL_POLL_MS);
|
|
const deadline = setTimeout(stopIfFailed, remainingMs, true);
|
|
process.once("disconnect", () => {
|
|
clearInterval(watcher);
|
|
clearTimeout(deadline);
|
|
});
|
|
process.send("armed", err => { if (err && process.connected) process.disconnect(); });
|
|
}
|
|
|
|
module.exports = {
|
|
createPanelUpdateMutex, createPanelUpdateState, rollbackPanelUpdateFiles, writePanelUpdateFileNoFollow, checkPanelUpdateParent, writePanelUpdateInfo,
|
|
createPanelScaleMutex, panelWorkerIdentity, getRestartRecoveryReason, isUnpublishedUpdate, trialHasFailed, RESTART_RECOVERY_MS,
|
|
launchPanel, markPanelUpdateReady, getLoadedUpdateId: () => loadedUpdateId,
|
|
isManagedRecoveryLauncher: () => launcherActive && isManagedPanelProcess(),
|
|
};
|
|
|
|
if (require.main === module || process.env.pm_exec_path === __filename) {
|
|
if (process.argv[2] === "--watch-panel-startup") watchPanelStartup(process.argv[3], process.argv[4], Number(process.argv[5]), process.argv[6] === "publish");
|
|
else if (process.argv[2] === "--can-autoscale") process.exitCode = canAutoscale(path.dirname(__dirname)) ? 0 : 1;
|
|
else if (process.argv[2] === "--agent") launchPanelAgent().catch(failStartup);
|
|
else launchPanel({ recoverBeforeService: ["--recover-before-service", "--recover-after-reboot"].includes(process.argv[2]) }).catch(failStartup);
|
|
} |