count(); $totalPages = max(1, (int) ceil($total / $perPage)); $page = min($page, $totalPages); $records = (clone $base)->orderByDesc('id') ->offset(($page - 1) * $perPage) ->limit($perPage) ->get(self::listColumns()); $snapshots = self::listSnapshots($records); $counts = ['running' => 0, 'stopped' => 0, 'other' => 0]; foreach ($snapshots as $vm) { $counts[self::listStateCategory($vm)]++; } // Runtime observations are scoped to the visible page. Never invent a // running/stopped count for rows that have no successful observation. $counts['other'] += max(0, $total - count($snapshots)); $vms = $snapshots; return [ 'vms' => $vms, 'stats' => [ 'total' => $total, 'running' => $counts['running'], 'stopped' => $counts['stopped'], 'other' => $counts['other'], ], 'pagination' => self::pagination($page, $perPage, $total, count($vms)), ]; } public static function detailForActor(array $actor, $id): array { $instance = self::visibleInstanceQuery($actor, $id)->first(self::columns()); if ($instance === null) { throw new CloudError('虚拟机不存在或无权访问', 404); } return self::snapshots( new \Illuminate\Database\Eloquent\Collection([$instance]), $actor )[0]; } /** Mutable database state for the detail poll, without static VM metadata. */ public static function statusForActor(array $actor, $id): array { $instance = self::visibleInstanceQuery($actor, $id)->first([ 'id', 'uuid', 'host_id', 'user_id', 'current_period_id', 'name', 'status', 'service_status', 'network_status', 'expires_at', 'traffic_quota_bytes', 'traffic_download_bytes', 'traffic_upload_bytes', ]); if ($instance === null) { throw new CloudError('虚拟机不存在或无权访问', 404); } $period = null; if ($instance->current_period_id !== null) { $period = CloudServicePeriod::where('id', $instance->current_period_id) ->where('instance_id', $instance->id) ->first(['starts_at', 'ends_at']); } $owner = (int) $instance->user_id === (int) $actor['user_id']; $global = ($actor['is_admin'] ?? false) && ($actor['is_super_admin'] ?? false) && ($actor['can_manage'] ?? false); $lifecycleActive = (string) $instance->status === 'active'; $canDelete = $lifecycleActive && ($owner || $global); $download = max(0, (int) $instance->traffic_download_bytes); $upload = max(0, (int) $instance->traffic_upload_bytes); $used = $download + $upload; $quota = max(0, (int) $instance->traffic_quota_bytes); $runtime = []; try { $runtime = CloudInstanceRuntimeService::forInstances([$instance])[ (string) $instance->id ] ?? []; } catch (\Throwable $error) { // Keep the detail endpoint usable during a rolling schema update. $runtime = []; } $runtimeState = CloudInstanceMetadata::state($runtime['state'] ?? 'unknown'); $runtimeTransition = $runtimeState === 'shutdown' ? 'shutdown' : null; $runtimeFresh = (bool) ($runtime['state_fresh'] ?? $runtime['fresh'] ?? false); $runtimeObserved = $runtime['state_observed_at'] ?? $runtime['last_success_at'] ?? null; $runtimeSync = strtolower(trim((string) ($runtime['state_sync_status'] ?? $runtime['sync_status'] ?? 'pending'))); if (!preg_match('/^[a-z0-9_-]{1,32}$/D', $runtimeSync)) { $runtimeSync = 'pending'; } $runtimeHint = trim((string) ($runtime['state_label_hint'] ?? '')); if ($runtimeHint === '') { $runtimeHint = in_array($runtimeSync, ['offline', 'unavailable'], true) ? '暂时无法同步' : ($runtimeState === 'unknown' ? '等待宿主机同步' : ''); } return [ 'id' => (string) $instance->id, 'api_id' => (string) $instance->id, 'uuid' => (string) $instance->uuid, 'name' => (string) $instance->name, 'state' => $runtimeState, 'state_transitioning' => $runtimeTransition !== null, 'state_transition' => $runtimeTransition, 'state_fresh' => $runtimeFresh, 'state_observed_at' => is_numeric($runtimeObserved) ? max(0, (int) $runtimeObserved) : null, 'state_sync_status' => $runtimeSync === 'unavailable' ? 'offline' : $runtimeSync, 'state_label_hint' => $runtimeHint, 'instance_status' => (string) $instance->status, 'service_status' => (string) $instance->service_status, 'network_status' => (string) $instance->network_status, 'service_expires_at' => $instance->expires_at === null ? null : (int) $instance->expires_at, 'current_period_started_at' => $period === null ? null : (int) $period->starts_at, 'current_period_ends_at' => $period === null ? null : (int) $period->ends_at, 'traffic_download_bytes' => $download, 'traffic_upload_bytes' => $upload, 'traffic_used_bytes' => $used, 'traffic_quota_bytes' => $quota, 'traffic_remaining_bytes' => $quota === 0 ? 0 : max(0, $quota - $used), 'is_owner' => $owner, 'can_operate' => $canDelete && $instance->serviceAvailable(), 'can_delete' => $canDelete, 'can_rename' => $canDelete, ]; } /** * Return actor-visible snapshots in the caller's requested id order. * Ordinary users stay owner scoped; read-only administrators retain the * historical all-instance view without inheriting mutation permissions. */ public static function forActorIds(array $actor, array $ids): array { $ordered = []; foreach ($ids as $id) { $number = filter_var($id, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); if ($number !== false) { if (!isset($ordered[(int) $number])) { $ordered[(int) $number] = count($ordered); } } } if ($ordered === []) { return []; } $records = self::visibleQuery($actor) ->whereIn('id', array_keys($ordered)) ->get(['id', 'uuid', 'host_id', 'name']); $runtime = []; try { // Resolve the cache against the current authorized DB identity. // This prevents a reused instance ID from inheriting a previous // host/UUID's last-known power state. $runtime = CloudInstanceRuntimeService::forInstances($records); } catch (\Throwable $error) { // The cache is optional during a rolling schema upgrade. Keep // authorization and the actor-visible identity independent of it. $runtime = []; } $vms = []; foreach ($records as $instance) { $cached = $runtime[(string) $instance->id] ?? [ 'state' => 'unknown', 'state_transitioning' => false, 'state_transition' => null, 'state_fresh' => false, 'state_observed_at' => null, 'state_sync_status' => 'pending', 'state_label_hint' => '等待宿主机同步', ]; $vms[] = [ 'id' => (string) $instance->id, 'api_id' => (string) $instance->id, 'uuid' => (string) $instance->uuid, 'name' => (string) $instance->name, ] + array_intersect_key($cached, array_flip([ 'state', 'state_transitioning', 'state_transition', 'state_fresh', 'state_observed_at', 'state_sync_status', 'state_label_hint', ])); } usort($vms, static fn (array $left, array $right): int => ($ordered[(int) $left['id']] ?? PHP_INT_MAX) <=> ($ordered[(int) $right['id']] ?? PHP_INT_MAX)); return $vms; } /** A deliberately small mutable status view merged with live engine data. */ public static function status(array $snapshot, array $live = []): array { $liveUuid = is_string($live['uuid'] ?? null) ? strtolower(trim($live['uuid'])) : ''; $liveMatches = $liveUuid !== '' && hash_equals( strtolower((string) $snapshot['uuid']), $liveUuid ); if (!$liveMatches) { $live = []; } $liveStateAvailable = $liveMatches && CloudInstanceMetadata::state($live['state'] ?? null) !== 'unknown'; // A malformed or unavailable live response must not erase a valid // cached observation. The runtime cache remains authoritative for // ordinary polling; the optional live probe only wins when its state // is in the bounded vocabulary. $state = $liveStateAvailable ? CloudInstanceMetadata::state($live['state']) : CloudInstanceMetadata::state($snapshot['state'] ?? 'unknown'); $transition = $state === 'shutdown' ? 'shutdown' : null; return [ 'id' => (string) $snapshot['id'], 'api_id' => (string) $snapshot['api_id'], 'uuid' => (string) $snapshot['uuid'], // Engine resource names are UUID-derived implementation details. 'name' => (string) ($snapshot['name'] ?? ''), 'state' => $state, 'state_transitioning' => $transition !== null, 'state_transition' => $transition, 'live_state_available' => $liveStateAvailable, 'state_fresh' => $liveStateAvailable || (bool) ($snapshot['state_fresh'] ?? false), 'state_observed_at' => $liveStateAvailable ? time() : ($snapshot['state_observed_at'] ?? null), 'state_sync_status' => $liveStateAvailable ? 'fresh' : (string) ($snapshot['state_sync_status'] ?? 'pending'), 'state_label_hint' => (string) ($snapshot['state_label_hint'] ?? ''), 'instance_status' => (string) $snapshot['instance_status'], 'service_status' => (string) $snapshot['service_status'], 'network_status' => (string) $snapshot['network_status'], 'service_expires_at' => $snapshot['service_expires_at'], 'current_period_started_at' => $snapshot['current_period_started_at'], 'current_period_ends_at' => $snapshot['current_period_ends_at'], 'traffic_download_bytes' => (int) $snapshot['traffic_download_bytes'], 'traffic_upload_bytes' => (int) $snapshot['traffic_upload_bytes'], 'traffic_used_bytes' => (int) $snapshot['traffic_used_bytes'], 'traffic_quota_bytes' => (int) $snapshot['traffic_quota_bytes'], 'traffic_remaining_bytes' => (int) $snapshot['traffic_remaining_bytes'], 'is_owner' => (bool) $snapshot['is_owner'], 'can_operate' => (bool) $snapshot['can_operate'], 'can_delete' => (bool) $snapshot['can_delete'], 'can_rename' => (bool) $snapshot['can_rename'], ]; } /** Minimal list-poll payload; billing and permissions belong to detail. */ public static function powerStatus(array $snapshot, array $live = []): array { $liveUuid = is_string($live['uuid'] ?? null) ? strtolower(trim($live['uuid'])) : ''; $matches = $liveUuid !== '' && hash_equals( strtolower((string) $snapshot['uuid']), $liveUuid ); $cachedState = CloudInstanceMetadata::state($snapshot['state'] ?? null); $liveAvailable = $matches && CloudInstanceMetadata::state($live['state'] ?? null) !== 'unknown'; $available = $liveAvailable || (($snapshot['state_fresh'] ?? false) === true); $state = $liveAvailable ? CloudInstanceMetadata::state($live['state']) : $cachedState; $transition = $state === 'shutdown' ? 'shutdown' : null; return [ 'id' => (string) $snapshot['id'], 'api_id' => (string) $snapshot['api_id'], 'uuid' => (string) $snapshot['uuid'], 'name' => (string) $snapshot['name'], 'state' => $state, 'state_transitioning' => $transition !== null, 'state_transition' => $transition, 'live_state_available' => $available, 'state_fresh' => $liveAvailable || (bool) ($snapshot['state_fresh'] ?? false), 'state_observed_at' => $liveAvailable ? time() : ($snapshot['state_observed_at'] ?? null), 'state_sync_status' => $liveAvailable ? 'fresh' : (string) ($snapshot['state_sync_status'] ?? 'pending'), 'state_label_hint' => (string) ($snapshot['state_label_hint'] ?? ''), ]; } /** Keep the paginated list bootstrap intentionally smaller than detail. */ private static function listItem(array $snapshot): array { $keys = [ 'id', 'api_id', 'uuid', 'name', 'state', 'region', 'location', 'state_transitioning', 'state_transition', 'state_fresh', 'state_observed_at', 'state_sync_status', 'state_label_hint', 'instance_status', 'os_source', 'os_name', 'install_iso', 'public_ip_cidr', 'public_ip', 'login_name', 'engine_metadata_version', 'vcpu', 'cpu_cores', 'memory_mib', 'ram_mib', 'disks', 'disk_gib', ]; return array_intersect_key($snapshot, array_flip($keys)); } private static function listSnapshots($instances): array { if ($instances->isEmpty()) { return []; } // The runtime table is the only source for a persisted power state. // Keep this optional so older installations can still render their // database-backed list while the runtime table is being provisioned. $runtime = self::runtimeMap($instances); $result = []; foreach ($instances as $instance) { $decoded = json_decode((string) $instance->spec_json, true); $spec = CloudInstanceMetadata::publicSpec( is_array($decoded) && !array_is_list($decoded) ? $decoded : [] ); // The selling region is an immutable customer-facing snapshot. // Never derive it from the current physical host: doing so leaks // placement and makes a live migration silently rename a service. $region = trim((string) ($spec['region'] ?? $spec['location'] ?? '')); $cached = $runtime[(int) $instance->id] ?? [ 'state' => 'unknown', 'state_transitioning' => false, 'state_transition' => null, 'state_fresh' => false, 'state_observed_at' => null, 'state_sync_status' => 'pending', 'state_label_hint' => '等待宿主机同步', ]; $result[] = self::listItem(array_merge($spec, [ 'id' => (string) $instance->id, 'api_id' => (string) $instance->id, 'uuid' => (string) $instance->uuid, 'name' => (string) $instance->name, 'instance_status' => (string) $instance->status, 'region' => $region, ], $cached)); } return $result; } /** * Return safe, actor-independent cached power state keyed by instance id. * The runtime service owns freshness and host-health decisions; this * adapter only limits the fields exposed to the user page. */ private static function runtimeMap($instances): array { if ($instances->isEmpty() || !class_exists(CloudInstanceRuntimeService::class) || !method_exists(CloudInstanceRuntimeService::class, 'forInstances')) { return []; } try { $rows = CloudInstanceRuntimeService::forInstances($instances); } catch (\Throwable $error) { // A missing table or a transient read failure must not hide the // database-backed instance list. The UI will show a sync hint. return []; } if (!is_array($rows)) { return []; } $result = []; foreach ($rows as $key => $row) { if (is_object($row) && method_exists($row, 'toArray')) { $row = $row->toArray(); } if (!is_array($row)) { continue; } $id = filter_var($row['instance_id'] ?? $row['id'] ?? $key, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); if ($id === false) { continue; } $state = CloudInstanceMetadata::state($row['state'] ?? 'unknown'); $fresh = filter_var($row['state_fresh'] ?? $row['fresh'] ?? false, FILTER_VALIDATE_BOOLEAN); $observed = $row['state_observed_at'] ?? $row['last_success_at'] ?? null; if (is_string($observed) && $observed !== '' && !is_numeric($observed)) { $observed = strtotime($observed) ?: null; } $observed = is_numeric($observed) ? max(0, (int) $observed) : null; $syncStatus = strtolower(trim((string) ($row['state_sync_status'] ?? $row['sync_status'] ?? 'pending'))); if (!preg_match('/^[a-z0-9_-]{1,32}$/D', $syncStatus)) { $syncStatus = 'pending'; } $hint = trim((string) ($row['state_label_hint'] ?? '')); if ($hint === '' || (function_exists('mb_strlen') ? mb_strlen($hint) : strlen($hint)) > 32) { $hint = $syncStatus === 'unavailable' || $syncStatus === 'offline' ? '暂时无法同步' : '等待宿主机同步'; } $result[(int) $id] = [ 'state' => $state, 'state_transitioning' => $state === 'shutdown', 'state_transition' => $state === 'shutdown' ? 'shutdown' : null, 'state_fresh' => $fresh, 'state_observed_at' => $observed, 'state_sync_status' => $syncStatus, 'state_label_hint' => $hint, ]; } return $result; } private static function snapshots($instances, array $actor): array { if ($instances->isEmpty()) { return []; } $instanceIds = $instances->pluck('id')->map(static fn ($id): int => (int) $id)->all(); $periodIds = $instances->pluck('current_period_id')->filter( static fn ($id): bool => $id !== null )->map(static fn ($id): int => (int) $id)->unique()->values()->all(); // Merge only identity-checked runtime observations into detail // snapshots. The runtime service rejects a reused ID whose host or // UUID no longer matches the current cloud_instances row. $runtime = self::runtimeMap($instances); $periods = []; if ($periodIds !== []) { foreach (CloudServicePeriod::whereIn('id', $periodIds) ->whereIn('instance_id', $instanceIds) ->get(['id', 'instance_id', 'starts_at', 'ends_at', 'status']) as $period) { $periods[(int) $period->id] = $period; } } $futurePeriods = []; foreach (CloudServicePeriod::whereIn('instance_id', $instanceIds) ->where('status', 'scheduled') ->selectRaw('instance_id, COUNT(*) AS period_count') ->groupBy('instance_id')->get() as $row) { $futurePeriods[(int) $row->instance_id] = (int) $row->period_count; } $result = []; foreach ($instances as $instance) { $period = $instance->current_period_id === null ? null : ($periods[(int) $instance->current_period_id] ?? null); if ($period !== null && (int) $period->instance_id !== (int) $instance->id) { $period = null; } $result[] = self::snapshot( $instance, $actor, $period, (int) ($futurePeriods[(int) $instance->id] ?? 0), $runtime[(int) $instance->id] ?? null ); } return $result; } private static function snapshot(CloudInstance $instance, array $actor, ?CloudServicePeriod $period, int $futurePeriods, ?array $runtime = null): array { $decoded = json_decode((string) $instance->spec_json, true); $spec = CloudInstanceMetadata::publicSpec( is_array($decoded) && !array_is_list($decoded) ? $decoded : [] ); $owner = (int) $instance->user_id === (int) $actor['user_id']; $global = ($actor['is_admin'] ?? false) && ($actor['is_super_admin'] ?? false) && ($actor['can_manage'] ?? false); $lifecycleActive = (string) $instance->status === 'active'; $canDelete = $lifecycleActive && ($owner || $global); $canOperate = $canDelete && $instance->serviceAvailable(); $quota = max(0, (int) $instance->traffic_quota_bytes); $download = max(0, (int) $instance->traffic_download_bytes); $upload = max(0, (int) $instance->traffic_upload_bytes); $used = $download + $upload; $region = trim((string) ($spec['region'] ?? $spec['location'] ?? '')); $createdAt = (int) $instance->created_at > 0 ? gmdate('Y-m-d\TH:i:s\Z', (int) $instance->created_at) : null; $runtime = is_array($runtime) ? $runtime : []; $runtimeState = CloudInstanceMetadata::state($runtime['state'] ?? 'unknown'); $runtimeTransition = $runtimeState === 'shutdown' ? 'shutdown' : null; $runtimeFresh = (bool) ($runtime['state_fresh'] ?? $runtime['fresh'] ?? false); $runtimeObserved = $runtime['state_observed_at'] ?? $runtime['last_success_at'] ?? null; $runtimeSync = strtolower(trim((string) ($runtime['state_sync_status'] ?? $runtime['sync_status'] ?? 'pending'))); if (!preg_match('/^[a-z0-9_-]{1,32}$/D', $runtimeSync)) { $runtimeSync = 'pending'; } $runtimeHint = trim((string) ($runtime['state_label_hint'] ?? '')); if ($runtimeHint === '') { $runtimeHint = in_array($runtimeSync, ['offline', 'unavailable'], true) ? '暂时无法同步' : ($runtimeState === 'unknown' ? '等待宿主机同步' : ''); } $maximumFuturePeriods = max(1, min(120, (int) Config::get('cloud_max_renewal_periods_ahead', 24))); return array_merge($spec, [ 'id' => (string) $instance->id, 'api_id' => (string) $instance->id, 'uuid' => (string) $instance->uuid, 'display_uuid' => (string) $instance->uuid, 'name' => (string) $instance->name, // Power state comes only from the identity-checked runtime cache; // the persisted specification is never treated as authoritative. 'state' => $runtimeState, 'state_transitioning' => $runtimeTransition !== null, 'state_transition' => $runtimeTransition, 'state_fresh' => $runtimeFresh, 'state_observed_at' => is_numeric($runtimeObserved) ? max(0, (int) $runtimeObserved) : null, 'state_sync_status' => $runtimeSync === 'unavailable' ? 'offline' : $runtimeSync, 'state_label_hint' => $runtimeHint, 'user_id' => (int) $instance->user_id, 'owner_user_id' => (int) $instance->user_id, 'region' => $region, 'country_code' => strtoupper(trim((string) ($spec['country_code'] ?? ''))), 'created_at' => $createdAt, 'instance_status' => (string) $instance->status, 'service_status' => (string) $instance->service_status, 'network_status' => (string) $instance->network_status, 'service_expires_at' => $instance->expires_at === null ? null : (int) $instance->expires_at, 'current_period_started_at' => $period === null ? null : (int) $period->starts_at, 'current_period_ends_at' => $period === null ? null : (int) $period->ends_at, 'prepaid_periods' => max(0, $futurePeriods), 'traffic_download_bytes' => $download, 'traffic_upload_bytes' => $upload, 'traffic_used_bytes' => $used, 'traffic_quota_bytes' => $quota, 'traffic_remaining_bytes' => $quota === 0 ? 0 : max(0, $quota - $used), 'renewal_price' => $instance->renewal_price === null ? null : (string) $instance->renewal_price, 'renewal_days' => max(0, (int) $instance->renewal_days), 'renewal_traffic_bytes' => max(0, (int) $instance->renewal_traffic_bytes), 'login_name' => (string) ($spec['login_name'] ?? (($spec['os_source'] ?? '') === 'cloud_template' ? 'root' : '')), 'is_owner' => $owner, 'can_operate' => $canOperate, 'can_delete' => $canDelete, 'can_rename' => $canDelete, 'can_view_credential' => $owner || $global, 'can_renew' => $lifecycleActive && $owner && $instance->expires_at !== null && (int) $instance->renewal_days > 0 && $instance->renewal_price !== null && $futurePeriods < $maximumFuturePeriods, 'has_initial_root_password' => ($owner || $global) && $instance->credential_cipher !== null, 'password_available' => ($owner || $global) && $instance->credential_cipher !== null, ]); } private static function visibleQuery(array $actor) { $query = CloudInstance::where('status', '<>', 'deleted'); if (!($actor['is_admin'] ?? false)) { $query->where('user_id', (int) $actor['user_id']); } return $query; } private static function visibleInstanceQuery(array $actor, $id) { $query = self::visibleQuery($actor); if (ctype_digit((string) $id)) { return $query->where('id', (int) $id); } return $query->where('uuid', (string) $id); } private static function columns(): array { return [ 'id', 'uuid', 'host_id', 'user_id', 'current_period_id', 'name', 'status', 'service_status', 'network_status', 'expires_at', 'renewal_price', 'renewal_days', 'renewal_traffic_bytes', 'traffic_quota_bytes', 'traffic_download_bytes', 'traffic_upload_bytes', 'spec_json', 'credential_cipher', 'created_at', 'updated_at', ]; } private static function listColumns(): array { return ['id', 'uuid', 'host_id', 'name', 'status', 'spec_json']; } private static function pagination(int $page, int $perPage, int $total, int $count): array { $pages = max(1, (int) ceil($total / $perPage)); return [ 'page' => $page, 'per_page' => $perPage, 'page_count' => $count, 'total' => $total, 'total_pages' => $pages, 'has_previous' => $page > 1, 'has_next' => $page < $pages, 'from' => $count === 0 ? 0 : (($page - 1) * $perPage) + 1, 'to' => $count === 0 ? 0 : (($page - 1) * $perPage) + $count, ]; } private static function stateCategory(string $state): string { $normalized = strtolower((string) preg_replace('/[_\s-]+/', '', $state)); if (in_array($normalized, ['running', 'blocked'], true)) { return 'running'; } if (in_array($normalized, ['shutoff', 'stopped', 'crashed'], true)) { return 'stopped'; } return 'other'; } /** Do not count a cached state as running/stopped while its host is offline. */ private static function listStateCategory(array $vm): string { $sync = strtolower(trim((string) ($vm['state_sync_status'] ?? 'pending'))); if (in_array($sync, ['offline', 'host_offline', 'unavailable', 'host_unreachable', 'pending'], true)) { return 'other'; } return self::stateCategory((string) ($vm['state'] ?? 'unknown')); } }