You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
7.4 KiB
JavaScript
67 lines
7.4 KiB
JavaScript
const root = document.querySelector('[data-admin-vpc]');
|
|
const byId = id => document.getElementById(id);
|
|
const canManage = root?.dataset.canManage === '1';
|
|
const state = { csrf: window.ADMIN_CSRF_TOKEN || '', regions: [], items: [], featureEnabled: false, busy: false, requestKey: '' };
|
|
|
|
function notice(message, error = false) {
|
|
const box = byId('admin-vpc-status'); box.textContent = message; box.className = `alert ${error ? 'alert-danger' : 'alert-info'} cloud-admin-notice`;
|
|
}
|
|
function errorMessage(payload, status) { return String(payload?.detail || payload?.error || `请求失败 (${status})`); }
|
|
async function api(path, options = {}) {
|
|
const method = (options.method || 'GET').toUpperCase(); const headers = new Headers({ Accept: 'application/json' });
|
|
if (!['GET', 'HEAD'].includes(method)) { headers.set('Content-Type', 'application/json'); headers.set('X-CSRF-Token', state.csrf); }
|
|
const response = await fetch(path, { method, headers, credentials: 'same-origin', cache: 'no-store', body: options.body === undefined ? undefined : JSON.stringify(options.body) });
|
|
let payload; try { payload = await response.json(); } catch { throw new Error('服务返回非 JSON 响应。'); }
|
|
if (response.status === 401) { location.assign('/auth/login'); throw new Error('登录已过期。'); }
|
|
if (!response.ok) throw new Error(errorMessage(payload, response.status)); return payload;
|
|
}
|
|
function newRequestKey() {
|
|
if (!globalThis.crypto?.getRandomValues) throw new Error('浏览器无法生成安全创建标识,请升级浏览器。');
|
|
const bytes = new Uint8Array(16); globalThis.crypto.getRandomValues(bytes); return Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('');
|
|
}
|
|
function renderRegions(selected = '') {
|
|
const select = byId('admin-vpc-pool-region'); select.replaceChildren();
|
|
const empty = document.createElement('option'); empty.value = ''; empty.textContent = state.regions.length ? '请选择地区' : '请先创建地区'; select.append(empty);
|
|
for (const region of state.regions) { const option = document.createElement('option'); option.value = String(region.id); option.textContent = `${region.name} · ${region.country_code}${region.status === 'active' ? '' : '(停用)'}`; option.selected = String(region.id) === String(selected); select.append(option); }
|
|
}
|
|
function lockAddressFields(editing) {
|
|
byId('admin-vpc-pool-region').disabled = !canManage || editing;
|
|
byId('admin-vpc-pool-cidr').disabled = !canManage || (editing && byId('admin-vpc-pool-cidr').dataset.locked === '1');
|
|
byId('admin-vpc-pool-prefix').disabled = !canManage || (editing && byId('admin-vpc-pool-prefix').dataset.locked === '1');
|
|
}
|
|
function resetForm() {
|
|
byId('admin-vpc-pool-form').reset(); byId('admin-vpc-pool-id').value = ''; byId('admin-vpc-pool-revision').value = '0'; byId('admin-vpc-pool-prefix').value = '24'; byId('admin-vpc-pool-state').value = 'active'; byId('admin-vpc-pool-title').textContent = '添加 VPC 地址池'; byId('admin-vpc-pool-capacity').textContent = '保存后显示可分配子网数量。'; delete byId('admin-vpc-pool-cidr').dataset.locked; delete byId('admin-vpc-pool-prefix').dataset.locked; state.requestKey = newRequestKey(); renderRegions(); lockAddressFields(false);
|
|
}
|
|
function editPool(pool) {
|
|
byId('admin-vpc-pool-id').value = pool.id; byId('admin-vpc-pool-revision').value = pool.revision; byId('admin-vpc-pool-title').textContent = `编辑地址池 · ${pool.name}`; renderRegions(pool.region_id); byId('admin-vpc-pool-name').value = pool.name; byId('admin-vpc-pool-cidr').value = pool.cidr; byId('admin-vpc-pool-prefix').value = pool.allocation_prefix; byId('admin-vpc-pool-state').value = pool.state; byId('admin-vpc-pool-cidr').dataset.locked = pool.address_locked ? '1' : '0'; byId('admin-vpc-pool-prefix').dataset.locked = pool.address_locked ? '1' : '0'; byId('admin-vpc-pool-capacity').textContent = `${pool.used} 个已占用 · ${pool.available} 个可用 · 共 ${pool.capacity} 个 /${pool.allocation_prefix} 子网${pool.address_locked ? ';地址边界已锁定' : ''}`; lockAddressFields(true);
|
|
}
|
|
function renderList() {
|
|
const list = byId('admin-vpc-pool-list'); list.replaceChildren();
|
|
if (!state.items.length) { const empty = document.createElement('p'); empty.className = 'text-muted'; empty.textContent = '暂无 VPC 地址池。'; list.append(empty); return; }
|
|
for (const pool of state.items) { const button = document.createElement('button'); button.type = 'button'; button.className = 'btn btn-light cloud-admin-host'; const strong = document.createElement('strong'); strong.textContent = pool.name; const detail = document.createElement('div'); detail.className = 'text-muted'; detail.textContent = `${pool.region_name} · ${pool.cidr} → /${pool.allocation_prefix} · ${pool.used}/${pool.capacity} · ${pool.state === 'active' ? '启用' : '停用'}`; button.append(strong, detail); button.addEventListener('click', () => editPool(pool)); list.append(button); }
|
|
}
|
|
async function load() {
|
|
const payload = await api('/api/v1/admin/vpc-cidr-pools'); state.regions = Array.isArray(payload.regions) ? payload.regions : []; state.items = Array.isArray(payload.items) ? payload.items : []; state.featureEnabled = payload.feature_enabled === true; renderList();
|
|
}
|
|
function requestBody() {
|
|
const regionId = Number(byId('admin-vpc-pool-region').value); const prefix = Number(byId('admin-vpc-pool-prefix').value); const id = byId('admin-vpc-pool-id').value;
|
|
if (!Number.isInteger(regionId) || regionId < 1) throw new Error('请选择所属地区。');
|
|
if (!Number.isInteger(prefix) || prefix < 16 || prefix > 28) throw new Error('VPC 分配前缀必须是 16 至 28 的整数。');
|
|
const result = { region_id: regionId, name: byId('admin-vpc-pool-name').value.trim(), cidr: byId('admin-vpc-pool-cidr').value.trim(), allocation_prefix: prefix, state: byId('admin-vpc-pool-state').value };
|
|
if (id) result.expected_revision = Number(byId('admin-vpc-pool-revision').value); else result.request_key = state.requestKey;
|
|
return result;
|
|
}
|
|
async function save(event) {
|
|
event.preventDefault(); if (!canManage || state.busy) return; let payload; try { payload = requestBody(); } catch (error) { notice(error.message, true); return; }
|
|
const id = byId('admin-vpc-pool-id').value; state.busy = true; byId('admin-vpc-pool-save').disabled = true; notice('正在保存 VPC 地址池…');
|
|
try { const result = await api(`/api/v1/admin/vpc-cidr-pools${id ? '/' + encodeURIComponent(id) : ''}`, { method: id ? 'PATCH' : 'POST', body: payload }); await load(); editPool(result.item); notice(id ? 'VPC 地址池已更新。' : 'VPC 地址池已创建。'); }
|
|
catch (error) { try { await load(); } catch {} notice(error.message, true); }
|
|
finally { state.busy = false; byId('admin-vpc-pool-save').disabled = !canManage; }
|
|
}
|
|
async function initialize() {
|
|
if (!root) return;
|
|
try { const session = await api('/api/v1/session'); state.csrf = session.csrf_token || state.csrf; if (!session.admin || !state.csrf) throw new Error('管理员会话无效,请重新登录。'); await load(); resetForm(); byId('admin-vpc-pool-new').addEventListener('click', resetForm); byId('admin-vpc-pool-form').addEventListener('submit', save); notice(state.featureEnabled ? 'VPC 地址池目录已读取。用户 VPC 功能已开启。' : 'VPC 地址池目录已读取。用户 VPC 功能已关闭,可在“站点设置 → 云功能开关”中启用。'); }
|
|
catch (error) { notice(error.message, true); }
|
|
}
|
|
void initialize();
|