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.
581 lines
25 KiB
PHP
581 lines
25 KiB
PHP
<?php
|
|
|
|
namespace App\Controllers;
|
|
|
|
use App\Services\AdminCsrf;
|
|
use App\Services\Auth;
|
|
use App\Services\Cloud\CloudAccess;
|
|
use App\Services\Cloud\CloudDeploymentPageService;
|
|
use App\Services\Cloud\CloudError;
|
|
use App\Services\Cloud\CloudInstancePageService;
|
|
use App\Services\Cloud\CloudInvoicePageService;
|
|
use App\Services\Cloud\CloudUserIsoFeature;
|
|
use App\Services\View;
|
|
|
|
/** User pages deliberately do not load the administrator theme styles. */
|
|
final class CloudPageController
|
|
{
|
|
public function index($request, $response, $args)
|
|
{
|
|
return $this->home($request, $response, $args);
|
|
}
|
|
|
|
public function home($request, $response, $args)
|
|
{
|
|
return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302);
|
|
}
|
|
|
|
public function instances($request, $response, $args)
|
|
{
|
|
$actor = CloudAccess::actor(false);
|
|
$user = $request->getAttribute('auth_user') ?? Auth::getUser();
|
|
$page = $this->pageNumber($request->getQueryParams()['page'] ?? '1');
|
|
$payload = CloudInstancePageService::forActor($actor, $page, 20);
|
|
$payload['user'] = $this->userBootstrap($user, $actor);
|
|
|
|
return $this->render($response, 'instances', '实例管理', '', '', [
|
|
'cloud_vm_rows' => array_map(
|
|
fn (array $vm): array => $this->vmListRow($vm),
|
|
$payload['vms']
|
|
),
|
|
'cloud_vm_stats' => $payload['stats'],
|
|
'cloud_vm_pagination' => $payload['pagination'],
|
|
'cloud_vm_scope_label' => ($actor['is_admin'] ?? false)
|
|
? '全部可见实例' : '我的实例',
|
|
'cloud_vm_bootstrap_json' => $this->safeJson($payload),
|
|
]);
|
|
}
|
|
|
|
public function detail($request, $response, $args)
|
|
{
|
|
$vmId = isset($args['id']) ? (string) $args['id'] : '';
|
|
if (preg_match('/^[1-9][0-9]*$/D', $vmId) !== 1) {
|
|
return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302);
|
|
}
|
|
$actor = CloudAccess::actor(false);
|
|
$user = $request->getAttribute('auth_user') ?? Auth::getUser();
|
|
try {
|
|
$vm = CloudInstancePageService::detailForActor($actor, $vmId);
|
|
} catch (CloudError $error) {
|
|
if ($error->httpStatus === 404) {
|
|
return $response->withHeader('Location', '/user/cloud/instances')
|
|
->withStatus(302);
|
|
}
|
|
throw $error;
|
|
}
|
|
$payload = ['vm' => $vm, 'user' => $this->userBootstrap($user, $actor)];
|
|
|
|
return $this->render($response, 'detail', '实例详情', $vmId, '', [
|
|
'cloud_vm_view' => $this->vmDetailView($vm),
|
|
'cloud_vm_bootstrap_json' => $this->safeJson($payload),
|
|
]);
|
|
}
|
|
|
|
public function deploy($request, $response, $args)
|
|
{
|
|
$actor = CloudAccess::actor(false);
|
|
$user = $request->getAttribute('auth_user') ?? Auth::getUser();
|
|
$plans = CloudDeploymentPageService::publicPagePlans();
|
|
$regions = CloudDeploymentPageService::regions($plans);
|
|
$catalog = CloudDeploymentPageService::templateCatalogForPage($actor);
|
|
$templates = is_array($catalog['templates'] ?? null)
|
|
? $catalog['templates'] : [];
|
|
$catalogUnavailable = ($catalog['catalog_unavailable'] ?? false) === true;
|
|
$keys = $this->sshKeyOptions((int) $actor['user_id']);
|
|
$defaultHostId = $regions === [] ? 0 : (int) $regions[0]['host_id'];
|
|
$bootstrapRegions = array_map(static fn (array $region): array =>
|
|
array_diff_key($region, ['plans' => true]), $regions);
|
|
$payload = [
|
|
'user' => $this->userBootstrap($user, $actor),
|
|
'plans' => $plans,
|
|
'regions' => $bootstrapRegions,
|
|
'templates' => $templates,
|
|
'ssh_keys' => $keys,
|
|
'default_host_id' => $defaultHostId,
|
|
'catalog_unavailable' => $catalogUnavailable,
|
|
];
|
|
|
|
return $this->render($response, 'deploy', '部署实例', '', '', [
|
|
'cloud_deploy_regions' => $regions,
|
|
'cloud_deploy_template_groups' => CloudDeploymentPageService::templateGroups($templates),
|
|
'cloud_deploy_ssh_keys' => $keys,
|
|
'cloud_deploy_default_host_id' => $defaultHostId,
|
|
'cloud_deploy_catalog_unavailable' => $catalogUnavailable,
|
|
'cloud_deploy_bootstrap_json' => $this->safeJson($payload),
|
|
]);
|
|
}
|
|
|
|
public function isoImages($request, $response, $args)
|
|
{
|
|
if (!CloudUserIsoFeature::enabled()) {
|
|
return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302);
|
|
}
|
|
return $this->render($response, 'isos', 'ISO 镜像');
|
|
}
|
|
|
|
public function sshKeys($request, $response, $args)
|
|
{
|
|
return $this->render($response, 'keys', 'SSH 公钥');
|
|
}
|
|
|
|
public function invoices($request, $response, $args)
|
|
{
|
|
$actor = CloudAccess::actor(false);
|
|
$user = $request->getAttribute('auth_user') ?? Auth::getUser();
|
|
$query = $request->getQueryParams();
|
|
$requestedPage = $query['page'] ?? '1';
|
|
$page = !is_array($requestedPage)
|
|
&& preg_match('/^[1-9][0-9]{0,8}$/D', (string) $requestedPage) === 1
|
|
? (int) $requestedPage : 1;
|
|
$payload = CloudInvoicePageService::forUser((int) $actor['user_id'], $page, 10);
|
|
$payload['balance'] = (string) $user->money;
|
|
$rows = array_map(fn (array $invoice): array => $this->invoiceListRow($invoice),
|
|
$payload['invoices']);
|
|
$json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG
|
|
| JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_INVALID_UTF8_SUBSTITUTE);
|
|
|
|
return $this->render($response, 'invoices', '账单信息', '', '', [
|
|
'cloud_invoice_rows' => $rows,
|
|
'cloud_invoice_pagination' => $payload['pagination'],
|
|
'cloud_invoice_balance' => $this->formatUsd($payload['balance']),
|
|
'cloud_invoice_bootstrap_json' => $json === false ? '{}' : $json,
|
|
]);
|
|
}
|
|
|
|
public function invoiceDetail($request, $response, $args)
|
|
{
|
|
$invoiceId = isset($args['id']) ? (string) $args['id'] : '';
|
|
if (!preg_match('/^[1-9][0-9]*$/', $invoiceId)) {
|
|
return $response->withHeader('Location', '/user/cloud/invoices')->withStatus(302);
|
|
}
|
|
|
|
return $this->render($response, 'invoice-detail', '账单详情', '', $invoiceId);
|
|
}
|
|
|
|
public function reinstall($request, $response, $args)
|
|
{
|
|
$vmId = $this->vmId($args);
|
|
if ($vmId === null) {
|
|
return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302);
|
|
}
|
|
$actor = CloudAccess::actor(false);
|
|
$user = $request->getAttribute('auth_user') ?? Auth::getUser();
|
|
try {
|
|
$vm = CloudInstancePageService::detailForActor($actor, $vmId);
|
|
} catch (CloudError $error) {
|
|
if ($error->httpStatus === 404) {
|
|
return $response->withHeader('Location', '/user/cloud/instances')
|
|
->withStatus(302);
|
|
}
|
|
throw $error;
|
|
}
|
|
$vm = $this->reinstallVm($vm);
|
|
$catalog = CloudDeploymentPageService::templateCatalogForPage($actor);
|
|
$templates = is_array($catalog['templates'] ?? null)
|
|
? $catalog['templates'] : [];
|
|
$catalogUnavailable = ($catalog['catalog_unavailable'] ?? false) === true;
|
|
$keys = $this->sshKeyOptions((int) $actor['user_id']);
|
|
$payload = [
|
|
'user' => $this->userBootstrap($user, $actor),
|
|
'vm' => $vm,
|
|
'templates' => $templates,
|
|
'ssh_keys' => $keys,
|
|
'catalog_unavailable' => $catalogUnavailable,
|
|
];
|
|
|
|
return $this->render($response, 'reinstall', '重装系统', $vmId, '', [
|
|
'cloud_reinstall_vm' => $vm,
|
|
'cloud_reinstall_template_groups' => CloudDeploymentPageService::templateGroups($templates),
|
|
'cloud_reinstall_ssh_keys' => $keys,
|
|
'cloud_reinstall_catalog_unavailable' => $catalogUnavailable,
|
|
'cloud_reinstall_bootstrap_json' => $this->safeJson($payload),
|
|
]);
|
|
}
|
|
|
|
public function rescue($request, $response, $args)
|
|
{
|
|
return $this->renderVmPage($response, $args, 'rescue', '紧急救援');
|
|
}
|
|
|
|
public function legacyShop($request, $response, $args)
|
|
{
|
|
return $response->withHeader('Location', '/user/cloud/deploy')->withStatus(302);
|
|
}
|
|
|
|
private function renderVmPage($response, $args, $page, $title)
|
|
{
|
|
$vmId = $this->vmId($args);
|
|
if ($vmId === null) {
|
|
return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302);
|
|
}
|
|
|
|
return $this->render($response, $page, $title, $vmId);
|
|
}
|
|
|
|
private function render($response, $page, $title, $vmId = '', $invoiceId = '', array $values = [])
|
|
{
|
|
$smarty = View::getSmarty('venix');
|
|
$smarty->assign('cloud_page', $page);
|
|
$smarty->assign('cloud_title', $title);
|
|
$smarty->assign('cloud_vm_id', $vmId);
|
|
$smarty->assign('cloud_invoice_id', $invoiceId);
|
|
$smarty->assign('cloud_invoice_rows', []);
|
|
$smarty->assign('cloud_invoice_pagination', [
|
|
'page' => 1, 'total' => 0, 'total_pages' => 1,
|
|
'has_previous' => false, 'has_next' => false,
|
|
]);
|
|
$smarty->assign('cloud_invoice_balance', '$—');
|
|
$smarty->assign('cloud_invoice_bootstrap_json', '{}');
|
|
$smarty->assign('cloud_vm_rows', []);
|
|
$smarty->assign('cloud_vm_stats', [
|
|
'total' => 0, 'running' => 0, 'stopped' => 0, 'other' => 0,
|
|
]);
|
|
$smarty->assign('cloud_vm_pagination', [
|
|
'page' => 1, 'per_page' => 20, 'total' => 0, 'total_pages' => 1,
|
|
'page_count' => 0, 'has_previous' => false, 'has_next' => false,
|
|
'from' => 0, 'to' => 0,
|
|
]);
|
|
$smarty->assign('cloud_vm_view', []);
|
|
$smarty->assign('cloud_vm_scope_label', '我的实例');
|
|
$smarty->assign('cloud_vm_bootstrap_json', '{}');
|
|
$smarty->assign('cloud_deploy_regions', []);
|
|
$smarty->assign('cloud_deploy_template_groups', []);
|
|
$smarty->assign('cloud_deploy_ssh_keys', []);
|
|
$smarty->assign('cloud_deploy_default_host_id', 0);
|
|
$smarty->assign('cloud_deploy_catalog_unavailable', false);
|
|
$smarty->assign('cloud_deploy_bootstrap_json', '{}');
|
|
$smarty->assign('cloud_reinstall_vm', []);
|
|
$smarty->assign('cloud_reinstall_template_groups', []);
|
|
$smarty->assign('cloud_reinstall_ssh_keys', []);
|
|
$smarty->assign('cloud_reinstall_catalog_unavailable', false);
|
|
$smarty->assign('cloud_reinstall_bootstrap_json', '{}');
|
|
foreach ($values as $name => $value) {
|
|
$smarty->assign($name, $value);
|
|
}
|
|
$response->getBody()->write($smarty->fetch('cloud/page.tpl'));
|
|
// Every cloud page is authenticated and may contain account- or
|
|
// tenant-specific data. In particular, the invoice list is now
|
|
// server-rendered, so intermediaries must never cache its HTML.
|
|
return $response->withHeader('Cache-Control', 'private, no-store');
|
|
}
|
|
|
|
private function invoiceListRow(array $invoice): array
|
|
{
|
|
[$statusLabel, $statusClass] = match (strtolower((string) ($invoice['status'] ?? ''))) {
|
|
'open' => ['待支付', 'warning'],
|
|
'overdue' => ['已逾期', 'failed'],
|
|
'paid' => ['已支付', 'running'],
|
|
'refunded' => ['已退款', 'other'],
|
|
'void' => ['已失效', 'other'],
|
|
'expired' => ['已失效', 'failed'],
|
|
'deleting', 'purge_deleting' => ['实例删除中', 'failed'],
|
|
'purge_pending' => ['等待永久删除', 'failed'],
|
|
'purge_stopping' => ['删除前正在关机', 'failed'],
|
|
'delete_failed' => ['自动删除失败', 'failed'],
|
|
'purge_stop_failed' => ['删除前关机失败', 'failed'],
|
|
'purge_failed' => ['自动删除失败', 'failed'],
|
|
default => [(string) ($invoice['status'] ?? '未知'), 'other'],
|
|
};
|
|
$fulfillment = strtolower((string) ($invoice['fulfillment_status']
|
|
?? $invoice['job_status'] ?? $invoice['order_status'] ?? ''));
|
|
[$fulfillmentLabel, $fulfillmentClass] = match ($fulfillment) {
|
|
'awaiting_payment', 'payment_pending', 'draft' => ['等待支付', 'warning'],
|
|
'queued', 'pending' => ['等待创建', 'warning'],
|
|
'provisioning', 'running' => ['创建中', 'warning'],
|
|
'completed', 'succeeded', 'active' => ['已开通', 'running'],
|
|
'failed' => ['创建失败', 'failed'],
|
|
'refunded' => ['开通失败,已退款', 'failed'],
|
|
'needs_attention' => ['需要管理员核查', 'failed'],
|
|
'uncertain' => ['正在核对结果', 'warning'],
|
|
default => ['', ''],
|
|
};
|
|
|
|
$invoice['created_display'] = (int) ($invoice['created_at'] ?? 0) > 0
|
|
? date('Y/m/d H:i:s', (int) $invoice['created_at']) : '时间未记录';
|
|
$invoice['amount_display'] = $this->formatUsd($invoice['amount'] ?? null);
|
|
$invoice['status_label'] = $statusLabel;
|
|
$invoice['status_class'] = $statusClass;
|
|
$invoice['fulfillment_label'] = $fulfillmentLabel;
|
|
$invoice['fulfillment_class'] = $fulfillmentClass;
|
|
$invoice['show_fulfillment'] = (string) ($invoice['purpose'] ?? '') === 'provision'
|
|
&& in_array(strtolower((string) ($invoice['status'] ?? '')), ['paid', 'refunded'], true)
|
|
&& $fulfillmentLabel !== '';
|
|
return $invoice;
|
|
}
|
|
|
|
private function formatUsd($value): string
|
|
{
|
|
if (!is_numeric($value) || (float) $value < 0) {
|
|
return '$—';
|
|
}
|
|
return '$' . number_format((float) $value, 2, '.', ',');
|
|
}
|
|
|
|
private function pageNumber($value): int
|
|
{
|
|
return !is_array($value)
|
|
&& preg_match('/^[1-9][0-9]{0,8}$/D', (string) $value) === 1
|
|
? (int) $value : 1;
|
|
}
|
|
|
|
private function userBootstrap($user, array $actor): array
|
|
{
|
|
return [
|
|
'csrf_token' => AdminCsrf::token(),
|
|
'user_id' => (string) $user->id,
|
|
'username' => (string) ($user->user_name ?: $user->email),
|
|
'admin' => (bool) $actor['is_admin'],
|
|
];
|
|
}
|
|
|
|
private function safeJson(array $value): string
|
|
{
|
|
$json = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG
|
|
| JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
|
|
| JSON_INVALID_UTF8_SUBSTITUTE);
|
|
return $json === false ? '{}' : $json;
|
|
}
|
|
|
|
private function vmId(array $args): ?string
|
|
{
|
|
$vmId = isset($args['id']) ? (string) $args['id'] : '';
|
|
return preg_match('/^[1-9][0-9]*$/D', $vmId) === 1 ? $vmId : null;
|
|
}
|
|
|
|
/** Deployment forms expose only the key identifier and safe display metadata. */
|
|
private function sshKeyOptions(int $userId): array
|
|
{
|
|
return array_map(static fn (array $key): array => [
|
|
'id' => $key['id'],
|
|
'name' => $key['name'],
|
|
'fingerprint' => $key['fingerprint'],
|
|
], CloudDeploymentPageService::sshKeys($userId));
|
|
}
|
|
|
|
/** Keep reinstall bootstrap small and free of internal host identifiers. */
|
|
private function reinstallVm(array $vm): array
|
|
{
|
|
$keys = [
|
|
'id', 'api_id', 'uuid', 'name', 'state', 'public_ip_cidr', 'public_ip',
|
|
'instance_status', 'service_status', 'network_status', 'can_operate',
|
|
'can_delete', 'is_owner',
|
|
];
|
|
$result = array_intersect_key($vm, array_flip($keys));
|
|
$address = trim((string) ($result['public_ip_cidr'] ?? $result['public_ip'] ?? ''));
|
|
$result['public_ip'] = $address === '' ? '' : (explode('/', $address, 2)[0] ?: '');
|
|
return $result;
|
|
}
|
|
|
|
private function vmListRow(array $vm): array
|
|
{
|
|
[$stateLabel, $stateClass] = $this->vmState((string) ($vm['state'] ?? 'unknown'));
|
|
[$systemLabel, $systemValue] = $this->vmSystem($vm);
|
|
return [
|
|
'api_id' => (string) ($vm['api_id'] ?? $vm['id'] ?? ''),
|
|
'uuid' => (string) ($vm['uuid'] ?? ''),
|
|
'name' => (string) ($vm['name'] ?? '未命名虚拟机'),
|
|
'state_label' => $stateLabel,
|
|
'state_class' => $stateClass,
|
|
'region' => trim((string) ($vm['region'] ?? '')) ?: '未设置',
|
|
'system_label' => $systemLabel,
|
|
'system_value' => $systemValue,
|
|
'ip' => $this->vmIp($vm),
|
|
'has_ip' => $this->vmIp($vm) !== '未获取',
|
|
'vcpu' => isset($vm['vcpu']) ? (int) $vm['vcpu']
|
|
: (isset($vm['cpu_cores']) ? (int) $vm['cpu_cores'] : null),
|
|
'memory_mib' => isset($vm['memory_mib']) ? (int) $vm['memory_mib']
|
|
: (isset($vm['ram_mib']) ? (int) $vm['ram_mib'] : null),
|
|
'disk_label' => $this->vmDisk($vm),
|
|
];
|
|
}
|
|
|
|
private function vmDetailView(array $vm): array
|
|
{
|
|
[$stateLabel, $stateClass] = $this->vmState((string) ($vm['state'] ?? 'unknown'));
|
|
[$systemLabel, $systemValue] = $this->vmSystem($vm);
|
|
[$serviceLabel, $serviceClass] = $this->serviceStatus(
|
|
(string) ($vm['service_status'] ?? '')
|
|
);
|
|
[$networkLabel, $networkClass] = $this->networkStatus(
|
|
(string) ($vm['network_status'] ?? '')
|
|
);
|
|
$quota = max(0, (int) ($vm['traffic_quota_bytes'] ?? 0));
|
|
$download = max(0, (int) ($vm['traffic_download_bytes'] ?? 0));
|
|
$upload = max(0, (int) ($vm['traffic_upload_bytes'] ?? 0));
|
|
$used = max(0, (int) ($vm['traffic_used_bytes'] ?? ($download + $upload)));
|
|
$remaining = $quota === 0 ? 0 : max(0, $quota - $used);
|
|
$passwordAvailable = (bool) ($vm['password_available'] ?? false);
|
|
$vcpu = isset($vm['vcpu']) ? (int) $vm['vcpu']
|
|
: (isset($vm['cpu_cores']) ? (int) $vm['cpu_cores'] : null);
|
|
$memory = isset($vm['memory_mib']) ? (int) $vm['memory_mib']
|
|
: (isset($vm['ram_mib']) ? (int) $vm['ram_mib'] : null);
|
|
|
|
return [
|
|
'name' => (string) ($vm['name'] ?? '虚拟机'),
|
|
'state_label' => $stateLabel,
|
|
'state_class' => $stateClass,
|
|
'region' => trim((string) ($vm['region'] ?? '')) ?: '未设置',
|
|
'ip' => $this->vmIp($vm),
|
|
'created_display' => $this->createdAgo($vm['created_at'] ?? null),
|
|
'system_label' => $systemLabel,
|
|
'system_value' => $systemValue,
|
|
'spec_display' => ($vcpu ?? '—') . ' vCPU · ' . ($memory ?? '—') . ' MiB',
|
|
'disk_display' => $this->vmDisk($vm),
|
|
'ssh_user' => trim((string) ($vm['login_name'] ?? '')) ?: '未记录',
|
|
'password_label' => $passwordAvailable ? '********' : '未记录',
|
|
'password_available' => $passwordAvailable,
|
|
'can_operate' => (bool) ($vm['can_operate'] ?? false),
|
|
'can_delete' => (bool) ($vm['can_delete'] ?? false),
|
|
'service_status_label' => $serviceLabel,
|
|
'service_status_class' => $serviceClass,
|
|
'network_status_label' => $networkLabel,
|
|
'network_status_class' => $networkClass,
|
|
'period_end_display' => $this->dateTime($vm['current_period_ends_at'] ?? null),
|
|
'traffic_rx_display' => $this->formatBytes($download),
|
|
'traffic_tx_display' => $this->formatBytes($upload),
|
|
'traffic_used_display' => $this->formatBytes($used),
|
|
'traffic_total_remaining_display' => $quota === 0
|
|
? '不限流量 / 不限流量'
|
|
: $this->formatBytes($quota) . ' / ' . $this->formatBytes($remaining),
|
|
'traffic_ratio' => $quota === 0 ? '' : number_format(
|
|
min(100, max(0, ($used / $quota) * 100)), 1, '.', ''
|
|
),
|
|
];
|
|
}
|
|
|
|
private function vmState(string $value): array
|
|
{
|
|
$normalized = strtolower((string) preg_replace('/[_\s-]+/', '', $value));
|
|
if (in_array($normalized, ['running', 'blocked'], true)) {
|
|
return ['运行中', 'running'];
|
|
}
|
|
if (in_array($normalized, ['shutoff', 'stopped'], true)) {
|
|
return ['已关机', 'stopped'];
|
|
}
|
|
return match ($normalized) {
|
|
'shutdown' => ['关机中', 'other'],
|
|
'crashed' => ['已崩溃', 'stopped'],
|
|
'paused' => ['已暂停', 'other'],
|
|
'pmsuspended' => ['已挂起', 'other'],
|
|
default => ['未知', 'other'],
|
|
};
|
|
}
|
|
|
|
private function vmSystem(array $vm): array
|
|
{
|
|
$source = (string) ($vm['os_source'] ?? '');
|
|
if ($source === 'iso') {
|
|
return ['安装镜像', trim((string) ($vm['install_iso'] ?? '')) ?: '未识别'];
|
|
}
|
|
if ($source === 'cloud_template') {
|
|
return ['系统镜像', trim((string) ($vm['os_name'] ?? '')) ?: '未识别'];
|
|
}
|
|
$value = trim((string) ($vm['os_name'] ?? ''));
|
|
if ($value === '') {
|
|
$value = trim((string) ($vm['install_iso'] ?? ''));
|
|
}
|
|
return ['系统', $value !== '' ? $value : '未识别'];
|
|
}
|
|
|
|
private function vmIp(array $vm): string
|
|
{
|
|
$value = trim((string) ($vm['public_ip_cidr'] ?? ''));
|
|
if ($value === '') {
|
|
$value = trim((string) ($vm['public_ip'] ?? ''));
|
|
}
|
|
return $value === '' ? '未获取' : (explode('/', $value, 2)[0] ?: '未获取');
|
|
}
|
|
|
|
private function vmDisk(array $vm): string
|
|
{
|
|
$size = 0.0;
|
|
foreach (is_array($vm['disks'] ?? null) ? $vm['disks'] : [] as $disk) {
|
|
if (!is_array($disk)) {
|
|
continue;
|
|
}
|
|
$value = $disk['capacity_gib'] ?? $disk['size_gib'] ?? 0;
|
|
if (is_numeric($value) && (float) $value > 0) {
|
|
$size += (float) $value;
|
|
}
|
|
}
|
|
if ($size <= 0 && is_numeric($vm['disk_gib'] ?? null)) {
|
|
$size = max(0, (float) $vm['disk_gib']);
|
|
}
|
|
if ($size <= 0) {
|
|
return '—';
|
|
}
|
|
return rtrim(rtrim(number_format($size, 2, '.', ''), '0'), '.') . ' GiB';
|
|
}
|
|
|
|
private function createdAgo($value): string
|
|
{
|
|
$timestamp = is_string($value) ? strtotime($value) : false;
|
|
if ($timestamp === false || $timestamp <= 0) {
|
|
return '未记录';
|
|
}
|
|
$elapsed = max(0, time() - $timestamp);
|
|
if ($elapsed < 60) {
|
|
return '创建于刚刚';
|
|
}
|
|
if ($elapsed < 3600) {
|
|
return '创建于 ' . intdiv($elapsed, 60) . ' 分钟前';
|
|
}
|
|
if ($elapsed < 86400) {
|
|
return '创建于 ' . intdiv($elapsed, 3600) . ' 小时前';
|
|
}
|
|
if ($elapsed < 2592000) {
|
|
return '创建于 ' . intdiv($elapsed, 86400) . ' 天前';
|
|
}
|
|
return '创建于 ' . intdiv($elapsed, 2592000) . ' 个月前';
|
|
}
|
|
|
|
private function serviceStatus(string $value): array
|
|
{
|
|
$labels = [
|
|
'active' => ['服务有效', 'active'], 'pending' => ['待生效', 'warning'],
|
|
'renewing' => ['续费处理中', 'warning'], 'exempt' => ['不受套餐限制', 'active'],
|
|
'suspended_expired' => ['已因到期停机', 'stopped'],
|
|
'suspended_traffic' => ['已因流量用尽暂停', 'stopped'],
|
|
'expired' => ['已到期', 'stopped'], 'deleting' => ['正在永久删除', 'warning'],
|
|
'purge_deleting' => ['正在永久删除', 'warning'],
|
|
'delete_failed' => ['自动删除失败,请联系管理员', 'stopped'],
|
|
];
|
|
return $labels[strtolower(str_replace('-', '_', trim($value)))]
|
|
?? [$value !== '' ? $value : '暂未提供', 'unknown'];
|
|
}
|
|
|
|
private function networkStatus(string $value): array
|
|
{
|
|
$labels = [
|
|
'active' => ['网络正常', 'active'], 'blocking' => ['正在暂停网络', 'warning'],
|
|
'blocked_traffic' => ['本期流量用尽,已断网', 'stopped'],
|
|
'blocked_expired' => ['实例已到期,网络已停用', 'stopped'],
|
|
'restoring' => ['正在恢复网络', 'warning'],
|
|
'restore_pending' => ['等待恢复网络', 'warning'],
|
|
'restore_failed' => ['网络恢复失败,请联系管理员', 'stopped'],
|
|
'exempt' => ['网络不受套餐限制', 'active'],
|
|
];
|
|
return $labels[strtolower(str_replace('-', '_', trim($value)))]
|
|
?? [$value !== '' ? $value : '暂未提供', 'unknown'];
|
|
}
|
|
|
|
private function dateTime($value): string
|
|
{
|
|
return is_numeric($value) && (int) $value > 0
|
|
? date('Y/m/d H:i:s', (int) $value) : '暂未提供';
|
|
}
|
|
|
|
private function formatBytes(int $value): string
|
|
{
|
|
$units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
|
|
$amount = max(0, $value);
|
|
$unit = 0;
|
|
while ($amount >= 1024 && $unit < count($units) - 1) {
|
|
$amount /= 1024;
|
|
$unit++;
|
|
}
|
|
$precision = $unit === 0 ? 0 : ($amount >= 100 ? 0 : ($amount >= 10 ? 1 : 2));
|
|
return number_format($amount, $precision, '.', '') . ' ' . $units[$unit];
|
|
}
|
|
}
|