'服务正常', 'exempt' => '免计费', 'expired' => '已到期', 'expired_grace' => '到期宽限期', 'suspending_expired' => '到期停用中', 'suspended_expired' => '到期已停用', 'suspend_failed' => '停用失败', 'resume_pending' => '等待恢复', 'resuming' => '恢复中', 'resume_failed' => '恢复失败', 'purge_stopping' => '清理前关机中', 'purge_stop_failed' => '清理前关机失败', 'purge_deleting' => '到期清理中', 'purge_failed' => '到期清理失败', ]; private const NETWORK_LABELS = [ 'active' => '正常', 'blocked_traffic' => '流量耗尽已断网', 'blocking' => '正在限制网络', 'block_failed' => '限制网络失败', 'blocking_expired' => '到期断网中', 'blocked_expired' => '到期已断网', 'restore_pending' => '等待恢复网络', 'restoring' => '网络恢复中', 'restore_failed' => '网络恢复失败', ]; public static function page(array $actor, array $input = []): array { self::authorize($actor); $filters = self::filters($input); $now = time(); $query = self::baseQuery(); self::applyFilters($query, $filters, $now); $summary = (clone $query)->selectRaw( 'COUNT(*) AS total, ' . "COALESCE(SUM(CASE WHEN cloud_instances.service_status <> 'exempt' " . 'AND cloud_instances.expires_at > ? AND cloud_instances.expires_at <= ? ' . 'THEN 1 ELSE 0 END), 0) AS expiring, ' . "COALESCE(SUM(CASE WHEN cloud_instances.network_status <> 'active' " . 'THEN 1 ELSE 0 END), 0) AS network_restricted, ' . 'COALESCE(SUM(CASE WHEN ' . self::attentionSql() . ' THEN 1 ELSE 0 END), 0) AS attention', [$now, $now + 7 * 86400, $now - 86400] )->first(); $counts = []; foreach (['total', 'expiring', 'network_restricted', 'attention'] as $key) { $counts[$key] = max(0, (int) ($summary?->$key ?? 0)); } $pages = max(1, (int) ceil($counts['total'] / $filters['per_page'])); $filters['page'] = min($filters['page'], $pages); if ($filters['sort'] === 'expiry') { $query->orderByRaw('CASE WHEN cloud_instances.expires_at IS NULL THEN 1 ELSE 0 END') ->orderBy('cloud_instances.expires_at')->orderBy('cloud_instances.id'); } else { $direction = $filters['sort'] === 'oldest' ? 'asc' : 'desc'; $query->orderBy('cloud_instances.created_at', $direction) ->orderBy('cloud_instances.id', $direction); } $records = $query->select(self::columns())->selectRaw( '(SELECT MAX(j.id) FROM cloud_jobs j WHERE ' . self::jobRelationSql('j') . " AND j.status IN ('queued','running','uncertain')) AS active_job_id" )->offset(($filters['page'] - 1) * $filters['per_page']) ->limit($filters['per_page'])->get(); $jobs = self::activeJobs($records); $items = []; foreach ($records as $instance) { $items[] = self::row($instance, $actor, $jobs[(string) $instance->active_job_id] ?? null, $now); } $hosts = []; foreach (CloudHost::orderBy('name')->orderBy('id')->get(['id', 'name', 'region']) as $host) { $hosts[] = ['id' => (string) $host->id, 'name' => (string) $host->name, 'region' => (string) $host->region]; } $from = $counts['total'] === 0 ? 0 : ($filters['page'] - 1) * $filters['per_page'] + 1; return [ 'items' => $items, 'pagination' => ['page' => $filters['page'], 'per_page' => $filters['per_page'], 'total' => $counts['total'], 'total_pages' => $pages, 'from' => $from, 'to' => $from === 0 ? 0 : $from + count($items) - 1], 'summary' => $counts, 'filters' => $filters, 'hosts' => $hosts, 'generated_at' => $now, ]; } public static function detail(array $actor, string $id): array { self::authorize($actor); $id = self::positiveInteger($id, '实例编号'); $instance = self::baseQuery()->where('cloud_instances.id', $id) ->first(self::columns()); if ($instance === null) { throw new CloudError('虚拟机不存在', 404); } // A creation task can predate the instance row. Only a verified order // may supply that fallback; an explicit, different instance_id wins. $orderId = null; if ($instance->order_id !== null) { $order = CloudOrder::where('id', $instance->order_id) ->where('user_id', $instance->user_id) ->where(static function ($query) use ($instance): void { $query->whereNull('instance_id')->orWhere('instance_id', $instance->id); })->first(['id']); $orderId = $order?->id; } $relation = static function ($query) use ($instance, $orderId): void { $query->where('instance_id', $instance->id); if ($orderId !== null) { $query->orWhere(static function ($fallback) use ($orderId): void { $fallback->whereNull('instance_id')->where('order_id', $orderId); }); } }; // job.user_id is the action's actor, not necessarily the instance owner. $jobRecords = CloudJob::where($relation)->orderByDesc('id') ->limit(self::DETAIL_LIMIT + 1)->get(self::jobColumns())->all(); $jobsTruncated = count($jobRecords) > self::DETAIL_LIMIT; $jobs = array_map([self::class, 'jobRow'], array_slice($jobRecords, 0, self::DETAIL_LIMIT)); $active = CloudJob::where($relation)->whereIn('status', ['queued', 'running', 'uncertain']) ->orderByDesc('id')->first(self::jobColumns()); $invoiceRecords = CloudInvoice::where('user_id', $instance->user_id) ->where($relation)->orderByDesc('id')->limit(self::DETAIL_LIMIT + 1) ->get(['id', 'purpose', 'status', 'amount', 'created_at', 'due_at'])->all(); $invoicesTruncated = count($invoiceRecords) > self::DETAIL_LIMIT; $now = time(); $invoices = []; foreach (array_slice($invoiceRecords, 0, self::DETAIL_LIMIT) as $invoice) { $status = (string) $invoice->status; if ($status === 'open' && (int) $invoice->due_at <= $now) { $status = 'overdue'; } $invoices[] = ['id' => (string) $invoice->id, 'purpose' => (string) $invoice->purpose, 'status' => $status, 'amount' => self::money($invoice->amount), 'created_at' => max(0, (int) $invoice->created_at), 'detail_url' => '/admin/billing?detail=' . $invoice->id]; } $row = self::row($instance, $actor, $active === null ? null : self::jobRow($active), $now); $spec = self::spec($instance->spec_json); $period = $instance->current_period_id === null ? null : CloudServicePeriod::where('id', $instance->current_period_id) ->where('instance_id', $instance->id)->first(['starts_at', 'ends_at']); $dns = is_array($spec['dns_servers'] ?? null) ? $spec['dns_servers'] : []; $dns = array_values(array_filter(array_slice($dns, 0, 8), static fn ($value): bool => is_string($value) && filter_var($value, FILTER_VALIDATE_IP) !== false)); $row += [ 'public_ip_cidr' => self::text($spec['public_ip_cidr'] ?? null, 64), 'gateway' => self::ip($spec['gateway'] ?? null), 'dns_servers' => $dns, 'bandwidth_mbps' => self::positiveOrNull($spec['bandwidth_mbps'] ?? null), 'os_source' => self::text($spec['os_source'] ?? null, 32), 'login_name' => self::text($spec['login_name'] ?? null, 32), // The engine can extend its UUID-derived name on collisions. Do // not invent that name from a UUID when it was never persisted. 'engine_name' => self::resourceName($spec['engine_name'] ?? null), 'current_period_started_at' => $period === null ? null : (int) $period->starts_at, 'current_period_ends_at' => $period === null ? null : (int) $period->ends_at, 'renewal_price' => $instance->renewal_price === null ? null : self::money($instance->renewal_price), 'renewal_days' => max(0, (int) $instance->renewal_days), 'renewal_traffic_bytes' => max(0, (int) $instance->renewal_traffic_bytes), 'traffic_download_bytes' => max(0, (int) $instance->traffic_download_bytes), 'traffic_upload_bytes' => max(0, (int) $instance->traffic_upload_bytes), 'updated_at' => max(0, (int) $instance->updated_at), ]; return ['instance' => $row, 'jobs' => $jobs, 'jobs_truncated' => $jobsTruncated, 'invoices' => $invoices, 'invoices_truncated' => $invoicesTruncated]; } public static function filters(array $input): array { $allowed = ['q', 'user_id', 'host_id', 'service_status', 'expiry', 'attention', 'sort', 'page', 'per_page']; foreach ($input as $key => $value) { if (!in_array($key, $allowed, true) || (!is_string($value) && !is_int($value))) { throw new CloudError('筛选参数无效', 400); } } $q = trim((string) ($input['q'] ?? '')); if (mb_strlen($q, 'UTF-8') > 80 || preg_match('/[\x00-\x1f\x7f]/u', $q) !== 0) { throw new CloudError('搜索关键词最多 80 个字符,且不能包含控制字符', 400); } $filters = ['q' => $q]; foreach (['user_id', 'host_id'] as $key) { $value = (string) ($input[$key] ?? ''); $filters[$key] = $value === '' ? null : self::positiveInteger($value, $key); } foreach ([ 'service_status' => array_merge([''], array_keys(self::SERVICE_LABELS)), 'expiry' => ['all', 'soon', 'expired', 'exempt'], 'attention' => ['all', 'network', 'jobs'], 'sort' => ['newest', 'oldest', 'expiry'], ] as $key => $values) { $value = (string) ($input[$key] ?? $values[0]); if (!in_array($value, $values, true)) { throw new CloudError('筛选参数 ' . $key . ' 无效', 400); } $filters[$key] = $value; } $filters['page'] = self::positiveInteger((string) ($input['page'] ?? '1'), '页码'); $filters['per_page'] = self::positiveInteger((string) ($input['per_page'] ?? '20'), '每页条数'); if (!in_array($filters['per_page'], [20, 50, 100], true)) { throw new CloudError('每页条数只能为 20、50 或 100', 400); } return $filters; } private static function authorize(array $actor): void { if (!($actor['is_admin'] ?? false)) { throw new CloudError('需要管理员权限', 403); } } private static function baseQuery() { return CloudInstance::where('cloud_instances.status', '<>', 'deleted') ->leftJoin('user as instance_user', 'instance_user.id', '=', 'cloud_instances.user_id') ->leftJoin('cloud_hosts as instance_host', 'instance_host.id', '=', 'cloud_instances.host_id') ->leftJoin('shop as instance_plan', 'instance_plan.id', '=', 'cloud_instances.plan_id'); } private static function columns(): array { $columns = ['id', 'uuid', 'host_id', 'user_id', 'order_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', 'traffic_synced_at', 'spec_json', 'created_at', 'updated_at']; return array_merge(array_map(static fn ($key): string => 'cloud_instances.' . $key, $columns), [ 'instance_user.user_name as owner_name', 'instance_user.email as owner_email', 'instance_host.name as host_name', 'instance_host.region as host_region', 'instance_plan.name as plan_name', ]); } private static function applyFilters($query, array $filters, int $now): void { foreach (['user_id', 'host_id'] as $key) { if ($filters[$key] !== null) { $query->where('cloud_instances.' . $key, $filters[$key]); } } if ($filters['service_status'] !== '') { $query->where('cloud_instances.service_status', $filters['service_status']); } if ($filters['expiry'] === 'exempt') { $query->where('cloud_instances.service_status', 'exempt'); } elseif ($filters['expiry'] === 'soon') { $query->where('cloud_instances.service_status', '<>', 'exempt') ->where('cloud_instances.expires_at', '>', $now) ->where('cloud_instances.expires_at', '<=', $now + 7 * 86400); } elseif ($filters['expiry'] === 'expired') { $query->where('cloud_instances.service_status', '<>', 'exempt') ->whereNotNull('cloud_instances.expires_at')->where('cloud_instances.expires_at', '<=', $now); } if ($filters['attention'] === 'network') { $query->where('cloud_instances.network_status', '<>', 'active'); } elseif ($filters['attention'] === 'jobs') { $query->whereRaw(self::attentionSql(), [$now - 86400]); } if ($filters['q'] === '') { return; } $like = '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $filters['q']) . '%'; $query->where(static function ($search) use ($filters, $like): void { $search->whereRaw("cloud_instances.name LIKE ? ESCAPE '!'", [$like]) ->orWhereRaw("cloud_instances.uuid LIKE ? ESCAPE '!'", [$like]); foreach (['public_ip_cidr', 'public_ip'] as $key) { // CASE also permits searching databases containing a damaged // old specification without calling JSON_EXTRACT on it. $search->orWhereRaw("(CASE WHEN JSON_VALID(cloud_instances.spec_json) " . "THEN JSON_EXTRACT(cloud_instances.spec_json, '$." . $key . "') " . "ELSE '' END) LIKE ? ESCAPE '!'", [$like]); } if (preg_match('/^[1-9][0-9]*$/D', $filters['q']) === 1 && strlen($filters['q']) < 19) { $search->orWhere('cloud_instances.id', (int) $filters['q']) ->orWhere('cloud_instances.user_id', (int) $filters['q']); } // Match the billing search privacy boundary: readonly operators // must not infer a masked account via repeated keyword searches. if (!AdminDataMasker::shouldMask()) { $search->orWhereRaw("instance_user.user_name LIKE ? ESCAPE '!'", [$like]) ->orWhereRaw("instance_user.email LIKE ? ESCAPE '!'", [$like]); } }); } private static function jobRelationSql(string $alias): string { return '(' . $alias . '.instance_id = cloud_instances.id OR (' . $alias . '.instance_id IS NULL AND ' . $alias . '.order_id = cloud_instances.order_id ' . 'AND EXISTS (SELECT 1 FROM cloud_orders job_order WHERE ' . 'job_order.id = cloud_instances.order_id ' . 'AND job_order.user_id = cloud_instances.user_id ' . 'AND (job_order.instance_id IS NULL OR job_order.instance_id = cloud_instances.id))))'; } private static function attentionSql(): string { return 'EXISTS (SELECT 1 FROM cloud_jobs attention_job WHERE ' . self::jobRelationSql('attention_job') . " AND (attention_job.status = 'uncertain' OR (attention_job.status = 'failed' " . 'AND attention_job.updated_at >= ?)))'; } private static function activeJobs($records): array { $ids = $records->pluck('active_job_id')->filter()->unique()->values()->all(); $result = []; if ($ids !== []) { foreach (CloudJob::whereIn('id', $ids)->get(self::jobColumns()) as $job) { $result[(string) $job->id] = self::jobRow($job); } } return $result; } private static function jobColumns(): array { return ['id', 'kind', 'status', 'attempts', 'error_code', 'result_json', 'payload_cipher', 'created_at', 'updated_at']; } private static function jobRow($job): array { $result = json_decode((string) $job->result_json, true); $labels = CloudJobService::labels($job); return ['id' => (string) $job->id, 'kind' => (string) $job->kind, 'kind_label' => $labels['kind_label'], 'action_label' => $labels['action_label'], 'status' => (string) $job->status, 'attempts' => max(0, (int) $job->attempts), 'error' => CloudOperationErrorCatalog::adminSummary( (string) $job->kind, (string) $job->status, $job->error_code, false, CloudJobService::action($job) ), 'phase' => self::jobText(is_array($result) ? ($result['phase'] ?? null) : null), 'created_at' => max(0, (int) $job->created_at), 'updated_at' => max(0, (int) $job->updated_at)]; } private static function row($instance, array $actor, ?array $job, int $now): array { $spec = self::spec($instance->spec_json); $cidr = self::text($spec['public_ip_cidr'] ?? null, 64); $publicIp = self::ip($cidr === null ? ($spec['public_ip'] ?? null) : explode('/', $cidr, 2)[0]); $service = (string) $instance->service_status; $expires = $instance->expires_at === null ? null : (int) $instance->expires_at; $used = max(0, (int) $instance->traffic_download_bytes) + max(0, (int) $instance->traffic_upload_bytes); $quota = max(0, (int) $instance->traffic_quota_bytes); $row = [ 'id' => (string) $instance->id, 'name' => (string) $instance->name, 'uuid' => (string) $instance->uuid, 'user_id' => (string) $instance->user_id, 'user_name' => AdminDataMasker::account($instance->owner_name ?? ''), 'user_email' => AdminDataMasker::email($instance->owner_email ?? ''), 'user_url' => ($actor['is_super_admin'] ?? false) && ($actor['can_manage'] ?? false) ? '/admin/user/' . $instance->user_id . '/edit' : '', 'host_id' => (string) $instance->host_id, 'host_name' => (string) ($instance->host_name ?? ''), 'region' => self::text($instance->host_region, 64) ?? self::text($spec['region'] ?? $spec['location'] ?? null, 64) ?? '', 'plan_name' => self::text($spec['plan_name'] ?? null, 120) ?? self::text($instance->plan_name, 120) ?? '', 'os_name' => self::text($spec['os_name'] ?? $spec['install_iso'] ?? null, 255) ?? '', 'guest_hostname' => self::hostname($spec['guest_hostname'] ?? $spec['hostname'] ?? null), 'public_ip' => $publicIp ?? '', 'vcpu' => self::positiveOrNull($spec['vcpu'] ?? null), 'memory_mib' => self::positiveOrNull($spec['memory_mib'] ?? null), 'disk_gib' => self::positiveOrNull($spec['disk_gib'] ?? null), 'instance_status' => (string) $instance->status, 'service_status' => $service, 'network_status' => (string) $instance->network_status, 'service_expires_at' => $expires, 'traffic_used_bytes' => $used, 'traffic_quota_bytes' => $quota, 'traffic_synced_at' => max(0, (int) $instance->traffic_synced_at), 'created_at' => max(0, (int) $instance->created_at), 'active_job' => $job, 'state' => 'unknown', 'can_manage' => ($actor['is_admin'] ?? false) && ($actor['is_super_admin'] ?? false) && ($actor['can_manage'] ?? false), 'detail_url' => '/user/cloud/instances/' . $instance->id, ]; $row['display'] = [ 'configuration' => ($row['vcpu'] === null ? '—' : $row['vcpu'] . ' 核') . ' · ' . ($row['memory_mib'] === null ? '—' : self::number($row['memory_mib'] / 1024) . ' GiB') . ' · ' . ($row['disk_gib'] === null ? '—' : self::number($row['disk_gib']) . ' GiB'), 'traffic' => $row['traffic_synced_at'] === 0 ? '未获取' : self::bytes($used) . ($service === 'exempt' ? ' · 免计费' : ' / ' . self::bytes($quota)), 'expiry' => $service === 'exempt' ? '免计费' : ($expires === null ? '—' : ($expires <= $now ? '已到期' : '剩余 ' . (int) ceil(($expires - $now) / 86400) . ' 天')), 'service' => $service === 'active' && $expires === null ? '期限未记录' : ($service === 'active' && $expires <= $now ? '已到期' : (self::SERVICE_LABELS[$service] ?? '未知')), 'network' => self::NETWORK_LABELS[(string) $instance->network_status] ?? '未知', 'lifecycle' => ['active' => '在管', 'deleting' => '删除中', 'delete_failed' => '删除失败'] [(string) $instance->status] ?? '未知', ]; return $row; } private static function spec($json): array { $value = json_decode((string) $json, true); return CloudInstanceMetadata::sanitizeSpec(is_array($value) && !array_is_list($value) ? $value : []); } private static function positiveInteger(string $value, string $label): int { if (preg_match('/^[1-9][0-9]*$/D', $value) !== 1 || filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) === false) { throw new CloudError($label . ' 无效', 400); } return (int) $value; } private static function positiveOrNull($value): ?float { if ((!is_int($value) && !is_float($value) && !is_string($value)) || !is_numeric($value)) { return null; } $number = (float) $value; return is_finite($number) && $number > 0 && $number <= 1048576 ? $number : null; } private static function text($value, int $limit): ?string { if (!is_string($value) || trim($value) === '' || preg_match('/[\x00-\x1f\x7f]/u', $value) !== 0) { return null; } return mb_substr(trim($value), 0, $limit, 'UTF-8'); } private static function ip($value): ?string { return is_string($value) && filter_var($value, FILTER_VALIDATE_IP) !== false ? $value : null; } private static function resourceName($value): ?string { return is_string($value) && preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/D', $value) === 1 ? $value : null; } private static function hostname($value): ?string { if (!is_string($value) || strlen($value) > 253 || str_ends_with($value, '.') || preg_match('/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/D', $value) !== 1) { return null; } return $value; } private static function jobText($value): ?string { // Progress and error text both cross the administrator API boundary; // redact them even for super administrators. return CloudOperationErrorCatalog::adminSummary(null, null, $value); } private static function bytes(int $bytes): string { foreach (['TiB' => 1099511627776, 'GiB' => 1073741824, 'MiB' => 1048576, 'KiB' => 1024] as $unit => $factor) { if ($bytes >= $factor) { return self::number($bytes / $factor) . ' ' . $unit; } } return $bytes . ' B'; } private static function number(float $value): string { return rtrim(rtrim(number_format($value, 2, '.', ''), '0'), '.'); } private static function money($value): string { return CloudMoney::decimal(CloudMoney::cents($value)); } }