80 lines
6.2 KiB
JavaScript
80 lines
6.2 KiB
JavaScript
import { createHash } from 'node:crypto';
|
||
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 environment = envName(process.env.NACOS_ENVIRONMENT);
|
||
const group = 'DEFAULT_GROUP';
|
||
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);
|
||
}
|
||
}
|
||
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);
|
||
}
|
||
}
|
||
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;
|
||
}
|
||
|
||
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 !== 3 || parts[1] !== group || !parts[0] || !parts[2]) throw new Error(`配置路径无效,必须为 namespace/${group}/dataId:${file}`);
|
||
return { namespace: parts[0], dataId: parts[2] };
|
||
}
|
||
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}`); } }
|