You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudAdminInstanceService.php

628 lines
30 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudInstance;
use App\Models\CloudInvoice;
use App\Models\CloudJob;
use App\Models\CloudOrder;
use App\Models\CloudServicePeriod;
use App\Services\AdminDataMasker;
/** Database-only administrator inventory. Never hydrate Agent/session state. */
final class CloudAdminInstanceService
{
private const DETAIL_LIMIT = 20;
private const SERVICE_LABELS = [
'active' => '服务正常', 'exempt' => '免计费', 'expired' => '已到期',
'expired_grace' => '到期宽限期',
'suspending_expired' => '到期停用中', 'suspended_expired' => '到期已停用',
'suspend_failed' => '停用失败', 'resume_pending' => '等待恢复',
'resuming' => '恢复中', 'resume_failed' => '恢复失败',
'purge_stopping' => '清理前关机中', 'purge_stop_failed' => '清理前关机失败',
'purge_force_required' => '等待确认强制删除',
'purge_deleting' => '到期清理中', 'purge_failed' => '到期清理失败',
];
private const NETWORK_LABELS = [
'active' => '正常', 'blocked_traffic' => '流量耗尽已断网',
'blocking' => '正在限制网络', 'block_failed' => '限制网络失败',
'blocking_expired' => '到期断网中', 'blocked_expired' => '到期已断网',
'restore_pending' => '等待恢复网络', 'restoring' => '网络恢复中',
'restore_failed' => '网络恢复失败',
'configuration_invalid' => '公网配置异常',
];
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);
$networkAttentionIds = self::networkAttentionIds($query);
if ($filters['attention'] === 'network') {
if ($networkAttentionIds === []) {
$query->whereRaw('1 = 0');
} else {
$query->whereIntegerInRaw(
'cloud_instances.id',
$networkAttentionIds
);
}
}
$summary = (clone $query)->selectRaw(
'COUNT(*) AS total, '
. "COALESCE(SUM(CASE WHEN cloud_instances.status = 'active' "
. "AND 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 ' . self::attentionSql()
. ' THEN 1 ELSE 0 END), 0) AS attention',
[$now, $now + 7 * 86400, $now - 86400]
)->first();
$counts = [];
foreach (['total', 'expiring', 'attention'] as $key) {
$counts[$key] = max(0, (int) ($summary?->$key ?? 0));
}
$counts['network_restricted'] = count($networkAttentionIds);
$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 ' . self::blockingJobSql('j') . ') 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)
->whereRaw(self::blockingJobSql('cloud_jobs'))
->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);
$rawSpec = self::rawSpec($instance->spec_json);
$spec = CloudInstanceMetadata::publicSpec($rawSpec);
$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'] : [];
$publicIpCidr = self::text($spec['public_ipv4_cidr'] ?? null, 64);
$publicIpv6Cidr = self::text($spec['public_ipv6_cidr'] ?? null, 64);
$networkValid = ($spec['public_network_valid'] ?? false) === true;
$ipv4Gateway = self::ip($spec['public_network']['ipv4']['gateway'] ?? null);
$ipv6Gateway = self::ip($spec['public_network']['ipv6']['gateway'] ?? null);
$managedCloudTemplate = ($spec['managed'] ?? false) === true
&& ($spec['os_source'] ?? null) === 'cloud_template';
$canMutate = $row['instance_status'] === 'active'
&& $instance->serviceAvailable($now);
$networkMutation =
CloudPublicNetworkMutationAdmission::inspect($instance);
$row += [
'public_ip_cidr' => $publicIpCidr,
'public_ipv4' => self::ip($spec['public_ipv4'] ?? null) ?? '',
'public_ipv4_cidr' => $publicIpCidr,
'public_ipv6' => self::ip($spec['public_ipv6'] ?? null) ?? '',
'public_ipv6_cidr' => $publicIpv6Cidr,
'public_network_valid' => $networkValid,
'public_network' => $spec['public_network'] ?? null,
'gateway' => $ipv4Gateway,
'ipv4_gateway' => $ipv4Gateway,
'ipv6_gateway' => $ipv6Gateway,
'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),
'network_change_supported' => $networkMutation->allowed()
&& $managedCloudTemplate && $networkValid,
'instance_settings_supported' => $canMutate && $managedCloudTemplate
&& $networkValid,
// The Agent can extend its UUID-derived name on collisions. Do
// not invent that name from a UUID when it was never persisted.
'agent_name' => self::resourceName($rawSpec['agent_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.status', 'active')
->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'] === 'jobs') {
$query->whereRaw(self::attentionSql(), [$now - 86400]);
}
if ($filters['q'] === '') {
return;
}
$like = '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $filters['q']) . '%';
$ipQuery = strtolower($filters['q']);
$ipLike = '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $ipQuery) . '%';
$packedIp = filter_var($ipQuery, FILTER_VALIDATE_IP) === false
? false : inet_pton($ipQuery);
$exactIp = is_string($packedIp) ? inet_ntop($packedIp) : null;
$exactIp = is_string($exactIp) ? $exactIp : null;
$query->where(static function ($search) use (
$filters,
$like,
$ipLike,
$exactIp
): void {
$search->whereRaw("cloud_instances.name LIKE ? ESCAPE '!'", [$like])
->orWhereRaw("cloud_instances.uuid LIKE ? ESCAPE '!'", [$like]);
$search->orWhereExists(static function ($addresses) use (
$ipLike,
$exactIp
): void {
$addresses->selectRaw('1')
->from('cloud_public_ips as searched_public_ip')
->whereColumn(
'searched_public_ip.instance_id',
'cloud_instances.id'
)->where('searched_public_ip.state', 'assigned');
if ($exactIp !== null) {
$addresses->where('searched_public_ip.address', $exactIp);
} else {
$addresses->whereRaw(
"searched_public_ip.address LIKE ? ESCAPE '!'",
[$ipLike]
);
}
});
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]);
}
});
}
/**
* Canonical PHP classification shared by summary, filtering and paging.
* The immutable public-network parser is deliberately not reimplemented
* with database-specific JSON expressions.
*
* @return list<int>
*/
private static function networkAttentionIds($query): array
{
$ids = [];
$records = (clone $query)->get([
'cloud_instances.id',
'cloud_instances.network_status',
'cloud_instances.spec_json',
]);
foreach ($records as $instance) {
$spec = CloudInstanceMetadata::publicSpec(
self::rawSpec($instance->spec_json)
);
if ((string) $instance->network_status !== 'active'
|| ($spec['public_network_valid'] ?? false) !== true) {
$ids[(int) $instance->id] = (int) $instance->id;
}
}
return array_values($ids);
}
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.phase = 'terminal' "
. "AND attention_job.outcome = 'failed' "
. "AND (attention_job.updated_at >= ? OR "
. "attention_job.effect_resolution = 'unknown')) OR "
. CloudJobRecoverySql::pendingSql('attention_job') . '))';
}
/** A terminal failure may keep a safety fence, but it is never active work. */
private static function blockingJobSql(string $alias): string
{
return '(' . $alias . ".phase <> 'terminal' OR ("
. $alias . ".phase = 'terminal' AND "
. $alias . ".outcome = 'failed' AND ("
. $alias . ".error_code = 'force_required' OR ("
. $alias . ".effect_resolution = 'unknown' AND ("
. $alias . '.effect_may_have_applied = 1 OR '
. $alias . '.safe_to_resubmit = 0)))) OR '
. CloudJobRecoverySql::pendingSql($alias) . ')';
}
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', 'operation_id', 'request_idempotency_key',
'request_fingerprint', 'parent_job_id', 'order_id', 'invoice_id',
'instance_id', 'snapshot_id', 'user_id', 'host_id',
'kind', 'execution_mode',
'phase', 'outcome', 'status', 'attempts', 'dispatch_attempts',
'dispatch_deadline_at', 'dispatch_started_at',
'agent_accepted_at', 'dispatched_at', 'receipt_deadline_at',
'completion_event_id', 'error_code', 'result_json', 'sealed_payload',
'effect_may_have_applied', 'safe_to_resubmit',
'effect_resolution', 'finalization_incident',
'finalization_error_code', 'available_at',
'terminal_at', 'created_at', 'updated_at'];
}
private static function jobRow($job): array
{
$result = json_decode((string) $job->result_json, true);
$labels = CloudJobService::labels($job);
$completed = (string) $job->phase === 'terminal';
$status = $completed && in_array((string) $job->outcome,
['succeeded', 'failed'], true)
? (string) $job->outcome : 'active';
$recovery = CloudJobService::recoveryPresentation($job, true);
$blocksMutation = !$completed || $recovery !== null
|| ($status === 'failed'
&& ((string) $job->error_code === 'force_required'
|| ((string) $job->effect_resolution === 'unknown'
&& ((bool) $job->effect_may_have_applied
|| !(bool) $job->safe_to_resubmit))));
return ['id' => (string) $job->id, 'kind' => (string) $job->kind,
'kind_label' => $labels['kind_label'], 'action_label' => $labels['action_label'],
'completed' => $completed, 'status' => $status,
'blocks_mutation' => $blocksMutation,
'effect_may_have_applied' => $job->effect_may_have_applied === null
? null : (bool) $job->effect_may_have_applied,
'safe_to_resubmit' => $job->safe_to_resubmit === null
? null : (bool) $job->safe_to_resubmit,
'effect_resolution' => (string) $job->effect_resolution,
'recovery' => $recovery,
'attempts' => max(0, (int) $job->attempts),
'error' => CloudOperationErrorCatalog::adminSummary(
(string) $job->kind, $status, $job->error_code,
false, CloudJobService::action($job)
),
'phase' => self::jobText(is_array($result) ? ($result['phase'] ?? null) : null),
'terminal_at' => $job->terminal_at === null
? null : max(0, (int) $job->terminal_at),
'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);
$networkValid = ($spec['public_network_valid'] ?? false) === true;
$publicIpv4 = self::ip($spec['public_ipv4'] ?? null);
$publicIpv6 = self::ip($spec['public_ipv6'] ?? null);
$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' => $publicIpv4 ?? '',
'public_ipv4' => $publicIpv4 ?? '',
'public_ipv6' => $publicIpv6 ?? '',
'public_network_valid' => $networkValid,
'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' => $networkValid
? (string) $instance->network_status : 'configuration_invalid',
'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) && $networkValid,
'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[$row['network_status']] ?? '未知',
'lifecycle' => ['active' => '在管', 'deleting' => '删除中', 'delete_failed' => '删除失败']
[(string) $instance->status] ?? '未知',
];
return $row;
}
private static function spec($json): array
{
return CloudInstanceMetadata::publicSpec(self::rawSpec($json));
}
private static function rawSpec($json): array
{
$value = json_decode((string) $json, true);
return 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));
}
}