This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { access, readFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { envName, latestSuccess, recordsRoot, snapshotRoot } from './release-store.mjs';
|
||||
|
||||
const environment = envName(process.env.RELEASE_ENVIRONMENT);
|
||||
const commitSha = process.env.RELEASE_SHA;
|
||||
const record = await latestSuccess(environment, 'nacos');
|
||||
if (!commitSha || record.commitSha !== commitSha || record.status !== 'success') throw new Error(`没有提交 ${commitSha} 对应的成功 Nacos 发布`);
|
||||
if (!record.activeSnapshotId || !record.snapshotId || !Array.isArray(record.files) || record.files.length === 0 || record.files.some((file) => !file.sha256 || !file.dataId || !file.namespace)) throw new Error('Nacos 发布记录不完整');
|
||||
const destinations = environment === 'prod' ? ['prod-center1', 'prod-center2'] : [environment];
|
||||
for (const destination of destinations) for (const file of record.files) {
|
||||
const path = join(snapshotRoot(environment, record.activeSnapshotId), destination, file.namespace, 'DEFAULT_GROUP', file.dataId);
|
||||
const content = await readFile(path, 'utf8');
|
||||
if (createHash('sha256').update(content, 'utf8').digest('hex') !== file.sha256) throw new Error(`Nacos 发布快照摘要不匹配:${destination}/${file.namespace}/${file.dataId}`);
|
||||
}
|
||||
await access(join(recordsRoot(environment), 'latest-success-nacos.json'));
|
||||
console.log(JSON.stringify(record));
|
||||
@@ -0,0 +1,20 @@
|
||||
const workflow = process.argv[2];
|
||||
const ref = process.argv[3] || process.env.GITHUB_REF_NAME;
|
||||
if (!workflow || !ref) throw new Error('用法:node dispatch-workflow.mjs <workflow.yml> <ref>');
|
||||
const token = process.env.GITHUB_TOKEN;
|
||||
if (!token) throw new Error('缺少 GITHUB_TOKEN');
|
||||
const server = process.env.GITHUB_SERVER_URL || 'http://192.168.5.15:3000';
|
||||
const repository = process.env.GITHUB_REPOSITORY || 'xiaowang/JayuCloud';
|
||||
const inputs = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.startsWith('DISPATCH_INPUT_')).map(([key, value]) => [key.slice('DISPATCH_INPUT_'.length).toLowerCase(), value]));
|
||||
if (process.env.AUTO_ROLLBACK === 'true') inputs.auto_rollback = 'true';
|
||||
const isNacosRollback = /^rollback-(dev|sit|prod)-nacos\.yml$/.test(workflow);
|
||||
if (isNacosRollback && !inputs.snapshot_id && process.env.RELEASE_STORE_ROOT && (process.env.RELEASE_ENVIRONMENT || process.env.NACOS_ENVIRONMENT)) {
|
||||
try { inputs.snapshot_id = JSON.parse(await (await import('node:fs/promises')).readFile(`${process.env.RELEASE_STORE_ROOT}/records/${process.env.RELEASE_ENVIRONMENT || process.env.NACOS_ENVIRONMENT}/pending-nacos.json`, 'utf8')).snapshotId; } catch {}
|
||||
}
|
||||
if (isNacosRollback && process.env.AUTO_ROLLBACK === 'true' && !inputs.snapshot_id) {
|
||||
console.log('没有待处理的 Nacos 发布快照,无需触发 Nacos 回退');
|
||||
process.exit(0);
|
||||
}
|
||||
const response = await fetch(`${server}/api/v1/repos/${repository}/actions/workflows/${workflow}/dispatches`, { method: 'POST', headers: { Authorization: `token ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ ref, inputs }) });
|
||||
if (!response.ok && response.status !== 204) throw new Error(`触发 ${workflow} 失败:HTTP ${response.status} ${await response.text()}`);
|
||||
console.log(`已触发 ${workflow} @ ${ref}`);
|
||||
@@ -1,133 +1,75 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFile, readdir } from 'node:fs/promises';
|
||||
import { mkdir, readFile, readdir, rm } from 'node:fs/promises';
|
||||
import { join, relative, sep } from 'node:path';
|
||||
import { atomicWrite, envName, listYamlFiles, recordsRoot, snapshotRoot, writeJson } from './release-store.mjs';
|
||||
|
||||
const repositoryRoot = process.cwd();
|
||||
const target = requiredNacosTarget('NACOS_ENVIRONMENT');
|
||||
const environment = envName(process.env.NACOS_ENVIRONMENT);
|
||||
const group = 'DEFAULT_GROUP';
|
||||
const configRoot = join(repositoryRoot, 'nacos', 'namespaces', target.environment);
|
||||
const configFiles = await collectYamlFiles(configRoot);
|
||||
|
||||
if (configFiles.length === 0) {
|
||||
throw new Error(`nacos/namespaces/${target.environment} 下没有可发布的 YAML 配置`);
|
||||
}
|
||||
|
||||
for (const destination of target.destinations) {
|
||||
await publishDestination(destination, configFiles);
|
||||
}
|
||||
|
||||
async function publishDestination(destination, files) {
|
||||
const nacosUrls = requiredEnvironment(`${destination.prefix}_URLS`).split(',').map((value) => normalizeNacosBaseUrl(value.trim())).filter(Boolean);
|
||||
if (nacosUrls.length < destination.verificationNodeCount) {
|
||||
throw new Error(`${destination.name} 至少需要 ${destination.verificationNodeCount} 个 Nacos 地址用于发布校验`);
|
||||
}
|
||||
const username = requiredEnvironment(`${destination.prefix}_USERNAME`);
|
||||
const password = requiredEnvironment(`${destination.prefix}_PASSWORD`);
|
||||
const token = await login(nacosUrls[0], username, password);
|
||||
for (const filePath of files) {
|
||||
const root = join(repositoryRoot, 'nacos', 'namespaces', destination.environment);
|
||||
const relativePath = relative(root, filePath).split(sep);
|
||||
if (relativePath.length !== 3 || relativePath[1] !== group) {
|
||||
throw new Error(`配置路径必须是 <namespace>/${group}/<dataId>.yaml:${relativePath.join('/')}`);
|
||||
}
|
||||
const [namespace, , dataId] = relativePath;
|
||||
const content = await readFile(filePath, 'utf8');
|
||||
await publish(nacosUrls[0], token, namespace, group, dataId, content);
|
||||
await verify(nacosUrls.slice(0, destination.verificationNodeCount), token, namespace, group, dataId, content);
|
||||
console.log(`已发布并校验 ${destination.name}/${namespace}/${group}/${dataId}`);
|
||||
const root = process.cwd();
|
||||
const configRoot = join(root, 'nacos', 'namespaces', environment);
|
||||
const files = await listYamlFiles(configRoot);
|
||||
if (!files.length) throw new Error(`没有可发布的 ${environment} YAML 配置`);
|
||||
const destinations = (environment === 'prod' ? [['NACOS_PROD', 'prod-center1', 2], ['NACOS_DR', 'prod-center2', 1]] : [[environment === 'dev' ? 'NACOS_DEV' : 'NACOS_SIT', environment, 1]]).map(([prefix, id, nodes]) => {
|
||||
const urls = required(`${prefix}_URLS`).split(',').map(normalize).filter(Boolean);
|
||||
if (urls.length < nodes) throw new Error(`${prefix} Nacos 地址不足`);
|
||||
return { prefix, id, urls, token: null, nodes };
|
||||
});
|
||||
for (const destination of destinations) destination.token = await login(destination.urls[0], required(`${destination.prefix}_USERNAME`), required(`${destination.prefix}_PASSWORD`));
|
||||
const groupName = group;
|
||||
const runId = process.env.GITHUB_RUN_ID || 'manual';
|
||||
const commitSha = process.env.GITHUB_SHA || 'unknown';
|
||||
const recordRoot = recordsRoot(environment);
|
||||
const snapshotId = `${new Date().toISOString().replaceAll(/[:.]/g, '-')}-${runId}`;
|
||||
const releaseId = `${environment}-${commitSha.slice(0, 12)}-${runId}`;
|
||||
const snapshot = snapshotRoot(environment, snapshotId);
|
||||
const activeSnapshotId = `active-${releaseId}`;
|
||||
const activeSnapshot = snapshotRoot(environment, activeSnapshotId);
|
||||
await mkdir(snapshot, { recursive: true });
|
||||
await mkdir(activeSnapshot, { recursive: true });
|
||||
const entries = [];
|
||||
for (const file of files) {
|
||||
const { namespace, dataId } = info(file);
|
||||
const content = await readFile(file, 'utf8');
|
||||
const entry = { namespace, dataId, sha256: sha256(content), previousSha256: {}, previousExists: {} };
|
||||
entries.push(entry);
|
||||
for (const destination of destinations) {
|
||||
const response = await fetch(`${destination.urls[0]}/nacos/v1/cs/configs?${new URLSearchParams({ dataId, group: groupName, tenant: namespace, accessToken: destination.token })}`);
|
||||
if (!response.ok && response.status !== 404) throw new Error(`读取当前 Nacos 配置失败:${destination.prefix}/${namespace}/${dataId} HTTP ${response.status}`);
|
||||
const oldContent = await response.text();
|
||||
entry.previousExists[destination.id] = response.status !== 404;
|
||||
entry.previousSha256[destination.id] = sha256(oldContent);
|
||||
await atomicWrite(join(snapshot, destination.id, namespace, groupName, dataId), oldContent);
|
||||
await atomicWrite(join(activeSnapshot, destination.id, namespace, groupName, dataId), content);
|
||||
}
|
||||
}
|
||||
|
||||
function requiredEnvironment(name) {
|
||||
const value = process.env[name];
|
||||
if (!value) {
|
||||
throw new Error(`缺少环境变量 ${name}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function normalizeNacosBaseUrl(value) {
|
||||
return value.replace(/\/+$/, '').replace(/\/nacos$/, '');
|
||||
}
|
||||
|
||||
function requiredNacosTarget(name) {
|
||||
const value = requiredEnvironment(name);
|
||||
const destinations = {
|
||||
dev: [{ name: 'dev', environment: 'dev', prefix: 'NACOS_DEV', verificationNodeCount: 1 }],
|
||||
sit: [{ name: 'sit', environment: 'sit', prefix: 'NACOS_SIT', verificationNodeCount: 1 }],
|
||||
'prod-center1': [{ name: 'prod-center1', environment: 'prod', prefix: 'NACOS_PROD', verificationNodeCount: 2 }],
|
||||
'prod-center2': [{ name: 'prod-center2', environment: 'prod', prefix: 'NACOS_DR', verificationNodeCount: 1 }],
|
||||
'prod-both': [
|
||||
{ name: 'prod-center1', environment: 'prod', prefix: 'NACOS_PROD', verificationNodeCount: 2 },
|
||||
{ name: 'prod-center2', environment: 'prod', prefix: 'NACOS_DR', verificationNodeCount: 1 },
|
||||
],
|
||||
}[value];
|
||||
if (!destinations) {
|
||||
throw new Error(`不支持的 Nacos 发布目标:${value}`);
|
||||
}
|
||||
return { environment: destinations[0].environment, destinations };
|
||||
}
|
||||
|
||||
async function collectYamlFiles(directory) {
|
||||
const entries = await readdir(directory, { withFileTypes: true });
|
||||
const files = [];
|
||||
for (const entry of entries) {
|
||||
const entryPath = join(directory, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
files.push(...await collectYamlFiles(entryPath));
|
||||
} else if (entry.isFile() && entry.name.endsWith('.yaml')) {
|
||||
files.push(entryPath);
|
||||
await writeJson(join(recordRoot, 'pending-nacos.json'), { environment, snapshotId, activeSnapshotId, commitSha, runId, releaseId, files: entries, createdAt: new Date().toISOString() });
|
||||
try {
|
||||
for (const file of files) {
|
||||
const { namespace, dataId } = info(file);
|
||||
const content = await readFile(file, 'utf8');
|
||||
for (const destination of destinations) {
|
||||
const response = await fetch(`${destination.urls[0]}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(destination.token)}`, { method: 'POST', body: new URLSearchParams({ dataId, group: groupName, tenant: namespace, type: 'yaml', content }) });
|
||||
const result = await response.text();
|
||||
if (!response.ok || result.trim() !== 'true') throw new Error(`发布失败:${destination.prefix}/${namespace}/${dataId} HTTP ${response.status}`);
|
||||
await verify(destination, namespace, dataId, content);
|
||||
}
|
||||
}
|
||||
return files.sort();
|
||||
const previous = await optionalJson(join(recordRoot, 'latest-success-nacos.json'));
|
||||
const record = { environment, status: 'success', commitSha, runId, releaseId, snapshotId, activeSnapshotId, previousReleaseId: previous?.releaseId || null, files: entries, publishedAt: new Date().toISOString() };
|
||||
await writeJson(join(recordRoot, 'latest-success-nacos.json'), record);
|
||||
await writeJson(join(recordRoot, 'nacos', `${releaseId}.json`), record);
|
||||
await rm(join(recordRoot, 'pending-nacos.json'), { force: true });
|
||||
console.log(`已发布并校验 ${environment} Nacos,回退快照 ${snapshotId}`);
|
||||
} catch (error) {
|
||||
console.error(error.message);
|
||||
console.error(`AUTO_ROLLBACK_SNAPSHOT_ID=${snapshotId}`);
|
||||
throw error;
|
||||
}
|
||||
|
||||
async function login(baseUrl, user, secret) {
|
||||
const body = new URLSearchParams({ username: user, password: secret });
|
||||
const response = await fetch(`${baseUrl}/nacos/v1/auth/login`, { method: 'POST', body });
|
||||
if (!response.ok) {
|
||||
throw new Error(`Nacos 登录失败:${baseUrl} HTTP ${response.status}`);
|
||||
}
|
||||
const payload = await response.json();
|
||||
if (!payload.accessToken) {
|
||||
throw new Error(`Nacos 登录响应缺少 accessToken:${baseUrl}`);
|
||||
}
|
||||
return payload.accessToken;
|
||||
}
|
||||
|
||||
async function publish(baseUrl, token, namespace, configGroup, dataId, content) {
|
||||
const body = new URLSearchParams({ dataId, group: configGroup, tenant: namespace, type: 'yaml', content });
|
||||
const response = await fetch(`${baseUrl}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(token)}`, { method: 'POST', body });
|
||||
const result = await response.text();
|
||||
if (!response.ok || result.trim() !== 'true') {
|
||||
throw new Error(`Nacos 发布失败:${baseUrl}/${namespace}/${dataId} HTTP ${response.status} ${result}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function verify(baseUrls, token, namespace, configGroup, dataId, expectedContent) {
|
||||
const expectedHash = sha256(expectedContent);
|
||||
for (const baseUrl of baseUrls) {
|
||||
const query = new URLSearchParams({ dataId, group: configGroup, tenant: namespace });
|
||||
let lastStatus = 0;
|
||||
let lastContent = '';
|
||||
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
||||
const response = await fetch(`${baseUrl}/nacos/v1/cs/configs?${query}&accessToken=${encodeURIComponent(token)}`);
|
||||
const content = await response.text();
|
||||
lastStatus = response.status;
|
||||
lastContent = content;
|
||||
if (response.ok && sha256(content) === expectedHash) {
|
||||
break;
|
||||
}
|
||||
if (attempt < 3) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}
|
||||
}
|
||||
if (lastStatus !== 200 || sha256(lastContent) !== expectedHash) {
|
||||
throw new Error(`Nacos 配置校验失败:${baseUrl}/${namespace}/${dataId} HTTP ${lastStatus} ${lastContent.slice(0, 200)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function sha256(value) {
|
||||
return createHash('sha256').update(value, 'utf8').digest('hex');
|
||||
}
|
||||
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'); }
|
||||
function info(file) { const parts = relative(configRoot, file).split(sep); if (parts.length !== 2) throw new Error(`配置路径无效:${file}`); return { namespace: parts[0], dataId: parts[1] }; }
|
||||
async function optionalJson(path) { try { return JSON.parse(await readFile(path, 'utf8')); } 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; }
|
||||
async function verify(destination, namespace, dataId, expected) { const expectedHash = sha256(expected); for (const base of destination.urls) { let status = 0; let content = ''; for (let attempt = 0; attempt < 3; attempt += 1) { const response = await fetch(`${base}/nacos/v1/cs/configs?${new URLSearchParams({ dataId, group: groupName, tenant: namespace, accessToken: destination.token })}`); status = response.status; content = await response.text(); if (status === 200 && sha256(content) === expectedHash) break; await new Promise((resolve) => setTimeout(resolve, 1000)); } if (status !== 200 || sha256(content) !== expectedHash) throw new Error(`Nacos 校验失败:${destination.prefix}/${base}/${namespace}/${dataId}`); } }
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFile, readdir } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { envName, latestSuccess, recordsRoot, writeJson } from './release-store.mjs';
|
||||
|
||||
const environment = envName(process.env.RELEASE_ENVIRONMENT);
|
||||
const commitSha = process.env.RELEASE_SHA;
|
||||
const nacos = await latestSuccess(environment, 'nacos');
|
||||
const packageDir = process.env.PACKAGE_DIRECTORY;
|
||||
if (!commitSha || nacos.commitSha !== commitSha || !packageDir) throw new Error('部署记录参数不完整');
|
||||
if (nacos.status !== 'success' || !nacos.files?.length || !nacos.activeSnapshotId) throw new Error('Nacos 发布已回退或发布记录不完整');
|
||||
const manifestPath = await findFile(packageDir, 'manifest.json');
|
||||
const manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
|
||||
const artifactPaths = {};
|
||||
for (const [name, fileName] of Object.entries({ core: 'JC-Salon-Core.jar', gateway: 'JC-Salon-Gateway.jar', frontend: 'jc-salon-frontend-dist.tar.gz' })) {
|
||||
const artifactPath = await findFile(packageDir, fileName);
|
||||
const sha256 = createHash('sha256').update(await readFile(artifactPath)).digest('hex');
|
||||
const expected = manifest.artifacts?.find((item) => item.Path?.endsWith(fileName))?.Sha256?.toLowerCase();
|
||||
if (!expected || expected !== sha256) throw new Error(`发布包摘要不匹配:${fileName}`);
|
||||
artifactPaths[name] = { path: artifactPath, sha256 };
|
||||
}
|
||||
const previous = await optional(join(recordsRoot(environment), 'latest-success-deploy.json'));
|
||||
const releaseId = `${environment}-${commitSha.slice(0, 12)}-${process.env.GITHUB_RUN_ID || 'manual'}`;
|
||||
const record = { environment, status: 'success', commitSha, releaseId, nacosReleaseId: nacos.releaseId, snapshotId: nacos.snapshotId, activeSnapshotId: nacos.activeSnapshotId, packageDir, manifestPath, artifacts: artifactPaths, previousReleaseId: previous?.releaseId || null, runId: process.env.GITHUB_RUN_ID || 'manual', deployedAt: new Date().toISOString() };
|
||||
await writeJson(join(recordsRoot(environment), 'deploy', `${releaseId}.json`), record);
|
||||
await writeJson(join(recordsRoot(environment), 'latest-success-deploy.json'), record);
|
||||
console.log(JSON.stringify(record));
|
||||
async function optional(path) { try { return JSON.parse(await readFile(path, 'utf8')); } catch { return null; } }
|
||||
async function findFile(root, name) {
|
||||
for (const entry of await readdir(root, { withFileTypes: true })) {
|
||||
const path = join(root, entry.name);
|
||||
if (entry.isDirectory()) { const nested = await optionalFind(path, name); if (nested) return nested; }
|
||||
else if (entry.name === name) return path;
|
||||
}
|
||||
throw new Error(`发布包缺少 ${name}`);
|
||||
}
|
||||
async function optionalFind(root, name) { try { return await findFile(root, name); } catch { return null; } }
|
||||
@@ -0,0 +1,10 @@
|
||||
import { join } from 'node:path';
|
||||
import { envName, recordsRoot, readJson, writeJson } from './release-store.mjs';
|
||||
|
||||
const environment = envName(process.env.RELEASE_ENVIRONMENT);
|
||||
const releaseId = process.env.ROLLBACK_RELEASE_ID;
|
||||
if (!releaseId) throw new Error('缺少 ROLLBACK_RELEASE_ID');
|
||||
const record = await readJson(join(recordsRoot(environment), 'deploy', `${releaseId}.json`));
|
||||
if (record.status !== 'success' || !record.packageDir || !record.activeSnapshotId) throw new Error('目标回退版本记录不完整');
|
||||
await writeJson(join(recordsRoot(environment), 'latest-success-deploy.json'), { ...record, restoredAt: new Date().toISOString() });
|
||||
console.log(`已将 ${environment} 成功版本指针更新到 ${releaseId}`);
|
||||
@@ -0,0 +1,62 @@
|
||||
import { mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
|
||||
export const storeRoot = process.env.RELEASE_STORE_ROOT || '/salon-release';
|
||||
|
||||
export function envName(value = process.env.NACOS_ENVIRONMENT) {
|
||||
if (!['dev', 'sit', 'prod'].includes(value)) throw new Error(`不支持的环境:${value}`);
|
||||
return value;
|
||||
}
|
||||
|
||||
export function environmentRoot(environment = envName()) {
|
||||
return join(storeRoot, environment);
|
||||
}
|
||||
|
||||
export function snapshotRoot(environment = envName(), snapshotId) {
|
||||
return join(storeRoot, 'nacos-snapshots', environment, snapshotId);
|
||||
}
|
||||
|
||||
export function recordsRoot(environment = envName()) {
|
||||
return join(storeRoot, 'records', environment);
|
||||
}
|
||||
|
||||
export async function atomicWrite(path, content) {
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
const temp = `${path}.tmp-${process.pid}-${Date.now()}`;
|
||||
await writeFile(temp, content, 'utf8');
|
||||
await rename(temp, path);
|
||||
}
|
||||
|
||||
export async function readJson(path) {
|
||||
return JSON.parse(await readFile(path, 'utf8'));
|
||||
}
|
||||
|
||||
export async function writeJson(path, value) {
|
||||
await atomicWrite(path, `${JSON.stringify(value, null, 2)}\n`);
|
||||
}
|
||||
|
||||
export async function latestSuccess(environment = envName(), kind = 'nacos') {
|
||||
const path = join(recordsRoot(environment), `latest-success-${kind}.json`);
|
||||
return readJson(path);
|
||||
}
|
||||
|
||||
export async function releaseRecord(environment, kind, releaseId) {
|
||||
return readJson(join(recordsRoot(environment), kind, `${releaseId}.json`));
|
||||
}
|
||||
|
||||
export async function listYamlFiles(root) {
|
||||
const result = [];
|
||||
for (const entry of await readdir(root, { withFileTypes: true })) {
|
||||
const path = join(root, entry.name);
|
||||
if (entry.isDirectory()) result.push(...await listYamlFiles(path));
|
||||
else if (entry.isFile() && entry.name.endsWith('.yaml')) result.push(path);
|
||||
}
|
||||
return result.sort();
|
||||
}
|
||||
|
||||
export function safeRelative(root, path) {
|
||||
const value = resolve(path);
|
||||
const base = resolve(root);
|
||||
if (!value.startsWith(`${base}/`) && !value.startsWith(`${base}\\`)) throw new Error(`路径越界:${path}`);
|
||||
return value.slice(base.length + 1).replaceAll('\\', '/');
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
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';
|
||||
|
||||
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 check = await fetch(`${base}/nacos/v1/cs/configs?${new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, accessToken: target.token })}`);
|
||||
const actual = await check.text();
|
||||
if (exists ? (!check.ok || sha256(actual) !== sha256(content)) : check.status !== 404) 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; }
|
||||
Reference in New Issue
Block a user