/** * CLB aideiver 辅助:查看目标、单活/双活、改权重。 * * Usage: * node server/scripts/tencent-clb-rolling.mjs status * node server/scripts/tencent-clb-rolling.mjs ensure-single # 仅 test-h5 + test-api(推荐) * node server/scripts/tencent-clb-rolling.mjs ensure-dual # 恢复双活(历史) * node server/scripts/tencent-clb-rolling.mjs weight --group api --instance api1 --weight 0 * node server/scripts/tencent-clb-rolling.mjs weight --group api --instance api --weight 10 * node server/scripts/tencent-clb-rolling.mjs weight --group h5 --instance h51 --weight 0 * * 设计:docs/design/20260909-prod-single-h5-api.md */ import { loadTencentCredentials, tc3Request } from './tencent-lib.mjs'; const REGION = 'ap-nanjing'; const LB_ID = 'lb-3g4yhjra'; const HTTPS_LISTENER = 'lbl-85u2icys'; const INSTANCES = { h5: { InstanceId: 'ins-9zdly5wm', Port: 80, Name: 'test-h5' }, h51: { InstanceId: 'ins-hvq9s3gi', Port: 80, Name: 'test-h51' }, api: { InstanceId: 'ins-dn3v0znu', Port: 3001, Name: 'test-api' }, api1: { InstanceId: 'ins-bzgxnhke', Port: 3001, Name: 'test-api1' }, }; const LOCATIONS = { h5: [ { domain: 'www.xdjchuanhui.com', url: '/', locationId: 'loc-1gs88zca' }, { domain: 'xdjchuanhui.com', url: '/', locationId: 'loc-43aiswp6' }, ], api: [ { domain: 'www.xdjchuanhui.com', url: '/api', locationId: 'loc-rno70k0w' }, { domain: 'xdjchuanhui.com', url: '/api', locationId: 'loc-muasnngi' }, ], }; function sleep(ms) { return new Promise((r) => setTimeout(r, ms)); } function parseArgs(argv) { const out = { _: [] }; for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (a.startsWith('--')) { const key = a.slice(2); const val = argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[++i] : true; out[key] = val; } else { out._.push(a); } } return out; } async function clb(cred, action, payload) { let lastErr; for (let attempt = 1; attempt <= 12; attempt++) { const json = await tc3Request({ ...cred, service: 'clb', region: REGION, version: '2018-03-17', action, payload, }); if (!json.Response?.Error) return json.Response; const e = json.Response.Error; lastErr = new Error(`${action}: ${e.Code} ${e.Message}`); if (/ResourceInOperating|try later|try again/i.test(`${e.Code} ${e.Message}`)) { console.warn(` busy (${attempt}/12), wait...`); await sleep(5000); continue; } throw lastErr; } throw lastErr; } async function waitTask(cred, taskId) { if (!taskId || String(taskId).includes('-')) return; for (let i = 0; i < 60; i++) { const r = await clb(cred, 'DescribeTaskStatus', { TaskId: String(taskId) }); if (r.Status === 0) return; if (r.Status === 2) throw new Error(`Task failed TaskId=${taskId}`); await sleep(2000); } } async function describeTargets(cred) { return clb(cred, 'DescribeTargets', { LoadBalancerId: LB_ID, ListenerIds: [HTTPS_LISTENER], }); } function printStatus(desc) { for (const l of desc.Listeners || []) { console.log(`LISTENER ${l.ListenerId} ${l.Protocol || ''} ${l.Port || ''}`); for (const r of l.Rules || []) { const targets = (r.Targets || []).map((t) => { const name = Object.values(INSTANCES).find((x) => x.InstanceId === t.InstanceId)?.Name || t.InstanceId; return `${name}:${t.Port} w=${t.Weight}`; }); console.log(` ${r.Domain}${r.Url} [${r.LocationId}] => ${targets.join(', ') || '(empty)'}`); } } } async function ensureRegistered(cred, group, instanceKey) { const inst = INSTANCES[instanceKey]; if (!inst) throw new Error(`Unknown instance ${instanceKey}`); const locs = LOCATIONS[group]; if (!locs) throw new Error(`Unknown group ${group}`); const desc = await describeTargets(cred); for (const loc of locs) { const rule = (desc.Listeners || []) .flatMap((l) => l.Rules || []) .find((r) => r.LocationId === loc.locationId); const current = rule?.Targets || []; const exists = current.some( (t) => t.InstanceId === inst.InstanceId && Number(t.Port) === inst.Port ); if (exists) { console.log(`OK already on ${loc.domain}${loc.url}: ${inst.Name}`); continue; } console.log(`Register ${inst.Name} on ${loc.domain}${loc.url}...`); const r = await clb(cred, 'RegisterTargets', { LoadBalancerId: LB_ID, ListenerId: HTTPS_LISTENER, LocationId: loc.locationId, Targets: [ { Type: 'CVM', InstanceId: inst.InstanceId, Port: inst.Port, Weight: 10, }, ], }); await waitTask(cred, r.TaskId); await sleep(3000); } } async function setWeight(cred, group, instanceKey, weight) { const inst = INSTANCES[instanceKey]; if (!inst) throw new Error(`Unknown instance ${instanceKey}`); const locs = LOCATIONS[group]; if (!locs) throw new Error(`Unknown group ${group}`); const w = Math.max(0, Math.min(100, Number(weight))); if (!Number.isFinite(w)) throw new Error(`Invalid weight ${weight}`); for (const loc of locs) { console.log(`Weight ${inst.Name} -> ${w} on ${loc.domain}${loc.url}`); const r = await clb(cred, 'ModifyTargetWeight', { LoadBalancerId: LB_ID, ListenerId: HTTPS_LISTENER, LocationId: loc.locationId, Targets: [ { Type: 'CVM', InstanceId: inst.InstanceId, Port: inst.Port, Weight: w, }, ], }); await waitTask(cred, r.TaskId); } } async function deregisterInstance(cred, group, instanceKey) { const inst = INSTANCES[instanceKey]; if (!inst) throw new Error(`Unknown instance ${instanceKey}`); const locs = LOCATIONS[group]; if (!locs) throw new Error(`Unknown group ${group}`); const desc = await describeTargets(cred); for (const loc of locs) { const rule = (desc.Listeners || []) .flatMap((l) => l.Rules || []) .find((r) => r.LocationId === loc.locationId); const current = rule?.Targets || []; const exists = current.some( (t) => t.InstanceId === inst.InstanceId && Number(t.Port) === inst.Port ); if (!exists) { console.log(`Already off ${loc.domain}${loc.url}: ${inst.Name}`); continue; } console.log(`Deregister ${inst.Name} from ${loc.domain}${loc.url}...`); const r = await clb(cred, 'DeregisterTargets', { LoadBalancerId: LB_ID, ListenerId: HTTPS_LISTENER, LocationId: loc.locationId, Targets: [ { Type: 'CVM', InstanceId: inst.InstanceId, Port: inst.Port, }, ], }); await waitTask(cred, r.TaskId); await sleep(3000); } } async function main() { const args = parseArgs(process.argv.slice(2)); const cmd = args._[0] || 'status'; const cred = loadTencentCredentials(); if (cmd === 'status') { printStatus(await describeTargets(cred)); return; } if (cmd === 'ensure-single' || cmd === 'ensure-single-api' || cmd === 'ensure-single-h5') { const doH5 = cmd === 'ensure-single' || cmd === 'ensure-single-h5'; const doApi = cmd === 'ensure-single' || cmd === 'ensure-single-api'; if (doH5) { console.log('Ensure single H5 (test-h5 only); keep test-h51 CVM but off CLB...'); await ensureRegistered(cred, 'h5', 'h5'); await setWeight(cred, 'h5', 'h5', 10); await deregisterInstance(cred, 'h5', 'h51'); } if (doApi) { console.log('Ensure single API (test-api only); keep test-api1 CVM but off CLB...'); await ensureRegistered(cred, 'api', 'api'); await setWeight(cred, 'api', 'api', 10); await deregisterInstance(cred, 'api', 'api1'); } console.log('\nAfter ensure-single:'); printStatus(await describeTargets(cred)); return; } if (cmd === 'ensure-dual' || cmd === 'ensure-dual-api' || cmd === 'ensure-dual-h5') { const doH5 = cmd === 'ensure-dual' || cmd === 'ensure-dual-h5'; const doApi = cmd === 'ensure-dual' || cmd === 'ensure-dual-api'; if (doH5) { console.log('Ensure dual H5 on HTTPS listener...'); await ensureRegistered(cred, 'h5', 'h5'); await ensureRegistered(cred, 'h5', 'h51'); await setWeight(cred, 'h5', 'h5', 10); await setWeight(cred, 'h5', 'h51', 10); } if (doApi) { console.log('Ensure dual API on HTTPS listener...'); await ensureRegistered(cred, 'api', 'api'); await ensureRegistered(cred, 'api', 'api1'); await setWeight(cred, 'api', 'api', 10); await setWeight(cred, 'api', 'api1', 10); } console.log('\nAfter ensure:'); printStatus(await describeTargets(cred)); return; } if (cmd === 'weight') { const group = String(args.group || ''); const instance = String(args.instance || ''); const weight = args.weight; if (!group || !instance || weight === undefined) { throw new Error('Usage: weight --group api|h5 --instance api|api1|h5|h51 --weight N'); } await setWeight(cred, group, instance, weight); printStatus(await describeTargets(cred)); return; } throw new Error(`Unknown command: ${cmd}`); } main().catch((err) => { console.error(err instanceof Error ? err.message : err); process.exit(1); });