selectorProbe = $selectorProbe ?? static fn ( int $hostId, array $actor, bool $requireReady ): array => CloudAgentSettingsService::probeNetworkSelectors( $hostId, $actor, $requireReady ); } public function read(int $hostId, array $actor): array { self::assertAdminRead($actor); return $this->response($this->host($hostId)); } public function discover(int $hostId, array $actor): array { CloudAccess::manage($actor); $host = $this->host($hostId); $probe = ($this->selectorProbe)($hostId, $actor, false); return [ 'host' => $this->hostDto($host), 'agent_revision' => (int) ($probe['agent_revision'] ?? 0), 'tested_revision' => (int) ($probe['tested_revision'] ?? 0), 'network_selectors' => $this->probeSelectors($probe), ]; } public function create(int $hostId, array $actor, array $body): array { CloudAccess::manage($actor); $requestKey = $body['request_key'] ?? null; if (!is_string($requestKey) || preg_match('/^[0-9a-f]{32}$/D', $requestKey) !== 1) { throw new CloudError('请提供有效的网络接入创建请求标识', 422); } return $this->save( $hostId, $requestKey, $body, true, null ); } public function update(int $hostId, string $attachmentKey, array $actor, array $body): array { CloudAccess::manage($actor); if (preg_match('/^[0-9a-f]{32}$/D', $attachmentKey) !== 1) { throw new CloudError('网络接入标识无效', 404); } $expectedRevision = $body['expected_revision'] ?? null; if (!is_int($expectedRevision) || $expectedRevision < 1) { throw new CloudError('网络接入版本无效,请刷新后重试', 422); } return $this->save( $hostId, $attachmentKey, $body, false, $expectedRevision ); } public function test(int $hostId, string $attachmentKey, array $actor, array $body): array { CloudAccess::manage($actor); if (preg_match('/^[0-9a-f]{32}$/D', $attachmentKey) !== 1) { throw new CloudError('网络接入标识无效', 404); } $expectedRevision = $body['expected_revision'] ?? null; if (!is_int($expectedRevision) || $expectedRevision < 1) { throw new CloudError('网络接入版本无效,请刷新后重试', 422); } $host = $this->host($hostId); $probe = ($this->selectorProbe)($hostId, $actor, true); $selectors = $this->probeSelectors($probe); $probeRevision = (int) ($probe['agent_revision'] ?? 0); $probeTestedRevision = (int) ($probe['tested_revision'] ?? 0); $failure = $host->getConnection()->transaction(function () use ( $hostId, $attachmentKey, $expectedRevision, $selectors, $probeRevision, $probeTestedRevision ): ?string { $lockedHost = CloudHost::where('id', $hostId) ->lockForUpdate()->first(); if ($lockedHost === null) { throw new CloudError('宿主机不存在', 404); } $agent = CloudHostAgent::where('host_id', $hostId) ->lockForUpdate()->first(); if ($agent === null || !$agent->isReady() || (int) $agent->revision !== $probeRevision || (int) $agent->tested_revision !== $probeTestedRevision || $probeRevision !== $probeTestedRevision) { throw new CloudError( 'Agent 配置或验证代数在测试期间已变化,请重新测试 Agent 后重试', 409 ); } $attachment = CloudHostNetworkAttachment::where('host_id', $hostId) ->where('attachment_key', $attachmentKey) ->lockForUpdate()->first(); if ($attachment === null) { throw new CloudError('网络接入不存在', 404); } if ((int) $attachment->config_revision !== $expectedRevision) { throw new CloudError('网络接入版本已变化,请刷新后重试', 409); } $persisted = CloudAgentSettingsService::testedNetworkSelectors($agent); $selector = (string) $attachment->network_selector; $now = time(); if (!in_array($selector, $persisted, true)) { $attachment->verification_state = 'stale'; $attachment->verification_error_code = 'agent_selector_evidence_stale'; $attachment->updated_at = $now; $attachment->save(); return 'Agent 最近一次完整能力测试不再包含该网络接入,请重新测试 Agent'; } if (!in_array($selector, $selectors, true)) { $attachment->verification_state = 'failed'; $attachment->verification_error_code = 'agent_network_selector_missing'; $attachment->updated_at = $now; $attachment->save(); return '宿主机 Agent 当前未发现该网络接入'; } $attachment->verified_agent_revision = (int) $agent->revision; $attachment->verification_state = 'verified'; $attachment->last_verified_at = $now; $attachment->verification_error_code = ''; $attachment->updated_at = $now; $attachment->save(); return null; }, 3); if ($failure !== null) { throw new CloudError($failure, 409); } return $this->response($host, $attachmentKey); } private function save(int $hostId, string $attachmentKey, array $body, bool $creating, ?int $expectedRevision): array { $desired = self::normalizeInput($body); $host = $this->host($hostId); $result = $host->getConnection()->transaction(function () use ( $hostId, $attachmentKey, $desired, $creating, $expectedRevision ): array { $host = CloudHost::where('id', $hostId)->lockForUpdate()->first(); if ($host === null) { throw new CloudError('宿主机不存在', 404); } $memberships = CloudHostPoolMembershipService::lockedRows($host); self::assertMembershipLine($memberships, $desired['line_id']); $agent = CloudHostAgent::where('host_id', $hostId) ->lockForUpdate()->first(); if ($agent === null || !$agent->isReady()) { throw new CloudError( '请先完成当前 Agent 配置版本的健康与能力测试', 409 ); } $testedSelectors = CloudAgentSettingsService::testedNetworkSelectors( $agent ); if (!in_array($desired['network_selector'], $testedSelectors, true)) { throw new CloudError( '所选网络接入不在 Agent 最近一次完整能力测试的候选列表中', 409 ); } $rows = CloudHostNetworkAttachment::where('host_id', $hostId) ->orderBy('id')->lockForUpdate()->get(); $attachment = $rows->first(static fn ($row): bool => hash_equals((string) $row->attachment_key, $attachmentKey) ); $duplicate = $rows->first(static fn ($row): bool => (string) $row->network_selector === $desired['network_selector'] && ($attachment === null || (int) $row->id !== (int) $attachment->id) ); if ($duplicate !== null) { throw new CloudError('该宿主机已存在相同网络选择器的接入', 409); } if ($creating) { if ($attachment !== null) { if (self::sameConfiguration($attachment, $desired)) { return ['replay' => true]; } throw new CloudError( '同一创建请求标识不能用于不同的网络接入配置', 409 ); } if ($rows->count() >= self::MAX_ATTACHMENTS) { throw new CloudError('一台宿主机最多配置 64 个网络接入', 409); } } else { if ($attachment === null) { throw new CloudError('网络接入不存在', 404); } if ((int) $attachment->config_revision !== $expectedRevision) { throw new CloudError('网络接入版本已变化,请刷新后重试', 409); } } $selectorChanged = $attachment !== null && (string) $attachment->network_selector !== $desired['network_selector']; $lineChanged = $attachment !== null && (int) $attachment->line_id !== $desired['line_id']; if (($selectorChanged || $lineChanged) && CloudPublicIpPool::where( 'network_attachment_id', (int) $attachment->id )->exists()) { throw new CloudError( '该网络接入已经绑定公网地址池,不能修改线路或网络选择器', 409 ); } $now = time(); if ($attachment === null) { $attachment = new CloudHostNetworkAttachment(); $attachment->attachment_key = $attachmentKey; $attachment->host_id = $hostId; $attachment->network_mode = 'selector'; $attachment->vlan_id = null; $attachment->routing_table = null; $attachment->config_revision = 1; $attachment->verified_agent_revision = 0; $attachment->verification_state = 'never'; $attachment->last_verified_at = 0; $attachment->verification_error_code = ''; $attachment->desired_revision = 1; $attachment->observed_revision = 0; $attachment->sync_state = 'never'; $attachment->last_error_code = ''; $attachment->created_at = $now; } elseif (self::sameConfiguration($attachment, $desired)) { return ['replay' => false]; } else { if ((int) $attachment->config_revision >= PHP_INT_MAX) { throw new CloudError('网络接入版本已达到上限', 409); } $attachment->config_revision = (int) $attachment->config_revision + 1; } $attachment->line_id = $desired['line_id']; $attachment->name = $desired['name']; $attachment->network_selector = $desired['network_selector']; $attachment->state = $desired['state']; $attachment->priority = $desired['priority']; if ($selectorChanged) { $attachment->verified_agent_revision = 0; $attachment->verification_state = 'never'; $attachment->last_verified_at = 0; $attachment->verification_error_code = ''; } $attachment->updated_at = $now; $attachment->save(); return ['replay' => false]; }, 3); return $this->response( $this->host($hostId), $attachmentKey, (bool) $result['replay'] ); } private static function assertAdminRead(array $actor): void { if (!($actor['is_admin'] ?? false)) { throw new CloudError('只有管理员可以查看宿主机网络接入', 403); } } private function response(CloudHost $host, ?string $savedKey = null, bool $replay = false): array { $agent = CloudHostAgent::find((int) $host->id); $testedSelectors = $agent === null ? [] : CloudAgentSettingsService::testedNetworkSelectors($agent); $lines = $this->lineOptions((int) $host->id); $lineNames = []; foreach ($lines as $line) { $lineNames[(int) $line['id']] = (string) $line['name']; } $items = []; foreach (CloudHostNetworkAttachment::where( 'host_id', (int) $host->id )->orderBy('priority')->orderBy('id')->get() as $attachment) { $storedState = (string) $attachment->verification_state; $currentEvidence = $agent !== null && $agent->isReady() && (int) $attachment->verified_agent_revision === (int) $agent->revision && in_array( (string) $attachment->network_selector, $testedSelectors, true ); $effectiveState = $storedState === 'verified' && !$currentEvidence ? 'stale' : $storedState; $items[] = [ 'attachment_key' => (string) $attachment->attachment_key, 'name' => self::safeText((string) $attachment->name, 80), 'line_id' => (int) $attachment->line_id, 'line_name' => $lineNames[(int) $attachment->line_id] ?? '线路关系已失效', 'network_selector' => (string) $attachment->network_selector, 'state' => (string) $attachment->state, 'priority' => (int) $attachment->priority, 'config_revision' => (int) $attachment->config_revision, 'verified_agent_revision' => (int) $attachment->verified_agent_revision, 'verification_state' => $effectiveState, 'ready' => $effectiveState === 'verified' && (string) $attachment->state === 'active', 'last_verified_at' => (int) $attachment->last_verified_at, 'verification_error_code' => self::safeCode( (string) $attachment->verification_error_code ), ]; } return [ 'host' => $this->hostDto($host), 'agent' => [ 'revision' => (int) ($agent?->revision ?? 0), 'tested_revision' => (int) ($agent?->tested_revision ?? 0), 'last_tested_at' => (int) ($agent?->last_tested_at ?? 0), 'network_selectors' => $testedSelectors, ], 'lines' => $lines, 'items' => $items, 'count' => count($items), 'maximum' => self::MAX_ATTACHMENTS, 'saved_attachment_key' => $savedKey, 'replay' => $replay, ]; } private function lineOptions(int $hostId): array { $memberships = CloudHostResourcePoolMembership::where( 'host_id', $hostId )->where('scheduler_state', 'active') ->orderBy('resource_pool_id')->orderBy('id')->get(); $poolIds = $memberships->pluck('resource_pool_id')->map( static fn ($id): int => (int) $id )->unique()->values()->all(); if ($poolIds === []) { return []; } $pools = CloudResourcePool::whereIn('id', $poolIds) ->where('status', 'active')->orderBy('id')->get(); $lineIds = $pools->pluck('line_id')->map( static fn ($id): int => (int) $id )->unique()->values()->all(); $lines = CloudNetworkLine::whereIn('id', $lineIds) ->where('status', 'active') ->orderBy('sort')->orderBy('id')->get()->keyBy('id'); $result = []; foreach ($pools as $pool) { $line = $lines[(int) $pool->line_id] ?? null; if ($line === null || isset($result[(int) $line->id])) { continue; } $result[(int) $line->id] = [ 'id' => (int) $line->id, 'name' => self::safeText((string) $line->name, 80), 'status' => self::safeCode((string) $line->status), ]; } return array_values($result); } private static function assertMembershipLine($memberships, int $lineId): void { $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 ); } $valid = CloudResourcePool::whereIn('id', $poolIds) ->where('line_id', $lineId)->where('status', 'active')->exists(); $line = CloudNetworkLine::find($lineId); if (!$valid || $line === null || (string) $line->status !== 'active') { throw new CloudError('所选线路不属于该宿主机的资源池成员关系', 409); } } private static function normalizeInput(array $body): array { $name = $body['name'] ?? null; $selector = $body['network_selector'] ?? null; $state = $body['state'] ?? null; $lineId = $body['line_id'] ?? null; $priority = $body['priority'] ?? 0; if (!is_string($name) || trim($name) === '' || mb_strlen(trim($name)) > 80 || preg_match('//u', $name) !== 1 || preg_match('/[\x00-\x1f\x7f]/u', $name) === 1) { throw new CloudError('网络接入名称需为 1 至 80 个字符', 422); } if (!CloudNetworkSelector::isValid($selector)) { throw new CloudError('网络选择器无效', 422); } if (!is_string($state) || !in_array($state, self::STATES, true)) { throw new CloudError('网络接入状态无效', 422); } if (!is_int($lineId) || $lineId < 1) { throw new CloudError('线路 ID 无效', 422); } if (!is_int($priority) || $priority < -10000 || $priority > 10000) { throw new CloudError('网络接入优先级必须为 -10000 至 10000 的整数', 422); } return [ 'name' => trim($name), 'network_selector' => $selector, 'line_id' => $lineId, 'state' => $state, 'priority' => $priority, ]; } private function probeSelectors(array $probe): array { $selectors = $probe['network_selectors'] ?? null; if (!is_array($selectors) || !array_is_list($selectors) || $selectors === [] || count($selectors) > self::MAX_ATTACHMENTS) { throw new CloudError('Agent 网络选择器响应无效', 502); } $previous = null; foreach ($selectors as $selector) { if (!CloudNetworkSelector::isValid($selector) || ($previous !== null && strcmp($previous, $selector) >= 0)) { throw new CloudError('Agent 网络选择器响应无效', 502); } $previous = $selector; } return $selectors; } private static function sameConfiguration( CloudHostNetworkAttachment $attachment, array $desired ): bool { return (string) $attachment->name === $desired['name'] && (int) $attachment->line_id === $desired['line_id'] && (string) $attachment->network_selector === $desired['network_selector'] && (string) $attachment->state === $desired['state'] && (int) $attachment->priority === $desired['priority']; } private function host(int $hostId): CloudHost { if ($hostId < 1 || ($host = CloudHost::find($hostId)) === null) { throw new CloudError('宿主机不存在', 404); } return $host; } private function hostDto(CloudHost $host): array { return [ 'id' => (int) $host->id, 'name' => self::safeText((string) $host->name, 80), 'default_network' => self::safeText( (string) $host->default_network, 128 ), ]; } private static function safeText(string $value, int $maximum): string { if (preg_match('//u', $value) !== 1) { return ''; } return mb_substr($value, 0, $maximum); } private static function safeCode(string $value): string { return preg_match('/^[a-z0-9_]{1,64}$/D', $value) === 1 ? $value : ''; } }