fix: make Ops gateway resilient to Synology reboot
This commit is contained in:
@@ -0,0 +1,145 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { cp, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||
const sourceRoot = resolve(scriptDir, "..");
|
||||
const artifactRoot = resolve(
|
||||
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(sourceRoot, "deploy-artifacts"),
|
||||
);
|
||||
const artifactId = "ops-agents-reboot-resilience-20260809-001";
|
||||
const component = "ops-agents";
|
||||
const files = [
|
||||
"docker-compose.synology.yml",
|
||||
"src/db/wait-for-database.test.ts",
|
||||
"src/db/wait-for-database.ts",
|
||||
"src/scripts/migrate.ts",
|
||||
];
|
||||
const predecessors = {
|
||||
"docker-compose.synology.yml": "e78d37368c3d255f257086773ba908e44aae2e475661b80ee17f98c3d55d178f",
|
||||
"src/scripts/migrate.ts": "8396a42deded31f1fe2381f772838a33b05bfd389075ebd34a5f546593f08769",
|
||||
};
|
||||
const newPaths = [
|
||||
"src/db/wait-for-database.test.ts",
|
||||
"src/db/wait-for-database.ts",
|
||||
];
|
||||
|
||||
await mkdir(artifactRoot, { recursive: true });
|
||||
const artifact = join(artifactRoot, `nodedc-${artifactId}.tgz`);
|
||||
const predecessorPath = join(artifactRoot, `nodedc-${artifactId}.predecessor.sha256`);
|
||||
const newPathsPath = join(artifactRoot, `nodedc-${artifactId}.new-paths`);
|
||||
await Promise.all([artifact, predecessorPath, newPathsPath].map(assertFresh));
|
||||
|
||||
const stage = await mkdtemp(join(tmpdir(), "nodedc-ops-agents-reboot-resilience-"));
|
||||
const payload = join(stage, "payload");
|
||||
|
||||
try {
|
||||
await mkdir(payload, { recursive: true });
|
||||
for (const relativePath of files) {
|
||||
validateRelativePath(relativePath);
|
||||
const source = join(sourceRoot, relativePath);
|
||||
const info = await lstat(source);
|
||||
if (!info.isFile() || info.isSymbolicLink()) {
|
||||
throw new Error(`invalid_source_file:${relativePath}`);
|
||||
}
|
||||
await mkdir(dirname(join(payload, relativePath)), { recursive: true });
|
||||
await cp(source, join(payload, relativePath), { force: false });
|
||||
}
|
||||
|
||||
await writeFile(
|
||||
join(stage, "manifest.env"),
|
||||
`id=${artifactId}\ncomponent=${component}\ntype=app-overlay\n`,
|
||||
"utf8",
|
||||
);
|
||||
await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
|
||||
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
|
||||
|
||||
const productionRoot = "/volume1/docker/nodedc-platform/ops-agents";
|
||||
await writeFile(
|
||||
predecessorPath,
|
||||
`${Object.entries(predecessors)
|
||||
.map(([relativePath, digest]) => `${digest} ${productionRoot}/${relativePath}`)
|
||||
.join("\n")}\n`,
|
||||
"utf8",
|
||||
);
|
||||
await writeFile(
|
||||
newPathsPath,
|
||||
`${newPaths.map((relativePath) => `${productionRoot}/${relativePath}`).join("\n")}\n`,
|
||||
"utf8",
|
||||
);
|
||||
|
||||
const artifactBytes = await readFile(artifact);
|
||||
console.log(JSON.stringify({
|
||||
ok: true,
|
||||
artifactId,
|
||||
component,
|
||||
artifact,
|
||||
artifactSha256: sha256(artifactBytes),
|
||||
files,
|
||||
predecessors,
|
||||
newPaths,
|
||||
expectedService: "agent-gateway",
|
||||
expectedHealthcheck: "http://172.22.0.222:18190/readyz",
|
||||
runnerChanged: false,
|
||||
databaseVolumeSelected: false,
|
||||
}, null, 2));
|
||||
} finally {
|
||||
await rm(stage, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
async function assertFresh(path) {
|
||||
try {
|
||||
await lstat(path);
|
||||
} catch (error) {
|
||||
if (error?.code === "ENOENT") return;
|
||||
throw error;
|
||||
}
|
||||
throw new Error(`output_already_exists:${path}`);
|
||||
}
|
||||
|
||||
function validateRelativePath(value) {
|
||||
if (
|
||||
typeof value !== "string"
|
||||
|| !value
|
||||
|| value.startsWith("/")
|
||||
|| value.split("/").some((part) => !part || part === "." || part === "..")
|
||||
) {
|
||||
throw new Error(`unsafe_relative_path:${value}`);
|
||||
}
|
||||
}
|
||||
|
||||
function canonicalTarScript() {
|
||||
return [
|
||||
"import gzip,io,pathlib,sys,tarfile",
|
||||
"root=pathlib.Path(sys.argv[2])",
|
||||
"with open(sys.argv[1],'wb') as out:",
|
||||
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
|
||||
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
|
||||
" for top in ('manifest.env','files.txt','payload'):",
|
||||
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
|
||||
" for x in paths:",
|
||||
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
|
||||
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
|
||||
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function run(command, args) {
|
||||
const result = spawnSync(command, args, {
|
||||
encoding: "utf8",
|
||||
maxBuffer: 128 * 1024 * 1024,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
|
||||
}
|
||||
}
|
||||
|
||||
function sha256(bytes) {
|
||||
return createHash("sha256").update(bytes).digest("hex");
|
||||
}
|
||||
Reference in New Issue
Block a user