feat(vpc): manage regional cidr pools

go
codex 3 weeks ago
parent 5d52af8e3c
commit f2f5bdda74

@ -8,7 +8,7 @@ use App\Services\Config;
/** Initializes only the clean-break PHP business and Agent log schemas. */
final class CloudSetup
{
private const SCHEMA_VERSION = 'go-agent-wss-v13-vpc-l3-v1';
private const SCHEMA_VERSION = 'go-agent-wss-v13-vpc-l3-v2';
private const MAIN_TABLES = [
'cloud_regions', 'cloud_network_lines', 'cloud_resource_pools',
'cloud_hosts', 'cloud_host_agents',
@ -75,11 +75,11 @@ final class CloudSetup
'cloud_vpc_cidr_pools' => [
'id', 'pool_key', 'region_id', 'name', 'cidr',
'prefix_length', 'allocation_prefix', 'state',
'created_at', 'updated_at',
'revision', 'created_at', 'updated_at',
],
'cloud_vpcs' => [
'id', 'vpc_key', 'user_id', 'region_id', 'cidr_pool_id',
'name', 'cidr', 'prefix_length', 'gateway', 'state',
'name', 'cidr', 'prefix_length', 'gateway', 'active_claim', 'state',
'desired_revision', 'deleted_at', 'created_at', 'updated_at',
],
'cloud_vpc_ports' => [
@ -216,7 +216,8 @@ final class CloudSetup
'chk_cloud_vpc_cidr_pool_state',
],
'cloud_vpcs' => [
'chk_cloud_vpc_prefix', 'chk_cloud_vpc_state',
'chk_cloud_vpc_prefix', 'chk_cloud_vpc_active_claim',
'chk_cloud_vpc_state',
'chk_cloud_vpc_deleted_at',
],
'cloud_vpc_ports' => [

@ -59,6 +59,11 @@ final class CloudPageController extends AdminController
->display('admin/hosts/index.tpl');
}
public function vpc($request, $response, $args)
{
return $this->view()->display('admin/cloud/vpc.tpl');
}
public function agents($request, $response, $args)
{
return $this->view()->display('admin/cloud/agents.tpl');

@ -0,0 +1,49 @@
<?php
namespace App\Controllers;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudAdminVpcCidrPoolService;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInput;
/** Administrator API for the region-owned VPC address catalog. */
final class CloudAdminVpcController
{
private function actor($request, bool $write): void
{
$actor = $request->getAttribute('cloud_actor') ?? CloudAccess::actor(false);
if (!($actor['is_admin'] ?? false)) {
throw new CloudError('需要管理员权限', 403);
}
if ($write) {
CloudAccess::manage($actor);
}
}
public function pools($request, $response, $args = [])
{
$method = strtoupper((string) $request->getMethod());
$write = $method !== 'GET';
$this->actor($request, $write);
$id = isset($args['id']) ? (int) $args['id'] : null;
if (!$write) {
$result = $id === null
? CloudAdminVpcCidrPoolService::listing()
: CloudAdminVpcCidrPoolService::read($id);
$status = 200;
} else {
$body = CloudInput::object($request);
CloudInput::only($body, [
'region_id', 'name', 'cidr', 'allocation_prefix', 'state',
'request_key', 'expected_revision',
]);
$result = $id === null
? CloudAdminVpcCidrPoolService::create($body)
: CloudAdminVpcCidrPoolService::update($id, $body);
$status = $id === null ? 201 : 200;
}
return $response->withJson($result, $status)
->withHeader('Cache-Control', 'private, no-store');
}
}

@ -22,6 +22,7 @@ final class CloudApi
|| preg_match('#^/api/v1/admin/system-logs(?:/|$)#D', $path) === 1
|| preg_match('#^/api/v1/admin/platform-test-policy(?:/|$)#D', $path) === 1
|| preg_match('#^/api/v1/admin/(?:resources|regions|network-lines|resource-pools|resource-reservations)(?:/|$)#D', $path) === 1
|| preg_match('#^/api/v1/admin/vpc-cidr-pools(?:/[1-9][0-9]*)?$#D', $path) === 1
|| preg_match('#^/api/v1/admin/hosts/[0-9]+/scheduling$#D', $path) === 1
|| preg_match('#^/api/v1/admin/hosts/[1-9][0-9]*/vpc-transport(?:/(?:discover|test))?$#D', $path) === 1
|| preg_match('#^/api/v1/admin/agents(?:/[1-9][0-9]*(?:/test)?)?$#D', $path) === 1

@ -13,6 +13,7 @@ final class CloudVpc extends Model
'region_id' => 'int',
'cidr_pool_id' => 'int',
'prefix_length' => 'int',
'active_claim' => 'int',
'desired_revision' => 'int',
'deleted_at' => 'int',
'created_at' => 'int',

@ -12,6 +12,7 @@ final class CloudVpcCidrPool extends Model
'region_id' => 'int',
'prefix_length' => 'int',
'allocation_prefix' => 'int',
'revision' => 'int',
'created_at' => 'int',
'updated_at' => 'int',
];

@ -0,0 +1,323 @@
<?php
namespace App\Services\Cloud;
use App\Models\CloudRegion;
use App\Models\CloudVpc;
use App\Models\CloudVpcCidrPool;
/** Region-scoped, non-overlapping RFC1918 allocation boundaries for VPCs. */
final class CloudAdminVpcCidrPoolService
{
private const STATES = ['active', 'disabled'];
public static function listing(): array
{
$regions = CloudRegion::query()->orderBy('sort')->orderBy('id')
->get(['id', 'code', 'name', 'country_code', 'status'])
->map(static fn ($region): array => [
'id' => (int) $region->id,
'code' => (string) $region->code,
'name' => (string) $region->name,
'country_code' => (string) $region->country_code,
'status' => (string) $region->status,
])->all();
$regionNames = [];
foreach ($regions as $region) {
$regionNames[$region['id']] = $region['name'];
}
$usage = CloudVpc::query()->where('active_claim', 1)
->selectRaw('cidr_pool_id, COUNT(*) AS row_count')
->groupBy('cidr_pool_id')->pluck('row_count', 'cidr_pool_id');
$items = CloudVpcCidrPool::query()->orderBy('region_id')->orderBy('id')
->get()->map(static fn ($pool): array => self::dto(
$pool,
(string) ($regionNames[(int) $pool->region_id]
?? '地区已缺失'),
(int) ($usage[(int) $pool->id] ?? 0)
))->all();
return [
'regions' => $regions,
'items' => $items,
'feature_enabled' => CloudVpcFeature::enabled(),
];
}
public static function read(int $id): array
{
$pool = self::pool($id);
$region = CloudRegion::find((int) $pool->region_id);
return ['item' => self::dto(
$pool,
(string) ($region?->name ?? '地区已缺失'),
self::activeUsage((int) $pool->id)
)];
}
public static function create(array $input): array
{
$requestKey = $input['request_key'] ?? null;
if (!is_string($requestKey)
|| preg_match('/^[0-9a-f]{32}$/D', $requestKey) !== 1) {
throw new CloudError('请提供有效的 VPC 地址池创建请求标识');
}
$desired = self::normalize($input);
$poolKey = substr(hash('sha256', "vpc-cidr-pool\0" . $requestKey),
0, 32);
return self::persist(null, $poolKey, 0, $desired);
}
public static function update(int $id, array $input): array
{
$expected = $input['expected_revision'] ?? null;
if (is_bool($expected) || !is_int($expected) || $expected < 1) {
throw new CloudError('VPC 地址池版本无效,请刷新后重试', 409);
}
return self::persist($id, '', $expected, self::normalize($input));
}
private static function persist(?int $id, string $poolKey,
int $expectedRevision, array $desired): array
{
$connection = (new CloudVpcCidrPool())->getConnection();
$pool = $connection->transaction(static function () use (
$id, $poolKey, $expectedRevision, $desired
): CloudVpcCidrPool {
$region = CloudRegion::query()->where('id', $desired['region_id'])
->lockForUpdate()->first();
if ($region === null) {
throw new CloudError('VPC 地址池所属地区不存在', 404);
}
$rows = CloudVpcCidrPool::query()
->where('region_id', $desired['region_id'])
->orderBy('id')->lockForUpdate()->get();
$pool = $id === null
? $rows->first(static fn ($row): bool =>
hash_equals((string) $row->pool_key, $poolKey))
: $rows->first(static fn ($row): bool =>
(int) $row->id === $id);
if ($id === null && $pool !== null) {
if (self::same($pool, $desired)) {
return $pool;
}
throw new CloudError(
'同一创建请求标识不能用于不同的 VPC 地址池配置', 409
);
}
if ($id !== null && $pool === null) {
if (CloudVpcCidrPool::find($id) !== null) {
throw new CloudError('VPC 地址池不允许更换所属地区', 409);
}
throw new CloudError('VPC 地址池不存在', 404);
}
if ($pool !== null
&& (int) $pool->revision !== $expectedRevision) {
throw new CloudError(
'VPC 地址池配置已被修改,请刷新后重试', 409
);
}
$usage = $pool === null ? 0 : CloudVpc::query()
->where('cidr_pool_id', (int) $pool->id)
->where('active_claim', 1)->orderBy('id')
->lockForUpdate()->get(['id'])->count();
if ($pool !== null && $usage > 0
&& ((string) $pool->cidr !== $desired['cidr']
|| (int) $pool->allocation_prefix
!== $desired['allocation_prefix'])) {
throw new CloudError(
'该地址池仍有 VPC 占用,不能修改 CIDR 或分配前缀', 409
);
}
foreach ($rows as $other) {
if ($pool !== null && (int) $other->id === (int) $pool->id) {
continue;
}
if (self::overlaps($desired['cidr'], (string) $other->cidr)) {
throw new CloudError(
'同一地区的 VPC 地址池不能重叠', 409
);
}
}
if ($pool !== null && self::same($pool, $desired)) {
return $pool;
}
$now = time();
if ($pool === null) {
$pool = new CloudVpcCidrPool();
$pool->pool_key = $poolKey;
$pool->created_at = $now;
$pool->revision = 1;
} else {
$pool->revision = (int) $pool->revision + 1;
}
foreach ($desired as $field => $value) {
$pool->{$field} = $value;
}
$pool->updated_at = $now;
$pool->save();
return $pool;
}, 3);
$region = CloudRegion::find((int) $pool->region_id);
return ['item' => self::dto(
$pool,
(string) ($region?->name ?? '地区已缺失'),
self::activeUsage((int) $pool->id)
)];
}
private static function normalize(array $input): array
{
$regionId = $input['region_id'] ?? null;
$name = $input['name'] ?? null;
$cidr = $input['cidr'] ?? null;
$allocationPrefix = $input['allocation_prefix'] ?? null;
$state = $input['state'] ?? null;
if (is_bool($regionId) || !is_int($regionId) || $regionId < 1) {
throw new CloudError('请选择有效的 VPC 地址池所属地区');
}
if (!is_string($name) || ($name = trim($name)) === ''
|| mb_strlen($name) > 80
|| preg_match('/[\x00-\x1f\x7f]/u', $name) === 1) {
throw new CloudError('VPC 地址池名称需为 1 至 80 个字符');
}
[$normalizedCidr, $prefix] = self::normalizeCidr($cidr);
if (is_bool($allocationPrefix) || !is_int($allocationPrefix)
|| $allocationPrefix < $prefix || $allocationPrefix > 28) {
throw new CloudError(
'VPC 分配前缀必须不小于地址池前缀,且不能大于 28'
);
}
if (!is_string($state) || !in_array($state, self::STATES, true)) {
throw new CloudError('VPC 地址池状态无效');
}
return [
'region_id' => $regionId,
'name' => $name,
'cidr' => $normalizedCidr,
'prefix_length' => $prefix,
'allocation_prefix' => $allocationPrefix,
'state' => $state,
];
}
private static function normalizeCidr(mixed $value): array
{
if (!is_string($value)
|| preg_match('/^([^\/]+)\/([0-9]{1,2})$/D', trim($value),
$match) !== 1
|| filter_var($match[1], FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4) === false) {
throw new CloudError('VPC 地址池必须填写有效的 RFC1918 IPv4 CIDR');
}
$prefix = (int) $match[2];
if ($prefix < 8 || $prefix > 28) {
throw new CloudError('VPC 地址池前缀必须为 /8 至 /28');
}
$address = self::number($match[1]);
$mask = self::mask($prefix);
$network = $address & $mask;
if ($network !== $address) {
throw new CloudError('VPC 地址池 CIDR 必须填写规范网络地址');
}
$end = $network | (~$mask & 0xffffffff);
if (!self::insidePrivateRange($network, $end)) {
throw new CloudError('VPC 地址池必须完整位于 RFC1918 私网范围');
}
return [long2ip($network) . '/' . $prefix, $prefix];
}
private static function insidePrivateRange(int $start, int $end): bool
{
foreach ([['10.0.0.0', 8], ['172.16.0.0', 12],
['192.168.0.0', 16]] as [$address, $prefix]) {
$base = self::number($address);
$last = $base | (~self::mask($prefix) & 0xffffffff);
if ($start >= $base && $end <= $last) {
return true;
}
}
return false;
}
private static function overlaps(string $left, string $right): bool
{
[$leftStart, $leftEnd] = self::bounds($left);
[$rightStart, $rightEnd] = self::bounds($right);
return $leftStart <= $rightEnd && $rightStart <= $leftEnd;
}
private static function bounds(string $cidr): array
{
[$address, $prefix] = explode('/', $cidr, 2);
$start = self::number($address) & self::mask((int) $prefix);
return [$start,
$start | (~self::mask((int) $prefix) & 0xffffffff)];
}
private static function number(string $address): int
{
$packed = inet_pton($address);
if ($packed === false || strlen($packed) !== 4) {
throw new CloudError('VPC IPv4 地址格式无效');
}
return (int) unpack('Naddress', $packed)['address'];
}
private static function mask(int $prefix): int
{
return (0xffffffff << (32 - $prefix)) & 0xffffffff;
}
private static function same(CloudVpcCidrPool $pool,
array $desired): bool
{
foreach ($desired as $field => $value) {
if ((string) $pool->{$field} !== (string) $value) {
return false;
}
}
return true;
}
private static function activeUsage(int $poolId): int
{
return (int) CloudVpc::query()->where('cidr_pool_id', $poolId)
->where('active_claim', 1)->count();
}
private static function pool(int $id): CloudVpcCidrPool
{
$pool = $id > 0 ? CloudVpcCidrPool::find($id) : null;
if ($pool === null) {
throw new CloudError('VPC 地址池不存在', 404);
}
return $pool;
}
private static function dto(CloudVpcCidrPool $pool, string $regionName,
int $used): array
{
$capacity = 1 << ((int) $pool->allocation_prefix
- (int) $pool->prefix_length);
return [
'id' => (int) $pool->id,
'pool_key' => (string) $pool->pool_key,
'region_id' => (int) $pool->region_id,
'region_name' => $regionName,
'name' => (string) $pool->name,
'cidr' => (string) $pool->cidr,
'prefix_length' => (int) $pool->prefix_length,
'allocation_prefix' => (int) $pool->allocation_prefix,
'state' => (string) $pool->state,
'revision' => (int) $pool->revision,
'used' => $used,
'capacity' => $capacity,
'available' => max(0, $capacity - $used),
'address_locked' => $used > 0,
'created_at' => (int) $pool->created_at,
'updated_at' => (int) $pool->updated_at,
];
}
}

@ -171,6 +171,7 @@ $app->group('/admin', function () {
$this->get('', 'App\Controllers\AdminController:index');
$this->get('/', 'App\Controllers\AdminController:index');
$this->get('/resources', 'App\Controllers\Admin\CloudPageController:resources');
$this->get('/vpc', 'App\Controllers\Admin\CloudPageController:vpc');
// Host network preparation (administrator only).
$this->get('/hosts', 'App\Controllers\Admin\CloudPageController:hosts');
$this->get('/agents', 'App\Controllers\Admin\CloudPageController:agents');

@ -139,6 +139,10 @@ $app->group('/api/v1', function () {
$this->get('/admin/billing/payments',
'App\Controllers\CloudAdminBillingController:payments');
$this->get('/admin/resources', 'App\Controllers\CloudAdminResourceController:resources');
$this->map(['GET', 'POST'], '/admin/vpc-cidr-pools',
'App\Controllers\CloudAdminVpcController:pools');
$this->map(['GET', 'PATCH'], '/admin/vpc-cidr-pools/{id:[1-9][0-9]*}',
'App\Controllers\CloudAdminVpcController:pools');
$this->get('/admin/platform-test-policy',
'App\Controllers\CloudAdminPlatformPolicyController:index');
$this->post('/admin/platform-test-policy/rules',

@ -0,0 +1,66 @@
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: [], 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 : []; 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 < 8 || prefix > 28) throw new Error('VPC 分配前缀必须是 8 至 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('VPC 地址池目录已读取。功能开关仍保持关闭。'); }
catch (error) { notice(error.message, true); }
}
void initialize();

@ -0,0 +1,59 @@
{assign var=admin_title value='VPC 私网'}
{assign var=admin_active value='vpc'}
{include file='admin/static_header.tpl'}
<link rel="stylesheet" href="/cloud/admin.css?v={$venix_asset_version}">
<section class="cloud-admin" data-admin-vpc data-can-manage="{if $admin_can_manage|default:false}1{else}0{/if}">
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column cloud-admin-page-head">
<div class="flex-grow-1">
<p class="admin-eyebrow mb-1">Private Networking</p>
<h4 class="fs-20 fw-semibold mb-1">VPC 私网</h4>
<p class="text-muted mb-0">按地区维护互不重叠的 RFC1918 地址池;每个用户 VPC 从所属地区取得一个独立子网。</p>
</div>
<div class="text-sm-end mt-3 mt-sm-0 cloud-admin-actions"><p id="admin-vpc-status" class="alert alert-info cloud-admin-notice" role="status" aria-live="polite">正在加载…</p></div>
</div>
<div class="alert alert-warning cloud-admin-guidance" role="note">
<i class="mdi mdi-shield-lock-outline"></i>
<span>VPC 功能开关当前保持关闭,直至 Agent 路由应用、实例网卡和恢复流程全部完成。停用地址池只停止新建 VPC,不会删除已有网络。</span>
</div>
<div class="cloud-admin-grid cloud-admin-host-layout">
<aside class="card cloud-admin-side">
<div class="card-body">
<div class="cloud-admin-card-head cloud-admin-card-head-compact">
<div><p class="admin-eyebrow mb-1">CIDR Pools</p><h5 class="mb-0">地区地址池</h5></div>
<button id="admin-vpc-pool-new" class="btn btn-primary" type="button" {if !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-plus me-1"></i>添加</button>
</div>
<div id="admin-vpc-pool-list" class="cloud-admin-host-list"></div>
</div>
</aside>
<form id="admin-vpc-pool-form" class="card cloud-admin-form-card">
<div class="card-body">
<div class="cloud-admin-card-head">
<div><p class="admin-eyebrow mb-1">Allocation Boundary</p><h5 id="admin-vpc-pool-title" class="mb-1">添加 VPC 地址池</h5><p class="text-muted mb-0">同一地区地址池不可重叠;已有 VPC 占用时 CIDR 与分配前缀自动锁定。</p></div>
<span class="cloud-admin-card-icon"><i class="mdi mdi-ip-network-outline"></i></span>
</div>
<input id="admin-vpc-pool-id" type="hidden">
<input id="admin-vpc-pool-revision" type="hidden" value="0">
<section class="cloud-admin-form-section">
<div class="cloud-admin-form-grid">
<div><label for="admin-vpc-pool-region" class="form-label">所属地区</label><select id="admin-vpc-pool-region" class="form-select" required {if !$admin_can_manage|default:false}disabled{/if}></select></div>
<div><label for="admin-vpc-pool-state" class="form-label">运行状态</label><select id="admin-vpc-pool-state" class="form-select" required {if !$admin_can_manage|default:false}disabled{/if}><option value="active">启用分配</option><option value="disabled">停用</option></select></div>
<div class="cloud-admin-full"><label for="admin-vpc-pool-name" class="form-label">地址池名称</label><input id="admin-vpc-pool-name" class="form-control" maxlength="80" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div><label for="admin-vpc-pool-cidr" class="form-label">RFC1918 CIDR</label><input id="admin-vpc-pool-cidr" class="form-control admin-mono" placeholder="例如 10.64.0.0/12" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div><label for="admin-vpc-pool-prefix" class="form-label">每个 VPC 的前缀</label><input id="admin-vpc-pool-prefix" class="form-control" type="number" min="8" max="28" value="24" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div id="admin-vpc-pool-capacity" class="cloud-admin-full form-text">保存后显示可分配子网数量。</div>
</div>
</section>
<div class="cloud-admin-form-footer">
<span class="text-muted">仅接受 10.0.0.0/8、172.16.0.0/12、192.168.0.0/16 内的规范网络地址。</span>
<button id="admin-vpc-pool-save" class="btn btn-primary" type="submit" {if !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-content-save-outline me-1"></i>保存地址池</button>
</div>
</div>
</form>
</div>
</section>
<script type="module" src="/cloud/admin-vpc.js?v={$venix_asset_version}"></script>
{include file='admin/static_footer.tpl'}

@ -160,6 +160,7 @@
<li class="menu-title">虚拟化</li>
<li><a class="{if $admin_active|default:'' == 'resources'}active{/if}" href="/admin/resources"><i class="mdi mdi-server-network-outline"></i><span>资源调度</span></a></li>
<li><a class="{if $admin_active|default:'' == 'vpc'}active{/if}" href="/admin/vpc"><i class="mdi mdi-lan"></i><span>VPC 私网</span></a></li>
<li><a class="{if $admin_active|default:'' == 'hosts'}active{/if}" href="/admin/hosts"><i class="mdi mdi-router-network"></i><span>计算节点</span></a></li>
<li><a class="{if $admin_active|default:'' == 'agents'}active{/if}" href="/admin/agents"><i class="mdi mdi-api"></i><span>Agent API</span></a></li>
<li><a class="{if $admin_active|default:'' == 'object-storage'}active{/if}" href="/admin/object-storage"><i class="mdi mdi-cloud-lock-outline"></i><span>对象存储</span></a></li>

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026102805' scope='global'}
{assign var=venix_asset_version value='2026102806' scope='global'}

@ -197,6 +197,7 @@ CREATE TABLE cloud_vpc_cidr_pools (
prefix_length TINYINT UNSIGNED NOT NULL,
allocation_prefix TINYINT UNSIGNED NOT NULL DEFAULT 24,
state VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'active',
revision BIGINT UNSIGNED NOT NULL DEFAULT 1,
created_at BIGINT UNSIGNED NOT NULL,
updated_at BIGINT UNSIGNED NOT NULL,
UNIQUE KEY cloud_vpc_cidr_pool_key (pool_key),
@ -484,25 +485,29 @@ CREATE TABLE cloud_vpcs (
cidr VARCHAR(18) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
prefix_length TINYINT UNSIGNED NOT NULL,
gateway VARCHAR(15) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
active_claim TINYINT UNSIGNED DEFAULT 1,
state VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'provisioning',
desired_revision BIGINT UNSIGNED NOT NULL DEFAULT 1,
deleted_at BIGINT UNSIGNED DEFAULT NULL,
created_at BIGINT UNSIGNED NOT NULL,
updated_at BIGINT UNSIGNED NOT NULL,
UNIQUE KEY cloud_vpc_key (vpc_key),
UNIQUE KEY cloud_vpc_region_cidr (region_id, cidr),
UNIQUE KEY cloud_vpc_region_cidr (region_id, cidr, active_claim),
KEY cloud_vpc_owner (user_id, state, id),
KEY cloud_vpc_region_state (region_id, state, id),
KEY cloud_vpc_pool_state (cidr_pool_id, state, id),
CONSTRAINT chk_cloud_vpc_prefix CHECK (
prefix_length BETWEEN 16 AND 28
),
CONSTRAINT chk_cloud_vpc_active_claim CHECK (
active_claim IS NULL OR active_claim = 1
),
CONSTRAINT chk_cloud_vpc_state CHECK (
state IN ('provisioning','active','degraded','deleting','deleted')
),
CONSTRAINT chk_cloud_vpc_deleted_at CHECK (
(state = 'deleted' AND deleted_at IS NOT NULL)
OR (state <> 'deleted' AND deleted_at IS NULL)
(state = 'deleted' AND active_claim IS NULL AND deleted_at IS NOT NULL)
OR (state <> 'deleted' AND active_claim = 1 AND deleted_at IS NULL)
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

@ -0,0 +1,146 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudAdminVpcCidrPoolService;
use App\Services\Cloud\CloudError;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$expectConflict = static function (callable $callback, string $message) use (
$assert
): void {
try {
$callback();
throw new RuntimeException($message);
} catch (CloudError $error) {
$assert($error->httpStatus === 409,
$message . ' (status ' . $error->httpStatus . ')');
}
};
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('cloud_regions', static function (Blueprint $table): void {
$table->increments('id'); $table->string('code'); $table->string('name');
$table->string('country_code', 2); $table->string('status');
$table->integer('sort'); $table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_vpc_cidr_pools',
static function (Blueprint $table): void {
$table->increments('id'); $table->string('pool_key', 32)->unique();
$table->integer('region_id'); $table->string('name');
$table->string('cidr', 18); $table->integer('prefix_length');
$table->integer('allocation_prefix'); $table->string('state');
$table->integer('revision'); $table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_vpcs', static function (Blueprint $table): void {
$table->increments('id'); $table->string('vpc_key', 32);
$table->integer('user_id'); $table->integer('region_id');
$table->integer('cidr_pool_id'); $table->string('name');
$table->string('cidr', 18); $table->integer('prefix_length');
$table->string('gateway', 15); $table->integer('active_claim')->nullable();
$table->string('state'); $table->integer('desired_revision');
$table->integer('deleted_at')->nullable(); $table->integer('created_at');
$table->integer('updated_at');
});
Capsule::table('cloud_regions')->insert([
['id' => 1, 'code' => 'hkg', 'name' => 'Hong Kong',
'country_code' => 'HK', 'status' => 'active', 'sort' => 0,
'created_at' => 1, 'updated_at' => 1],
['id' => 2, 'code' => 'nrt', 'name' => 'Tokyo',
'country_code' => 'JP', 'status' => 'active', 'sort' => 1,
'created_at' => 1, 'updated_at' => 1],
]);
$created = CloudAdminVpcCidrPoolService::create([
'request_key' => str_repeat('a', 32), 'region_id' => 1,
'name' => 'HKG Private', 'cidr' => '10.64.0.0/12',
'allocation_prefix' => 24, 'state' => 'active',
]);
$pool = $created['item'];
$assert($pool['revision'] === 1 && $pool['capacity'] === 4096
&& $pool['available'] === 4096 && $pool['address_locked'] === false,
'VPC pool capacity or initial revision is incorrect.');
$replay = CloudAdminVpcCidrPoolService::create([
'request_key' => str_repeat('a', 32), 'region_id' => 1,
'name' => 'HKG Private', 'cidr' => '10.64.0.0/12',
'allocation_prefix' => 24, 'state' => 'active',
]);
$assert($replay['item']['id'] === $pool['id']
&& Capsule::table('cloud_vpc_cidr_pools')->count() === 1,
'Idempotent VPC pool creation produced a duplicate.');
$expectConflict(static fn () => CloudAdminVpcCidrPoolService::create([
'request_key' => str_repeat('b', 32), 'region_id' => 1,
'name' => 'Overlap', 'cidr' => '10.64.16.0/20',
'allocation_prefix' => 24, 'state' => 'active',
]), 'Overlapping pools in one region were accepted.');
$otherRegion = CloudAdminVpcCidrPoolService::create([
'request_key' => str_repeat('c', 32), 'region_id' => 2,
'name' => 'NRT Private', 'cidr' => '10.64.0.0/12',
'allocation_prefix' => 24, 'state' => 'active',
]);
$assert($otherRegion['item']['region_id'] === 2,
'Identical private ranges in isolated regions were incorrectly rejected.');
try {
CloudAdminVpcCidrPoolService::create([
'request_key' => str_repeat('d', 32), 'region_id' => 1,
'name' => 'Noncanonical', 'cidr' => '10.80.1.1/16',
'allocation_prefix' => 24, 'state' => 'active',
]);
throw new RuntimeException('Noncanonical private CIDR was accepted.');
} catch (CloudError $error) {
$assert($error->httpStatus === 422,
'Noncanonical CIDR rejection used the wrong status.');
}
$updated = CloudAdminVpcCidrPoolService::update($pool['id'], [
'region_id' => 1, 'name' => 'HKG Primary', 'cidr' => '10.64.0.0/12',
'allocation_prefix' => 24, 'state' => 'active',
'expected_revision' => 1,
]);
$assert($updated['item']['revision'] === 2
&& $updated['item']['name'] === 'HKG Primary',
'VPC pool update did not advance the revision.');
Capsule::table('cloud_vpcs')->insert([
'id' => 1, 'vpc_key' => str_repeat('e', 32), 'user_id' => 7,
'region_id' => 1, 'cidr_pool_id' => $pool['id'], 'name' => 'prod',
'cidr' => '10.64.0.0/24', 'prefix_length' => 24,
'gateway' => '10.64.0.1', 'active_claim' => 1, 'state' => 'active',
'desired_revision' => 1, 'deleted_at' => null,
'created_at' => 2, 'updated_at' => 2,
]);
$expectConflict(static fn () => CloudAdminVpcCidrPoolService::update(
$pool['id'], [
'region_id' => 1, 'name' => 'HKG Primary',
'cidr' => '10.96.0.0/12', 'allocation_prefix' => 24,
'state' => 'active', 'expected_revision' => 2,
]
), 'Occupied VPC pool boundary was editable.');
$disabled = CloudAdminVpcCidrPoolService::update($pool['id'], [
'region_id' => 1, 'name' => 'HKG Primary', 'cidr' => '10.64.0.0/12',
'allocation_prefix' => 24, 'state' => 'disabled',
'expected_revision' => 2,
]);
$assert($disabled['item']['revision'] === 3
&& $disabled['item']['used'] === 1
&& $disabled['item']['address_locked'] === true,
'Occupied pool could not be safely disabled or usage was lost.');
echo "Administrator VPC CIDR pool service passed.\n";

@ -0,0 +1,50 @@
<?php
$root = dirname(__DIR__);
$routes = file_get_contents($root . '/config/routes.php');
$apiRoutes = file_get_contents($root . '/config/routes_cloud.php');
$pageController = file_get_contents(
$root . '/app/Controllers/Admin/CloudPageController.php'
);
$apiController = file_get_contents(
$root . '/app/Controllers/CloudAdminVpcController.php'
);
$sidebar = file_get_contents(
$root . '/resources/views/venix/admin/static_header.tpl'
);
$template = file_get_contents(
$root . '/resources/views/venix/admin/cloud/vpc.tpl'
);
$javascript = file_get_contents($root . '/public/cloud/admin-vpc.js');
$assets = file_get_contents(
$root . '/resources/views/venix/layout_assets.tpl'
);
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$assert(str_contains($routes, "'/vpc'")
&& str_contains($pageController, "display('admin/cloud/vpc.tpl')")
&& str_contains($sidebar, 'href="/admin/vpc"'),
'Administrator VPC page is not reachable from the virtualization sidebar.');
$assert(str_contains($apiRoutes, "'/admin/vpc-cidr-pools'")
&& str_contains($apiRoutes, "'/admin/vpc-cidr-pools/{id:")
&& str_contains($apiController, 'CloudAccess::manage($actor)')
&& str_contains($apiController,
"'Cache-Control', 'private, no-store'"),
'Administrator VPC CIDR pool API contract is incomplete.');
$assert(str_contains($template, 'data-admin-vpc')
&& str_contains($template, 'id="admin-vpc-pool-form"')
&& str_contains($template, '/cloud/admin-vpc.js?v={$venix_asset_version}')
&& str_contains($javascript, 'globalThis.crypto?.getRandomValues')
&& str_contains($javascript, "method: id ? 'PATCH' : 'POST'"),
'Administrator VPC CIDR pool UI lost its versioned or idempotent workflow.');
$assert(preg_match("/venix_asset_version value='([0-9]+)'/", $assets,
$version) === 1
&& (int) $version[1] >= 2026102806,
'Administrator VPC browser assets were not cache-busted.');
echo "Administrator VPC CIDR pool page and API contracts passed.\n";

@ -22,7 +22,7 @@ $assert(stripos($schema, 'compatibility import') === false
$assert(!preg_match('/\bengine_[A-Za-z0-9_]*\b/', $schema),
'cloud.sql retained an engine-prefixed identifier.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v13-vpc-l3-v1'")
"SCHEMA_VERSION = 'go-agent-wss-v13-vpc-l3-v2'")
&& !str_contains($setup, "SCHEMA_VERSION = 'go-v1'"),
'Outbound Agent schema must reject the incompatible earlier Go database.');
$assert(str_contains($schema,

@ -41,11 +41,17 @@ $assert(str_contains($schema,
$assert(str_contains($schema, 'cloud_vpc_cidr_pool_region (region_id, cidr)')
&& str_contains($schema,
'allocation_prefix BETWEEN prefix_length AND 28')
&& str_contains($schema, 'cloud_vpc_region_cidr (region_id, cidr)')
&& str_contains($schema, 'revision BIGINT UNSIGNED NOT NULL DEFAULT 1')
&& str_contains($schema,
'cloud_vpc_region_cidr (region_id, cidr, active_claim)')
&& str_contains($schema, 'cloud_vpc_pool_state (cidr_pool_id, state, id)'),
'Region-scoped VPC CIDR allocation is not protected.');
$assert(str_contains($schema,
'cloud_vpc_region_cidr (region_id, cidr, active_claim)')
&& str_contains($schema,
'active_claim IS NULL OR active_claim = 1')
&& str_contains($schema,
'cloud_vpc_port_ip_claim (vpc_id, private_ip, active_claim)')
&& str_contains($schema,
'cloud_vpc_port_instance_claim (instance_id, active_claim)')
@ -76,7 +82,7 @@ $assert(str_contains($jobs, 'vpc_id BIGINT UNSIGNED DEFAULT NULL')
'Cloud jobs cannot be correlated to VPC or VPC-port work.');
$assert(str_contains($setup,
"private const SCHEMA_VERSION = 'go-agent-wss-v13-vpc-l3-v1'")
"private const SCHEMA_VERSION = 'go-agent-wss-v13-vpc-l3-v2'")
&& str_contains($setup, "'name' => 'cloud_vpc_enabled'")
&& str_contains($setup, "'value' => 'false'")
&& str_contains($setup, "'cloud_job_vpc', 'cloud_job_vpc_port'")

Loading…
Cancel
Save