self::overviewWithPools($actor, $pools), 'networks' => self::listing($actor, $input), 'pools' => $pools, ]; } public static function overview(array $actor): array { return self::overviewWithPools( $actor, CloudAdminVpcCidrPoolService::listing() ); } private static function overviewWithPools(array $actor, array $pools): array { $sets = self::operationalSets(); $total = CloudVpc::query()->where('active_claim', 1)->count(); $portCount = CloudVpcPort::query()->where('active_claim', 1)->count(); $batchCount = CloudVpcMembershipBatch::query() ->where('active_claim', 1)->count(); $degraded = count($sets['degraded']); $changing = count($sets['changing']); $attention = self::listing($actor, [ 'state' => 'degraded', 'page' => 1, 'per_page' => 20, ]); return [ 'feature' => [ 'enabled' => CloudVpcFeature::enabled(), 'settings_url' => '/admin/config', ], 'summary' => [ 'total' => $total, 'active' => max(0, $total - $degraded - $changing), 'changing' => $changing, 'degraded' => $degraded, 'ports' => $portCount, 'active_batches' => $batchCount, ], 'regions' => self::regionReadiness($pools), 'attention' => $attention['items'], 'updated_at' => time(), ]; } public static function listing(array $actor, array $input = []): array { $filters = self::filters($input); $sets = self::operationalSets(); $query = CloudVpc::query()->from('cloud_vpcs as vpc') ->join('cloud_regions as region', 'region.id', '=', 'vpc.region_id') ->leftJoin('user as owner', 'owner.id', '=', 'vpc.user_id') ->where('vpc.active_claim', 1); if ($filters['q'] !== '') { $like = '%' . self::escapeLike($filters['q']) . '%'; $query->where(static function ($search) use ($like): void { $search->whereRaw("vpc.name LIKE ? ESCAPE '!'", [$like]) ->orWhereRaw("vpc.vpc_key LIKE ? ESCAPE '!'", [$like]) ->orWhereRaw("vpc.cidr LIKE ? ESCAPE '!'", [$like]) ->orWhereRaw("owner.user_name LIKE ? ESCAPE '!'", [$like]) ->orWhereRaw("owner.email LIKE ? ESCAPE '!'", [$like]); }); } if ($filters['region_id'] > 0) { $query->where('vpc.region_id', $filters['region_id']); } if ($filters['state'] === 'degraded') { self::whereIds($query, $sets['degraded']); } elseif ($filters['state'] === 'changing') { self::whereIds($query, $sets['changing']); } elseif ($filters['state'] === 'active') { $excluded = array_values(array_unique(array_merge( $sets['degraded'], $sets['changing'] ))); if ($excluded !== []) { $query->whereNotIn('vpc.id', $excluded); } } $total = (clone $query)->count('vpc.id'); $pages = max(1, (int) ceil($total / $filters['per_page'])); $page = min($filters['page'], $pages); $rows = $query->orderByDesc('vpc.updated_at')->orderByDesc('vpc.id') ->forPage($page, $filters['per_page'])->get([ 'vpc.*', 'region.name as region_name', 'region.code as region_code', 'owner.user_name as owner_name', 'owner.email as owner_email', ]); $ids = $rows->pluck('id')->map( static fn ($id): int => (int) $id )->all(); $related = self::related($ids); $items = $rows->map(static fn ($vpc): array => self::row( $vpc, $actor, $sets, $related ))->all(); return [ 'items' => $items, 'filters' => $filters, 'pagination' => [ 'page' => $page, 'per_page' => $filters['per_page'], 'total' => $total, 'total_pages' => $pages, 'from' => $total === 0 ? 0 : (($page - 1) * $filters['per_page']) + 1, 'to' => min($total, $page * $filters['per_page']), ], ]; } public static function detail(array $actor, int $vpcId): array { if ($vpcId < 1) { throw new CloudError('VPC 不存在', 404); } $vpc = CloudVpc::query()->from('cloud_vpcs as vpc') ->join('cloud_regions as region', 'region.id', '=', 'vpc.region_id') ->leftJoin('user as owner', 'owner.id', '=', 'vpc.user_id') ->where('vpc.id', $vpcId)->where('vpc.active_claim', 1) ->first([ 'vpc.*', 'region.name as region_name', 'region.code as region_code', 'owner.user_name as owner_name', 'owner.email as owner_email', ]); if ($vpc === null) { throw new CloudError('VPC 不存在或已经删除', 404); } $sets = self::operationalSets(); $related = self::related([$vpcId]); $ports = CloudVpcPort::query()->from('cloud_vpc_ports as port') ->leftJoin('cloud_instances as instance', 'instance.id', '=', 'port.instance_id') ->leftJoin('cloud_hosts as host', 'host.id', '=', 'instance.host_id') ->leftJoin('cloud_hosts as migration_host', 'migration_host.id', '=', 'port.migration_host_id') ->where('port.vpc_id', $vpcId)->where('port.active_claim', 1) ->orderBy('port.id')->get([ 'port.*', 'instance.name as instance_name', 'instance.uuid as instance_uuid', 'instance.spec_json as instance_spec_json', 'instance.host_id as current_host_id', 'host.name as host_name', 'migration_host.name as migration_host_name', ])->map(static function ($port): array { $spec = json_decode((string) ($port->instance_spec_json ?? ''), true); $public = CloudInstanceMetadata::publicSpec( is_array($spec) && !array_is_list($spec) ? $spec : [] ); $networkValid = ($public['public_network_valid'] ?? false) === true; return [ 'id' => (int) $port->id, 'instance_id' => (int) $port->instance_id, 'instance_name' => (string) ($port->instance_name ?? ''), 'instance_uuid' => (string) ($port->instance_uuid ?? ''), 'host_id' => (int) ($port->migration_host_id ?? $port->current_host_id ?? 0), 'host_name' => (string) ($port->migration_host_name ?? $port->host_name ?? ''), 'public_ip' => $networkValid ? (string) ($public['public_ipv4'] ?? '') : '', 'public_ipv4' => $networkValid ? (string) ($public['public_ipv4'] ?? '') : '', 'public_ipv6' => $networkValid ? (string) ($public['public_ipv6'] ?? '') : '', 'public_network_valid' => $networkValid, 'private_ip' => (string) $port->private_ip, 'mac_address' => (string) $port->mac_address, 'state' => (string) $port->state, 'desired_revision' => (int) $port->desired_revision, 'applied_revision' => (int) $port->applied_revision, 'last_operation_id' => (string) ($port->last_operation_id ?? ''), 'last_error_code' => (string) $port->last_error_code, 'updated_at' => (int) $port->updated_at, 'instance_url' => '/admin/cloud/instances?q=' . rawurlencode( (string) ($port->instance_uuid ?? $port->instance_id) ), ]; })->all(); $hostStates = CloudVpcHostState::query() ->from('cloud_vpc_host_states as state') ->leftJoin('cloud_hosts as host', 'host.id', '=', 'state.host_id') ->where('state.vpc_id', $vpcId)->orderBy('state.host_id') ->get(['state.*', 'host.name as host_name']) ->map(static fn ($state): array => self::hostState($state))->all(); $batchModels = CloudVpcMembershipBatch::query() ->where('vpc_id', $vpcId)->orderByDesc('id')->limit(10)->get(); $batchIds = $batchModels->pluck('id')->map( static fn ($id): int => (int) $id )->all(); $itemCounts = []; if ($batchIds !== []) { $countRows = CloudVpcMembershipBatchItem::query() ->whereIn('batch_id', $batchIds) ->selectRaw('batch_id, state, COUNT(*) AS row_count') ->groupBy('batch_id')->groupBy('state')->get(); foreach ($countRows as $row) { $itemCounts[(int) $row->batch_id][(string) $row->state] = (int) $row->row_count; } } $batches = $batchModels->map(static fn ($batch): array => self::batch( $batch, $itemCounts[(int) $batch->id] ?? [] ))->all(); $jobs = CloudJob::query()->where(static function ($query) use ( $vpcId, $batchIds ): void { $query->where('vpc_id', $vpcId); if ($batchIds !== []) { $query->orWhereIn('vpc_batch_id', $batchIds); } })->orderByDesc('id')->limit(20)->get([ 'id', 'operation_id', 'kind', 'phase', 'outcome', 'status', 'error_code', 'vpc_batch_id', 'created_at', 'updated_at', ])->map(static function ($job): array { $labels = CloudOperationCatalog::labels((string) $job->kind); $terminal = (string) $job->phase === 'terminal'; $statusLabel = !$terminal ? '执行中' : ((string) $job->outcome === 'succeeded' ? '已完成' : '失败'); return [ 'id' => (int) $job->id, 'operation_id' => (string) $job->operation_id, 'kind' => (string) $job->kind, 'kind_label' => $labels['kind_label'], 'phase' => (string) $job->phase, 'outcome' => $job->outcome === null ? null : (string) $job->outcome, 'status' => (string) $job->status, 'status_label' => $statusLabel, 'error_code' => (string) ($job->error_code ?? ''), 'batch_id' => $job->vpc_batch_id === null ? null : (int) $job->vpc_batch_id, 'updated_at' => (int) $job->updated_at, 'url' => '/admin/operations?q=' . (int) $job->id, ]; })->all(); return [ 'vpc' => self::row($vpc, $actor, $sets, $related), 'ports' => $ports, 'host_states' => $hostStates, 'batches' => $batches, 'jobs' => $jobs, ]; } private static function regionReadiness(array $poolPayload): array { $eligibleRegionIds = CloudVpcRegionReadiness::eligibleRegionIds(); $poolSummary = []; foreach ($poolPayload['items'] as $pool) { $regionId = (int) $pool['region_id']; $poolSummary[$regionId]['pools_total'] = ($poolSummary[$regionId]['pools_total'] ?? 0) + 1; if ($pool['state'] === 'active') { $poolSummary[$regionId]['pools_active'] = ($poolSummary[$regionId]['pools_active'] ?? 0) + 1; $poolSummary[$regionId]['capacity'] = ($poolSummary[$regionId]['capacity'] ?? 0) + (int) $pool['capacity']; $poolSummary[$regionId]['used'] = ($poolSummary[$regionId]['used'] ?? 0) + (int) $pool['used']; $poolSummary[$regionId]['available'] = ($poolSummary[$regionId]['available'] ?? 0) + (int) $pool['available']; } } $hostRows = CloudHost::query()->from('cloud_hosts as host') ->join('cloud_host_resource_pool_memberships as membership', 'membership.host_id', '=', 'host.id') ->join('cloud_resource_pools as resource_pool', 'resource_pool.id', '=', 'membership.resource_pool_id') ->join('cloud_network_lines as network_line', 'network_line.id', '=', 'resource_pool.line_id') ->leftJoin('cloud_host_vpc_transports as transport', 'transport.host_id', '=', 'host.id') ->get([ 'host.id', 'host.enabled', 'membership.scheduler_state', 'resource_pool.status as pool_status', 'network_line.status as line_status', 'network_line.region_id', 'transport.sync_state', 'transport.desired_revision', 'transport.observed_revision', 'transport.last_error_code', ]); $hosts = []; foreach ($hostRows as $row) { $regionId = (int) $row->region_id; $hostId = (int) $row->id; $schedulable = (bool) $row->enabled && (string) $row->scheduler_state === 'active' && (string) $row->pool_status === 'active' && (string) $row->line_status === 'active'; $ready = $schedulable && (string) $row->sync_state === 'ready' && (int) $row->desired_revision === (int) $row->observed_revision; $hosts[$regionId][$hostId]['schedulable'] = ($hosts[$regionId][$hostId]['schedulable'] ?? false) || $schedulable; $hosts[$regionId][$hostId]['ready'] = ($hosts[$regionId][$hostId]['ready'] ?? false) || $ready; if ((string) ($row->last_error_code ?? '') !== '') { $hosts[$regionId][$hostId]['error'] = (string) $row->last_error_code; } } $regions = CloudRegion::query()->orderBy('sort')->orderBy('id')->get([ 'id', 'code', 'name', 'country_code', 'status', ]); return $regions->map(static function ($region) use ( $poolSummary, $hosts, $eligibleRegionIds ): array { $id = (int) $region->id; $pool = $poolSummary[$id] ?? []; $regionHosts = $hosts[$id] ?? []; $hostTotal = count($regionHosts); $schedulable = count(array_filter($regionHosts, static fn (array $host): bool => $host['schedulable'])); $ready = count(array_filter($regionHosts, static fn (array $host): bool => $host['ready'])); $hasReadyHost = in_array($id, $eligibleRegionIds, true); $blockers = []; if ((string) $region->status !== 'active') { $blockers[] = ['code' => 'region_disabled', 'label' => '地区已停用']; } if ((int) ($pool['pools_active'] ?? 0) === 0) { $blockers[] = ['code' => 'pool_unavailable', 'label' => '没有启用中的 VPC 地址池']; } elseif ((int) ($pool['available'] ?? 0) === 0) { $blockers[] = ['code' => 'pool_exhausted', 'label' => 'VPC 地址空间已用尽']; } if ($schedulable === 0) { $blockers[] = ['code' => 'host_unavailable', 'label' => '没有可调度计算节点']; } elseif (!$hasReadyHost) { $blockers[] = ['code' => 'transport_unverified', 'label' => '计算节点 VPC 传输尚未验证']; } return [ 'id' => $id, 'code' => (string) $region->code, 'name' => (string) $region->name, 'country_code' => (string) $region->country_code, 'status' => (string) $region->status, 'pools_total' => (int) ($pool['pools_total'] ?? 0), 'pools_active' => (int) ($pool['pools_active'] ?? 0), 'capacity' => (int) ($pool['capacity'] ?? 0), 'used' => (int) ($pool['used'] ?? 0), 'available' => (int) ($pool['available'] ?? 0), 'hosts_total' => $hostTotal, 'hosts_schedulable' => $schedulable, 'hosts_ready' => $ready, 'ready' => $blockers === [] && $hasReadyHost, 'blockers' => $blockers, ]; })->all(); } private static function filters(array $input): array { $q = trim((string) ($input['q'] ?? '')); if (mb_strlen($q) > 120) { throw new CloudError('VPC 搜索条件不能超过 120 个字符'); } $state = (string) ($input['state'] ?? ''); if (!in_array($state, self::FILTER_STATES, true)) { throw new CloudError('VPC 状态筛选无效'); } $region = filter_var($input['region_id'] ?? 0, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]); $page = filter_var($input['page'] ?? 1, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); $perPage = filter_var($input['per_page'] ?? 20, FILTER_VALIDATE_INT); if ($region === false || $page === false || $perPage === false || !in_array($perPage, self::PER_PAGE, true)) { throw new CloudError('VPC 分页或地区筛选无效'); } return ['q' => $q, 'state' => $state, 'region_id' => $region, 'page' => $page, 'per_page' => $perPage]; } private static function operationalSets(): array { $degraded = CloudVpc::query()->where('active_claim', 1) ->where('state', 'degraded')->pluck('id')->map( static fn ($id): int => (int) $id )->all(); $degraded = array_merge($degraded, CloudVpcPort::query()->from('cloud_vpc_ports as port') ->join('cloud_vpcs as port_vpc', 'port_vpc.id', '=', 'port.vpc_id') ->where('port.active_claim', 1) ->where('port_vpc.active_claim', 1) ->where('port.last_error_code', '<>', '') ->pluck('port.vpc_id')->map( static fn ($id): int => (int) $id )->all(), CloudVpcHostState::query()->from('cloud_vpc_host_states as host_state') ->join('cloud_vpcs as host_vpc', 'host_vpc.id', '=', 'host_state.vpc_id') ->where('host_vpc.active_claim', 1) ->where(static function ($query): void { $query->whereIn('host_state.sync_state', ['failed', 'unknown']) ->orWhere('host_state.last_error_code', '<>', '') ->orWhere(static function ($readyMismatch): void { $readyMismatch->where( 'host_state.sync_state', 'ready' )->where(static function ($mismatch): void { $mismatch->whereColumn( 'host_state.desired_revision', '<>', 'host_state.applied_revision' )->orWhereNull('host_state.applied_digest') ->orWhereColumn( 'host_state.desired_digest', '<>', 'host_state.applied_digest' ); }); }); })->pluck('host_state.vpc_id')->map( static fn ($id): int => (int) $id )->all(), CloudVpcMembershipBatch::query() ->from('cloud_vpc_membership_batches as batch') ->join('cloud_vpcs as batch_vpc', 'batch_vpc.id', '=', 'batch.vpc_id') ->where('batch.active_claim', 1) ->where('batch_vpc.active_claim', 1) ->where('batch.state', 'blocked') ->pluck('batch.vpc_id')->map( static fn ($id): int => (int) $id )->all() ); $degraded = array_values(array_unique($degraded)); $changing = array_merge( CloudVpc::query()->where('active_claim', 1) ->whereIn('state', ['provisioning', 'deleting']) ->pluck('id')->map(static fn ($id): int => (int) $id)->all(), CloudVpcMembershipBatch::query() ->from('cloud_vpc_membership_batches as active_batch') ->join('cloud_vpcs as active_batch_vpc', 'active_batch_vpc.id', '=', 'active_batch.vpc_id') ->where('active_batch.active_claim', 1) ->where('active_batch_vpc.active_claim', 1) ->pluck('active_batch.vpc_id')->map( static fn ($id): int => (int) $id )->all(), CloudVpcHostState::query() ->from('cloud_vpc_host_states as pending_state') ->join('cloud_vpcs as pending_vpc', 'pending_vpc.id', '=', 'pending_state.vpc_id') ->where('pending_vpc.active_claim', 1) ->whereIn('pending_state.sync_state', ['pending', 'applying']) ->pluck('pending_state.vpc_id')->map( static fn ($id): int => (int) $id )->all() ); $changing = array_values(array_diff(array_unique($changing), $degraded)); return ['degraded' => $degraded, 'changing' => $changing]; } private static function related(array $ids): array { if ($ids === []) { return ['ports' => [], 'hosts' => [], 'batches' => []]; } $ports = CloudVpcPort::query()->whereIn('vpc_id', $ids) ->where('active_claim', 1) ->selectRaw('vpc_id, COUNT(*) AS row_count') ->groupBy('vpc_id')->pluck('row_count', 'vpc_id')->all(); $hosts = CloudVpcHostState::query()->whereIn('vpc_id', $ids) ->orderBy('host_id')->get()->groupBy('vpc_id')->map( static function ($states): array { $ready = 0; foreach ($states as $state) { if (self::hostReady($state)) { $ready++; } } return ['total' => $states->count(), 'ready' => $ready]; } )->all(); $batches = CloudVpcMembershipBatch::query()->whereIn('vpc_id', $ids) ->where('active_claim', 1)->orderByDesc('id')->get() ->keyBy('vpc_id')->map(static fn ($batch): array => self::batch($batch))->all(); return ['ports' => $ports, 'hosts' => $hosts, 'batches' => $batches]; } private static function row($vpc, array $actor, array $sets, array $related): array { $id = (int) $vpc->id; $state = in_array($id, $sets['degraded'], true) ? 'degraded' : (in_array($id, $sets['changing'], true) ? 'changing' : 'active'); $display = [ 'active' => ['label' => '正常', 'tone' => 'success'], 'changing' => ['label' => '变更中', 'tone' => 'warning'], 'degraded' => ['label' => '需要处理', 'tone' => 'danger'], ][$state]; $hosts = $related['hosts'][$id] ?? ['total' => 0, 'ready' => 0]; return [ 'id' => $id, 'vpc_key' => (string) $vpc->vpc_key, 'name' => (string) $vpc->name, 'user_id' => (int) $vpc->user_id, 'owner_name' => AdminDataMasker::account( (string) ($vpc->owner_name ?? '') ), 'owner_email' => AdminDataMasker::email( (string) ($vpc->owner_email ?? '') ), 'owner_url' => ($actor['is_super_admin'] ?? false) && ($actor['can_manage'] ?? false) ? '/admin/user/' . (int) $vpc->user_id . '/edit' : '', 'region_id' => (int) $vpc->region_id, 'region_name' => (string) ($vpc->region_name ?? ''), 'region_code' => (string) ($vpc->region_code ?? ''), 'cidr' => (string) $vpc->cidr, 'gateway' => (string) $vpc->gateway, 'desired_revision' => (int) $vpc->desired_revision, 'state' => $state, 'raw_state' => (string) $vpc->state, 'display' => $display, 'port_count' => (int) ($related['ports'][$id] ?? 0), 'host_summary' => [ 'total' => (int) $hosts['total'], 'ready' => (int) $hosts['ready'], ], 'active_batch' => $related['batches'][$id] ?? null, 'updated_at' => (int) $vpc->updated_at, ]; } private static function batch($batch, array $itemCounts = []): array { $total = array_sum($itemCounts); $finished = (int) ($itemCounts['succeeded'] ?? 0) + (int) ($itemCounts['failed'] ?? 0) + (int) ($itemCounts['unknown'] ?? 0); return [ 'id' => (int) $batch->id, 'batch_key' => (string) $batch->batch_key, 'job_id' => (int) $batch->parent_job_id, 'kind' => (string) $batch->kind, 'state' => (string) $batch->state, 'desired_revision' => (int) $batch->desired_revision, 'active' => $batch->active_claim !== null, 'last_error_code' => (string) $batch->last_error_code, 'terminal_at' => $batch->terminal_at === null ? null : (int) $batch->terminal_at, 'updated_at' => (int) $batch->updated_at, 'items' => [ 'total' => $total, 'finished' => $finished, 'succeeded' => (int) ($itemCounts['succeeded'] ?? 0), 'failed' => (int) ($itemCounts['failed'] ?? 0), 'unknown' => (int) ($itemCounts['unknown'] ?? 0), ], 'job_url' => '/admin/operations?q=' . (int) $batch->parent_job_id, ]; } private static function hostState($state): array { return [ 'id' => (int) $state->id, 'host_id' => (int) $state->host_id, 'host_name' => (string) ($state->host_name ?? ''), 'sync_state' => (string) $state->sync_state, 'desired_revision' => (int) $state->desired_revision, 'applied_revision' => (int) $state->applied_revision, 'digest_match' => $state->applied_digest !== null && hash_equals((string) $state->desired_digest, (string) $state->applied_digest), 'ready' => self::hostReady($state), 'last_operation_id' => (string) ($state->last_operation_id ?? ''), 'last_error_code' => (string) $state->last_error_code, 'last_success_at' => (int) $state->last_success_at, 'last_failure_at' => (int) $state->last_failure_at, 'updated_at' => (int) $state->updated_at, 'host_url' => '/admin/hosts?q=' . (int) $state->host_id, ]; } private static function hostReady($state): bool { return (string) $state->sync_state === 'ready' && (int) $state->desired_revision === (int) $state->applied_revision && $state->applied_digest !== null && hash_equals((string) $state->desired_digest, (string) $state->applied_digest) && (string) $state->last_error_code === ''; } private static function whereIds($query, array $ids): void { if ($ids === []) { $query->whereRaw('1 = 0'); return; } $query->whereIn('vpc.id', $ids); } private static function escapeLike(string $value): string { return str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $value); } }