feat: bind public pools to network attachments

go
codex 3 weeks ago
parent aa408ed8bc
commit 669ca96226

@ -36,8 +36,9 @@ final class CloudAdminHostNetworkController
} else {
$body = CloudInput::object($request);
CloudInput::only($body, [
'name', 'cidr', 'gateway', 'dns_servers', 'reserved_ips',
'guest_prefix_length', 'state', 'request_key',
'network_attachment_id', 'name', 'cidr', 'gateway',
'dns_servers', 'reserved_ips', 'guest_prefix_length',
'state', 'request_key',
]);
$result = $service->create($hostId, $actor, $body);
$status = 201;
@ -52,8 +53,9 @@ final class CloudAdminHostNetworkController
$actor = $this->actor($request, true);
$body = CloudInput::object($request);
CloudInput::only($body, [
'name', 'cidr', 'gateway', 'dns_servers', 'reserved_ips',
'guest_prefix_length', 'state', 'expected_revision',
'network_attachment_id', 'name', 'cidr', 'gateway',
'dns_servers', 'reserved_ips', 'guest_prefix_length',
'state', 'expected_revision',
]);
$result = (new CloudAdminHostNetworkService())->update(
(int) ($args['id'] ?? 0),

@ -3,6 +3,7 @@
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudHostAgent;
use App\Models\CloudHostNetworkAttachment;
use App\Models\CloudHostResourcePoolMembership;
use App\Models\CloudNetworkLine;
@ -126,35 +127,14 @@ final class CloudAdminHostNetworkService
}
$memberships = CloudHostPoolMembershipService::lockedRows($lockedHost);
$membership = CloudHostPoolMembershipService::selected(
$memberships
);
if ($membership === null) {
throw new CloudError(
'请先将宿主机加入资源池,再配置该线路的公网地址池',
409
);
}
$resourcePool = CloudResourcePool::where(
'id', (int) $membership->resource_pool_id
$agent = CloudHostAgent::where(
'host_id', (int) $lockedHost->id
)->lockForUpdate()->first();
if ($resourcePool === null || (int) $resourcePool->line_id < 1) {
throw new CloudError('宿主机资源池或线路配置已失效', 409);
}
$selector = (string) $lockedHost->default_network;
if (!CloudNetworkSelector::isValid($selector)) {
throw new CloudError(
'请先在面板配置 bridge:网桥名 或 network:libvirt网络名;旧选择器须核对实际映射后迁移',
409
);
}
$attachmentKey = substr(hash('sha256', $selector), 0, 32);
$attachments = CloudHostNetworkAttachment::where(
'host_id', (int) $lockedHost->id
)->orderBy('id')->lockForUpdate()->get();
$attachment = $attachments->first(static fn ($row): bool =>
hash_equals((string) $row->attachment_key, $attachmentKey)
(int) $row->id === $desired['network_attachment_id']
);
$poolRows = CloudPublicIpPool::where(
@ -185,12 +165,7 @@ final class CloudAdminHostNetworkService
if ($creating) {
if ($pool !== null || $live !== null) {
if ($pool !== null && self::sameCreateRequest(
$pool,
$originalAttachment,
$desired,
$attachmentKey,
$selector,
(int) $resourcePool->line_id
$pool, $desired
)) {
if ((string) $pool->sync_state === 'applied') {
return [
@ -225,6 +200,19 @@ final class CloudAdminHostNetworkService
}
}
if ($attachment === null) {
throw new CloudError('所选网络接入不存在或不属于该宿主机', 409);
}
$line = self::assertMembershipLine(
$memberships, (int) $attachment->line_id
);
if ($creating || $desired['state'] === 'active') {
self::assertAttachmentReady($attachment, $agent);
if ((string) $line->status !== 'active') {
throw new CloudError('网络接入所属线路未启用', 409);
}
}
if ($pool === null && self::catalogCount($poolRows) >= self::MAX_POOLS) {
throw new CloudError(
'一台宿主机最多配置 32 个公网地址池',
@ -265,35 +253,11 @@ final class CloudAdminHostNetworkService
}
$occupied = $pool === null ? 0
: ($occupiedByPool[(int) $pool->id] ?? 0);
$attachmentLineChanged = $attachment !== null
&& (int) $attachment->line_id
!== (int) $resourcePool->line_id;
if ($attachmentLineChanged) {
foreach ($poolRows as $row) {
if ((int) $row->network_attachment_id
=== (int) $attachment->id
&& ($occupiedByPool[(int) $row->id] ?? 0) > 0) {
throw new CloudError(
'公网接入仍有关联地址被占用,不能切换所属线路',
409
);
}
}
}
$current = $live ?? ($pool === null ? null : [
...self::poolConfig($pool),
'network_selector' => (string) (
$originalAttachment?->network_selector ?? ''
),
]);
$current = $live ?? ($pool === null
? null : self::poolConfig($pool));
$attachmentChanged = $pool !== null && (
$originalAttachment === null
|| (string) $originalAttachment->attachment_key
!== $attachmentKey
|| (string) $originalAttachment->network_selector
!== $selector
|| (int) $originalAttachment->line_id
!== (int) $resourcePool->line_id
|| (int) $originalAttachment->id !== (int) $attachment->id
);
$occupiedAddresses = $pool === null ? []
: ($occupiedAddressesByPool[(int) $pool->id] ?? []);
@ -313,7 +277,7 @@ final class CloudAdminHostNetworkService
if ($occupied > 0 && ($attachmentChanged
|| ($current !== null
&& self::occupiedUnsafeRuntimeChanged(
$current, $desired, $selector
$current, $desired
)))) {
throw new CloudError(
'该地址池仍有实例或任务占用,只能修改名称、运行状态和未占用的保留 / 禁用 IP',
@ -327,25 +291,6 @@ final class CloudAdminHostNetworkService
$revision = $revisionBase + 1;
$now = time();
if ($attachment === null) {
$attachment = new CloudHostNetworkAttachment();
$attachment->attachment_key = $attachmentKey;
$attachment->host_id = (int) $lockedHost->id;
$attachment->vlan_id = null;
$attachment->routing_table = null;
$attachment->state = 'disabled';
$attachment->priority = 0;
$attachment->desired_revision = 0;
$attachment->observed_revision = 0;
$attachment->sync_state = 'never';
$attachment->last_error_code = '';
$attachment->created_at = $now;
}
$attachment->line_id = (int) $resourcePool->line_id;
$attachment->name = mb_substr($selector, 0, 80);
$attachment->network_mode = 'selector';
$attachment->network_selector = $selector;
if ($pool === null) {
$pool = new CloudPublicIpPool();
$pool->pool_key = $poolKey;
@ -377,20 +322,9 @@ final class CloudAdminHostNetworkService
$pool->last_error_code = '';
$pool->updated_at = $now;
// The attachment row must exist before its identifier can be
// referenced by the pool row. Both remain inside this transaction.
// Pool revisions are independent. The parent revision represents
// evidence for the shared selector, so another child mutation
// must not invalidate an already confirmed egress attachment.
$attachment->desired_revision = max(
1, (int) $attachment->desired_revision
);
$attachment->updated_at = $now;
$attachment->save();
$pool->network_attachment_id = (int) $attachment->id;
$pool->save();
self::materializeIpLedger($pool);
self::refreshAttachmentAggregate($attachment);
return [
'replay' => false,
@ -398,7 +332,8 @@ final class CloudAdminHostNetworkService
'payload' => [
'revision' => $revision,
'state' => $desired['state'],
'network_selector' => $selector,
'network_attachment_id' => (int) $attachment->id,
'network_selector' => (string) $attachment->network_selector,
'cidr' => $desired['cidr'],
'gateway' => $desired['gateway'],
'dns_servers' => $desired['dns_servers'],
@ -414,6 +349,41 @@ final class CloudAdminHostNetworkService
{
$dbRows = CloudPublicIpPool::where('host_id', (int) $host->id)
->orderBy('priority')->orderBy('id')->get();
$attachmentRows = CloudHostNetworkAttachment::where(
'host_id', (int) $host->id
)->orderBy('priority')->orderBy('id')->get();
$lineIds = $attachmentRows->pluck('line_id')->map(
static fn ($id): int => (int) $id
)->filter()->unique()->values()->all();
$lines = $lineIds === [] ? collect()
: CloudNetworkLine::whereIn('id', $lineIds)->get()->keyBy('id');
$agent = CloudHostAgent::find((int) $host->id);
$testedSelectors = $agent === null ? []
: CloudAgentSettingsService::testedNetworkSelectors($agent);
$activePoolIds = CloudHostResourcePoolMembership::where(
'host_id', (int) $host->id
)->where('scheduler_state', 'active')
->pluck('resource_pool_id')->map(
static fn ($id): int => (int) $id
)->unique()->values()->all();
$activeLineIds = $activePoolIds === [] ? []
: CloudResourcePool::whereIn('id', $activePoolIds)
->where('status', 'active')->pluck('line_id')->mapWithKeys(
static fn ($id): array => [(int) $id => true]
)->all();
$attachments = [];
$attachmentsById = [];
foreach ($attachmentRows as $attachmentRow) {
$dto = self::attachmentDto(
$attachmentRow,
$lines->get((int) $attachmentRow->line_id),
$agent,
$testedSelectors,
$activeLineIds
);
$attachments[] = $dto;
$attachmentsById[(int) $attachmentRow->id] = $dto;
}
$byKey = [];
foreach ($dbRows as $row) {
$byKey[(string) $row->pool_key] = $row;
@ -438,10 +408,16 @@ final class CloudAdminHostNetworkService
foreach ($catalog['items'] as $live) {
$key = (string) $live['pool_key'];
$row = $byKey[$key] ?? null;
$attachmentId = (int) (
$row?->network_attachment_id
?? ($live['network_attachment_id'] ?? 0)
);
$items[] = self::poolDto(
$row,
$live,
$row === null ? 0 : ($occupied[(int) $row->id] ?? 0)
$row === null ? 0 : ($occupied[(int) $row->id] ?? 0),
$attachmentsById[$attachmentId]
?? self::missingAttachmentDto($attachmentId)
);
$seen[$key] = true;
}
@ -453,20 +429,20 @@ final class CloudAdminHostNetworkService
$items[] = self::poolDto(
$row,
null,
$occupied[(int) $row->id] ?? 0
$occupied[(int) $row->id] ?? 0,
$attachmentsById[(int) $row->network_attachment_id]
?? self::missingAttachmentDto(
(int) $row->network_attachment_id
)
);
}
$context = $this->lineContext((int) $host->id);
return [
'host' => [
'id' => (int) $host->id,
'name' => self::safeText((string) $host->name, 80),
'default_network' => self::safeText(
(string) $host->default_network, 128
),
],
'line' => $context,
'attachments' => $attachments,
'items' => $items,
'count' => count($items),
'maximum' => self::MAX_POOLS,
@ -474,24 +450,6 @@ final class CloudAdminHostNetworkService
];
}
private function lineContext(int $hostId): ?array
{
$host = CloudHost::find($hostId);
$rows = CloudHostResourcePoolMembership::where('host_id', $hostId)
->orderBy('resource_pool_id')->orderBy('id')->get();
$membership = $host === null ? null
: CloudHostPoolMembershipService::selected($rows);
$resourcePool = $membership === null ? null
: CloudResourcePool::find((int) $membership->resource_pool_id);
$lineId = $resourcePool === null ? null : (int) $resourcePool->line_id;
$line = $lineId === null ? null : CloudNetworkLine::find($lineId);
return $line === null ? null : [
'id' => (int) $line->id,
'name' => self::safeText((string) $line->name, 80),
'status' => self::safeText((string) $line->status, 16),
];
}
/** The panel database is the sole catalog for scheduling and IP capacity. */
private function databaseCatalog(int $hostId): array
{
@ -507,6 +465,7 @@ final class CloudAdminHostNetworkService
$items[] = [
'pool_key' => (string) $row->pool_key,
'revision' => max(0, (int) $row->desired_revision),
'network_attachment_id' => (int) $row->network_attachment_id,
'network_selector' => (string) (
$attachments[(int) $row->network_attachment_id]->network_selector
?? ''
@ -518,13 +477,76 @@ final class CloudAdminHostNetworkService
return ['items' => $items];
}
/** Return the line referenced by an active membership on this host. */
private static function assertMembershipLine($memberships,
int $lineId): CloudNetworkLine
{
$poolIds = [];
foreach ($memberships as $membership) {
if ((string) $membership->scheduler_state === 'active') {
$poolIds[] = (int) $membership->resource_pool_id;
}
}
$poolIds = array_values(array_unique($poolIds));
if ($poolIds === []) {
throw new CloudError(
'请先将宿主机加入该线路的资源池,再配置公网地址池',
409
);
}
$hasLine = CloudResourcePool::whereIn('id', $poolIds)
->where('line_id', $lineId)
->where('status', 'active')
->exists();
$line = CloudNetworkLine::find($lineId);
if (!$hasLine || $line === null) {
throw new CloudError(
'所选网络接入的线路没有启用中的资源池成员关系',
409
);
}
return $line;
}
/** Active pools require current, exact Agent evidence for the attachment. */
private static function assertAttachmentReady(
CloudHostNetworkAttachment $attachment,
?CloudHostAgent $agent
): void {
if ((string) $attachment->state !== 'active') {
throw new CloudError('所选网络接入未启用', 409);
}
$testedSelectors = $agent === null ? []
: CloudAgentSettingsService::testedNetworkSelectors($agent);
if ($agent === null || !$agent->isReady()
|| (string) $attachment->verification_state !== 'verified'
|| (int) $attachment->verified_agent_revision
!== (int) $agent->revision
|| (int) $attachment->last_verified_at < 1
|| !in_array(
(string) $attachment->network_selector,
$testedSelectors,
true
)) {
throw new CloudError(
'所选网络接入没有当前 Agent 版本的有效验证证据,请重新测试',
409
);
}
}
private static function normalizeInput(array $body, int $status = 422): array
{
$attachmentId = $body['network_attachment_id'] ?? null;
$name = $body['name'] ?? '';
$state = $body['state'] ?? null;
$prefix = $body['guest_prefix_length'] ?? null;
$dns = $body['dns_servers'] ?? null;
$reserved = $body['reserved_ips'] ?? null;
if (is_bool($attachmentId) || !is_int($attachmentId)
|| $attachmentId < 1) {
throw new CloudError('请选择有效的宿主机网络接入', $status);
}
if (!is_string($name) || trim($name) === ''
|| mb_strlen(trim($name)) > 80
|| preg_match('//u', $name) !== 1
@ -570,6 +592,7 @@ final class CloudAdminHostNetworkService
$reserved, '保留 IP', true, $cidr, $status
);
return [
'network_attachment_id' => $attachmentId,
'name' => trim($name),
'cidr' => $cidr,
'gateway' => $gateway,
@ -727,20 +750,13 @@ final class CloudAdminHostNetworkService
}
private static function sameCreateRequest(CloudPublicIpPool $pool,
?CloudHostNetworkAttachment $attachment, array $desired,
string $attachmentKey, string $selector, int $lineId): bool
array $desired): bool
{
return (string) $pool->name === $desired['name']
&& (string) $pool->state === $desired['state']
&& !self::runtimeChanged([
...self::poolConfig($pool),
'network_selector' => (string) (
$attachment?->network_selector ?? ''
),
], $desired, $selector)
&& $attachment !== null
&& (string) $attachment->attachment_key === $attachmentKey
&& (int) $attachment->line_id === $lineId;
&& (int) $pool->network_attachment_id
=== $desired['network_attachment_id']
&& !self::runtimeChanged(self::poolConfig($pool), $desired);
}
private static function poolConfig(CloudPublicIpPool $pool): array
@ -754,103 +770,25 @@ final class CloudAdminHostNetworkService
];
}
private static function runtimeChanged(array $current, array $desired,
string $selector): bool
private static function runtimeChanged(array $current,
array $desired): bool
{
return self::occupiedUnsafeRuntimeChanged(
$current, $desired, $selector
) || array_values($current['reserved_ips'] ?? [])
return self::occupiedUnsafeRuntimeChanged($current, $desired)
|| array_values($current['reserved_ips'] ?? [])
!== $desired['reserved_ips'];
}
/** Changes here can invalidate the network identity of an occupied IP. */
private static function occupiedUnsafeRuntimeChanged(array $current,
array $desired, string $selector): bool
array $desired): bool
{
return (string) ($current['network_selector'] ?? $selector) !== $selector
|| (string) ($current['cidr'] ?? '') !== $desired['cidr']
return (string) ($current['cidr'] ?? '') !== $desired['cidr']
|| (string) ($current['gateway'] ?? '') !== $desired['gateway']
|| array_values($current['dns_servers'] ?? []) !== $desired['dns_servers']
|| (int) ($current['guest_prefix_length'] ?? 0)
!== $desired['guest_prefix_length'];
}
/** Recompute selector availability without coupling independent pools. */
private static function refreshAttachmentAggregate(
CloudHostNetworkAttachment $attachment): void
{
$pools = CloudPublicIpPool::where(
'network_attachment_id', (int) $attachment->id
)->orderBy('id')->get();
$states = $pools->pluck('state')->all();
$attachment->state = in_array('active', $states, true)
? 'active'
: (in_array('draining', $states, true) ? 'draining' : 'disabled');
$rank = [
'applied' => 0,
'never' => 1,
'pending' => 2,
'failed' => 3,
'uncertain' => 4,
];
$aggregate = $pools->isEmpty() ? 'never' : 'applied';
$aggregateRank = $rank[$aggregate];
$errorCode = '';
$confirmedRevision = 0;
$desiredRevision = max(1, (int) $attachment->desired_revision);
$observedRevision = max(0, (int) $attachment->observed_revision);
foreach ($pools as $pool) {
$desiredRevision = max(
$desiredRevision, (int) $pool->desired_revision
);
$observedRevision = max(
$observedRevision, (int) $pool->observed_revision
);
$childState = (string) $pool->sync_state;
if ($childState === 'applied'
&& (int) $pool->observed_revision
< (int) $pool->desired_revision) {
$childState = 'pending';
}
if (!isset($rank[$childState])) {
$childState = 'uncertain';
}
if ($childState === 'applied') {
$confirmedRevision = max(
$confirmedRevision,
(int) $pool->observed_revision
);
}
if ($rank[$childState] > $aggregateRank) {
$aggregate = $childState;
$aggregateRank = $rank[$childState];
$candidate = (string) $pool->last_error_code;
$errorCode = preg_match('/^[a-z0-9_]{1,64}$/D', $candidate) === 1
? $candidate : 'host_public_pool_child_' . $childState;
}
}
if ($confirmedRevision > 0) {
// One applied child is sufficient to keep the shared selector
// usable; a failed sibling does not rewrite another pool's intent.
$evidenceRevision = max(
$desiredRevision, $observedRevision, $confirmedRevision
);
$attachment->desired_revision = $evidenceRevision;
$attachment->observed_revision = $evidenceRevision;
$attachment->sync_state = 'applied';
$attachment->last_error_code = '';
} else {
$attachment->desired_revision = $desiredRevision;
$attachment->observed_revision = min(
$observedRevision, max(0, $desiredRevision - 1)
);
$attachment->sync_state = $aggregate;
$attachment->last_error_code = $errorCode;
}
$attachment->save();
}
/** Materialize the configured CIDR into the panel-owned address ledger. */
private static function materializeIpLedger(CloudPublicIpPool $pool): void
{
@ -909,10 +847,83 @@ final class CloudAdminHostNetworkService
}
}
private static function attachmentDto(
CloudHostNetworkAttachment $attachment,
?CloudNetworkLine $line,
?CloudHostAgent $agent,
array $testedSelectors,
array $activeLineIds
): array {
$storedVerification = (string) $attachment->verification_state;
$currentEvidence = $agent !== null && $agent->isReady()
&& (int) $attachment->verified_agent_revision
=== (int) $agent->revision
&& (int) $attachment->last_verified_at > 0
&& in_array(
(string) $attachment->network_selector,
$testedSelectors,
true
);
$verification = $storedVerification === 'verified'
&& !$currentEvidence ? 'stale' : $storedVerification;
$lineDto = $line === null ? null : [
'id' => (int) $line->id,
'name' => self::safeText((string) $line->name, 80),
'status' => self::safeText((string) $line->status, 16),
];
return [
'id' => (int) $attachment->id,
'attachment_key' => (string) $attachment->attachment_key,
'name' => self::safeText((string) $attachment->name, 80),
'line_id' => (int) $attachment->line_id,
'line_name' => $lineDto['name'] ?? '线路关系已失效',
'line' => $lineDto,
'network_selector' => (string) $attachment->network_selector,
'state' => (string) $attachment->state,
'config_revision' => (int) $attachment->config_revision,
'verified_agent_revision' =>
(int) $attachment->verified_agent_revision,
'verification_state' => $verification,
'ready' => $verification === 'verified'
&& (string) $attachment->state === 'active'
&& $line !== null && (string) $line->status === 'active'
&& isset($activeLineIds[(int) $attachment->line_id]),
'last_verified_at' => (int) $attachment->last_verified_at,
'verification_error_code' => self::safeText(
(string) $attachment->verification_error_code, 64
),
];
}
private static function missingAttachmentDto(int $attachmentId): array
{
return [
'id' => max(0, $attachmentId),
'attachment_key' => '',
'name' => '网络接入已缺失',
'line_id' => null,
'line_name' => '线路关系已失效',
'line' => null,
'network_selector' => '',
'state' => 'missing',
'config_revision' => 0,
'verified_agent_revision' => 0,
'verification_state' => 'missing',
'ready' => false,
'last_verified_at' => 0,
'verification_error_code' => 'network_attachment_missing',
];
}
private static function poolDto(?CloudPublicIpPool $row, ?array $live,
int $occupied): array
int $occupied, ?array $attachment): array
{
$desired = $row === null ? null : self::poolConfig($row);
$attachmentId = (int) (
$row?->network_attachment_id
?? ($live['network_attachment_id'] ?? 0)
);
$attachment ??= self::missingAttachmentDto($attachmentId);
return [
'pool_key' => (string) ($row?->pool_key ?? $live['pool_key']),
'name' => self::safeText(
@ -936,7 +947,10 @@ final class CloudAdminHostNetworkService
$row?->observed_revision ?? $live['revision']
),
'live_revision' => $row === null ? null : (int) $row->observed_revision,
'network_selector' => (string) ($live['network_selector'] ?? ''),
'network_attachment_id' => $attachmentId,
'attachment' => $attachment,
'line' => $attachment['line'],
'network_selector' => (string) $attachment['network_selector'],
'sync_state' => (string) ($row?->sync_state ?? 'untracked'),
'sync_message' => self::syncMessage(
(string) ($row?->sync_state ?? 'untracked')

@ -14,7 +14,7 @@ const {
const root = document.querySelector('[data-cloud-admin]');
const byId = id => document.getElementById(id);
const state = { csrf: window.ADMIN_CSRF_TOKEN || '', hosts: [], hostRegions: [], hostSummary: {}, expandedHostRegions: new Set(), hostRegionsInitialized: false, selectedHost: '', busy: false, configBusy: false, configOpener: null, configScroll: null, storageBusy: false, storageOpener: null, storageScroll: null, storageObserver: null, schedulingBusy: false, schedulingOpener: null, schedulingScroll: null, networkPoolBusy: false, networkPoolOpener: null, networkPoolScroll: null, networkPoolPayload: null, networkPoolEpoch: 0, networkPoolHostId: '', vpcTransportBusy: false, vpcTransportOpener: null, vpcTransportScroll: null, vpcTransportHostId: '', vpcTransportCandidates: [], taskObservers: new Set() };
const state = { csrf: window.ADMIN_CSRF_TOKEN || '', hosts: [], hostRegions: [], hostSummary: {}, expandedHostRegions: new Set(), hostRegionsInitialized: false, selectedHost: '', busy: false, configBusy: false, configOpener: null, configScroll: null, storageBusy: false, storageOpener: null, storageScroll: null, storageObserver: null, schedulingBusy: false, schedulingOpener: null, schedulingScroll: null, networkAttachmentBusy: false, networkAttachmentOpener: null, networkAttachmentScroll: null, networkAttachmentPayload: null, networkAttachmentCandidates: [], networkAttachmentEpoch: 0, networkAttachmentHostId: '', networkPoolBusy: false, networkPoolOpener: null, networkPoolScroll: null, networkPoolPayload: null, networkPoolEpoch: 0, networkPoolHostId: '', vpcTransportBusy: false, vpcTransportOpener: null, vpcTransportScroll: null, vpcTransportHostId: '', vpcTransportCandidates: [], taskObservers: new Set() };
const requestRuntime = window.VenixAdminRequestRuntime.create({
csrfToken: () => state.csrf,
taskReceiptValidator: taskUrl,
@ -235,6 +235,7 @@ function hostDrawerNotice(id, message, error = false) {
}
const hostStorageNotice = hostDrawerNotice.bind(null, 'host-storage-status');
const hostSchedulingNotice = hostDrawerNotice.bind(null, 'host-scheduling-status');
const hostNetworkAttachmentNotice = hostDrawerNotice.bind(null, 'host-network-attachments-status');
const hostNetworkPoolNotice = hostDrawerNotice.bind(null, 'host-network-pools-status');
const hostVpcTransportNotice = hostDrawerNotice.bind(null, 'host-vpc-transport-status');
function lockHostDrawerScroll(drawer) {
@ -330,6 +331,7 @@ function openHostConfigTool(kind) {
if (!hostId || state.configBusy) return;
const openers = {
scheduling: openHostScheduling,
networkAttachments: openHostNetworkAttachments,
networkPools: openHostNetworkPools,
vpc: openHostVpcTransport,
storage: openHostStorage,
@ -662,6 +664,195 @@ async function deleteHostMembership(item, button) {
} catch (error) { hostSchedulingNotice(error.message, true); }
finally { state.schedulingBusy = false; if (button?.isConnected) button.disabled = false; }
}
function networkAttachmentStateLabel(value) { return ({ active: '启用', draining: '排空', disabled: '停用' })[value] || '状态异常'; }
function networkAttachmentVerificationLabel(value) { return ({ verified: '已验证', stale: '验证已过期', failed: '验证失败', never: '尚未验证' })[value] || '验证状态异常'; }
function addSelectOption(select, value, label, disabled = false) {
const option = element('option', '', label); option.value = String(value); option.disabled = disabled; select.append(option); return option;
}
function fillNetworkAttachmentLineSelect(select, selected = '') {
select.replaceChildren();
const lines = Array.isArray(state.networkAttachmentPayload?.lines) ? state.networkAttachmentPayload.lines : [];
addSelectOption(select, '', lines.length ? '请选择宿主机有效线路' : '当前宿主机没有可用线路', true);
for (const line of lines) addSelectOption(select, Number(line.id), `${line.name}(${line.status || 'active'})`);
const current = String(selected || '');
if (current && !lines.some(line => String(line.id) === current)) addSelectOption(select, current, `线路 #${current}(关系已失效)`, true);
select.value = current;
}
function fillNetworkAttachmentSelectorSelect(select, selected = '') {
select.replaceChildren();
const candidates = Array.isArray(state.networkAttachmentCandidates) ? state.networkAttachmentCandidates : [];
addSelectOption(select, '', candidates.length ? '请选择 Agent 已测试候选' : 'Agent 没有已测试候选', true);
for (const selector of candidates) addSelectOption(select, selector, selector);
const current = String(selected || '');
if (current && !candidates.includes(current)) addSelectOption(select, current, `${current}(候选已失效)`, true);
select.value = current;
}
function networkAttachmentStateSelect(name, value) {
const select = document.createElement('select'); select.className = 'form-select'; select.name = name;
for (const [stateValue, label] of [['active', '启用'], ['draining', '排空'], ['disabled', '停用']]) addSelectOption(select, stateValue, label);
select.value = value || 'disabled'; return select;
}
function networkAttachmentBody(form, creating = false) {
const value = name => form.elements.namedItem(name)?.value ?? '';
const lineId = Number(value('line_id')); const priority = Number(value('priority'));
if (!Number.isInteger(lineId) || lineId < 1) throw new Error('请选择有效线路。');
if (!Number.isInteger(priority) || priority < -1000000 || priority > 1000000) throw new Error('优先级必须是 -1000000 至 1000000 的整数。');
const selector = value('network_selector');
if (!state.networkAttachmentCandidates.includes(selector)) throw new Error('请选择 Agent 最近一次完整能力测试中的网络候选。');
const body = { name: value('name').trim(), line_id: lineId, network_selector: selector, state: value('state'), priority };
if (creating) body.request_key = form.dataset.requestKey || '';
else body.expected_revision = Number(value('expected_revision'));
if (creating && !/^[0-9a-f]{32}$/.test(body.request_key)) throw new Error('创建请求标识已失效,请重新打开网络接入。');
if (!creating && (!Number.isInteger(body.expected_revision) || body.expected_revision < 1)) throw new Error('网络接入版本无效,请刷新后重试。');
return body;
}
function renderNetworkAttachmentForm(item) {
const form = element('form', 'cloud-admin-form-section'); form.dataset.attachmentKey = item.attachment_key;
const expected = networkPoolInput('hidden', 'expected_revision', Number(item.config_revision || 0));
const heading = element('div', 'd-flex align-items-start justify-content-between gap-3 flex-wrap mb-3');
const copy = element('div', 'min-w-0'); copy.append(element('h6', 'mb-1', item.name || item.network_selector), element('div', 'text-muted admin-mono fs-13', item.attachment_key));
const badge = element('span', `badge ${item.ready === true ? 'bg-success-subtle text-success' : 'bg-light text-dark'}`, `${networkAttachmentStateLabel(item.state)} · ${networkAttachmentVerificationLabel(item.verification_state)}`);
heading.append(copy, badge);
const name = networkPoolInput('text', 'name', item.name, { required: true, maxLength: 80 });
const line = document.createElement('select'); line.className = 'form-select'; line.name = 'line_id'; line.required = true; fillNetworkAttachmentLineSelect(line, item.line_id);
const selector = document.createElement('select'); selector.className = 'form-select admin-mono'; selector.name = 'network_selector'; selector.required = true; fillNetworkAttachmentSelectorSelect(selector, item.network_selector);
const status = networkAttachmentStateSelect('state', item.state);
const priority = networkPoolInput('number', 'priority', Number(item.priority || 0), { required: true, min: -1000000, max: 1000000 });
for (const [control, suffix] of [[name, 'name'], [line, 'line'], [selector, 'selector'], [status, 'state'], [priority, 'priority']]) control.id = `host-network-attachment-${item.attachment_key}-${suffix}`;
const grid = element('div', 'cloud-admin-form-grid');
grid.append(networkPoolField('接入名称', name, true), networkPoolField('所属线路', line), networkPoolField('Agent 网络候选', selector), networkPoolField('运行状态', status), networkPoolField('优先级', priority));
const verifiedAt = Number(item.last_verified_at || 0) > 0 ? new Date(Number(item.last_verified_at) * 1000).toLocaleString() : '从未';
const error = item.verification_error_code ? ` · ${item.verification_error_code}` : '';
const metadata = element('p', 'form-text mb-0', `配置版本 ${Number(item.config_revision || 0)} · Agent 验证版本 ${Number(item.verified_agent_revision || 0)} · 最近验证 ${verifiedAt}${error}`);
const actions = element('div', 'd-flex justify-content-between align-items-center gap-2 flex-wrap mt-3'); actions.append(metadata);
const buttons = element('div', 'd-flex gap-2 flex-wrap');
const test = element('button', 'btn btn-light', '验证接入'); test.type = 'button'; test.disabled = !canManage; test.addEventListener('click', () => testHostNetworkAttachment(item.attachment_key, Number(item.config_revision || 0), test));
const save = element('button', 'btn btn-outline-primary', '保存接入'); save.type = 'submit'; save.disabled = !canManage; buttons.append(test, save); actions.append(buttons);
form.addEventListener('submit', event => saveHostNetworkAttachment(event, item.attachment_key));
form.append(expected, heading, grid, actions);
if (!canManage) for (const control of form.querySelectorAll('input,textarea,select,button')) control.disabled = true;
return form;
}
function networkAttachmentContextCurrent(hostId, epoch) {
const dialog = byId('host-network-attachments-drawer');
return dialog?.open === true && state.networkAttachmentEpoch === epoch && String(state.networkAttachmentHostId) === String(hostId);
}
function syncNetworkAttachmentButtons() {
const lines = Array.isArray(state.networkAttachmentPayload?.lines) ? state.networkAttachmentPayload.lines : [];
const form = byId('host-network-attachment-create-form');
const ready = state.networkAttachmentCandidates.length > 0 && lines.length > 0 && /^[0-9a-f]{32}$/.test(form?.dataset?.requestKey || '');
byId('host-network-attachment-discover').disabled = !canManage || state.networkAttachmentBusy;
byId('host-network-attachment-create-submit').disabled = !canManage || state.networkAttachmentBusy || !ready;
}
function prepareNetworkAttachmentCreateForm(reset = true) {
const form = byId('host-network-attachment-create-form');
if (reset) {
form.reset();
try { form.dataset.requestKey = newNetworkAttachmentRequestKey(); }
catch { delete form.dataset.requestKey; }
}
fillNetworkAttachmentLineSelect(byId('host-network-attachment-new-line'));
fillNetworkAttachmentSelectorSelect(byId('host-network-attachment-new-selector'));
byId('host-network-attachment-new-state').value = 'disabled'; byId('host-network-attachment-new-priority').value = '0';
syncNetworkAttachmentButtons();
}
function clearNetworkAttachmentPayload() {
state.networkAttachmentPayload = null; state.networkAttachmentCandidates = []; state.networkAttachmentHostId = '';
byId('host-network-attachments-list')?.replaceChildren(); byId('host-network-attachments-summary')?.replaceChildren();
syncNetworkAttachmentButtons();
}
function renderHostNetworkAttachments(payload, hostId, epoch, resetCreate = true) {
if (!networkAttachmentContextCurrent(hostId, epoch)) return false;
if (!payload?.host?.id || String(payload.host.id) !== String(hostId)) throw new Error('宿主机网络接入响应与当前抽屉不一致,请重新打开。');
state.networkAttachmentPayload = payload;
state.networkAttachmentCandidates = Array.isArray(payload?.agent?.network_selectors) ? [...new Set(payload.agent.network_selectors)] : [];
const items = Array.isArray(payload.items) ? payload.items : [];
byId('host-network-attachments-title').textContent = `${payload.host.name || `宿主机 #${payload.host.id}`} · 网络接入`;
const cachedHost = state.hosts.find(host => Number(host.id) === Number(hostId));
const summary = byId('host-network-attachments-summary'); summary.replaceChildren();
for (const [label, value] of [['兼容默认网络(旧入口)', hostNetworkLabel(cachedHost?.default_network || payload.host.default_network)], ['Agent 版本 / 已测试版本', `${Number(payload?.agent?.revision || 0)} / ${Number(payload?.agent?.tested_revision || 0)}`], ['网络接入', `${items.length} / ${Number(payload.maximum || 64)}`]]) summary.append(element('dt', '', label), element('dd', label.startsWith('兼容默认网络') ? 'admin-mono' : '', value));
const list = byId('host-network-attachments-list'); list.replaceChildren();
if (!items.length) list.append(element('p', 'text-muted py-3', '暂无网络接入。请先确认 Agent 已完成当前版本能力测试,再从候选中创建。'));
for (const item of items) list.append(renderNetworkAttachmentForm(item));
prepareNetworkAttachmentCreateForm(resetCreate);
hostNetworkAttachmentNotice('网络接入的线路与 selector 独立验证;公网地址池只能绑定已验证且启用的接入。');
return true;
}
function closeHostNetworkAttachments() {
++state.networkAttachmentEpoch; state.networkAttachmentBusy = false; clearNetworkAttachmentPayload();
const dialog = byId('host-network-attachments-drawer'); if (!dialog?.open) { finishHostDrawerClose('networkAttachment'); return; }
closeHostDrawer('host-network-attachments-drawer', 'networkAttachment');
}
async function openHostNetworkAttachments(hostId, opener) {
if (state.networkAttachmentBusy) return;
const epoch = ++state.networkAttachmentEpoch; clearNetworkAttachmentPayload(); state.networkAttachmentHostId = String(hostId);
state.networkAttachmentBusy = true; state.networkAttachmentOpener = opener; syncNetworkAttachmentButtons();
const dialog = byId('host-network-attachments-drawer'); hostNetworkAttachmentNotice('正在读取宿主机网络接入…');
if (!dialog.open) { lockHostDrawerScroll('networkAttachment'); window.VenixDrawerMotion.openDrawerWithMotion(dialog); }
try {
const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments`);
if (networkAttachmentContextCurrent(hostId, epoch)) renderHostNetworkAttachments(payload, hostId, epoch);
} catch (error) { if (networkAttachmentContextCurrent(hostId, epoch)) hostNetworkAttachmentNotice(error.message, true); }
finally { if (networkAttachmentContextCurrent(hostId, epoch)) { state.networkAttachmentBusy = false; syncNetworkAttachmentButtons(); } }
}
function newNetworkAttachmentRequestKey() {
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('');
}
async function discoverHostNetworkAttachments() {
const hostId = state.networkAttachmentHostId; const epoch = state.networkAttachmentEpoch;
if (!hostId || !canManage || state.networkAttachmentBusy) return;
state.networkAttachmentBusy = true; syncNetworkAttachmentButtons(); hostNetworkAttachmentNotice('正在从 Agent 重新发现网络候选…');
try {
const discovered = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments/discover`, { method: 'POST', body: {} });
if (!networkAttachmentContextCurrent(hostId, epoch)) return;
const tested = Array.isArray(state.networkAttachmentPayload?.agent?.network_selectors) ? state.networkAttachmentPayload.agent.network_selectors : [];
const live = Array.isArray(discovered?.network_selectors) ? discovered.network_selectors : [];
state.networkAttachmentCandidates = live.filter(selector => tested.includes(selector));
const list = byId('host-network-attachments-list'); list.replaceChildren();
for (const item of state.networkAttachmentPayload?.items || []) list.append(renderNetworkAttachmentForm(item));
prepareNetworkAttachmentCreateForm(false);
const omitted = live.length - state.networkAttachmentCandidates.length;
hostNetworkAttachmentNotice(omitted > 0 ? `已发现 ${live.length} 个候选,其中 ${omitted} 个尚无完整 Agent 测试证据;请先重新测试 Agent。` : `已核对 ${live.length} 个 Agent 候选。`, omitted > 0);
} catch (error) { if (networkAttachmentContextCurrent(hostId, epoch)) hostNetworkAttachmentNotice(error.message, true); }
finally { if (networkAttachmentContextCurrent(hostId, epoch)) { state.networkAttachmentBusy = false; syncNetworkAttachmentButtons(); } }
}
async function createHostNetworkAttachment(event) {
event.preventDefault(); const form = event.currentTarget; const hostId = state.networkAttachmentHostId; const epoch = state.networkAttachmentEpoch;
if (!hostId || !canManage || state.networkAttachmentBusy) return;
let body; try { body = networkAttachmentBody(form, true); } catch (error) { hostNetworkAttachmentNotice(error.message, true); return; }
state.networkAttachmentBusy = true; syncNetworkAttachmentButtons(); hostNetworkAttachmentNotice('正在创建网络接入…');
try {
const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments`, { method: 'POST', body });
if (networkAttachmentContextCurrent(hostId, epoch)) { renderHostNetworkAttachments(payload, hostId, epoch); hostNetworkAttachmentNotice('网络接入已创建,请完成精确验证后再绑定公网地址池。'); }
} catch (error) { if (networkAttachmentContextCurrent(hostId, epoch)) hostNetworkAttachmentNotice(error.message, true); }
finally { if (networkAttachmentContextCurrent(hostId, epoch)) { state.networkAttachmentBusy = false; syncNetworkAttachmentButtons(); } }
}
async function saveHostNetworkAttachment(event, attachmentKey) {
event.preventDefault(); const form = event.currentTarget; const hostId = state.networkAttachmentHostId; const epoch = state.networkAttachmentEpoch;
if (!hostId || !canManage || state.networkAttachmentBusy) return;
let body; try { body = networkAttachmentBody(form); } catch (error) { hostNetworkAttachmentNotice(error.message, true); return; }
state.networkAttachmentBusy = true; syncNetworkAttachmentButtons(); hostNetworkAttachmentNotice('正在保存网络接入…');
try {
const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments/${encodeURIComponent(attachmentKey)}`, { method: 'PUT', body });
if (networkAttachmentContextCurrent(hostId, epoch)) { renderHostNetworkAttachments(payload, hostId, epoch); hostNetworkAttachmentNotice('网络接入已保存;selector 变化后必须重新验证。'); }
} catch (error) { if (networkAttachmentContextCurrent(hostId, epoch)) hostNetworkAttachmentNotice(error.message, true); }
finally { if (networkAttachmentContextCurrent(hostId, epoch)) { state.networkAttachmentBusy = false; syncNetworkAttachmentButtons(); } }
}
async function testHostNetworkAttachment(attachmentKey, expectedRevision, button) {
const hostId = state.networkAttachmentHostId; const epoch = state.networkAttachmentEpoch;
if (!hostId || !canManage || state.networkAttachmentBusy) return;
state.networkAttachmentBusy = true; if (button) button.disabled = true; syncNetworkAttachmentButtons(); hostNetworkAttachmentNotice('正在精确验证网络接入…');
try {
const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments/${encodeURIComponent(attachmentKey)}/test`, { method: 'POST', body: { expected_revision: expectedRevision } });
if (networkAttachmentContextCurrent(hostId, epoch)) { renderHostNetworkAttachments(payload, hostId, epoch); hostNetworkAttachmentNotice('网络接入已通过当前 Agent 版本验证。'); }
} catch (error) {
if (!networkAttachmentContextCurrent(hostId, epoch)) return;
try { renderHostNetworkAttachments(await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments`), hostId, epoch); } catch {}
hostNetworkAttachmentNotice(error.message, true);
} finally { if (networkAttachmentContextCurrent(hostId, epoch)) { state.networkAttachmentBusy = false; if (button?.isConnected) button.disabled = false; syncNetworkAttachmentButtons(); } }
}
function networkPoolStateLabel(value) { return ({ active: '启用分配', draining: '排空', disabled: '停用' })[value] || '状态异常'; }
function networkPoolInput(type, name, value, options = {}) {
const control = document.createElement(type === 'textarea' ? 'textarea' : type === 'select' ? 'select' : 'input');
@ -690,13 +881,45 @@ function networkPoolField(label, control, wide = false) {
wrapper.append(caption, control);
return wrapper;
}
function networkPoolAttachmentId(attachment) { return Number(attachment?.id ?? attachment?.network_attachment_id ?? 0); }
function networkPoolAttachments() { return Array.isArray(state.networkPoolPayload?.attachments) ? state.networkPoolPayload.attachments : []; }
function networkPoolAttachmentById(id) { return networkPoolAttachments().find(attachment => networkPoolAttachmentId(attachment) === Number(id)) || null; }
function networkPoolAttachmentLabel(attachment) {
const line = attachment?.line?.name || attachment?.line_name || `线路 #${Number(attachment?.line_id || 0)}`;
return `${attachment?.name || attachment?.network_selector || '未命名接入'} · ${line}${attachment?.ready === true ? '' : '(未就绪)'}`;
}
function fillNetworkPoolAttachmentSelect(select, selected = '', currentAttachment = null) {
select.replaceChildren();
const attachments = networkPoolAttachments(); const selectedId = Number(selected || 0);
addSelectOption(select, '', attachments.length ? '请选择已验证网络接入' : '暂无网络接入', true);
for (const attachment of attachments) {
const id = networkPoolAttachmentId(attachment); const isCurrent = id === selectedId;
addSelectOption(select, id, networkPoolAttachmentLabel(attachment), attachment.ready !== true && !isCurrent);
}
if (selectedId > 0 && !attachments.some(attachment => networkPoolAttachmentId(attachment) === selectedId)) {
addSelectOption(select, selectedId, networkPoolAttachmentLabel(currentAttachment || { id: selectedId, name: `接入 #${selectedId}`, line_name: '关系已失效' }), false);
}
select.value = selectedId > 0 ? String(selectedId) : '';
}
function networkPoolAttachmentDetail(id, fallback = null) {
const attachment = networkPoolAttachmentById(id) || fallback;
if (!attachment) return '选择后显示派生线路与 selector。';
const line = attachment?.line?.name || attachment?.line_name || `线路 #${Number(attachment?.line_id || 0)}`;
return `派生线路:${line} · selector:${attachment.network_selector || '已失效'} · ${attachment.ready === true ? '已验证就绪' : networkAttachmentVerificationLabel(attachment.verification_state)}`;
}
function networkPoolAttachmentField(select, detail, wide = true) {
const wrapper = networkPoolField('网络接入', select, wide); wrapper.append(detail); return wrapper;
}
function networkPoolBody(form) {
const value = name => form.elements.namedItem(name)?.value ?? '';
const prefix = Number(value('guest_prefix_length'));
const expectedRevision = Number(value('expected_revision'));
const networkAttachmentId = Number(value('network_attachment_id'));
if (!Number.isInteger(prefix) || prefix < 24 || prefix > 30) throw new Error('客户机网络前缀必须是 24 至 30 的整数。');
if (!Number.isInteger(expectedRevision) || expectedRevision < 1) throw new Error('地址池版本无效,请刷新后重试。');
if (!Number.isInteger(networkAttachmentId) || networkAttachmentId < 1) throw new Error('请选择有效的宿主机网络接入。');
return {
network_attachment_id: networkAttachmentId,
name: value('name').trim(), cidr: value('cidr').trim(), gateway: value('gateway').trim(),
dns_servers: formList(value('dns_servers')), reserved_ips: formList(value('reserved_ips')),
guest_prefix_length: prefix, state: value('state'), expected_revision: expectedRevision,
@ -712,6 +935,10 @@ function renderNetworkPoolForm(pool) {
const badge = element('span', 'badge bg-light text-dark', `${networkPoolStateLabel(pool.state)} · ${pool.sync_message || '等待应用'}`);
heading.append(copy, badge);
const grid = element('div', 'cloud-admin-form-grid');
const attachment = document.createElement('select'); attachment.className = 'form-select'; attachment.name = 'network_attachment_id'; attachment.required = true;
fillNetworkPoolAttachmentSelect(attachment, pool.network_attachment_id, pool.attachment);
const attachmentDetail = element('div', 'form-text', networkPoolAttachmentDetail(pool.network_attachment_id, pool.attachment));
attachment.addEventListener('change', () => { attachmentDetail.textContent = networkPoolAttachmentDetail(attachment.value, pool.attachment); });
const name = networkPoolInput('text', 'name', pool.name, { required: true, maxLength: 80 });
const cidr = networkPoolInput('text', 'cidr', pool.cidr, { required: true, mono: true });
const gateway = networkPoolInput('text', 'gateway', pool.gateway, { required: true, mono: true });
@ -719,8 +946,8 @@ function renderNetworkPoolForm(pool) {
const status = networkPoolInput('select', 'state', pool.state);
const dns = networkPoolInput('text', 'dns_servers', Array.isArray(pool.dns_servers) ? pool.dns_servers.join(', ') : '', { required: true, mono: true });
const reserved = networkPoolInput('textarea', 'reserved_ips', Array.isArray(pool.reserved_ips) ? pool.reserved_ips.join(', ') : '', { mono: true, rows: 3 });
for (const [control, suffix] of [[name, 'name'], [cidr, 'cidr'], [gateway, 'gateway'], [prefix, 'prefix'], [status, 'state'], [dns, 'dns'], [reserved, 'reserved']]) control.id = `host-network-pool-${pool.pool_key}-${suffix}`;
grid.append(networkPoolField('地址池名称', name, true), networkPoolField('实际公网 CIDR', cidr), networkPoolField('公网网关', gateway), networkPoolField('客户机网络前缀', prefix), networkPoolField('运行状态', status), networkPoolField('DNS(逗号或空格分隔)', dns, true), networkPoolField('保留 / 禁用 IP', reserved, true));
for (const [control, suffix] of [[attachment, 'attachment'], [name, 'name'], [cidr, 'cidr'], [gateway, 'gateway'], [prefix, 'prefix'], [status, 'state'], [dns, 'dns'], [reserved, 'reserved']]) control.id = `host-network-pool-${pool.pool_key}-${suffix}`;
grid.append(networkPoolAttachmentField(attachment, attachmentDetail), networkPoolField('地址池名称', name, true), networkPoolField('实际公网 CIDR', cidr), networkPoolField('公网网关', gateway), networkPoolField('客户机网络前缀', prefix), networkPoolField('运行状态', status), networkPoolField('DNS(逗号或空格分隔)', dns, true), networkPoolField('保留 / 禁用 IP', reserved, true));
const metadata = element('p', 'form-text mb-0', `面板版本 ${Number(pool.revision || 0)} · 已应用版本 ${pool.live_revision === null ? '未确认' : Number(pool.live_revision)} · 占用 ${Number(pool.occupied_count || 0)} 个地址`);
const actions = element('div', 'd-flex justify-content-between align-items-center gap-2 flex-wrap mt-3');
actions.append(metadata);
@ -729,8 +956,8 @@ function renderNetworkPoolForm(pool) {
form.append(expectedRevision, heading, grid);
const runtimeLocked = Number(pool.occupied_count || 0) > 0;
if (runtimeLocked) {
for (const control of [cidr, gateway, prefix, dns]) control.disabled = true;
form.append(element('p', 'alert alert-warning mt-3 mb-0', '该地址池仍有实例或任务占用;CIDR、网关、客户机前缀和 DNS 已锁定。仍可编辑未占用的保留 / 禁用 IP,已分配或任务占用的 IP 会被拒绝。'));
for (const control of [attachment, cidr, gateway, prefix, dns]) control.disabled = true;
form.append(element('p', 'alert alert-warning mt-3 mb-0', '该地址池仍有实例或任务占用;网络接入、CIDR、网关、客户机前缀和 DNS 已锁定。仍可编辑未占用的保留 / 禁用 IP,已分配或任务占用的 IP 会被拒绝。'));
}
if (!canManage) for (const control of form.querySelectorAll('input,textarea,select,button')) control.disabled = true;
form.append(actions);
@ -743,10 +970,11 @@ function networkPoolContextCurrent(hostId, epoch) {
}
function syncNetworkPoolButtons() {
const payload = state.networkPoolPayload; const items = Array.isArray(payload?.items) ? payload.items : [];
const readyAttachments = networkPoolAttachments().filter(attachment => attachment.ready === true);
const add = byId('host-network-pool-add');
if (add) add.disabled = state.networkPoolBusy || !canManage || !payload || !payload.line || items.length >= Number(payload.maximum || 32);
if (add) add.disabled = state.networkPoolBusy || !canManage || !payload || readyAttachments.length === 0 || items.length >= Number(payload.maximum || 32);
const submit = byId('host-network-pool-create-submit');
if (submit) submit.disabled = state.networkPoolBusy || !canManage;
if (submit) submit.disabled = state.networkPoolBusy || !canManage || readyAttachments.length === 0;
}
function clearNetworkPoolPayload() {
state.networkPoolPayload = null; state.networkPoolHostId = '';
@ -759,13 +987,16 @@ function renderHostNetworkPools(payload, hostId, epoch) {
if (!networkPoolContextCurrent(hostId, epoch)) return false;
if (!payload?.host?.id || String(payload.host.id) !== String(hostId)) throw new Error('宿主机地址池响应与当前抽屉不一致,请重新打开。');
state.networkPoolPayload = payload;
const host = payload?.host || {}; const line = payload?.line || null; const items = Array.isArray(payload?.items) ? payload.items : [];
const host = payload?.host || {}; const items = Array.isArray(payload?.items) ? payload.items : []; const attachments = networkPoolAttachments();
byId('host-network-pools-title').textContent = `${host.name || `宿主机 #${host.id}`} · 公网地址池`;
const summary = byId('host-network-pools-summary'); summary.replaceChildren();
for (const [label, value] of [['默认网络接入', hostNetworkLabel(host.default_network)], ['所属线路', line ? `${line.name}(${line.status})` : '尚未加入资源池'], ['地址池数量', `${items.length} / ${Number(payload?.maximum || 32)}`]]) summary.append(element('dt', '', label), element('dd', label === '默认网络接入' ? 'admin-mono' : '', value));
const cachedHost = state.hosts.find(item => Number(item.id) === Number(hostId));
for (const [label, value] of [['兼容默认网络(旧入口)', hostNetworkLabel(cachedHost?.default_network)], ['可用网络接入', `${attachments.filter(item => item.ready === true).length} / ${attachments.length}`], ['地址池数量', `${items.length} / ${Number(payload?.maximum || 32)}`]]) summary.append(element('dt', '', label), element('dd', label.startsWith('兼容默认网络') ? 'admin-mono' : '', value));
const list = byId('host-network-pools-list'); list.replaceChildren();
if (!items.length) list.append(element('p', 'text-muted py-3', '暂无公网地址池。添加后面板会生成并维护可用 IP 账本。'));
for (const pool of items) list.append(renderNetworkPoolForm(pool));
fillNetworkPoolAttachmentSelect(byId('host-network-pool-new-attachment'));
byId('host-network-pool-new-attachment-detail').textContent = networkPoolAttachmentDetail('');
const createForm = byId('host-network-pool-create-form'); createForm.hidden = true; delete createForm.dataset.requestKey;
syncNetworkPoolButtons();
hostNetworkPoolNotice('每个地址池由面板保存并维护 IP 账本,宿主机 Agent 只执行明确下发的网络操作。');
@ -802,15 +1033,21 @@ function showNetworkPoolCreate() {
try { form.dataset.requestKey = newNetworkPoolRequestKey(); }
catch (error) { hostNetworkPoolNotice(error.message, true); return; }
byId('host-network-pool-new-prefix').value = '28'; byId('host-network-pool-new-state').value = 'active'; form.hidden = false;
fillNetworkPoolAttachmentSelect(byId('host-network-pool-new-attachment'));
const firstReady = networkPoolAttachments().find(attachment => attachment.ready === true);
if (firstReady) byId('host-network-pool-new-attachment').value = String(networkPoolAttachmentId(firstReady));
byId('host-network-pool-new-attachment-detail').textContent = networkPoolAttachmentDetail(byId('host-network-pool-new-attachment').value);
byId('host-network-pool-new-name').focus({ preventScroll: true }); form.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
function hideNetworkPoolCreate() { const form = byId('host-network-pool-create-form'); form.hidden = true; delete form.dataset.requestKey; }
function newNetworkPoolBody(form) {
const prefix = Number(byId('host-network-pool-new-prefix').value);
const networkAttachmentId = Number(byId('host-network-pool-new-attachment').value);
if (!Number.isInteger(prefix) || prefix < 24 || prefix > 30) throw new Error('客户机网络前缀必须是 24 至 30 的整数。');
if (!Number.isInteger(networkAttachmentId) || networkAttachmentId < 1) throw new Error('请选择已验证的宿主机网络接入。');
const requestKey = form.dataset.requestKey || '';
if (!/^[0-9a-f]{32}$/.test(requestKey)) throw new Error('创建请求标识已失效,请取消后重新添加。');
return { name: byId('host-network-pool-new-name').value.trim(), cidr: byId('host-network-pool-new-cidr').value.trim(), gateway: byId('host-network-pool-new-gateway').value.trim(), dns_servers: formList(byId('host-network-pool-new-dns').value), reserved_ips: formList(byId('host-network-pool-new-reserved').value), guest_prefix_length: prefix, state: byId('host-network-pool-new-state').value, request_key: requestKey };
return { network_attachment_id: networkAttachmentId, name: byId('host-network-pool-new-name').value.trim(), cidr: byId('host-network-pool-new-cidr').value.trim(), gateway: byId('host-network-pool-new-gateway').value.trim(), dns_servers: formList(byId('host-network-pool-new-dns').value), reserved_ips: formList(byId('host-network-pool-new-reserved').value), guest_prefix_length: prefix, state: byId('host-network-pool-new-state').value, request_key: requestKey };
}
async function createHostNetworkPool(event) {
event.preventDefault(); if (!canManage || state.networkPoolBusy) return;
@ -979,6 +1216,7 @@ async function initialize() {
byId('host-new').addEventListener('click', event => openNewHostConfig(event.currentTarget)); byId('host-form').addEventListener('submit', saveHost);
byId('host-config-close').addEventListener('click', closeHostConfig); const configDrawer = byId('host-config-drawer'); configDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostConfig(); }); configDrawer.addEventListener('click', event => { if (event.target === configDrawer) closeHostConfig(); });
byId('host-config-scheduling').addEventListener('click', () => openHostConfigTool('scheduling'));
byId('host-config-network-attachments').addEventListener('click', () => openHostConfigTool('networkAttachments'));
byId('host-config-network-pools').addEventListener('click', () => openHostConfigTool('networkPools'));
byId('host-config-vpc').addEventListener('click', () => openHostConfigTool('vpc'));
byId('host-config-storage')?.addEventListener('click', () => openHostConfigTool('storage'));
@ -988,7 +1226,10 @@ async function initialize() {
const storageDrawer = byId('host-storage-drawer'); storageDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostStorage(); }); storageDrawer.addEventListener('click', event => { if (event.target === storageDrawer) closeHostStorage(); });
byId('host-scheduling-form').addEventListener('submit', saveHostScheduling); byId('host-membership-create-form').addEventListener('submit', createHostMembership); byId('host-scheduling-close').addEventListener('click', closeHostScheduling);
const schedulingDrawer = byId('host-scheduling-drawer'); schedulingDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostScheduling(); }); schedulingDrawer.addEventListener('click', event => { if (event.target === schedulingDrawer) closeHostScheduling(); });
byId('host-network-attachments-close').addEventListener('click', closeHostNetworkAttachments); byId('host-network-attachment-create-form').addEventListener('submit', createHostNetworkAttachment); byId('host-network-attachment-discover').addEventListener('click', discoverHostNetworkAttachments);
const attachmentDrawer = byId('host-network-attachments-drawer'); attachmentDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostNetworkAttachments(); }); attachmentDrawer.addEventListener('click', event => { if (event.target === attachmentDrawer) closeHostNetworkAttachments(); });
byId('host-network-pools-close').addEventListener('click', closeHostNetworkPools); byId('host-network-pool-add')?.addEventListener('click', showNetworkPoolCreate); byId('host-network-pool-create-cancel').addEventListener('click', hideNetworkPoolCreate); byId('host-network-pool-create-form').addEventListener('submit', createHostNetworkPool);
byId('host-network-pool-new-attachment').addEventListener('change', event => { byId('host-network-pool-new-attachment-detail').textContent = networkPoolAttachmentDetail(event.currentTarget.value); });
const networkDrawer = byId('host-network-pools-drawer'); networkDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostNetworkPools(); }); networkDrawer.addEventListener('click', event => { if (event.target === networkDrawer) closeHostNetworkPools(); });
byId('host-vpc-transport-close').addEventListener('click', closeHostVpcTransport); byId('host-vpc-transport-form').addEventListener('submit', saveHostVpcTransport); byId('host-vpc-transport-discover').addEventListener('click', discoverHostVpcTransport); byId('host-vpc-transport-test').addEventListener('click', testHostVpcTransport); byId('host-vpc-transport-candidate').addEventListener('change', selectHostVpcTransportCandidate);
const vpcTransportDrawer = byId('host-vpc-transport-drawer'); vpcTransportDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostVpcTransport(); }); vpcTransportDrawer.addEventListener('click', event => { if (event.target === vpcTransportDrawer) closeHostVpcTransport(); });

@ -47,6 +47,7 @@
<dl id="host-config-metrics" class="admin-instance-details cloud-admin-host-config-metrics"></dl>
<div class="cloud-admin-host-tool-grid" aria-label="计算节点管理工具">
<button id="host-config-scheduling" class="btn btn-outline-primary" type="button" aria-controls="host-scheduling-drawer" aria-haspopup="dialog"><i class="mdi mdi-gauge me-1"></i>调度与容量</button>
<button id="host-config-network-attachments" class="btn btn-outline-primary" type="button" aria-controls="host-network-attachments-drawer" aria-haspopup="dialog"><i class="mdi mdi-ethernet me-1"></i>网络接入</button>
<button id="host-config-network-pools" class="btn btn-outline-primary" type="button" aria-controls="host-network-pools-drawer" aria-haspopup="dialog"><i class="mdi mdi-ip-network-outline me-1"></i>公网地址池</button>
<button id="host-config-vpc" class="btn btn-outline-primary" type="button" aria-controls="host-vpc-transport-drawer" aria-haspopup="dialog"><i class="mdi mdi-lan me-1"></i>VPC 私网传输</button>
{if $admin_can_manage|default:false}<button id="host-config-storage" class="btn btn-outline-primary" type="button" aria-controls="host-storage-drawer" aria-haspopup="dialog"><i class="mdi mdi-database-cog-outline me-1"></i>存储目录</button>{/if}
@ -64,7 +65,7 @@
</div>
</section>
<section class="cloud-admin-form-section" aria-labelledby="host-network-title">
<div class="cloud-admin-section-title"><span><i class="mdi mdi-access-point-network"></i></span><div><h6 id="host-network-title">默认网络接入</h6><p>选择宿主机已经存在的网桥或 libvirt 网络;面板不会创建或修改宿主机网卡。</p></div></div>
<div class="cloud-admin-section-title"><span><i class="mdi mdi-access-point-network"></i></span><div><h6 id="host-network-title">兼容默认网络接入</h6><p>仅供旧入口和未迁移功能兼容;公网地址池必须在“网络接入”中绑定经过 Agent 验证的线路与 selector。</p></div></div>
<div class="cloud-admin-form-grid">
<div><label for="host-network-type" class="form-label">接入类型</label><select id="host-network-type" class="form-select" required {if !$admin_can_manage|default:false}disabled{/if}><option value="">请选择类型</option><option value="bridge" selected>Linux 网桥</option><option value="network">libvirt 网络</option></select></div>
<div><label for="host-network-name" class="form-label">网桥 / 网络名称</label><input id="host-network-name" class="form-control admin-mono" value="br0" required maxlength="15" pattern="[A-Za-z0-9][A-Za-z0-9_.\-]{ldelim}0,14{rdelim}" autocomplete="off" spellcheck="false" placeholder="例如 br0" {if !$admin_can_manage|default:false}disabled{/if}></div>
@ -207,6 +208,43 @@
</footer>
</dialog>
<dialog id="host-network-attachments-drawer" data-admin-instance-drawer data-admin-host-network-attachments-drawer aria-labelledby="host-network-attachments-title">
<header class="admin-instance-drawer-header">
<div>
<p class="admin-eyebrow mb-1">Network Attachments</p>
<h2 id="host-network-attachments-title">网络接入</h2>
</div>
<button id="host-network-attachments-close" class="btn btn-light" type="button" aria-label="关闭网络接入"><i class="mdi mdi-close"></i></button>
</header>
<div class="admin-instance-drawer-body">
<p id="host-network-attachments-status" class="alert alert-info" role="status" aria-live="polite">请选择宿主机。</p>
<dl id="host-network-attachments-summary" class="admin-instance-details mb-3"></dl>
<form id="host-network-attachment-create-form" class="cloud-admin-form-section">
<div class="cloud-admin-section-title">
<span><i class="mdi mdi-ethernet"></i></span>
<div><h6>新增网络接入</h6><p>selector 只能从 Agent 最近一次完整能力测试的候选列表中选择,不能手工填写。</p></div>
</div>
<div class="cloud-admin-form-grid">
<div class="cloud-admin-full"><label for="host-network-attachment-new-name" class="form-label">接入名称</label><input id="host-network-attachment-new-name" class="form-control" maxlength="80" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div><label for="host-network-attachment-new-line" class="form-label">所属线路</label><select id="host-network-attachment-new-line" class="form-select" required {if !$admin_can_manage|default:false}disabled{/if}></select></div>
<div><label for="host-network-attachment-new-selector" class="form-label">Agent 网络候选</label><select id="host-network-attachment-new-selector" class="form-select admin-mono" required {if !$admin_can_manage|default:false}disabled{/if}></select></div>
<div><label for="host-network-attachment-new-state" class="form-label">运行状态</label><select id="host-network-attachment-new-state" class="form-select" {if !$admin_can_manage|default:false}disabled{/if}><option value="disabled">停用</option><option value="draining">排空</option><option value="active">启用</option></select></div>
<div><label for="host-network-attachment-new-priority" class="form-label">优先级</label><input id="host-network-attachment-new-priority" class="form-control" type="number" min="-1000000" max="1000000" value="0" required {if !$admin_can_manage|default:false}disabled{/if}></div>
</div>
<div class="d-flex justify-content-end gap-2 flex-wrap mt-3">
<button id="host-network-attachment-discover" class="btn btn-light" type="button" {if !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-radar me-1"></i>重新发现候选</button>
<button id="host-network-attachment-create-submit" class="btn btn-primary" type="submit" {if !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-plus me-1"></i>新增接入</button>
</div>
</form>
<div id="host-network-attachments-list" aria-live="polite"></div>
</div>
<footer class="admin-instance-drawer-footer">
<span class="text-muted"><code>default_network</code> 仅为兼容默认值,不是公网地址池的线路或 selector 事实来源。</span>
</footer>
</dialog>
<dialog id="host-network-pools-drawer" data-admin-instance-drawer data-admin-host-network-drawer aria-labelledby="host-network-pools-title">
<header class="admin-instance-drawer-header">
<div>
@ -224,9 +262,10 @@
<form id="host-network-pool-create-form" class="cloud-admin-form-section" hidden>
<div class="cloud-admin-section-title">
<span><i class="mdi mdi-ip-network-outline"></i></span>
<div><h6>添加公网地址池</h6><p>新地址池自动生成稳定标识,并使用宿主机当前默认网络。</p></div>
<div><h6>添加公网地址池</h6><p>新地址池自动生成稳定标识,并绑定一个已验证的宿主机网络接入。</p></div>
</div>
<div class="cloud-admin-form-grid">
<div class="cloud-admin-full"><label for="host-network-pool-new-attachment" class="form-label">网络接入</label><select id="host-network-pool-new-attachment" class="form-select" required {if !$admin_can_manage|default:false}disabled{/if}></select><div id="host-network-pool-new-attachment-detail" class="form-text">选择后显示派生线路与 selector。</div></div>
<div class="cloud-admin-full"><label for="host-network-pool-new-name" class="form-label">地址池名称</label><input id="host-network-pool-new-name" class="form-control" maxlength="80" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div><label for="host-network-pool-new-cidr" class="form-label">实际公网 CIDR</label><input id="host-network-pool-new-cidr" class="form-control admin-mono" placeholder="填写供应商分配的实际公网 CIDR" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div><label for="host-network-pool-new-gateway" class="form-label">公网网关</label><input id="host-network-pool-new-gateway" class="form-control admin-mono" placeholder="填写该 CIDR 的实际网关" required {if !$admin_can_manage|default:false}disabled{/if}></div>

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

@ -19,6 +19,9 @@ $service = $read(
'app/Services/Cloud/CloudHostNetworkAttachmentService.php'
);
$agent = $read('app/Services/Cloud/CloudAgentSettingsService.php');
$template = $read('resources/views/venix/admin/hosts/index.tpl');
$client = $read('public/cloud/admin-hosts.js');
$assets = $read('resources/views/venix/layout_assets.tpl');
$assert(str_contains($schema, 'network_selectors_json LONGTEXT NOT NULL')
&& str_contains($schema,
@ -68,4 +71,29 @@ $assert(str_contains($service, 'CloudHostPoolMembershipService::lockedRows')
&& str_contains($service, 'CloudPublicIpPool::where('),
'Attachment writes lost membership, idempotency, CAS or bound-pool guards.');
$assert(str_contains($template, 'id="host-config-network-attachments"')
&& str_contains($template, 'id="host-network-attachments-drawer"')
&& str_contains($template, 'id="host-network-attachment-new-selector"')
&& str_contains($template, 'default_network</code> 仅为兼容默认值')
&& str_contains($template,
'{if !$admin_can_manage|default:false}disabled{/if}')
&& str_contains($client, "networkAttachments: openHostNetworkAttachments")
&& str_contains($client,
'/network-attachments/discover`, { method: \'POST\', body: {} }')
&& str_contains($client,
'/network-attachments/${encodeURIComponent(attachmentKey)}/test`')
&& str_contains($client, "{ method: 'PUT', body }")
&& str_contains($client, "{ method: 'POST', body }")
&& str_contains($client,
'if (!hostId || !canManage || state.networkAttachmentBusy) return;')
&& str_contains($client,
'state.networkAttachmentCandidates.includes(selector)')
&& str_contains($client, 'expected_revision: expectedRevision')
&& !file_exists($root . '/public/cloud/admin-host-network.css'),
'Network attachment drawer lost exact Agent candidates, CAS writes, read-only guards or shared drawer styling.');
$assert(preg_match("/venix_asset_version value='([0-9]+)'/", $assets, $match) === 1
&& (int) $match[1] >= 2026110205,
'Shared browser asset version does not cover the network attachment drawer.');
echo "Administrator host network attachment contracts passed.\n";

@ -7,13 +7,13 @@ const requestRuntimeSource = await readFile(
new URL('../public/cloud/admin-request-runtime.js', import.meta.url), 'utf8');
const source = adminSource.slice(adminSource.indexOf('const root ='))
.replace('void initialize();', '')
+ '\nglobalThis.hostUI = { initialize, fillHost, saveHost, renderHostNetworkPools, state };';
+ '\nglobalThis.hostUI = { initialize, fillHost, saveHost, renderHostNetworkAttachments, createHostNetworkAttachment, networkAttachmentBody, renderHostNetworkPools, state };';
const submit = { preventDefault() {} };
const descendants = node => [node, ...(node?.children || []).flatMap(descendants)];
function fixture(canManage = true) {
const elements = new Map();
const selectIds = new Set(['host-country-code', 'host-network-type']);
const selectIds = new Set(['host-country-code', 'host-network-type', 'host-network-attachment-new-line', 'host-network-attachment-new-selector', 'host-network-attachment-new-state', 'host-network-pool-new-attachment', 'host-network-pool-new-state']);
class Element {
constructor(tag = 'input') {
this.tag = tag; this.value = ''; this.textContent = ''; this.dataset = {};
@ -135,24 +135,65 @@ function fixture(canManage = true) {
{
const test = fixture();
test.state.hosts = [{ id: 7, default_network: 'bridge:br0' }];
test.state.networkPoolHostId = '7';
test.get('host-network-pools-drawer').open = true;
test.renderHostNetworkPools({ host: { id: 7, default_network: 'bridge:br0' }, items: [] }, 7, 0);
test.renderHostNetworkPools({ host: { id: 7 }, attachments: [], items: [] }, 7, 0);
const summary = test.get('host-network-pools-summary').children;
assert.equal(summary[0].textContent, '默认网络接入');
assert.equal(summary[0].textContent, '兼容默认网络(旧入口)');
assert.equal(summary[1].textContent, 'Linux 网桥 · br0');
}
{
const test = fixture();
test.state.hosts = [{ id: 7, default_network: 'bridge:br0' }];
test.state.networkAttachmentHostId = '7';
test.get('host-network-attachments-drawer').open = true;
const selector = 'bridge:br-public';
test.renderHostNetworkAttachments({
host: { id: 7, name: 'Host' },
agent: { revision: 4, tested_revision: 4, network_selectors: [selector] },
lines: [{ id: 3, name: 'China optimized', status: 'active' }],
maximum: 64,
items: [{
attachment_key: 'b'.repeat(32), name: 'Public uplink', line_id: 3,
line_name: 'China optimized', network_selector: selector, state: 'active',
priority: 10, config_revision: 2, verified_agent_revision: 4,
verification_state: 'verified', ready: true, last_verified_at: 1,
verification_error_code: '',
}],
}, 7, 0);
assert.deepEqual(Array.from(test.get('host-network-attachment-new-selector').options, option => option.value), ['', selector]);
assert.match(test.get('host-network-attachments-summary').children[0].textContent, /兼容默认网络/);
const body = test.networkAttachmentBody({
dataset: { requestKey: 'c'.repeat(32) },
elements: { namedItem: name => ({ value: ({ name: 'Public uplink', line_id: '3', network_selector: selector, state: 'active', priority: '10' })[name] }) },
}, true);
assert.equal(body.line_id, 3);
assert.equal(body.network_selector, selector);
assert.equal(body.request_key, 'c'.repeat(32));
}
{
const test = fixture(false);
test.state.networkAttachmentHostId = '7';
await test.createHostNetworkAttachment({ preventDefault() {}, currentTarget: test.get('host-network-attachment-create-form') });
assert.equal(test.writes().length, 0, 'Read-only administrator sent a network attachment mutation.');
}
{
const test = fixture();
test.state.hosts = [{ id: 7, default_network: 'bridge:br0' }];
test.state.networkPoolHostId = '7';
test.get('host-network-pools-drawer').open = true;
test.renderHostNetworkPools({
host: { id: 7, name: 'Host', default_network: 'bridge:br0' },
line: { id: 3, name: 'China optimized', status: 'active' },
host: { id: 7, name: 'Host' },
attachments: [{ id: 11, name: 'Public uplink', line_id: 3, line_name: 'China optimized', network_selector: 'bridge:br-public', state: 'active', verification_state: 'verified', ready: true }],
maximum: 32,
items: [{
pool_key: 'a'.repeat(32), name: 'Public pool', cidr: '8.8.8.0/29',
network_attachment_id: 11,
attachment: { id: 11, name: 'Public uplink', line_id: 3, line_name: 'China optimized', network_selector: 'bridge:br-public', state: 'active', verification_state: 'verified', ready: true },
gateway: '8.8.8.1', guest_prefix_length: 29,
dns_servers: ['1.1.1.1'], reserved_ips: [], state: 'active',
revision: 1, expected_revision: 1, live_revision: 1,
@ -161,7 +202,7 @@ function fixture(canManage = true) {
}, 7, 0);
const nodes = descendants(test.get('host-network-pools-list'));
const control = name => nodes.find(node => node.name === name);
for (const name of ['cidr', 'gateway', 'guest_prefix_length', 'dns_servers']) {
for (const name of ['network_attachment_id', 'cidr', 'gateway', 'guest_prefix_length', 'dns_servers']) {
assert.equal(control(name)?.disabled, true, `${name} remained editable on an occupied pool.`);
}
assert.equal(control('reserved_ips')?.disabled, false,
@ -172,4 +213,4 @@ function fixture(canManage = true) {
'The occupied-pool warning did not explain the per-address safety rule.');
}
console.log('Host network defaults, canonical writes, legacy blocking, name bounds, read-only controls, pool summary and occupied-pool disabled-IP editing passed.');
console.log('Host network defaults, attachments, canonical writes, legacy blocking, read-only controls, pool binding and occupied-pool safety passed.');

@ -41,12 +41,15 @@ $assert(str_contains($routes,
$assert(str_contains($controller, 'CloudAccess::manage($actor);')
&& str_contains($controller, '$write = $method !== \'GET\';')
&& substr_count($controller, "'network_attachment_id'") === 2
&& substr_count($controller,
"'name', 'cidr', 'gateway', 'dns_servers', 'reserved_ips'") === 2
"'network_attachment_id', 'name', 'cidr', 'gateway'") === 2
&& substr_count($controller,
"'dns_servers', 'reserved_ips', 'guest_prefix_length'") === 2
&& str_contains($controller,
"'guest_prefix_length', 'state', 'request_key'")
"'state', 'request_key'")
&& str_contains($controller,
"'guest_prefix_length', 'state', 'expected_revision'")
"'state', 'expected_revision'")
&& str_contains($controller,
"->withHeader('Cache-Control', 'private, no-store')"),
'Pool writes must be super-admin-only and use a strict request/response boundary.');
@ -59,28 +62,34 @@ $assert(str_contains($service, 'private const MAX_POOLS = 32;')
&& !str_contains($service, 'bin2hex(random_bytes(16))')
&& !str_contains($service, 'CloudAgentClient')
&& str_contains($service, 'CloudHostPoolMembershipService::lockedRows')
&& str_contains($service, 'CloudHostPoolMembershipService::selected')
&& str_contains($service, "\$lockedHost->default_network")
&& str_contains($service,
'CloudNetworkSelector::isValid($selector)')
&& str_contains($service, "\$attachment->network_mode = 'selector';")
&& !str_contains($service, 'CloudHostPoolMembershipService::selected')
&& !str_contains($service, 'CloudHostPoolMembershipService::primary')
&& !str_contains($service, 'default_network')
&& !str_contains($service, 'CloudNetworkSelector::isValid')
&& !str_contains($service, 'new CloudHostNetworkAttachment')
&& str_contains($service, "'network_attachment_id' => \$attachmentId")
&& str_contains($service, 'CloudHostNetworkAttachment')
&& str_contains($service, 'CloudHostAgent')
&& str_contains($service,
"(string) \$attachment->verification_state !== 'verified'")
&& str_contains($service,
'(int) $attachment->verified_agent_revision')
&& str_contains($service,
'CloudAgentSettingsService::testedNetworkSelectors($agent)')
&& str_contains($service, 'assertMembershipLine(')
&& str_contains($service, 'CloudPublicIpPool')
&& str_contains($service, 'desired_revision')
&& str_contains($service, 'observed_revision')
&& str_contains($service, 'sync_state')
&& str_contains($service, 'refreshAttachmentAggregate')
&& str_contains($service,
"'uncertain' => 4")
&& str_contains($service,
'if ($confirmedRevision > 0)')
&& str_contains($service,
'$attachment->observed_revision = $evidenceRevision;'),
'The service must persist host/line attachment desired state and independent pool revisions.');
&& !str_contains($service, 'refreshAttachmentAggregate')
&& !str_contains($service, '$attachment->save();'),
'Pools must bind verified attachments without rewriting attachment state.');
$assert(str_contains($service,
"preg_match('/^[0-9a-f]{32}$/D', \$requestKey)")
&& str_contains($service, 'sameCreateRequest(')
&& str_contains($service,
'(int) $pool->network_attachment_id')
&& str_contains($service, "'replay' => true")
&& str_contains($service,
'存在尚未核对的地址池创建记录,请刷新后编辑该记录,不能继续创建新地址池')
@ -107,7 +116,9 @@ $assert(str_contains($service, 'assertNoOverlap(')
&& str_contains($service, 'occupiedUnsafeRuntimeChanged')
&& str_contains($service, '$originalAttachment')
&& str_contains($service, '$attachmentChanged')
&& str_contains($service, '$attachmentLineChanged')
&& str_contains($service, "'attachments' => \$attachments")
&& str_contains($service, "'attachment' => \$attachment")
&& str_contains($service, "'line' => \$attachment['line']")
&& !str_contains($service, '->delete()'),
'Pool limits, overlap checks, occupied runtime locks and soft lifecycle states are required.');
$assert(str_contains($service, 'materializeIpLedger(')
@ -139,6 +150,9 @@ $assert(!str_contains($hostController, "'public_pool_cidr', 'public_gateway'")
$assert(str_contains($template, 'id="host-network-pools-drawer"')
&& str_contains($template, 'data-admin-host-network-drawer')
&& str_contains($template, 'id="host-network-pool-new-attachment"')
&& str_contains($template, '选择后显示派生线路与 selector')
&& !str_contains($template, '使用宿主机当前默认网络')
&& str_contains($template,
'{if !$admin_can_manage|default:false}disabled{/if}')
&& str_contains($client, 'window.VenixDrawerMotion.openDrawerWithMotion')
@ -151,17 +165,21 @@ $assert(str_contains($template, 'id="host-network-pools-drawer"')
&& str_contains($client, 'globalThis.crypto?.getRandomValues')
&& str_contains($client, 'request_key: requestKey')
&& str_contains($client, 'expected_revision: expectedRevision')
&& str_contains($client,
'network_attachment_id: networkAttachmentId')
&& str_contains($client, 'networkPoolAttachmentDetail(')
&& str_contains($client, 'const readyAttachments = networkPoolAttachments()')
&& str_contains($client,
'const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-pools`);')
&& str_contains($client, 'save.disabled = !canManage')
&& str_contains($client, 'for (const control of [cidr, gateway, prefix, dns]) control.disabled = true;')
&& str_contains($client, 'for (const control of [attachment, cidr, gateway, prefix, dns]) control.disabled = true;')
&& !str_contains($client, '[cidr, gateway, prefix, dns, reserved]')
&& str_contains($client, '已分配或任务占用的 IP 会被拒绝')
&& !file_exists($root . '/public/cloud/admin-host-network.css'),
'The responsive pool editor must lock network identity while allowing unoccupied disabled-IP edits.');
$assert(preg_match("/venix_asset_version value='([0-9]+)'/", $assets, $match) === 1
&& (int) $match[1] >= 2026100316,
&& (int) $match[1] >= 2026110205,
'The shared browser asset version must cover the host pool drawer release.');
echo "Administrator host public-pool contracts passed.\n";

@ -3,6 +3,8 @@ declare(strict_types=1);
require dirname(__DIR__) . '/vendor/autoload.php';
$System_Config['cloud_data_key'] = base64_encode(str_repeat('n', 32));
use App\Models\CloudPublicIp;
use App\Models\CloudPublicIpPool;
use App\Services\Cloud\CloudAdminHostNetworkService;
@ -41,7 +43,20 @@ $schema->create('cloud_hosts', static function (Blueprint $table): void {
$table->increments('id');
$table->string('name');
$table->boolean('enabled')->default(true);
$table->string('default_network');
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_host_agents', static function (Blueprint $table): void {
$table->integer('host_id')->primary();
$table->text('sealed_api_secret');
$table->boolean('enabled');
$table->integer('revision');
$table->integer('tested_revision');
$table->string('last_test_status');
$table->string('last_error_code');
$table->string('last_agent_version');
$table->text('network_selectors_json');
$table->integer('last_tested_at');
$table->integer('created_at');
$table->integer('updated_at');
});
@ -53,6 +68,7 @@ $schema->create('cloud_network_lines', static function (Blueprint $table): void
$schema->create('cloud_resource_pools', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('line_id');
$table->string('status');
});
$schema->create('cloud_host_resource_pool_memberships',
static function (Blueprint $table): void {
@ -79,6 +95,11 @@ $schema->create('cloud_host_network_attachments',
$table->integer('routing_table')->nullable();
$table->string('state');
$table->integer('priority');
$table->integer('config_revision');
$table->integer('verified_agent_revision');
$table->string('verification_state');
$table->integer('last_verified_at');
$table->string('verification_error_code');
$table->integer('desired_revision');
$table->integer('observed_revision');
$table->string('sync_state');
@ -124,20 +145,35 @@ $schema->create('cloud_public_ips', static function (Blueprint $table): void {
$now = time();
$hostId = Capsule::table('cloud_hosts')->insertGetId([
'name' => 'Host 1', 'enabled' => 1,
'default_network' => 'bridge:br0',
'created_at' => $now, 'updated_at' => $now,
]);
$foreignHostId = Capsule::table('cloud_hosts')->insertGetId([
'name' => 'Host 2', 'enabled' => 1,
'created_at' => $now, 'updated_at' => $now,
]);
$lineId = Capsule::table('cloud_network_lines')->insertGetId([
'name' => 'China optimized', 'status' => 'active',
]);
$otherLineId = Capsule::table('cloud_network_lines')->insertGetId([
'name' => 'No membership', 'status' => 'active',
]);
$resourcePoolId = Capsule::table('cloud_resource_pools')->insertGetId([
'line_id' => $lineId,
'line_id' => $lineId, 'status' => 'active',
]);
Capsule::table('cloud_host_resource_pool_memberships')->insert([
'host_id' => $hostId, 'resource_pool_id' => $resourcePoolId,
'scheduler_state' => 'active', 'priority' => 0, 'weight' => 100,
'created_at' => $now, 'updated_at' => $now,
]);
$selectors = ['bridge:br0', 'bridge:br1', 'bridge:br2'];
Capsule::table('cloud_host_agents')->insert([
'host_id' => $hostId, 'sealed_api_secret' => 'sealed', 'enabled' => 1,
'revision' => 1, 'tested_revision' => 1,
'last_test_status' => 'healthy', 'last_error_code' => '',
'last_agent_version' => 'test',
'network_selectors_json' => json_encode($selectors, JSON_THROW_ON_ERROR),
'last_tested_at' => $now, 'created_at' => $now, 'updated_at' => $now,
]);
$selector = 'bridge:br0';
$attachmentId = Capsule::table('cloud_host_network_attachments')->insertGetId([
'attachment_key' => substr(hash('sha256', $selector), 0, 32),
@ -145,6 +181,54 @@ $attachmentId = Capsule::table('cloud_host_network_attachments')->insertGetId([
'name' => $selector, 'network_mode' => 'selector',
'network_selector' => $selector, 'vlan_id' => null,
'routing_table' => null, 'state' => 'active', 'priority' => 0,
'config_revision' => 1, 'verified_agent_revision' => 1,
'verification_state' => 'verified', 'last_verified_at' => $now,
'verification_error_code' => '',
'desired_revision' => 1, 'observed_revision' => 1,
'sync_state' => 'applied', 'last_error_code' => '',
'created_at' => $now, 'updated_at' => $now,
]);
$attachmentBId = Capsule::table(
'cloud_host_network_attachments'
)->insertGetId([
'attachment_key' => str_repeat('c', 32),
'host_id' => $hostId, 'line_id' => $lineId,
'name' => 'Secondary', 'network_mode' => 'selector',
'network_selector' => 'bridge:br1', 'vlan_id' => null,
'routing_table' => null, 'state' => 'active', 'priority' => 10,
'config_revision' => 1, 'verified_agent_revision' => 1,
'verification_state' => 'verified', 'last_verified_at' => $now,
'verification_error_code' => '',
'desired_revision' => 1, 'observed_revision' => 1,
'sync_state' => 'applied', 'last_error_code' => '',
'created_at' => $now, 'updated_at' => $now,
]);
$noMembershipAttachmentId = Capsule::table(
'cloud_host_network_attachments'
)->insertGetId([
'attachment_key' => str_repeat('d', 32),
'host_id' => $hostId, 'line_id' => $otherLineId,
'name' => 'No membership', 'network_mode' => 'selector',
'network_selector' => 'bridge:br2', 'vlan_id' => null,
'routing_table' => null, 'state' => 'active', 'priority' => 20,
'config_revision' => 1, 'verified_agent_revision' => 1,
'verification_state' => 'verified', 'last_verified_at' => $now,
'verification_error_code' => '',
'desired_revision' => 1, 'observed_revision' => 1,
'sync_state' => 'applied', 'last_error_code' => '',
'created_at' => $now, 'updated_at' => $now,
]);
$foreignAttachmentId = Capsule::table(
'cloud_host_network_attachments'
)->insertGetId([
'attachment_key' => str_repeat('e', 32),
'host_id' => $foreignHostId, 'line_id' => $lineId,
'name' => 'Foreign', 'network_mode' => 'selector',
'network_selector' => 'bridge:foreign', 'vlan_id' => null,
'routing_table' => null, 'state' => 'active', 'priority' => 0,
'config_revision' => 1, 'verified_agent_revision' => 1,
'verification_state' => 'verified', 'last_verified_at' => $now,
'verification_error_code' => '',
'desired_revision' => 1, 'observed_revision' => 1,
'sync_state' => 'applied', 'last_error_code' => '',
'created_at' => $now, 'updated_at' => $now,
@ -181,11 +265,18 @@ $actor = [
'user_id' => 1, 'is_admin' => true, 'is_super_admin' => true,
'can_manage' => true, 'session_id' => 'network-pool-test',
];
$body = static fn (int $revision, array $reserved, string $dns = '1.1.1.1') => [
$body = static fn (
int $revision,
array $reserved,
string $dns = '1.1.1.1',
?int $targetAttachmentId = null,
string $state = 'active'
) => [
'network_attachment_id' => $targetAttachmentId ?? $attachmentId,
'name' => 'Public pool', 'cidr' => '8.8.8.0/29',
'gateway' => '8.8.8.1', 'dns_servers' => [$dns],
'reserved_ips' => $reserved, 'guest_prefix_length' => 29,
'state' => 'active', 'expected_revision' => $revision,
'state' => $state, 'expected_revision' => $revision,
];
$service = new CloudAdminHostNetworkService();
@ -196,12 +287,24 @@ $pool = CloudPublicIpPool::find($poolId);
$assigned = CloudPublicIp::where('address', '8.8.8.2')->first();
$disabled = CloudPublicIp::where('address', '8.8.8.3')->first();
$assert(($saved['saved_pool_key'] ?? null) === $poolKey
&& !array_key_exists('default_network', $saved['host'])
&& count($saved['attachments']) === 3
&& (int) $saved['items'][0]['network_attachment_id'] === $attachmentId
&& (int) $saved['items'][0]['attachment']['id'] === $attachmentId
&& (int) $saved['items'][0]['line']['id'] === $lineId
&& (int) $pool->desired_revision === 2
&& json_decode((string) $pool->reserved_ips_json, true) === ['8.8.8.3']
&& (string) $assigned->state === 'assigned'
&& (int) $assigned->instance_id === 51
&& (string) $disabled->state === 'disabled',
'An unoccupied IP was not disabled without disturbing the assigned IP.');
Capsule::table('cloud_host_resource_pool_memberships')
->where('host_id', $hostId)->update(['scheduler_state' => 'disabled']);
$withoutMembership = $service->read($hostId, $actor);
$assert($withoutMembership['attachments'][0]['ready'] === false,
'Attachment remained ready without an active line membership.');
Capsule::table('cloud_host_resource_pool_memberships')
->where('host_id', $hostId)->update(['scheduler_state' => 'active']);
$expectCloudError(
static fn () => $service->update(
@ -237,4 +340,192 @@ $assert((int) $pool->desired_revision === 3
&& (string) $disabled->state === 'available',
'Removing an unoccupied disabled IP did not restore its availability.');
echo "Occupied pools allow only unoccupied disabled-IP edits.\n";
$expectCloudError(
static fn () => $service->update(
$hostId,
$poolKey,
$actor,
$body(3, [], '1.1.1.1', $attachmentBId)
),
409,
'只能修改名称、运行状态和未占用的保留 / 禁用 IP'
);
$pool->refresh();
$assert((int) $pool->network_attachment_id === $attachmentId
&& (int) $pool->desired_revision === 3,
'An occupied pool switched to a different attachment.');
$expectCloudError(
static fn () => $service->update(
$hostId,
$poolKey,
$actor,
$body(2, [], '1.1.1.1', $foreignAttachmentId)
),
409,
'版本已变化'
);
$expectCloudError(
static fn () => $service->update(
$hostId,
$poolKey,
$actor,
$body(3, [], '1.1.1.1', $foreignAttachmentId)
),
409,
'不存在或不属于该宿主机'
);
$expectCloudError(
static fn () => $service->update(
$hostId,
$poolKey,
$actor,
$body(3, [], '1.1.1.1', $noMembershipAttachmentId)
),
409,
'没有启用中的资源池成员关系'
);
$createBody = [
'network_attachment_id' => $attachmentBId,
'name' => 'Second public pool',
'cidr' => '8.8.4.0/29',
'gateway' => '8.8.4.1',
'dns_servers' => ['1.0.0.1'],
'reserved_ips' => [],
'guest_prefix_length' => 29,
'state' => 'active',
'request_key' => str_repeat('f', 32),
];
$created = $service->create($hostId, $actor, $createBody);
$createdPoolKey = (string) $created['saved_pool_key'];
$createdPool = CloudPublicIpPool::where(
'pool_key', $createdPoolKey
)->first();
$replayed = $service->create($hostId, $actor, $createBody);
$assert($createdPool !== null
&& (int) $createdPool->network_attachment_id === $attachmentBId
&& (int) $createdPool->desired_revision === 1
&& (string) $createdPool->sync_state === 'applied'
&& (int) $createdPool->observed_revision === 1
&& (string) $replayed['saved_pool_key'] === $createdPoolKey
&& CloudPublicIpPool::where('pool_key', $createdPoolKey)->count() === 1,
'Create/replay did not preserve one applied attachment-bound pool.');
$expectCloudError(
static fn () => $service->create(
$hostId,
$actor,
array_replace($createBody, [
'network_attachment_id' => $attachmentId,
])
),
409,
'同一创建请求标识不能用于不同的公网地址池配置'
);
$switched = $service->update(
$hostId,
$createdPoolKey,
$actor,
[
...$createBody,
'network_attachment_id' => $attachmentId,
'expected_revision' => 1,
]
);
$createdPool->refresh();
$assert((int) $createdPool->network_attachment_id === $attachmentId
&& (int) $createdPool->desired_revision === 2
&& (int) $switched['items'][1]['attachment']['id'] === $attachmentId,
'An unoccupied pool could not switch its explicit attachment.');
Capsule::table('cloud_public_ip_pools')->where('id', $createdPool->id)
->update(['network_attachment_id' => 999999]);
$missingRead = $service->read($hostId, $actor);
$missingItem = array_values(array_filter(
$missingRead['items'],
static fn (array $item): bool =>
(string) $item['pool_key'] === $createdPoolKey
))[0] ?? null;
$assert(is_array($missingItem)
&& $missingItem['attachment']['state'] === 'missing'
&& $missingItem['line'] === null,
'A missing attachment made the read model unavailable.');
Capsule::table('cloud_public_ip_pools')->where('id', $createdPool->id)
->update(['network_attachment_id' => $attachmentId]);
Capsule::table('cloud_host_network_attachments')
->where('id', $attachmentBId)->update(['state' => 'disabled']);
$expectCloudError(
static fn () => $service->create(
$hostId,
$actor,
array_replace($createBody, [
'request_key' => str_repeat('1', 32),
'cidr' => '8.8.5.0/29',
'gateway' => '8.8.5.1',
])
),
409,
'网络接入未启用'
);
Capsule::table('cloud_host_network_attachments')
->where('id', $attachmentBId)->update([
'state' => 'active', 'verification_state' => 'stale',
]);
$expectCloudError(
static fn () => $service->create(
$hostId,
$actor,
array_replace($createBody, [
'request_key' => str_repeat('2', 32),
'cidr' => '8.8.6.0/29',
'gateway' => '8.8.6.1',
])
),
409,
'没有当前 Agent 版本的有效验证证据'
);
Capsule::table('cloud_host_network_attachments')
->where('id', $attachmentBId)->update([
'verification_state' => 'verified',
]);
Capsule::table('cloud_host_agents')->where('host_id', $hostId)->update([
'revision' => 2, 'tested_revision' => 2,
]);
$expectCloudError(
static fn () => $service->create(
$hostId,
$actor,
array_replace($createBody, [
'request_key' => str_repeat('3', 32),
'cidr' => '8.8.7.0/29',
'gateway' => '8.8.7.1',
])
),
409,
'没有当前 Agent 版本的有效验证证据'
);
Capsule::table('cloud_host_network_attachments')
->where('id', $attachmentBId)->update([
'verified_agent_revision' => 2,
]);
Capsule::table('cloud_host_agents')->where('host_id', $hostId)->update([
'network_selectors_json' => json_encode(
['bridge:br0'], JSON_THROW_ON_ERROR
),
]);
$expectCloudError(
static fn () => $service->create(
$hostId,
$actor,
array_replace($createBody, [
'request_key' => str_repeat('4', 32),
'cidr' => '8.8.9.0/29',
'gateway' => '8.8.9.1',
])
),
409,
'没有当前 Agent 版本的有效验证证据'
);
echo "Public pools bind explicit, verified host attachments safely.\n";

@ -241,10 +241,10 @@ namespace {
$schema->create('cloud_network_lines', function (Blueprint $t) { $t->increments('id'); $t->integer('region_id'); $t->integer('traffic_pool_group_id')->nullable(); $t->string('code'); $t->string('name'); $t->integer('is_default')->default(0); $t->string('status'); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_resource_pools', function (Blueprint $t) { $t->increments('id'); $t->integer('line_id'); $t->string('code'); $t->string('name'); $t->string('status'); $t->string('scheduling_policy')->default('balanced'); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_hosts', function (Blueprint $t) { $t->increments('id'); $t->string('name'); $t->string('region')->default(''); $t->string('country_code')->default(''); $t->integer('enabled'); $t->integer('resource_pool_id')->nullable(); $t->string('scheduler_state')->default('disabled'); $t->string('default_network'); $t->integer('created_at')->default(0); $t->integer('updated_at')->default(0); });
$schema->create('cloud_host_agents', function (Blueprint $t) { $t->integer('host_id')->primary(); $t->text('sealed_api_secret'); $t->integer('enabled')->default(0); $t->integer('revision')->default(1); $t->integer('tested_revision')->default(0); $t->string('last_test_status')->default('never'); $t->string('last_error_code')->default(''); $t->string('last_agent_version')->default(''); $t->integer('last_tested_at')->default(0); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_host_agents', function (Blueprint $t) { $t->integer('host_id')->primary(); $t->text('sealed_api_secret'); $t->integer('enabled')->default(0); $t->integer('revision')->default(1); $t->integer('tested_revision')->default(0); $t->string('last_test_status')->default('never'); $t->string('last_error_code')->default(''); $t->string('last_agent_version')->default(''); $t->text('network_selectors_json')->default('[]'); $t->integer('last_tested_at')->default(0); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_host_storage_configurations', function (Blueprint $t) { $t->integer('host_id')->primary(); $t->integer('revision')->default(0); $t->string('state')->default('applying'); });
$schema->create('cloud_host_resource_pool_memberships', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('resource_pool_id'); $t->string('scheduler_state')->default('disabled'); $t->integer('priority')->default(0); $t->integer('weight')->default(100); $t->integer('revision')->default(1); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['host_id', 'resource_pool_id']); });
$schema->create('cloud_host_network_attachments', function (Blueprint $t) { $t->increments('id'); $t->string('attachment_key'); $t->integer('host_id'); $t->integer('line_id'); $t->string('name'); $t->string('network_mode')->default('selector'); $t->string('network_selector'); $t->integer('vlan_id')->nullable(); $t->integer('routing_table')->nullable(); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_host_network_attachments', function (Blueprint $t) { $t->increments('id'); $t->string('attachment_key'); $t->integer('host_id'); $t->integer('line_id'); $t->string('name'); $t->string('network_mode')->default('selector'); $t->string('network_selector'); $t->integer('vlan_id')->nullable(); $t->integer('routing_table')->nullable(); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('config_revision')->default(1); $t->integer('verified_agent_revision')->default(0); $t->string('verification_state')->default('never'); $t->integer('last_verified_at')->default(0); $t->string('verification_error_code')->default(''); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_public_ip_pools', function (Blueprint $t) { $t->increments('id'); $t->string('pool_key'); $t->integer('host_id'); $t->integer('network_attachment_id'); $t->string('name'); $t->string('cidr'); $t->string('gateway'); $t->integer('guest_prefix_length'); $t->text('dns_servers_json'); $t->text('reserved_ips_json'); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_host_capacity_policies', function (Blueprint $t) { $t->integer('host_id')->primary(); foreach (['configured_cpu_cores', 'configured_memory_mib', 'configured_disk_gib', 'safety_cpu_cores', 'safety_memory_mib', 'safety_disk_gib', 'max_instances', 'created_at', 'updated_at'] as $v) { $t->integer($v)->default(0); } });
$schema->create('cloud_public_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('public_ip_pool_id')->nullable(); $t->string('address')->unique(); $t->integer('prefix_length'); $t->string('state'); $t->integer('reservation_id')->nullable()->unique(); $t->integer('instance_id')->nullable(); $t->string('operation_id')->nullable()->unique(); $t->integer('created_at'); $t->integer('updated_at'); });
@ -362,6 +362,7 @@ namespace {
'last_test_status' => 'healthy',
'last_error_code' => '',
'last_agent_version' => 'test',
'network_selectors_json' => '["bridge:br0"]',
'last_tested_at' => $now,
'created_at' => $now,
'updated_at' => $now,
@ -373,7 +374,7 @@ namespace {
'state' => 'applied',
]);
$membership = new CloudHostResourcePoolMembership(); $membership->host_id = $host->id; $membership->resource_pool_id = $pool->id; $membership->scheduler_state = 'active'; $membership->priority = 0; $membership->weight = 100; $membership->created_at = $membership->updated_at = $now; $membership->save();
$attachment = new CloudHostNetworkAttachment(); $attachment->attachment_key = str_repeat('a', 32); $attachment->host_id = $host->id; $attachment->line_id = $line->id; $attachment->name = 'Primary selector'; $attachment->network_mode = 'selector'; $attachment->network_selector = 'bridge:br0'; $attachment->state = 'active'; $attachment->priority = 0; $attachment->desired_revision = 1; $attachment->observed_revision = 1; $attachment->sync_state = 'applied'; $attachment->last_error_code = ''; $attachment->created_at = $attachment->updated_at = $now; $attachment->save();
$attachment = new CloudHostNetworkAttachment(); $attachment->attachment_key = str_repeat('a', 32); $attachment->host_id = $host->id; $attachment->line_id = $line->id; $attachment->name = 'Primary selector'; $attachment->network_mode = 'selector'; $attachment->network_selector = 'bridge:br0'; $attachment->state = 'active'; $attachment->priority = 0; $attachment->config_revision = 1; $attachment->verified_agent_revision = 1; $attachment->verification_state = 'verified'; $attachment->last_verified_at = $now; $attachment->verification_error_code = ''; $attachment->desired_revision = 1; $attachment->observed_revision = 1; $attachment->sync_state = 'applied'; $attachment->last_error_code = ''; $attachment->created_at = $attachment->updated_at = $now; $attachment->save();
$sourcePoolKey = str_repeat('1', 32); $targetPoolKey = str_repeat('2', 32);
$sourcePublicPool = new CloudPublicIpPool(); $sourcePublicPool->pool_key = $sourcePoolKey; $sourcePublicPool->host_id = $host->id; $sourcePublicPool->network_attachment_id = $attachment->id; $sourcePublicPool->name = 'Primary public pool'; $sourcePublicPool->cidr = '203.0.113.16/29'; $sourcePublicPool->gateway = '203.0.113.17'; $sourcePublicPool->guest_prefix_length = 28; $sourcePublicPool->dns_servers_json = '["1.1.1.1"]'; $sourcePublicPool->reserved_ips_json = '[]'; $sourcePublicPool->state = 'active'; $sourcePublicPool->priority = 0; $sourcePublicPool->desired_revision = 1; $sourcePublicPool->observed_revision = 1; $sourcePublicPool->sync_state = 'applied'; $sourcePublicPool->last_error_code = ''; $sourcePublicPool->created_at = $sourcePublicPool->updated_at = $now; $sourcePublicPool->save();
$targetPublicPool = new CloudPublicIpPool(); $targetPublicPool->pool_key = $targetPoolKey; $targetPublicPool->host_id = $host->id; $targetPublicPool->network_attachment_id = $attachment->id; $targetPublicPool->name = 'Secondary public pool'; $targetPublicPool->cidr = '203.0.113.32/29'; $targetPublicPool->gateway = '203.0.113.33'; $targetPublicPool->guest_prefix_length = 28; $targetPublicPool->dns_servers_json = '["1.0.0.1"]'; $targetPublicPool->reserved_ips_json = '[]'; $targetPublicPool->state = 'active'; $targetPublicPool->priority = 10; $targetPublicPool->desired_revision = 1; $targetPublicPool->observed_revision = 1; $targetPublicPool->sync_state = 'applied'; $targetPublicPool->last_error_code = ''; $targetPublicPool->created_at = $targetPublicPool->updated_at = $now; $targetPublicPool->save();

@ -99,7 +99,8 @@ $assert(str_contains($schema, 'parent_job_id BIGINT UNSIGNED DEFAULT NULL')
&& str_contains($schema, 'active_job_id BIGINT UNSIGNED DEFAULT NULL'),
'Fresh schema lacks aggregate/child or single-dispatch links.');
$assert(!str_contains($hostNetwork, 'CloudAgentSettingsService')
$assert(str_contains($hostNetwork,
'CloudAgentSettingsService::testedNetworkSelectors($agent)')
&& !str_contains($hostNetwork, '->request(')
&& !str_contains($hostNetwork, 'markOutcome(')
&& str_contains($hostNetwork, '->transaction(')

Loading…
Cancel
Save