Files
JayuCloud/.gitea/scripts/rollback-nacos.mjs
T

68 lines
5.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { createHash } from 'node:crypto';
import { readFile, readdir, rm } from 'node:fs/promises';
import { join } from 'node:path';
import { envName, recordsRoot, snapshotRoot, writeJson } from './release-store.mjs';
import { verifyConfigReadback } from './nacos-readback.mjs';
const environment = envName(process.env.NACOS_ENVIRONMENT);
const group = 'DEFAULT_GROUP';
const destinations = environment === 'prod' ? [['NACOS_PROD', 'prod-center1'], ['NACOS_DR', 'prod-center2']] : [[environment === 'dev' ? 'NACOS_DEV' : 'NACOS_SIT', environment]];
const targets = [];
for (const [prefix, id] of destinations) {
const urls = required(`${prefix}_URLS`).split(',').map(normalize).filter(Boolean);
if (!urls.length) throw new Error(`${prefix}_URLS 为空`);
targets.push({ prefix, id, urls, token: await login(urls[0], required(`${prefix}_USERNAME`), required(`${prefix}_PASSWORD`)) });
}
const root = recordsRoot(environment);
const pending = await optional(join(root, 'pending-nacos.json'));
const latest = await optional(join(root, 'latest-success-nacos.json'));
let selected = process.env.NACOS_RELEASE_ID
? await optional(join(root, 'nacos', `${process.env.NACOS_RELEASE_ID}.json`))
: null;
if (process.env.NACOS_RELEASE_ID && !selected) throw new Error(`找不到 Nacos 发布记录:${process.env.NACOS_RELEASE_ID}`);
if (!process.env.NACOS_SNAPSHOT_ID && !pending && !selected && latest?.previousReleaseId) selected = await optional(join(root, 'nacos', `${latest.previousReleaseId}.json`));
const snapshotId = process.env.NACOS_SNAPSHOT_ID || (selected ? selected.activeSnapshotId : pending?.snapshotId || latest?.snapshotId);
if (!snapshotId) throw new Error(`没有 ${environment} Nacos 回退快照`);
if (!selected && !pending) selected = await findSnapshotRecord(join(root, 'nacos'), snapshotId);
const snapshot = snapshotRoot(environment, snapshotId);
const entries = selected?.files || pending?.files || latest?.files || [];
const selectedIsActive = selected?.activeSnapshotId === snapshotId;
if (!entries.length) throw new Error('回退记录缺少配置清单');
for (const target of targets) {
for (const entry of entries) {
for (const base of target.urls) {
const exists = selectedIsActive || entry.previousExists?.[target.id] !== false;
const path = join(snapshot, target.id, entry.namespace, group, entry.dataId);
const content = exists ? await readFile(path, 'utf8') : '';
const expectedHash = selectedIsActive ? entry.sha256 : entry.previousSha256?.[target.id];
if (exists && (!expectedHash || sha256(content) !== expectedHash)) throw new Error(`回退快照摘要不匹配:${target.id}/${entry.namespace}/${entry.dataId}`);
const query = new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, accessToken: target.token });
const response = exists
? await fetch(`${base}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(target.token)}`, { method: 'POST', body: new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, type: 'yaml', content }) })
: await fetch(`${base}/nacos/v1/cs/configs?${query}`, { method: 'DELETE' });
if (!response.ok || (exists && (await response.text()).trim() !== 'true')) throw new Error(`回退失败:${target.id}/${entry.namespace}/${entry.dataId}`);
const checkUrl = `${base}/nacos/v1/cs/configs?${new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, accessToken: target.token })}`;
if (!(await verifyConfigReadback(checkUrl, content, exists))) throw new Error(`回退摘要校验失败:${target.id}/${entry.namespace}/${entry.dataId}`);
}
}
}
await writeJson(join(root, 'last-rollback.json'), { environment, snapshotId, source: process.env.AUTO_ROLLBACK === 'true' ? 'automatic' : 'manual', rollbackAt: new Date().toISOString() });
if (selectedIsActive && selected) await writeJson(join(root, 'latest-success-nacos.json'), selected);
await rm(join(root, 'pending-nacos.json'), { force: true });
console.log(`已回退 ${environment} Nacos:${snapshotId}`);
function required(name) { if (!process.env[name]) throw new Error(`缺少环境变量 ${name}`); return process.env[name]; }
function normalize(value) { return value.replace(/\/+$/, '').replace(/\/nacos$/, ''); }
function sha256(value) { return createHash('sha256').update(value, 'utf8').digest('hex'); }
async function optional(path) { try { return JSON.parse(await readFile(path, 'utf8')); } catch { return null; } }
async function findSnapshotRecord(directory, id) {
try {
for (const file of await readdir(directory)) {
if (!file.endsWith('.json')) continue;
const record = await optional(join(directory, file));
if (record?.snapshotId === id || record?.activeSnapshotId === id) return record;
}
} catch {}
return null;
}
async function login(base, user, password) { const response = await fetch(`${base}/nacos/v1/auth/login`, { method: 'POST', body: new URLSearchParams({ username: user, password }) }); if (!response.ok) throw new Error(`Nacos 登录失败:HTTP ${response.status}`); const result = await response.json(); if (!result.accessToken) throw new Error('Nacos 登录响应缺少 accessToken'); return result.accessToken; }