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', 'spec_json', ]); 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([ 'id', 'instance_id', 'user_id', 'starts_at', 'ends_at', 'traffic_pool_group_id', 'traffic_quota_mode', 'traffic_quota_bytes', ]); } $trafficAccounting = CloudTrafficPoolReadModel::forPeriod( (int) $instance->user_id, $period ); $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); $decoded = json_decode((string) $instance->spec_json, true); $publicNetwork = CloudInstanceMetadata::publicSpec( is_array($decoded) && !array_is_list($decoded) ? $decoded : [] ); $publicNetworkValid = ($publicNetwork['public_network_valid'] ?? false) === true; $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'); $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' ? '等待宿主机同步' : ''); } $operation = self::operationTransitions( new \Illuminate\Database\Eloquent\Collection([$instance]) )[(int) $instance->id] ?? null; return array_merge([ 'id' => (string) $instance->id, 'api_id' => (string) $instance->id, 'uuid' => (string) $instance->uuid, 'name' => (string) $instance->name, 'state' => $runtimeState, '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' => $publicNetworkValid ? (string) $instance->network_status : 'configuration_invalid', 'service_expires_at' => $instance->expires_at === null ? null : (int) $instance->expires_at, 'service_paused' => self::servicePaused( (string) $instance->service_status, $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() && $publicNetworkValid, 'can_delete' => $canDelete, 'can_rename' => $canDelete, ], $trafficAccounting, self::transitionProjection( $runtimeState, $operation )); } /** * 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', 'service_status', 'expires_at', 'spec_json', ]); $transitions = self::operationTransitions($records); $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) { $decoded = json_decode((string) $instance->spec_json, true); $publicNetwork = CloudInstanceMetadata::publicSpec( is_array($decoded) && !array_is_list($decoded) ? $decoded : [] ); $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[] = array_merge($publicNetwork, [ 'id' => (string) $instance->id, 'api_id' => (string) $instance->id, 'uuid' => (string) $instance->uuid, 'name' => (string) $instance->name, 'service_status' => (string) $instance->service_status, 'service_expires_at' => $instance->expires_at === null ? null : (int) $instance->expires_at, 'service_paused' => self::servicePaused( (string) $instance->service_status, $instance->expires_at ), 'operation_transition' => $transitions[(int) $instance->id]['transition'] ?? null, 'shutdown_convergence_until' => $transitions[(int) $instance->id]['shutdown_until'] ?? null, ], 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 Agent 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'); $operation = [ 'transition' => $snapshot['operation_transition'] ?? null, 'shutdown_until' => $snapshot['shutdown_convergence_until'] ?? null, ]; return array_merge([ 'id' => (string) $snapshot['id'], 'api_id' => (string) $snapshot['api_id'], 'uuid' => (string) $snapshot['uuid'], // Agent resource names are UUID-derived implementation details. 'name' => (string) ($snapshot['name'] ?? ''), 'state' => $state, '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'], 'service_paused' => self::servicePaused( (string) $snapshot['service_status'], $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'], 'traffic_accounting_mode' => (string) ( $snapshot['traffic_accounting_mode'] ?? 'legacy' ), 'traffic_pool' => is_array($snapshot['traffic_pool'] ?? null) ? $snapshot['traffic_pool'] : null, 'is_owner' => (bool) $snapshot['is_owner'], 'can_operate' => (bool) $snapshot['can_operate'], 'can_delete' => (bool) $snapshot['can_delete'], 'can_rename' => (bool) $snapshot['can_rename'], ], self::transitionProjection($state, $operation)); } /** 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 = self::transitionProjection($state, [ 'transition' => $snapshot['operation_transition'] ?? null, 'shutdown_until' => $snapshot['shutdown_convergence_until'] ?? null, ]); $serviceStatus = (string) ($snapshot['service_status'] ?? ''); $serviceExpiresAt = isset($snapshot['service_expires_at']) ? (int) $snapshot['service_expires_at'] : 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['state_transitioning'], 'state_transition' => $transition['state_transition'], 'operation_transition' => $transition['operation_transition'], 'shutdown_convergence_until' => $transition['shutdown_convergence_until'], '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'] ?? ''), 'service_status' => $serviceStatus, 'service_expires_at' => $serviceExpiresAt, 'service_paused' => self::servicePaused( $serviceStatus, $serviceExpiresAt ), ]; } /** * Project user-visible active operations plus a bounded graceful-shutdown * convergence window for actor-scoped rows. The encrypted task body, job * identifiers and host placement never leave this service; power actions * are decoded through the canonical allow-list. */ private static function operationTransitions($instances): array { if ($instances->isEmpty()) { return []; } $instanceIds = $instances->pluck('id')->map( static fn ($id): int => (int) $id )->all(); $shutdownCutoff = time() - self::SHUTDOWN_CONVERGENCE_SECONDS; try { $lockedUpgrades = CloudJobService::blockingQueryForInstances( $instanceIds )->where('kind', 'instance_upgrade') ->where('phase', 'terminal') ->orderByDesc('id') ->get(['id', 'instance_id']); $jobs = CloudJob::whereIn('instance_id', $instanceIds) ->whereIn('kind', ['action', 'reinstall', 'instance_upgrade']) ->where(static function ($query) use ($shutdownCutoff): void { $query->whereIn('status', ['queued', 'running']) ->orWhere('updated_at', '>=', $shutdownCutoff); }) ->orderByDesc('id') ->get(['id', 'instance_id', 'kind', 'status', 'sealed_payload', 'updated_at']); } catch (\Throwable $error) { // Keep status polling available during a rolling schema upgrade. return []; } $result = []; $seen = []; foreach ($lockedUpgrades as $job) { $instanceId = (int) $job->instance_id; if ($instanceId < 1 || isset($seen[$instanceId])) { continue; } $seen[$instanceId] = true; $result[$instanceId] = ['transition' => 'locked', 'shutdown_until' => null]; } foreach ($jobs as $job) { $instanceId = (int) $job->instance_id; if ($instanceId < 1 || isset($seen[$instanceId])) { continue; } // Instance mutations share one job lane. Any newer recent // terminal row must therefore suppress an older successful // shutdown window, even when the newer result is uncertain or // failed. $seen[$instanceId] = true; $status = (string) $job->status; if (in_array($status, ['queued', 'running'], true)) { $kind = (string) $job->kind; $transition = $kind === 'reinstall' ? 'reinstall' : ($kind === 'instance_upgrade' ? 'upgrade' : self::operationTransition(CloudJobService::action($job))); if ($transition !== null) { $result[$instanceId] = ['transition' => $transition, 'shutdown_until' => null]; } continue; } if ($status === 'succeeded' && (string) $job->kind === 'action' && CloudJobService::action($job) === 'shutdown') { $until = max(0, (int) $job->updated_at) + self::SHUTDOWN_CONVERGENCE_SECONDS; if ($until >= time()) { $result[$instanceId] = ['transition' => null, 'shutdown_until' => $until]; } } } return $result; } /** Bound browser-visible transition values independently of job data. */ private static function operationTransition($value): ?string { return is_string($value) && in_array( $value, ['start', 'shutdown', 'reinstall', 'upgrade', 'locked'], true ) ? $value : null; } private static function transitionProjection(string $state, ?array $operation = null): array { $operation = is_array($operation) ? $operation : []; $operationTransition = self::operationTransition( $operation['transition'] ?? null ); $shutdownUntil = filter_var( $operation['shutdown_until'] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]] ); $shutdownConverging = $shutdownUntil !== false && $shutdownUntil >= time() && !self::stoppedState($state); $transition = $operationTransition ?? (($shutdownConverging || $state === 'shutdown') ? 'shutdown' : null); return [ 'state_transitioning' => $transition !== null, 'state_transition' => $transition, 'operation_transition' => $operationTransition, 'shutdown_convergence_until' => $shutdownConverging ? $shutdownUntil : null, ]; } private static function stoppedState(string $state): bool { return in_array($state, ['shutoff', 'stopped', 'crashed'], true); } /** 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', 'operation_transition', 'shutdown_convergence_until', 'state_observed_at', 'state_sync_status', 'state_label_hint', 'instance_status', 'service_status', 'network_status', 'service_expires_at', 'service_paused', 'os_source', 'os_name', 'install_iso', 'public_network_valid', 'public_network', 'public_ipv4', 'public_ipv4_cidr', 'public_ipv6', 'public_ipv6_cidr', 'public_ip_cidr', 'public_ip', 'login_name', 'agent_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); $transitions = self::operationTransitions($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' => '等待宿主机同步', ]; $snapshot = 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, 'service_status' => (string) $instance->service_status, 'network_status' => ($spec['public_network_valid'] ?? false) === true ? (string) $instance->network_status : 'configuration_invalid', 'service_expires_at' => $instance->expires_at === null ? null : (int) $instance->expires_at, 'service_paused' => self::servicePaused( (string) $instance->service_status, $instance->expires_at ), 'region' => $region, ], $cached); $result[] = self::listItem(array_merge($snapshot, self::transitionProjection((string) $cached['state'], $transitions[(int) $instance->id] ?? null))); } 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); $transitions = self::operationTransitions($instances); $periods = []; if ($periodIds !== []) { foreach (CloudServicePeriod::whereIn('id', $periodIds) ->whereIn('instance_id', $instanceIds) ->get([ 'id', 'instance_id', 'user_id', 'starts_at', 'ends_at', 'traffic_pool_group_id', 'traffic_quota_mode', 'traffic_quota_bytes', 'status', ]) as $period) { $periods[(int) $period->id] = $period; } } $trafficByPeriod = CloudTrafficPoolReadModel::forPeriods( array_values($periods) ); $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 || (int) $period->user_id !== (int) $instance->user_id)) { $period = null; } $result[] = self::snapshot( $instance, $actor, $period, (int) ($futurePeriods[(int) $instance->id] ?? 0), $runtime[(int) $instance->id] ?? null, $transitions[(int) $instance->id] ?? null, $period === null ? null : ($trafficByPeriod[(int) $period->id] ?? null) ); } return $result; } private static function snapshot(CloudInstance $instance, array $actor, ?CloudServicePeriod $period, int $futurePeriods, ?array $runtime = null, ?array $operation = null, ?array $trafficAccounting = 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); $publicNetworkValid = ($spec['public_network_valid'] ?? false) === true; $canOperate = $canDelete && $instance->serviceAvailable() && $publicNetworkValid; $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'); $transition = self::transitionProjection($runtimeState, $operation); $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))); $trafficAccounting ??= CloudTrafficPoolReadModel::forPeriod( (int) $instance->user_id, $period ); 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' => $transition['state_transitioning'], 'state_transition' => $transition['state_transition'], 'operation_transition' => $transition['operation_transition'], 'shutdown_convergence_until' => $transition['shutdown_convergence_until'], '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' => $publicNetworkValid ? (string) $instance->network_status : 'configuration_invalid', 'service_expires_at' => $instance->expires_at === null ? null : (int) $instance->expires_at, 'service_paused' => self::servicePaused( (string) $instance->service_status, $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->sealed_credential !== null, 'password_available' => ($owner || $global) && $instance->sealed_credential !== null, ], $trafficAccounting); } 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', 'sealed_credential', 'created_at', 'updated_at', ]; } private static function listColumns(): array { return [ 'id', 'uuid', 'host_id', 'name', 'status', 'service_status', 'network_status', 'expires_at', '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 { if ((string) ($vm['network_status'] ?? '') === 'configuration_invalid' || (bool) ($vm['service_paused'] ?? false) || (bool) ($vm['state_transitioning'] ?? false)) { return 'other'; } $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')); } /** * User-visible commercial suspension is independent of libvirt power. * Expiry deliberately disconnects networking without powering QEMU off, * so callers must not rewrite the identity-checked runtime state itself. */ private static function servicePaused(string $status, $expiresAt, ?int $now = null): bool { if (strtolower(trim($status)) === 'exempt' || !is_numeric($expiresAt) || (int) $expiresAt <= 0) { return false; } return (int) $expiresAt <= ($now ?? time()); } }