networkAttachmentId(); $source = $catalog['attachments'][$sourceId] ?? null; $hasAutomaticIpv4 = is_array($source) && self::ipv4OptionCount($source) > 0; $state = $catalog['malformed'] ? 'invalid' : ($hasAutomaticIpv4 ? 'ready' : 'not_configured'); $availability = self::availability($instance, $state, true); return [ 'instance_id' => (string) $instance->id, 'address_family' => 4, 'configuration_state' => $state, 'active_job' => $availability['active_job'], 'can_change' => $availability['can_change'], 'message' => $availability['message'], ]; } /** Administrator inventory is explicit and never used as write authority. */ public static function adminOptions(CloudInstance $instance): array { $context = self::context($instance); $catalog = self::catalog($context); $currentAttachmentId = $context['claim_set']->networkAttachmentId(); $attachments = array_values($catalog['attachments']); $hasCandidate = false; foreach ($attachments as $attachment) { $hasIpv4 = self::ipv4OptionCount($attachment) > 0; $hasIpv6 = ($attachment['ipv6']['pools'] ?? []) !== []; if (($attachment['current'] && ($hasIpv4 || $hasIpv6)) || (!$attachment['current'] && $hasIpv4 && $hasIpv6)) { $hasCandidate = true; break; } } $state = $catalog['malformed'] ? 'invalid' : ($hasCandidate ? 'ready' : 'not_configured'); $availability = self::availability($instance, $state); return [ 'instance_id' => (string) $instance->id, 'host_id' => (string) $context['host']->id, 'host_name' => (string) $context['host']->name, 'region' => (string) $context['host']->region, 'current_attachment_id' => (string) $currentAttachmentId, 'current_public_network' => $context['claim_set']->publicNetwork()->toArray(), 'attachments' => $attachments, 'configuration_state' => $state, 'active_job' => $availability['active_job'], 'can_change' => $availability['can_change'], 'message' => $availability['message'], ]; } private static function context(CloudInstance $instance): array { try { $spec = json_decode( (string) $instance->spec_json, true, 64, JSON_THROW_ON_ERROR ); $projected = CloudPublicNetworkSnapshot::fromArray( is_array($spec) ? ($spec['public_network'] ?? null) : null ); } catch (\Throwable) { throw new CloudError( '虚拟机双栈公网配置损坏,暂不能更换地址', 409 ); } if (!is_array($spec) || array_is_list($spec) || ($spec['managed'] ?? false) !== true || ($spec['os_source'] ?? null) !== 'cloud_template' || (int) ($instance->host_id ?? 0) < 1 || (int) ($instance->reservation_id ?? 0) < 1 || (int) ($instance->resource_pool_id ?? 0) < 1) { throw new CloudError( '当前虚拟机不是支持网络配置的面板云镜像实例', 409 ); } $claimSet = CloudPublicNetworkAllocationService::currentClaimSet( (int) $instance->reservation_id, 'committed', (int) $instance->id ); if (!hash_equals( $claimSet->publicNetwork()->fingerprint(), $projected->fingerprint() )) { throw new CloudError('虚拟机双栈公网投影与地址账本不一致', 409); } $host = CloudHost::find((int) $instance->host_id); $agent = CloudHostAgent::find((int) $instance->host_id); $resourcePool = CloudResourcePool::find( (int) $instance->resource_pool_id ); if (!$host instanceof CloudHost || !(bool) $host->enabled || !$agent instanceof CloudHostAgent || !$agent->isReady() || !$resourcePool instanceof CloudResourcePool || (int) ($resourcePool->line_id ?? 0) < 1) { throw new CloudError('宿主机公网网络变更能力不可用', 409); } return [ 'instance' => $instance, 'host' => $host, 'agent' => $agent, 'resource_pool' => $resourcePool, 'claim_set' => $claimSet, 'line_id' => (int) $resourcePool->line_id, ]; } private static function catalog(array $context): array { $instance = $context['instance']; $agent = $context['agent']; $testedSelectors = CloudAgentSettingsService::testedNetworkSelectors( $agent ); $attachmentRows = CloudHostNetworkAttachment::where( 'host_id', (int) $instance->host_id )->where('line_id', $context['line_id']) ->where('state', 'active') ->where('verification_state', 'verified') ->where('verified_agent_revision', (int) $agent->revision) ->where('last_verified_at', '>', 0) ->whereIn('network_selector', $testedSelectors) ->orderBy('priority')->orderBy('id') ->limit(self::MAX_ATTACHMENTS + 1)->get(); $malformed = $attachmentRows->count() > self::MAX_ATTACHMENTS; $attachmentRows = $attachmentRows->take(self::MAX_ATTACHMENTS); $attachments = []; foreach ($attachmentRows as $attachment) { if (!CloudPlacementNetworkService::attachmentReadyForAgent( $attachment, $agent ) || !CloudAgentSettingsService::publicNetworkReady( $agent, (string) $attachment->network_selector, (int) $attachment->verified_agent_revision )) { continue; } $id = (int) $attachment->id; $name = trim((string) ($attachment->name ?? '')); $attachments[$id] = [ 'attachment_id' => (string) $id, 'label' => $name !== '' ? $name : (string) $attachment->network_selector, 'network_selector' => (string) $attachment->network_selector, 'current' => $id === $context['claim_set']->networkAttachmentId(), 'ipv4' => ['pools' => []], 'ipv6' => ['pools' => []], ]; } if ($attachments === []) { return ['attachments' => [], 'malformed' => $malformed]; } $poolRows = CloudPublicIpPool::where( 'host_id', (int) $instance->host_id )->whereIn('network_attachment_id', array_keys($attachments)) ->where('state', 'active') ->where('sync_state', 'applied') ->whereColumn( 'observed_revision', '=', 'desired_revision' ) ->orderBy('network_attachment_id')->orderBy('address_family') ->orderBy('priority')->orderBy('id') ->limit(self::MAX_POOLS + 1)->get(); if ($poolRows->count() > self::MAX_POOLS) { $malformed = true; $poolRows = $poolRows->take(self::MAX_POOLS); } $pools = []; $ipv4Ids = []; $ipv6Ids = []; foreach ($poolRows as $pool) { $parsed = self::pool($pool, $context['host']); if ($parsed === null || !isset($attachments[(int) $pool->network_attachment_id])) { $malformed = true; continue; } $dto = $parsed['dto']; $pools[(int) $pool->id] = [ 'row' => $pool, 'dto' => $dto, 'contract' => $parsed['contract'], 'excluded' => $dto['excluded_addresses'], ]; if ((int) $pool->address_family === 4) { $ipv4Ids[] = (int) $pool->id; } else { $ipv6Ids[] = (int) $pool->id; } } $ipv6Occupied = []; if ($ipv6Ids !== []) { $rows = CloudPublicIp::where('host_id', (int) $instance->host_id) ->whereIn('public_ip_pool_id', $ipv6Ids) ->whereIn('state', [ 'reserved', 'assigned', 'changing', 'uncertain', ])->selectRaw( 'public_ip_pool_id, COUNT(*) AS aggregate' )->groupBy('public_ip_pool_id')->get(); foreach ($rows as $row) { $ipv6Occupied[(int) $row->public_ip_pool_id] = (int) $row->aggregate; } } $available = $ipv4Ids === [] ? collect() : CloudPublicIp::where('host_id', (int) $instance->host_id) ->whereIn('public_ip_pool_id', $ipv4Ids) ->where('address_family', 4) ->where('state', 'available') ->whereNull('reservation_id') ->whereNull('reservation_ip_claim_id') ->whereNull('instance_id')->whereNull('operation_id') ->orderBy('id')->limit(self::MAX_IPV4_OPTIONS + 1)->get(); if ($available->count() > self::MAX_IPV4_OPTIONS) { $malformed = true; $available = $available->take(self::MAX_IPV4_OPTIONS); } $options = []; foreach ($available as $ip) { $poolId = (int) $ip->public_ip_pool_id; $pool = $pools[$poolId] ?? null; if (!is_array($pool) || !self::availableIpv4( $ip, $pool['row'], $pool['contract'], $pool['excluded'] )) { $malformed = true; continue; } $options[$poolId][] = [ 'address_cidr' => (string) $ip->address . '/' . (int) $ip->prefix_length, ]; } foreach ($pools as $poolId => $pool) { $row = $pool['row']; $family = (int) $row->address_family; if ($family === 6 && ($ipv6Occupied[$poolId] ?? 0) >= (int) $row->max_allocations) { continue; } $attachmentId = (int) $row->network_attachment_id; $dto = $pool['dto']; if ($family === 4) { $dto['available_options'] = $options[$poolId] ?? []; } $familyKey = $family === 6 ? 'ipv6' : 'ipv4'; $attachments[$attachmentId][$familyKey]['pools'][] = $dto; } return [ 'attachments' => $attachments, 'malformed' => $malformed, ]; } private static function pool(CloudPublicIpPool $pool, CloudHost $host): ?array { try { $contract = CloudPublicIpPoolContract::fromRow($pool); $family = $contract->family(); $network = $contract->network(); $gateway = $contract->gateway(); $dns = $contract->dnsServers(); $reserved = $contract->reservedAddresses(); $allocationStart = $contract->allocationStart()?->text(); $allocationEnd = $contract->allocationEnd()?->text(); $excluded = []; foreach (array_merge($reserved, $dns, [$gateway->text()]) as $raw) { $address = CloudIpAddress::parse($raw); if ($address->family() === $family) { $excluded[$address->text()] = $address->text(); } } $management = CloudPanelUsageService::managementAddress($host); if (is_string($management) && $management !== '') { $managementAddress = CloudIpAddress::parse($management); if ($managementAddress->family() === $family) { $excluded[$managementAddress->text()] = $managementAddress->text(); } } return ['contract' => $contract, 'dto' => [ 'pool_key' => $contract->poolKey(), 'name' => trim((string) ($pool->name ?? '')), 'cidr' => $network->canonical(), 'guest_prefix' => $contract->guestPrefixLength(), 'gateway' => $gateway->text(), 'gateway_on_link' => $contract->gatewayOnLink(), 'dns_servers' => $dns, 'sparse' => $family === 6, 'allocation_start' => $allocationStart, 'allocation_end' => $allocationEnd, 'excluded_addresses' => array_values($excluded), ]]; } catch (\Throwable) { return null; } } private static function availableIpv4(CloudPublicIp $ip, CloudPublicIpPool $pool, CloudPublicIpPoolContract $contract, array $excluded): bool { try { $address = CloudIpAddress::parse((string) $ip->address); return (int) $ip->host_id === (int) $pool->host_id && (int) $ip->public_ip_pool_id === (int) $pool->id && $contract->family() === 4 && (int) $ip->address_family === 4 && (int) $ip->prefix_length === $contract->guestPrefixLength() && hash_equals($address->text(), (string) $ip->address) && is_string($ip->address_binary) && hash_equals($address->binary(), $ip->address_binary) && $contract->addressAllowed($address) && !in_array($address->text(), $excluded, true); } catch (\Throwable) { return false; } } private static function ipv4OptionCount(array $attachment): int { $count = 0; foreach ($attachment['ipv4']['pools'] ?? [] as $pool) { $count += count($pool['available_options'] ?? []); } return $count; } private static function availability(CloudInstance $instance, string $configurationState, bool $tenant = false): array { $decision = CloudPublicNetworkMutationAdmission::inspect($instance); $canChange = $decision->allowed() && $configurationState === 'ready'; $message = match (true) { $configurationState === 'invalid' => $tenant ? '面板公网 IPv4 地址池配置异常,请联系管理员。' : '面板公网地址池配置异常,请先修复双栈地址账本。', !$decision->allowed() => $decision->message, $configurationState !== 'ready' => $tenant ? '当前公网 IPv4 地址池没有可用目标地址。' : '当前公网地址池没有可用目标地址。', default => '', }; return [ 'active_job' => $decision->activeJob, 'can_change' => $canChange, 'message' => $message, ]; } }