|
|
|
|
@ -0,0 +1,820 @@
|
|
|
|
|
import { toast } from './toast.js?v=2026100802';
|
|
|
|
|
|
|
|
|
|
const byId = id => document.getElementById(id);
|
|
|
|
|
const state = {
|
|
|
|
|
csrfToken: '', userId: '', regions: [], instances: [], vpcs: [],
|
|
|
|
|
selectedKey: '', selected: null, busy: false, stopped: false, detailDirty: false,
|
|
|
|
|
listEpoch: 0, detailEpoch: 0, listController: null, detailController: null,
|
|
|
|
|
pollTimer: 0,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const STATUS_LABELS = Object.freeze({
|
|
|
|
|
applying: '应用中', waiting: '等待宿主机回读', uncertain: '结果待核对',
|
|
|
|
|
degraded: '部分失败', active: '已生效', deleting: '清理中', unknown: '状态未知',
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
function element(tag, className = '', textContent = '') {
|
|
|
|
|
const node = document.createElement(tag);
|
|
|
|
|
if (className) node.className = className;
|
|
|
|
|
if (textContent !== '') node.textContent = String(textContent);
|
|
|
|
|
return node;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function field(label, value, className = '') {
|
|
|
|
|
const wrapper = element('div', `vpc-fact ${className}`.trim());
|
|
|
|
|
wrapper.append(element('dt', '', label), element('dd', '', value));
|
|
|
|
|
return wrapper;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function setError(message = '') {
|
|
|
|
|
const node = byId('vpc-page-error');
|
|
|
|
|
if (!node) return;
|
|
|
|
|
node.textContent = message;
|
|
|
|
|
node.hidden = !message;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function setNotice(message = '', kind = '') {
|
|
|
|
|
const node = byId('vpc-page-notice');
|
|
|
|
|
if (!node) return;
|
|
|
|
|
node.textContent = message;
|
|
|
|
|
node.className = `vpc-notice ${kind}`.trim();
|
|
|
|
|
node.hidden = !message;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function setFormError(id, message = '') {
|
|
|
|
|
const node = byId(id);
|
|
|
|
|
if (!node) return;
|
|
|
|
|
node.textContent = message;
|
|
|
|
|
node.hidden = !message;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function secureTransportRequired() {
|
|
|
|
|
return location.protocol !== 'https:'
|
|
|
|
|
&& !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function api(path, options = {}) {
|
|
|
|
|
const method = String(options.method || 'GET').toUpperCase();
|
|
|
|
|
const headers = new Headers({ Accept: 'application/json', ...(options.headers || {}) });
|
|
|
|
|
if (!['GET', 'HEAD'].includes(method)) {
|
|
|
|
|
if (secureTransportRequired()) throw new Error('请通过 HTTPS 修改 VPC 私网配置。');
|
|
|
|
|
if (!state.csrfToken) throw new Error('会话安全令牌缺失,请刷新页面。');
|
|
|
|
|
headers.set('X-CSRF-Token', state.csrfToken);
|
|
|
|
|
headers.set('Content-Type', 'application/json');
|
|
|
|
|
}
|
|
|
|
|
const response = await fetch(path, {
|
|
|
|
|
method, headers, credentials: 'same-origin', cache: 'no-store',
|
|
|
|
|
signal: options.signal,
|
|
|
|
|
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
|
|
|
|
});
|
|
|
|
|
let payload = null;
|
|
|
|
|
try { payload = response.status === 204 ? null : await response.json(); }
|
|
|
|
|
catch { throw new Error('服务返回了非 JSON 数据,请检查 PHP 及反代配置。'); }
|
|
|
|
|
if (response.status === 401) {
|
|
|
|
|
location.assign('/auth/login');
|
|
|
|
|
throw new Error('登录已过期。');
|
|
|
|
|
}
|
|
|
|
|
if (!response.ok || payload?.ret === 0) {
|
|
|
|
|
const detail = Array.isArray(payload?.detail)
|
|
|
|
|
? payload.detail.map(item => item?.msg || '输入错误').join(';') : payload?.detail;
|
|
|
|
|
throw new Error(String(detail || payload?.message || payload?.error
|
|
|
|
|
|| `请求失败 (${response.status})`));
|
|
|
|
|
}
|
|
|
|
|
return payload;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function requestKey(prefix) {
|
|
|
|
|
const uuid = typeof crypto?.randomUUID === 'function'
|
|
|
|
|
? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
|
|
|
return `${prefix}-${uuid}`.slice(0, 128);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function entityKey() {
|
|
|
|
|
const value = typeof crypto?.randomUUID === 'function'
|
|
|
|
|
? crypto.randomUUID().replaceAll('-', '')
|
|
|
|
|
: `${Date.now()}${Math.random().toString(16).slice(2)}`;
|
|
|
|
|
return value.replace(/[^a-f0-9]/gi, '').toLowerCase().padEnd(32, '0').slice(0, 32);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function safeText(value, fallback = '—') {
|
|
|
|
|
const text = value === null || value === undefined ? '' : String(value).trim();
|
|
|
|
|
return text || fallback;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function rootStatus(root) {
|
|
|
|
|
const sync = String(root?.sync_state || '').toLowerCase();
|
|
|
|
|
const raw = String(root?.state || '').toLowerCase();
|
|
|
|
|
if (root?.usable === true) return 'active';
|
|
|
|
|
if (sync === 'waiting' || sync === 'waiting_observed') return 'waiting';
|
|
|
|
|
if (sync === 'uncertain' || raw === 'uncertain') return 'uncertain';
|
|
|
|
|
if (raw === 'degraded' || sync === 'failed') return 'degraded';
|
|
|
|
|
if (raw === 'deleting') return 'deleting';
|
|
|
|
|
if (raw === 'applying' || ['pending', 'queued', 'running'].includes(sync)) return 'applying';
|
|
|
|
|
return raw === 'active' ? 'uncertain' : (raw || 'unknown');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function childStatus(value) {
|
|
|
|
|
const raw = String(value || '').toLowerCase();
|
|
|
|
|
return ['active', 'applying', 'waiting', 'uncertain', 'degraded', 'deleting', 'deleted']
|
|
|
|
|
.includes(raw) ? raw : 'unknown';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function statusPill(status, extra = '') {
|
|
|
|
|
const normalized = status === 'waiting_observed' ? 'waiting' : String(status || 'unknown');
|
|
|
|
|
const pill = element('span', `vpc-state-pill ${normalized}`.trim(),
|
|
|
|
|
STATUS_LABELS[normalized] || normalized);
|
|
|
|
|
if (extra) pill.title = extra;
|
|
|
|
|
return pill;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function errorLabel(code) {
|
|
|
|
|
return {
|
|
|
|
|
vpc_no_members: 'VPC 已创建;加入至少一个实例后才会应用私网数据面。',
|
|
|
|
|
vpc_data_plane_deferred: 'Fabric 已就绪,正在等待私网数据面回读。',
|
|
|
|
|
vpc_observation_incomplete: '宿主机回读尚未完整,请稍后核对。',
|
|
|
|
|
}[String(code || '')] || '';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function regionName(regionId) {
|
|
|
|
|
const row = state.regions.find(item => Number(item.id) === Number(regionId));
|
|
|
|
|
return row ? safeText(row.name, `地区 ${regionId}`) : `地区 ${regionId || '未知'}`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function instanceName(instanceId) {
|
|
|
|
|
const row = state.instances.find(item => Number(item.id) === Number(instanceId));
|
|
|
|
|
return row ? safeText(row.name, `实例 #${instanceId}`) : `实例 #${instanceId}`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function instanceRegion(instanceId) {
|
|
|
|
|
const row = state.instances.find(item => Number(item.id) === Number(instanceId));
|
|
|
|
|
return row ? safeText(row.region, '地区待核验') : '地区待核验';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function normalizeRoot(value) {
|
|
|
|
|
if (!value || typeof value !== 'object') return null;
|
|
|
|
|
return {
|
|
|
|
|
...value,
|
|
|
|
|
vpc_key: String(value.vpc_key || ''),
|
|
|
|
|
name: String(value.name || '未命名 VPC'),
|
|
|
|
|
cidr: String(value.cidr || ''),
|
|
|
|
|
region_id: Number(value.region_id || 0),
|
|
|
|
|
desired_revision: Number(value.desired_revision || 0),
|
|
|
|
|
observed_revision: Number(value.observed_revision || 0),
|
|
|
|
|
last_error_code: value.last_error_code ? String(value.last_error_code) : '',
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function normalizeDocument(value) {
|
|
|
|
|
if (!value || typeof value !== 'object') return null;
|
|
|
|
|
const root = normalizeRoot(value.vpc);
|
|
|
|
|
if (!root) return null;
|
|
|
|
|
return {
|
|
|
|
|
vpc: root,
|
|
|
|
|
subnets: Array.isArray(value.subnets) ? value.subnets : [],
|
|
|
|
|
members: Array.isArray(value.members) ? value.members : [],
|
|
|
|
|
routes: Array.isArray(value.routes) ? value.routes : [],
|
|
|
|
|
acl_rules: Array.isArray(value.acl_rules) ? value.acl_rules : [],
|
|
|
|
|
operations: Array.isArray(value.operations) ? value.operations : [],
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function needsPolling() {
|
|
|
|
|
return state.vpcs.some(vpc => rootStatus(vpc) !== 'active')
|
|
|
|
|
|| (state.selected && rootStatus(state.selected.vpc) !== 'active');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function markDetailDirty() {
|
|
|
|
|
if (state.detailDirty) return;
|
|
|
|
|
state.detailDirty = true;
|
|
|
|
|
setNotice('详情中有未保存修改,自动状态核对已暂停。', 'warning');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function confirmDetailMutation() {
|
|
|
|
|
return !state.detailDirty
|
|
|
|
|
|| confirm('当前 VPC 有未保存修改,继续操作会丢失这些修改。继续吗?');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function clearDetailDirty() {
|
|
|
|
|
state.detailDirty = false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function refreshRouteEditorState() {
|
|
|
|
|
const editor = byId('vpc-route-editor');
|
|
|
|
|
if (!editor) return;
|
|
|
|
|
const allowed = new Set((state.selected?.members || [])
|
|
|
|
|
.filter(item => !['deleting', 'deleted'].includes(childStatus(item.state)))
|
|
|
|
|
.map(item => String(item.private_ip || '')));
|
|
|
|
|
for (const row of editor.querySelectorAll('.vpc-editor-row')) {
|
|
|
|
|
const value = row.querySelector('[data-route-field="next_hop_ip"]')?.value || '';
|
|
|
|
|
if (!value || !allowed.has(String(value))) row.dataset.invalid = 'true';
|
|
|
|
|
else delete row.dataset.invalid;
|
|
|
|
|
}
|
|
|
|
|
const blocked = Boolean(editor.querySelector('[data-vpc-tombstone-state="deleting"]'));
|
|
|
|
|
const save = document.querySelector('[data-vpc-save="routes"]');
|
|
|
|
|
if (save) save.disabled = state.busy || blocked
|
|
|
|
|
|| Boolean(editor.querySelector('[data-invalid="true"]'));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function schedulePoll(delay = needsPolling() ? 8000 : 30000) {
|
|
|
|
|
clearTimeout(state.pollTimer);
|
|
|
|
|
if (state.stopped || document.visibilityState === 'hidden') return;
|
|
|
|
|
state.pollTimer = window.setTimeout(async () => {
|
|
|
|
|
if (state.stopped || document.visibilityState === 'hidden') return;
|
|
|
|
|
if (state.busy) { schedulePoll(1500); return; }
|
|
|
|
|
await loadList(true);
|
|
|
|
|
if (state.selectedKey && !state.detailDirty) {
|
|
|
|
|
await loadDetail(state.selectedKey, true);
|
|
|
|
|
}
|
|
|
|
|
schedulePoll();
|
|
|
|
|
}, delay);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function renderSummary() {
|
|
|
|
|
const active = state.vpcs.filter(item => rootStatus(item) === 'active').length;
|
|
|
|
|
const attention = state.vpcs.length - active;
|
|
|
|
|
byId('vpc-stat-total').textContent = String(state.vpcs.length);
|
|
|
|
|
byId('vpc-stat-active').textContent = String(active);
|
|
|
|
|
byId('vpc-stat-attention').textContent = String(attention);
|
|
|
|
|
byId('vpc-list-caption').textContent = state.vpcs.length
|
|
|
|
|
? `${state.vpcs.length} 个 VPC · 状态每 ${needsPolling() ? '8' : '30'} 秒自动核对`
|
|
|
|
|
: '还没有已创建的 VPC';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function renderList() {
|
|
|
|
|
const container = byId('vpc-list');
|
|
|
|
|
container.replaceChildren();
|
|
|
|
|
const rows = state.vpcs.map(root => {
|
|
|
|
|
const row = element('button', `vpc-list-row${root.vpc_key === state.selectedKey ? ' selected' : ''}`);
|
|
|
|
|
row.type = 'button';
|
|
|
|
|
row.dataset.vpcKey = root.vpc_key;
|
|
|
|
|
const main = element('span', 'vpc-list-main');
|
|
|
|
|
const heading = element('span', 'vpc-list-heading');
|
|
|
|
|
heading.append(element('strong', '', root.name), statusPill(rootStatus(root), root.last_error_code));
|
|
|
|
|
main.append(heading, element('small', '', `${root.cidr} · ${regionName(root.region_id)}`));
|
|
|
|
|
const meta = element('span', 'vpc-list-meta');
|
|
|
|
|
meta.append(element('small', '', `目标 revision ${root.desired_revision || 0}`),
|
|
|
|
|
element('small', '', root.usable === true ? '宿主机回读已确认' : '等待实际回读'));
|
|
|
|
|
row.append(main, meta);
|
|
|
|
|
return row;
|
|
|
|
|
});
|
|
|
|
|
container.append(...rows);
|
|
|
|
|
byId('vpc-list-empty').hidden = rows.length !== 0;
|
|
|
|
|
byId('vpc-list-reconcile').disabled = !state.selectedKey || state.busy
|
|
|
|
|
|| rootStatus(state.vpcs.find(item => item.vpc_key === state.selectedKey)) === 'active';
|
|
|
|
|
renderSummary();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function section(title, description, className = '') {
|
|
|
|
|
const card = element('section', `vpc-subpanel ${className}`.trim());
|
|
|
|
|
const header = element('div', 'vpc-subpanel-heading');
|
|
|
|
|
header.append(element('div', '', ''), element('span', 'vpc-subpanel-count', ''));
|
|
|
|
|
header.firstChild.append(element('h3', '', title), element('p', '', description));
|
|
|
|
|
card.append(header);
|
|
|
|
|
return card;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function button(label, className = 'button button-outline small') {
|
|
|
|
|
const node = element('button', className, label);
|
|
|
|
|
node.type = 'button';
|
|
|
|
|
return node;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function input(labelText, value = '', type = 'text', placeholder = '') {
|
|
|
|
|
const wrapper = element('div', 'field');
|
|
|
|
|
const id = `vpc-field-${Math.random().toString(16).slice(2)}`;
|
|
|
|
|
const label = element('label', '', labelText);
|
|
|
|
|
const control = document.createElement(type === 'select' ? 'select' : 'input');
|
|
|
|
|
control.id = id;
|
|
|
|
|
if (type !== 'select') {
|
|
|
|
|
control.type = type; control.value = value === null ? '' : String(value);
|
|
|
|
|
if (placeholder) control.placeholder = placeholder;
|
|
|
|
|
}
|
|
|
|
|
label.htmlFor = id;
|
|
|
|
|
wrapper.append(label, control);
|
|
|
|
|
return { wrapper, control };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function renderDetail() {
|
|
|
|
|
const container = byId('vpc-detail');
|
|
|
|
|
const doc = state.selected;
|
|
|
|
|
if (!doc) { container.replaceChildren(); return; }
|
|
|
|
|
const root = doc.vpc;
|
|
|
|
|
container.replaceChildren();
|
|
|
|
|
byId('vpc-detail-title').textContent = root.name;
|
|
|
|
|
byId('vpc-detail-caption').textContent = `${root.cidr} · ${regionName(root.region_id)}`;
|
|
|
|
|
|
|
|
|
|
const overview = element('section', 'vpc-detail-overview');
|
|
|
|
|
const overviewHeading = element('div', 'vpc-detail-overview-heading');
|
|
|
|
|
const status = rootStatus(root);
|
|
|
|
|
const rootHint = errorLabel(root.last_error_code);
|
|
|
|
|
overviewHeading.append(statusPill(status, root.last_error_code),
|
|
|
|
|
element('span', 'vpc-readback-note', root.usable === true
|
|
|
|
|
? 'WireGuard、私网路由和实例网卡均已回读确认。'
|
|
|
|
|
: (rootHint || '配置仍在宿主机应用或核对,期间不要重复创建同一成员。')));
|
|
|
|
|
const actions = element('div', 'vpc-detail-actions');
|
|
|
|
|
const reconcile = button('核对 / 重试', 'button button-primary small');
|
|
|
|
|
reconcile.dataset.vpcAction = 'reconcile'; reconcile.disabled = state.busy || status === 'active';
|
|
|
|
|
actions.append(reconcile);
|
|
|
|
|
overviewHeading.append(actions);
|
|
|
|
|
const facts = element('dl', 'vpc-facts');
|
|
|
|
|
facts.append(field('VPC CIDR', root.cidr), field('地区', regionName(root.region_id)),
|
|
|
|
|
field('目标 revision', root.desired_revision || 0), field('已观测 revision', root.observed_revision || 0),
|
|
|
|
|
field('同步状态', safeText(root.sync_state)), field('最近错误', root.last_error_code || '无'));
|
|
|
|
|
overview.append(overviewHeading, facts);
|
|
|
|
|
container.append(overview);
|
|
|
|
|
|
|
|
|
|
container.append(renderSubnets(doc));
|
|
|
|
|
container.append(renderMembers(doc));
|
|
|
|
|
container.append(renderRoutes(doc));
|
|
|
|
|
container.append(renderAcl(doc));
|
|
|
|
|
container.append(renderOperations(doc));
|
|
|
|
|
clearDetailDirty();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function renderSubnets(doc) {
|
|
|
|
|
const card = section('子网与 CIDR', '子网是 VPC 内的地址范围;当前数据面使用成员精确 /32,不自动提供网关。', 'vpc-subnets');
|
|
|
|
|
const form = element('form', 'vpc-inline-form'); form.dataset.vpcForm = 'subnet';
|
|
|
|
|
const cidr = input('新增子网 CIDR', '', 'text', '10.40.1.0/24');
|
|
|
|
|
cidr.control.name = 'cidr'; cidr.control.required = true; cidr.control.maxLength = 18;
|
|
|
|
|
const save = button('添加子网', 'button button-primary small'); save.type = 'submit';
|
|
|
|
|
form.append(cidr.wrapper, save); card.append(form);
|
|
|
|
|
const list = element('div', 'vpc-row-list');
|
|
|
|
|
for (const row of doc.subnets) {
|
|
|
|
|
const item = element('div', 'vpc-data-row');
|
|
|
|
|
const copy = element('div', 'vpc-row-copy');
|
|
|
|
|
copy.append(element('strong', '', row.cidr || '未知子网'), element('small', '', `状态:${STATUS_LABELS[childStatus(row.state)] || safeText(row.state)}`));
|
|
|
|
|
if (row.last_error_code) copy.append(element('small', 'vpc-row-error', row.last_error_code));
|
|
|
|
|
const remove = button('删除', 'button button-outline small danger');
|
|
|
|
|
remove.dataset.vpcRemoveSubnet = row.subnet_key;
|
|
|
|
|
remove.disabled = state.busy || ['deleting', 'deleted'].includes(childStatus(row.state));
|
|
|
|
|
item.append(copy, remove); list.append(item);
|
|
|
|
|
}
|
|
|
|
|
if (!doc.subnets.length) list.append(element('p', 'vpc-empty-inline', '暂无子网。'));
|
|
|
|
|
card.append(list); return card;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function renderMembers(doc) {
|
|
|
|
|
const card = section('成员与私网 IP', '把同一地区的实例加入 VPC;私网 IP 由 PHP 租约账本分配并在宿主机回读后生效。', 'vpc-members');
|
|
|
|
|
const form = element('form', 'vpc-inline-form vpc-member-form'); form.dataset.vpcForm = 'member';
|
|
|
|
|
const subnet = input('加入子网', '', 'select'); subnet.control.name = 'subnet_key'; subnet.control.required = true;
|
|
|
|
|
for (const row of doc.subnets.filter(item => !['deleting', 'deleted'].includes(childStatus(item.state)))) {
|
|
|
|
|
subnet.control.append(new Option(row.cidr, row.subnet_key));
|
|
|
|
|
}
|
|
|
|
|
const instance = input('选择实例', '', 'select'); instance.control.name = 'instance_id'; instance.control.required = true;
|
|
|
|
|
const vpcRegionId = Number(doc.vpc.region_id || 0);
|
|
|
|
|
const attached = new Set(doc.members
|
|
|
|
|
.filter(item => childStatus(item.state) !== 'deleted')
|
|
|
|
|
.map(item => Number(item.instance_id)));
|
|
|
|
|
for (const row of state.instances.filter(item => item.service_available !== false)) {
|
|
|
|
|
const sameRegion = !row.region_id || Number(row.region_id) === vpcRegionId;
|
|
|
|
|
const alreadyAttached = attached.has(Number(row.id));
|
|
|
|
|
const suffix = alreadyAttached ? ' · 已在当前 VPC' : (!sameRegion ? ' · 地区不匹配' : '');
|
|
|
|
|
const option = new Option(`${row.name} · ${safeText(row.region, '地区待核验')}${suffix}`, String(row.id));
|
|
|
|
|
option.dataset.regionId = row.region_id || '';
|
|
|
|
|
option.disabled = alreadyAttached || !sameRegion;
|
|
|
|
|
instance.control.append(option);
|
|
|
|
|
}
|
|
|
|
|
const ip = input('指定私网 IP(可选)', '', 'text', '自动分配'); ip.control.name = 'private_ip'; ip.control.maxLength = 15;
|
|
|
|
|
const save = button('加入 VPC', 'button button-primary small'); save.type = 'submit';
|
|
|
|
|
form.append(subnet.wrapper, instance.wrapper, ip.wrapper, save); card.append(form);
|
|
|
|
|
const list = element('div', 'vpc-row-list');
|
|
|
|
|
for (const row of doc.members.filter(item => childStatus(item.state) !== 'deleted')) {
|
|
|
|
|
const item = element('div', 'vpc-data-row');
|
|
|
|
|
const copy = element('div', 'vpc-row-copy');
|
|
|
|
|
copy.append(element('strong', '', `${instanceName(row.instance_id)} · ${safeText(row.private_ip)}`),
|
|
|
|
|
element('small', '', `${instanceRegion(row.instance_id)} · 状态:${STATUS_LABELS[childStatus(row.state)] || safeText(row.state)}`));
|
|
|
|
|
if (row.last_error_code) copy.append(element('small', 'vpc-row-error', row.last_error_code));
|
|
|
|
|
const remove = button('退出 VPC', 'button button-outline small danger');
|
|
|
|
|
remove.dataset.vpcRemoveMember = row.member_key;
|
|
|
|
|
remove.disabled = state.busy || childStatus(row.state) === 'deleting';
|
|
|
|
|
item.append(copy, remove); list.append(item);
|
|
|
|
|
}
|
|
|
|
|
if (!doc.members.some(item => childStatus(item.state) !== 'deleted')) list.append(element('p', 'vpc-empty-inline', '暂无成员。'));
|
|
|
|
|
card.append(list); return card;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function routeRow(value = {}) {
|
|
|
|
|
const row = element('div', 'vpc-editor-row');
|
|
|
|
|
row.dataset.routeKey = value.route_key || entityKey();
|
|
|
|
|
const destination = input('目标 /32', value.destination_cidr || '', 'text', '10.40.2.7/32');
|
|
|
|
|
destination.control.dataset.routeField = 'destination_cidr';
|
|
|
|
|
const nextHop = input('下一跳成员 IP', value.next_hop_ip || '', 'select');
|
|
|
|
|
nextHop.control.dataset.routeField = 'next_hop_ip';
|
|
|
|
|
const members = (state.selected?.members || [])
|
|
|
|
|
.filter(item => !['deleting', 'deleted'].includes(childStatus(item.state)));
|
|
|
|
|
let foundNextHop = false;
|
|
|
|
|
for (const member of members) {
|
|
|
|
|
const memberIp = String(member.private_ip || '');
|
|
|
|
|
if (memberIp === String(value.next_hop_ip || '')) foundNextHop = true;
|
|
|
|
|
nextHop.control.append(new Option(`${safeText(member.private_ip)} · ${instanceName(member.instance_id)}`, memberIp));
|
|
|
|
|
}
|
|
|
|
|
nextHop.control.value = String(value.next_hop_ip || '');
|
|
|
|
|
if (!foundNextHop) {
|
|
|
|
|
row.dataset.invalid = 'true';
|
|
|
|
|
if (value.next_hop_ip) {
|
|
|
|
|
const missing = new Option(`${value.next_hop_ip} · 成员状态待核验`, value.next_hop_ip);
|
|
|
|
|
missing.disabled = true;
|
|
|
|
|
nextHop.control.append(missing);
|
|
|
|
|
nextHop.control.value = String(value.next_hop_ip);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
const metric = input('Metric', value.metric || 100, 'number'); metric.control.min = '1'; metric.control.max = '65535'; metric.control.dataset.routeField = 'metric';
|
|
|
|
|
const remove = button('移除', 'button button-outline small danger'); remove.dataset.editorRemove = 'route';
|
|
|
|
|
row.append(destination.wrapper, nextHop.wrapper, metric.wrapper, remove); return row;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function renderRoutes(doc) {
|
|
|
|
|
const card = section('Route', '路由目标当前限制为 VPC 内的精确 /32,下一跳必须是本 VPC 成员私网 IP。保存会替换整套路由。', 'vpc-routes');
|
|
|
|
|
const list = element('div', 'vpc-editor-list'); list.id = 'vpc-route-editor';
|
|
|
|
|
const tombstones = doc.routes.filter(row => ['deleting', 'deleted'].includes(childStatus(row.state)));
|
|
|
|
|
const editable = doc.routes.filter(row => !['deleting', 'deleted'].includes(childStatus(row.state)));
|
|
|
|
|
for (const row of editable) list.append(routeRow(row));
|
|
|
|
|
for (const row of tombstones) {
|
|
|
|
|
const item = element('div', 'vpc-tombstone-row');
|
|
|
|
|
item.dataset.vpcTombstone = 'true';
|
|
|
|
|
item.dataset.vpcTombstoneState = childStatus(row.state);
|
|
|
|
|
const pending = childStatus(row.state) === 'deleting';
|
|
|
|
|
item.append(element('strong', '', row.destination_cidr || '已删除路由'),
|
|
|
|
|
element('small', '', pending
|
|
|
|
|
? '状态:清理中;完成前不能覆盖整套路由'
|
|
|
|
|
: '状态:已清理;这是历史记录,可继续编辑其他路由'));
|
|
|
|
|
list.append(item);
|
|
|
|
|
}
|
|
|
|
|
if (!editable.length && !tombstones.length) list.append(element('p', 'vpc-empty-inline', '暂无自定义路由;同 VPC 成员的 /32 由数据面维护。'));
|
|
|
|
|
const toolbar = element('div', 'vpc-editor-toolbar');
|
|
|
|
|
const add = button('添加路由', 'button button-outline small'); add.dataset.editorAdd = 'route';
|
|
|
|
|
const save = button('保存路由', 'button button-primary small'); save.dataset.vpcSave = 'routes';
|
|
|
|
|
const pendingTombstones = tombstones.some(row => childStatus(row.state) === 'deleting');
|
|
|
|
|
add.disabled = state.busy || pendingTombstones;
|
|
|
|
|
save.disabled = state.busy || pendingTombstones || Boolean(list.querySelector('[data-invalid="true"]'));
|
|
|
|
|
toolbar.append(add, save); card.append(list, toolbar); return card;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function aclRow(value = {}) {
|
|
|
|
|
const row = element('div', 'vpc-editor-row vpc-acl-row');
|
|
|
|
|
row.dataset.aclKey = value.rule_key || entityKey();
|
|
|
|
|
const priority = input('优先级', value.priority || 100, 'number'); priority.control.min = '1'; priority.control.max = '1000000'; priority.control.dataset.aclField = 'priority';
|
|
|
|
|
const direction = input('方向', '', 'select'); direction.control.dataset.aclField = 'direction';
|
|
|
|
|
for (const option of [['ingress', '入站'], ['egress', '出站']]) direction.control.append(new Option(option[1], option[0]));
|
|
|
|
|
direction.control.value = value.direction || 'ingress';
|
|
|
|
|
const action = input('动作', '', 'select'); action.control.dataset.aclField = 'action';
|
|
|
|
|
for (const option of [['allow', '允许'], ['deny', '拒绝']]) action.control.append(new Option(option[1], option[0]));
|
|
|
|
|
action.control.value = value.action || 'deny';
|
|
|
|
|
const protocol = input('协议', '', 'select'); protocol.control.dataset.aclField = 'protocol';
|
|
|
|
|
for (const option of [['all', '全部'], ['tcp', 'TCP'], ['udp', 'UDP'], ['icmp', 'ICMP']]) protocol.control.append(new Option(option[1], option[0]));
|
|
|
|
|
protocol.control.value = value.protocol || 'all';
|
|
|
|
|
const source = input('源 CIDR', value.source_cidr || '', 'text', '10.40.0.0/16'); source.control.dataset.aclField = 'source_cidr';
|
|
|
|
|
const destination = input('目标 CIDR', value.destination_cidr || '', 'text', '10.40.0.0/16'); destination.control.dataset.aclField = 'destination_cidr';
|
|
|
|
|
const from = input('起始端口', value.port_from ?? '', 'number', 'TCP/UDP 可选'); from.control.min = '1'; from.control.max = '65535'; from.control.dataset.aclField = 'port_from';
|
|
|
|
|
const to = input('结束端口', value.port_to ?? '', 'number', 'TCP/UDP 可选'); to.control.min = '1'; to.control.max = '65535'; to.control.dataset.aclField = 'port_to';
|
|
|
|
|
const remove = button('移除', 'button button-outline small danger'); remove.dataset.editorRemove = 'acl';
|
|
|
|
|
row.append(priority.wrapper, direction.wrapper, action.wrapper, protocol.wrapper, source.wrapper, destination.wrapper, from.wrapper, to.wrapper, remove); return row;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function renderAcl(doc) {
|
|
|
|
|
const card = section('VPC ACL', '默认策略由数据面保持拒绝;这里只提交结构化规则,不会修改实例公网防火墙。保存会替换整套 ACL。', 'vpc-acl');
|
|
|
|
|
const list = element('div', 'vpc-editor-list'); list.id = 'vpc-acl-editor';
|
|
|
|
|
const tombstones = doc.acl_rules.filter(row => ['deleting', 'deleted'].includes(childStatus(row.state)));
|
|
|
|
|
const editable = doc.acl_rules.filter(row => !['deleting', 'deleted'].includes(childStatus(row.state)));
|
|
|
|
|
for (const row of editable) list.append(aclRow(row));
|
|
|
|
|
for (const row of tombstones) {
|
|
|
|
|
const item = element('div', 'vpc-tombstone-row');
|
|
|
|
|
item.dataset.vpcTombstone = 'true';
|
|
|
|
|
item.dataset.vpcTombstoneState = childStatus(row.state);
|
|
|
|
|
const pending = childStatus(row.state) === 'deleting';
|
|
|
|
|
item.append(element('strong', '', `规则 ${safeText(row.rule_key)}`),
|
|
|
|
|
element('small', '', pending
|
|
|
|
|
? '状态:清理中;完成前不能覆盖整套 ACL'
|
|
|
|
|
: '状态:已清理;这是历史记录,可继续编辑其他规则'));
|
|
|
|
|
list.append(item);
|
|
|
|
|
}
|
|
|
|
|
if (!editable.length && !tombstones.length) list.append(element('p', 'vpc-empty-inline', '暂无自定义 ACL 规则。'));
|
|
|
|
|
const toolbar = element('div', 'vpc-editor-toolbar');
|
|
|
|
|
const add = button('添加规则', 'button button-outline small'); add.dataset.editorAdd = 'acl';
|
|
|
|
|
const save = button('保存 ACL', 'button button-primary small'); save.dataset.vpcSave = 'acl';
|
|
|
|
|
const pendingTombstones = tombstones.some(row => childStatus(row.state) === 'deleting');
|
|
|
|
|
add.disabled = state.busy || pendingTombstones;
|
|
|
|
|
save.disabled = state.busy || pendingTombstones;
|
|
|
|
|
toolbar.append(add, save); card.append(list, toolbar); return card;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function renderOperations(doc) {
|
|
|
|
|
const card = section('最近操作', '每次修改都会生成独立的 VPC revision;只有宿主机精确回读后才会进入 active。', 'vpc-operations');
|
|
|
|
|
const list = element('div', 'vpc-operation-list');
|
|
|
|
|
for (const row of doc.operations.slice(0, 12)) {
|
|
|
|
|
const item = element('div', 'vpc-operation-row');
|
|
|
|
|
item.append(element('span', '', safeText(row.kind)), statusPill(row.status === 'waiting_observed' ? 'waiting' : row.status),
|
|
|
|
|
element('small', '', `revision ${row.desired_revision || 0}${row.error_code ? ` · ${row.error_code}` : ''}`));
|
|
|
|
|
list.append(item);
|
|
|
|
|
}
|
|
|
|
|
if (!doc.operations.length) list.append(element('p', 'vpc-empty-inline', '暂无操作记录。'));
|
|
|
|
|
card.append(list); return card;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function createRegionOptions() {
|
|
|
|
|
const select = byId('vpc-create-region');
|
|
|
|
|
select.replaceChildren();
|
|
|
|
|
if (!state.regions.length) {
|
|
|
|
|
select.append(new Option('暂无可用 Fabric 地区', ''));
|
|
|
|
|
select.disabled = true;
|
|
|
|
|
byId('vpc-create-region-hint').textContent = '管理员尚未完成可用 Fabric 映射,暂不能创建 VPC。';
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
select.disabled = false;
|
|
|
|
|
select.append(new Option('请选择地区', ''));
|
|
|
|
|
for (const row of state.regions) select.append(new Option(String(row.name), String(row.id)));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function loadList(silent = false) {
|
|
|
|
|
const epoch = ++state.listEpoch;
|
|
|
|
|
state.listController?.abort(); state.listController = new AbortController();
|
|
|
|
|
try {
|
|
|
|
|
const payload = await api('/api/v1/vpcs', { signal: state.listController.signal });
|
|
|
|
|
if (epoch !== state.listEpoch || state.stopped) return;
|
|
|
|
|
state.vpcs = Array.isArray(payload?.vpcs) ? payload.vpcs.map(normalizeRoot).filter(Boolean) : [];
|
|
|
|
|
renderList();
|
|
|
|
|
if (!silent) setError('');
|
|
|
|
|
} catch (error) {
|
|
|
|
|
if (error?.name === 'AbortError') return;
|
|
|
|
|
if (!silent || !state.vpcs.length) setError(error.message);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function loadDetail(key, silent = false, allowDirty = false) {
|
|
|
|
|
if (!key) return;
|
|
|
|
|
if (state.detailDirty && !allowDirty) return;
|
|
|
|
|
const epoch = ++state.detailEpoch;
|
|
|
|
|
state.detailController?.abort(); state.detailController = new AbortController();
|
|
|
|
|
try {
|
|
|
|
|
const payload = await api(`/api/v1/vpcs/${encodeURIComponent(key)}`, { signal: state.detailController.signal });
|
|
|
|
|
if (epoch !== state.detailEpoch || state.stopped || key !== state.selectedKey) return;
|
|
|
|
|
state.selected = normalizeDocument(payload);
|
|
|
|
|
byId('vpc-detail-panel').hidden = !state.selected;
|
|
|
|
|
renderDetail();
|
|
|
|
|
if (!silent) setError('');
|
|
|
|
|
} catch (error) {
|
|
|
|
|
if (error?.name === 'AbortError') return;
|
|
|
|
|
if (!silent) setError(error.message);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function selectVpc(key) {
|
|
|
|
|
if (state.detailDirty
|
|
|
|
|
&& !confirm('当前 VPC 有未保存修改,切换后会丢失这些修改。继续吗?')) return;
|
|
|
|
|
clearDetailDirty();
|
|
|
|
|
state.selectedKey = String(key || '');
|
|
|
|
|
state.selected = null;
|
|
|
|
|
byId('vpc-detail-panel').hidden = !state.selectedKey;
|
|
|
|
|
renderList();
|
|
|
|
|
await loadDetail(state.selectedKey);
|
|
|
|
|
schedulePoll(5000);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function applyDocument(payload, message = '') {
|
|
|
|
|
const doc = normalizeDocument(payload);
|
|
|
|
|
if (doc) {
|
|
|
|
|
clearDetailDirty();
|
|
|
|
|
state.selected = doc;
|
|
|
|
|
state.selectedKey = doc.vpc.vpc_key;
|
|
|
|
|
if (!state.vpcs.some(item => item.vpc_key === doc.vpc.vpc_key)) state.vpcs.unshift(doc.vpc);
|
|
|
|
|
else state.vpcs = state.vpcs.map(item => item.vpc_key === doc.vpc.vpc_key ? doc.vpc : item);
|
|
|
|
|
byId('vpc-detail-panel').hidden = false;
|
|
|
|
|
renderList(); renderDetail();
|
|
|
|
|
}
|
|
|
|
|
if (message) { setNotice(message, 'success'); toast(message, 'success'); }
|
|
|
|
|
schedulePoll(1500);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function mutate(path, method, body, message) {
|
|
|
|
|
if (state.busy) return null;
|
|
|
|
|
clearTimeout(state.pollTimer);
|
|
|
|
|
const controls = [...document.querySelectorAll('#vpc-workspace button, #vpc-workspace input, #vpc-workspace select')];
|
|
|
|
|
const previousDisabled = new Map(controls.map(node => [node, node.disabled]));
|
|
|
|
|
state.busy = true; controls.forEach(node => { node.disabled = true; });
|
|
|
|
|
let succeeded = false;
|
|
|
|
|
try {
|
|
|
|
|
const payload = await api(path, { method, body });
|
|
|
|
|
await applyDocument(payload, message);
|
|
|
|
|
succeeded = true;
|
|
|
|
|
return payload;
|
|
|
|
|
} catch (error) {
|
|
|
|
|
setError(error.message); setNotice(''); return null;
|
|
|
|
|
} finally {
|
|
|
|
|
state.busy = false;
|
|
|
|
|
if (!succeeded) previousDisabled.forEach((disabled, node) => { node.disabled = disabled; });
|
|
|
|
|
createRegionOptions(); renderList();
|
|
|
|
|
if (succeeded && state.selected) renderDetail();
|
|
|
|
|
else refreshRouteEditorState();
|
|
|
|
|
schedulePoll(succeeded ? 1500 : undefined);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function createVpc(event) {
|
|
|
|
|
event.preventDefault(); if (state.busy) return;
|
|
|
|
|
setFormError('vpc-create-error', ''); setError('');
|
|
|
|
|
clearTimeout(state.pollTimer);
|
|
|
|
|
const form = event.currentTarget;
|
|
|
|
|
const body = {
|
|
|
|
|
name: form.name.value.trim(), region_id: Number(form.region_id.value),
|
|
|
|
|
cidr: form.cidr.value.trim(), max_members: Number(form.max_members.value || 256),
|
|
|
|
|
};
|
|
|
|
|
if (form.subnet_cidr.value.trim()) body.subnet_cidr = form.subnet_cidr.value.trim();
|
|
|
|
|
// Keep one idempotency key for the same form values until the server has
|
|
|
|
|
// acknowledged the create. A lost 202 response must be retryable without
|
|
|
|
|
// allocating a second VPC/CIDR; changing the values starts a new intent.
|
|
|
|
|
const fingerprint = JSON.stringify(body);
|
|
|
|
|
if (form.dataset.requestFingerprint !== fingerprint
|
|
|
|
|
|| !/^[A-Za-z0-9_.:-]{8,128}$/.test(form.dataset.requestKey || '')) {
|
|
|
|
|
form.dataset.requestKey = requestKey('vpc-create');
|
|
|
|
|
form.dataset.requestFingerprint = fingerprint;
|
|
|
|
|
}
|
|
|
|
|
body.request_key = form.dataset.requestKey;
|
|
|
|
|
state.busy = true;
|
|
|
|
|
try {
|
|
|
|
|
const payload = await api('/api/v1/vpcs', { method: 'POST', body });
|
|
|
|
|
delete form.dataset.requestKey; delete form.dataset.requestFingerprint;
|
|
|
|
|
form.reset(); form.max_members.value = '256';
|
|
|
|
|
byId('vpc-create-panel').hidden = true;
|
|
|
|
|
await applyDocument(payload, 'VPC 已创建,正在等待宿主机回读。');
|
|
|
|
|
} catch (error) { setFormError('vpc-create-error', error.message); }
|
|
|
|
|
finally { state.busy = false; createRegionOptions(); renderList(); schedulePoll(1500); }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function submitSubnet(form) {
|
|
|
|
|
if (!confirmDetailMutation()) return;
|
|
|
|
|
const value = form.cidr.value.trim();
|
|
|
|
|
if (!value) return;
|
|
|
|
|
const payload = await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/subnets`, 'POST', {
|
|
|
|
|
cidr: value, request_key: requestKey('subnet-add'),
|
|
|
|
|
}, '子网目标已提交,等待宿主机回读。');
|
|
|
|
|
if (payload) form.reset();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function submitMember(form) {
|
|
|
|
|
if (!confirmDetailMutation()) return;
|
|
|
|
|
const body = { subnet_key: form.subnet_key.value, instance_id: Number(form.instance_id.value), request_key: requestKey('member-add') };
|
|
|
|
|
if (form.private_ip.value.trim()) body.private_ip = form.private_ip.value.trim();
|
|
|
|
|
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/members`, 'POST', body,
|
|
|
|
|
'实例已加入 VPC 目标,私网网卡将在实际回读后显示为可用。');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function readRoutes() {
|
|
|
|
|
return [...document.querySelectorAll('#vpc-route-editor .vpc-editor-row')].map(row => ({
|
|
|
|
|
route_key: row.dataset.routeKey,
|
|
|
|
|
destination_cidr: row.querySelector('[data-route-field="destination_cidr"]').value.trim(),
|
|
|
|
|
next_hop_ip: row.querySelector('[data-route-field="next_hop_ip"]').value,
|
|
|
|
|
metric: Number(row.querySelector('[data-route-field="metric"]').value || 100),
|
|
|
|
|
}));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function readAcl() {
|
|
|
|
|
return [...document.querySelectorAll('#vpc-acl-editor .vpc-editor-row')].map(row => {
|
|
|
|
|
const value = fieldName => row.querySelector(`[data-acl-field="${fieldName}"]`).value.trim();
|
|
|
|
|
const item = {
|
|
|
|
|
rule_key: row.dataset.aclKey, priority: Number(value('priority') || 100),
|
|
|
|
|
direction: value('direction'), action: value('action'), protocol: value('protocol'),
|
|
|
|
|
source_cidr: value('source_cidr'), destination_cidr: value('destination_cidr'),
|
|
|
|
|
port_from: value('port_from') === '' ? null : Number(value('port_from')),
|
|
|
|
|
port_to: value('port_to') === '' ? null : Number(value('port_to')),
|
|
|
|
|
};
|
|
|
|
|
return item;
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function saveEditor(kind) {
|
|
|
|
|
if (kind === 'routes') {
|
|
|
|
|
refreshRouteEditorState();
|
|
|
|
|
if (document.querySelector('#vpc-route-editor [data-vpc-tombstone-state="deleting"]')) {
|
|
|
|
|
setError('路由仍有删除中的记录,待宿主机回读完成后再保存整套路由。');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if (document.querySelector('#vpc-route-editor [data-invalid="true"]')) {
|
|
|
|
|
setError('路由下一跳必须选择当前仍在 VPC 中的成员私网 IP。');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if (kind === 'acl' && document.querySelector('#vpc-acl-editor [data-vpc-tombstone-state="deleting"]')) {
|
|
|
|
|
setError('ACL 仍有删除中的记录,待宿主机回读完成后再保存整套 ACL。');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
const body = kind === 'routes'
|
|
|
|
|
? { routes: readRoutes(), request_key: requestKey('routes') }
|
|
|
|
|
: { rules: readAcl(), request_key: requestKey('acl') };
|
|
|
|
|
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/${kind === 'routes' ? 'routes' : 'acl'}`,
|
|
|
|
|
'PUT', body, `${kind === 'routes' ? '路由' : 'ACL'} 目标已提交,等待宿主机回读。`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function reconcile() {
|
|
|
|
|
if (!state.selectedKey || state.busy) return;
|
|
|
|
|
if (state.detailDirty
|
|
|
|
|
&& !confirm('当前 VPC 有未保存修改,核对后会丢失这些修改。继续吗?')) return;
|
|
|
|
|
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/reconcile`, 'POST', {}, '已请求重新核对 VPC 状态。');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function removeSubnet(key) {
|
|
|
|
|
if (!state.selectedKey || state.busy || !confirmDetailMutation()
|
|
|
|
|
|| !confirm('确认删除这个子网?子网必须没有成员和地址租约。')) return;
|
|
|
|
|
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/subnets/${encodeURIComponent(key)}`,
|
|
|
|
|
'DELETE', { request_key: requestKey('subnet-remove') }, '子网删除目标已提交。');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function removeMember(key) {
|
|
|
|
|
if (!state.selectedKey || state.busy || !confirmDetailMutation()
|
|
|
|
|
|| !confirm('确认让这个实例退出 VPC?宿主机回读确认前,私网 IP 不会重新分配。')) return;
|
|
|
|
|
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/members/${encodeURIComponent(key)}`,
|
|
|
|
|
'DELETE', { request_key: requestKey('member-remove') }, '成员退出目标已提交,等待私网网卡移除回读。');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function handleClick(event) {
|
|
|
|
|
const listRow = event.target.closest('[data-vpc-key]');
|
|
|
|
|
if (listRow && listRow.closest('#vpc-list')) { selectVpc(listRow.dataset.vpcKey); return; }
|
|
|
|
|
const removeSubnetKey = event.target.closest('[data-vpc-remove-subnet]')?.dataset.vpcRemoveSubnet;
|
|
|
|
|
if (removeSubnetKey) { removeSubnet(removeSubnetKey); return; }
|
|
|
|
|
const removeMemberKey = event.target.closest('[data-vpc-remove-member]')?.dataset.vpcRemoveMember;
|
|
|
|
|
if (removeMemberKey) { removeMember(removeMemberKey); return; }
|
|
|
|
|
const action = event.target.closest('[data-vpc-action]')?.dataset.vpcAction;
|
|
|
|
|
if (action === 'reconcile') { reconcile(); return; }
|
|
|
|
|
const add = event.target.closest('[data-editor-add]')?.dataset.editorAdd;
|
|
|
|
|
if (add) {
|
|
|
|
|
const list = byId(add === 'route' ? 'vpc-route-editor' : 'vpc-acl-editor');
|
|
|
|
|
if (list.querySelector('[data-vpc-tombstone-state="deleting"]')) return;
|
|
|
|
|
list.querySelector('.vpc-empty-inline')?.remove();
|
|
|
|
|
list.append(add === 'route' ? routeRow() : aclRow());
|
|
|
|
|
markDetailDirty();
|
|
|
|
|
refreshRouteEditorState();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
const remove = event.target.closest('[data-editor-remove]')?.dataset.editorRemove;
|
|
|
|
|
if (remove) {
|
|
|
|
|
event.target.closest('.vpc-editor-row')?.remove(); markDetailDirty(); refreshRouteEditorState(); return;
|
|
|
|
|
}
|
|
|
|
|
const save = event.target.closest('[data-vpc-save]')?.dataset.vpcSave;
|
|
|
|
|
if (save) saveEditor(save);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function handleSubmit(event) {
|
|
|
|
|
const kind = event.target.dataset.vpcForm;
|
|
|
|
|
if (kind === 'subnet') { event.preventDefault(); submitSubnet(event.target); }
|
|
|
|
|
if (kind === 'member') { event.preventDefault(); submitMember(event.target); }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function handleDetailInput(event) {
|
|
|
|
|
if (event.target.closest('#vpc-detail')) {
|
|
|
|
|
markDetailDirty();
|
|
|
|
|
if (event.target.matches('[data-route-field="next_hop_ip"]')) refreshRouteEditorState();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function readBootstrap() {
|
|
|
|
|
const node = byId('vpc-bootstrap');
|
|
|
|
|
let payload;
|
|
|
|
|
try { payload = JSON.parse(node?.textContent || '{}'); } catch { throw new Error('VPC 页面初始数据无效,请刷新页面。'); }
|
|
|
|
|
const user = payload?.user;
|
|
|
|
|
if (!user || !/^[a-f0-9]{64}$/.test(String(user.csrf_token || ''))
|
|
|
|
|
|| !/^[1-9]\d*$/.test(String(user.user_id || ''))) {
|
|
|
|
|
throw new Error('VPC 页面安全会话缺失,请刷新页面。');
|
|
|
|
|
}
|
|
|
|
|
state.csrfToken = String(user.csrf_token); state.userId = String(user.user_id);
|
|
|
|
|
state.regions = Array.isArray(payload.regions) ? payload.regions : [];
|
|
|
|
|
state.instances = Array.isArray(payload.instances) ? payload.instances : [];
|
|
|
|
|
state.vpcs = Array.isArray(payload.vpcs) ? payload.vpcs.map(normalizeRoot).filter(Boolean) : [];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function bind() {
|
|
|
|
|
byId('vpc-create-open').addEventListener('click', () => {
|
|
|
|
|
const form = byId('vpc-create-form');
|
|
|
|
|
form.reset(); form.max_members.value = '256';
|
|
|
|
|
delete form.dataset.requestKey; delete form.dataset.requestFingerprint;
|
|
|
|
|
byId('vpc-create-panel').hidden = false; byId('vpc-create-name').focus();
|
|
|
|
|
});
|
|
|
|
|
byId('vpc-create-close').addEventListener('click', () => {
|
|
|
|
|
const form = byId('vpc-create-form');
|
|
|
|
|
byId('vpc-create-panel').hidden = true;
|
|
|
|
|
delete form.dataset.requestKey; delete form.dataset.requestFingerprint;
|
|
|
|
|
});
|
|
|
|
|
byId('vpc-create-form').addEventListener('submit', createVpc);
|
|
|
|
|
byId('vpc-refresh').addEventListener('click', async () => {
|
|
|
|
|
if (state.detailDirty && !confirm('当前 VPC 有未保存修改,刷新后会丢失这些修改。继续吗?')) return;
|
|
|
|
|
await loadList(); if (state.selectedKey) await loadDetail(state.selectedKey, false, true); schedulePoll(8000);
|
|
|
|
|
});
|
|
|
|
|
byId('vpc-list-reconcile').addEventListener('click', reconcile);
|
|
|
|
|
byId('vpc-workspace').addEventListener('click', handleClick);
|
|
|
|
|
byId('vpc-workspace').addEventListener('submit', handleSubmit);
|
|
|
|
|
byId('vpc-workspace').addEventListener('input', handleDetailInput);
|
|
|
|
|
byId('vpc-workspace').addEventListener('change', handleDetailInput);
|
|
|
|
|
byId('vpc-detail-refresh').addEventListener('click', () => {
|
|
|
|
|
if (state.detailDirty && !confirm('当前 VPC 有未保存修改,刷新后会丢失这些修改。继续吗?')) return;
|
|
|
|
|
loadDetail(state.selectedKey, false, true);
|
|
|
|
|
});
|
|
|
|
|
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') schedulePoll(1000); else clearTimeout(state.pollTimer); });
|
|
|
|
|
window.addEventListener('beforeunload', () => { state.stopped = true; state.listController?.abort(); state.detailController?.abort(); clearTimeout(state.pollTimer); }, { once: true });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function initialize() {
|
|
|
|
|
try {
|
|
|
|
|
readBootstrap(); bind(); createRegionOptions(); renderList();
|
|
|
|
|
await loadList();
|
|
|
|
|
if (state.vpcs.length) await selectVpc(state.selectedKey || state.vpcs[0].vpc_key);
|
|
|
|
|
schedulePoll(3000);
|
|
|
|
|
} catch (error) { setError(error.message); }
|
|
|
|
|
}
|