perf: server-render instance pages

dev
admin 2 months ago
parent 1e1f68d503
commit ea84d9519e

@ -119,12 +119,28 @@ class FakeVMService:
raise VMError("libvirt API 不可用", 502)
return [self.vm, *self.other_vms]
def list_vm_states(self):
self.calls.append(("list_vm_states",))
if self.list_error:
raise VMError("libvirt API 不可用", 502)
return [
{"uuid": vm["uuid"], "name": vm["name"], "state": vm["state"]}
for vm in [self.vm, *self.other_vms]
]
def get_vm(self, vm_id):
self.calls.append(("get_vm", vm_id))
if vm_id != self.vm["uuid"]:
raise VMError("虚拟机不存在", 404)
return self.vm
def get_vm_state(self, vm_id):
self.calls.append(("get_vm_state", vm_id))
if vm_id != self.vm["uuid"]:
raise VMError("虚拟机不存在", 404)
return {"uuid": self.vm["uuid"], "name": self.vm["name"],
"state": self.vm["state"]}
def create_vm(self, spec):
self.calls.append(("create_vm", spec))
return self.vm
@ -835,6 +851,12 @@ def test_vm_crud_actions_and_error_mapping(web):
headers = {"X-CSRF-Token": csrf}
assert client.get("/api/v1/resources").json()["isos"] == ["AlmaLinux-10.iso"]
assert client.get("/api/v1/vms").json()["items"][0]["uuid"] == VM_ID
assert client.get("/api/v1/vm-states").json() == {"items": [{
"uuid": VM_ID, "name": "alma-test", "state": "running",
}]}
assert client.get(f"/api/v1/vms/{VM_ID}/state").json() == {
"uuid": VM_ID, "name": "alma-test", "state": "running",
}
assert client.get(f"/api/v1/vms/{VM_ID}").json()["name"] == "alma-test"
missing = client.get("/api/v1/vms/missing")
assert missing.status_code == 404 and missing.json() == {"error": "虚拟机不存在"}
@ -847,7 +869,8 @@ def test_vm_crud_actions_and_error_mapping(web):
deleted = client.delete(f"/api/v1/vms/{VM_ID}?delete_disks=true", headers=headers)
assert deleted.status_code == 200 and deleted.json()["deleted"] is True
assert service.calls == [
("resources",), ("list_vms",), ("get_vm", VM_ID), ("get_vm", "missing"),
("resources",), ("list_vms",), ("list_vm_states",),
("get_vm_state", VM_ID), ("get_vm", VM_ID), ("get_vm", "missing"),
("create_vm", CREATE_BODY), ("get_vm", VM_ID),
("action", VM_ID, "reboot"), ("get_vm", VM_ID),
("delete_vm", VM_ID, True),

@ -1051,6 +1051,24 @@ def test_stable_host_identity_and_namespaces():
assert LogStore.METRIC_TABLE == "engine_vm_metric_samples"
def test_lightweight_vm_state_reads_are_allowlisted(boundary):
client, _engine, _store, _logs, services = boundary
listed = call(client, "GET", "/internal/v1/hosts/hk/vm-states", SUPER)
assert listed.status_code == 200, listed.text
assert listed.json()["items"] == [{
"uuid": VM_ID, "name": "alma-test", "state": "running",
}]
single = call(
client, "GET", f"/internal/v1/hosts/hk/vms/{VM_ID}/state", SUPER,
)
assert single.status_code == 200, single.text
assert single.json() == {
"uuid": VM_ID, "name": "alma-test", "state": "running",
}
assert ("list_vm_states",) in services["hk"].calls
assert ("get_vm_state", VM_ID) in services["hk"].calls
def test_only_paid_operations_can_create_and_retry_never_duplicates(boundary):
client, engine, store, _, services = boundary
path = "/internal/v1/hosts/hk/vms"

@ -799,6 +799,12 @@ class VMServiceTests(unittest.TestCase):
self.assertEqual(self.service.console_port(vm["uuid"]), 5907)
self.assertEqual(self.service.list_vms()[0]["uuid"], vm["uuid"])
self.assertEqual(self.service.get_vm(vm["uuid"])["name"], "alma-test")
self.assertEqual(self.service.list_vm_states(), [{
"uuid": vm["uuid"], "name": "alma-test", "state": "running",
}])
self.assertEqual(self.service.get_vm_state(vm["uuid"]), {
"uuid": vm["uuid"], "name": "alma-test", "state": "running",
})
disk_name = "alma-test.qcow2"
self.assertIn(disk_name, self.backend.pools["images"].volumes)
root = self.backend.domains[0].root

@ -2173,6 +2173,23 @@ def create_app(
vm, parse_credential(records.get(credential_key(profile, vm["uuid"]))), profile,
) for vm in vms]}
@app.get("/api/v1/vm-states")
def list_vm_states(_session: Session = Depends(require_approved)):
profile = current_profile()
vms = new_service(profile).list_vm_states()
if database_mode:
account = account_for_session(_session)
if not account["admin"]:
owned_ids = state.users.list_owned_vm_ids(host_scope(profile), account["id"])
vms = [vm for vm in vms if vm["uuid"] in owned_ids]
return {"items": vms}
@app.get("/api/v1/vms/{vm_id}/state")
def get_vm_state(vm_id: str, _session: Session = Depends(require_approved)):
profile = current_profile()
require_vm_access(_session, profile, vm_id)
return new_service(profile).get_vm_state(vm_id)
@app.get("/api/v1/vms/{vm_id}")
def get_vm(vm_id: str, _session: Session = Depends(require_approved)):
profile = current_profile()

@ -42,8 +42,9 @@ VM_ID = r"[0-9a-fA-F-]{36}"
JSON_LIMIT = 1024 * 1024
READ_PATHS = (
r"host", r"resources", r"vm-templates", r"rescue-templates", r"user-isos", r"vms",
r"vm-states",
r"user-isos/[0-9a-f]{32}",
rf"vms/{VM_ID}(?:/metrics|/traffic/daily|/rescue)?",
rf"vms/{VM_ID}(?:/state|/metrics|/traffic/daily|/rescue)?",
r"(?:reinstall-jobs|rescue-jobs|vm-templates/import-jobs|rescue-templates/import-jobs|user-isos/import-jobs)/[A-Za-z0-9_-]+",
)
WRITE_PATHS = {

@ -498,6 +498,29 @@ class VMService:
key=lambda row: row["name"].casefold(),
)
@staticmethod
def _vm_state_dict(domain: Any) -> dict[str, Any]:
"""Return the live power fields without parsing domain XML or disks."""
info = domain.info()
return {
"uuid": domain.UUIDString(),
"name": domain.name(),
"state": STATES.get(info[0], "unknown"),
}
def list_vm_states(self) -> list[dict[str, Any]]:
"""Fetch lightweight power state for every persistent domain."""
with self._connect() as conn:
rows: list[dict[str, Any]] = []
for domain in conn.listAllDomains(0):
try:
rows.append(self._vm_state_dict(domain))
except libvirt.libvirtError:
# A domain can disappear between listAllDomains() and
# info(). Preserve the rest of the host inventory.
continue
return sorted(rows, key=lambda row: row["name"].casefold())
def provisioning_absent(self, vm_uuid: str, name: str) -> bool:
"""Only certify refund safety after a fresh host/volume inventory.
@ -519,6 +542,11 @@ class VMService:
with self._connect() as conn:
return self._vm_dict(self._domain(conn, uuid))
def get_vm_state(self, uuid: str) -> dict[str, Any]:
"""Fetch one domain's power state without loading its XML metadata."""
with self._connect() as conn:
return self._vm_state_dict(self._domain(conn, uuid))
def metric_counters(self) -> list[RawVMStats]:
"""Fetch running-domain counters in one libvirt API round trip.

@ -17,6 +17,7 @@ use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudEngineClient;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInput;
use App\Services\Cloud\CloudInstancePageService;
use App\Services\Cloud\CloudJobService;
use App\Services\Cloud\CloudInvoicePageService;
use App\Services\Cloud\CloudInvoicePaymentService;
@ -504,12 +505,112 @@ final class CloudApiController
$contexts[(int) $instance->id] ?? []))->all()]);
}
/** Database-only paginated instance rows used after the SSR first page. */
public function vmPage($request, $response)
{
$actor = $this->billingActor($request);
$value = $request->getQueryParams()['page'] ?? '1';
if (is_array($value)
|| preg_match('/^[1-9][0-9]{0,8}$/D', (string) $value) !== 1) {
throw new CloudError('实例页码无效');
}
return $this->json($response, CloudInstancePageService::forActor(
$actor, (int) $value, 20
));
}
/**
* Lightweight live state for the visible list page. Database ownership is
* resolved before any engine response is considered, and engine UUIDs are
* intersected with that owner-scoped set before being returned.
*/
public function vmStatuses($request, $response)
{
$actor = $this->actor($request);
$raw = $request->getQueryParams()['ids'] ?? '';
if (is_array($raw) || preg_match('/^[1-9][0-9]*(?:,[1-9][0-9]*){0,99}$/D',
(string) $raw) !== 1) {
throw new CloudError('实例编号列表无效');
}
$ids = array_values(array_unique(array_map('intval', explode(',', (string) $raw))));
$snapshots = CloudInstancePageService::forActorIds($actor, $ids);
$live = [];
$engine = new CloudEngineClient();
foreach ($this->vmSnapshotsByHost($snapshots) as $hostId => $group) {
$allowed = [];
foreach ($group as $snapshot) {
$allowed[strtolower((string) $snapshot['uuid'])] = true;
}
try {
$payload = $engine->host((int) $hostId, 'GET', 'vm-states', $actor);
foreach (is_array($payload['items'] ?? null) ? $payload['items'] : [] as $item) {
if (!is_array($item) || !is_string($item['uuid'] ?? null)) {
continue;
}
$uuid = strtolower(trim($item['uuid']));
if (isset($allowed[$uuid])) {
$live[$uuid] = $item;
}
}
} catch (CloudError $error) {
// The database rows remain visible with an unknown state; one
// offline host must not hide instances from another host.
}
}
$statuses = [];
foreach ($snapshots as $snapshot) {
$uuid = strtolower((string) $snapshot['uuid']);
$statuses[] = CloudInstancePageService::powerStatus(
$snapshot, $live[$uuid] ?? []
);
}
return $this->json($response, ['vms' => $statuses]);
}
/** Lightweight live state for one owner-scoped detail page. */
public function vmStatus($request, $response, $args)
{
$actor = $this->actor($request);
$snapshot = CloudInstancePageService::statusForActor($actor, $args['id']);
$live = [];
try {
$candidate = (new CloudEngineClient())->host(
(int) $snapshot['host_id'],
'GET',
'vms/' . rawurlencode((string) $snapshot['uuid']) . '/state',
$actor
);
if (is_array($candidate)
&& is_string($candidate['uuid'] ?? null)
&& hash_equals(strtolower((string) $snapshot['uuid']),
strtolower(trim($candidate['uuid'])))) {
$live = $candidate;
}
} catch (CloudError $error) {
// Preserve the database snapshot when the host is unavailable.
}
return $this->json($response,
CloudInstancePageService::status($snapshot, $live));
}
public function vm($request, $response, $args)
{
$actor = $this->actor($request);
return $this->json($response, $this->vmData(CloudAccess::instance($args['id'], $actor), $actor));
}
private function vmSnapshotsByHost(array $snapshots): array
{
$groups = [];
foreach ($snapshots as $snapshot) {
$hostId = max(0, (int) ($snapshot['host_id'] ?? 0));
if ($hostId > 0) {
$groups[$hostId][] = $snapshot;
}
}
return $groups;
}
public function metrics($request, $response, $args)
{
$actor = $this->actor($request);

@ -2,8 +2,11 @@
namespace App\Controllers;
use App\Services\AdminCsrf;
use App\Services\Auth;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInstancePageService;
use App\Services\Cloud\CloudInvoicePageService;
use App\Services\Cloud\CloudUserIsoFeature;
use App\Services\View;
@ -23,12 +26,48 @@ final class CloudPageController
public function instances($request, $response, $args)
{
return $this->render($response, 'instances', '实例管理');
$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)
{
return $this->renderVmPage($response, $args, 'detail', '实例详情');
$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)
@ -122,6 +161,18 @@ final class CloudPageController
]);
$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', '{}');
foreach ($values as $name => $value) {
$smarty->assign($name, $value);
}
@ -183,4 +234,241 @@ final class CloudPageController
}
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 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];
}
}

@ -12,11 +12,12 @@ final class CloudApi
{
try {
$path = (string) $request->getUri()->getPath();
// Billing is owned entirely by PHP and never calls the private
// libvirt engine. Authenticating these routes must therefore not
// create or look up a cloud_sessions row.
$invoiceOnly = preg_match('#^/api/v1/invoices(?:/|$)#D', $path) === 1;
$actor = CloudAccess::actor(!$invoiceOnly);
// Billing and paginated instance snapshots are owned entirely by
// PHP and never call the private libvirt engine. Authenticating
// these routes must therefore not create a cloud_sessions row.
$databaseOnly = preg_match('#^/api/v1/invoices(?:/|$)#D', $path) === 1
|| $path === '/api/v1/vms/page';
$actor = CloudAccess::actor(!$databaseOnly);
if (AdminCsrf::requiresProtection($request->getMethod())) {
if ($request->getHeaderLine('X-CSRF-Token') !== '') {
$request = $request->withHeader(AdminCsrf::HEADER_NAME, $request->getHeaderLine('X-CSRF-Token'));

@ -0,0 +1,460 @@
<?php
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudInstance;
use App\Models\CloudServicePeriod;
use App\Services\Config;
/**
* Database-only, actor-scoped instance snapshots for user-facing pages.
*
* This service must never contact the private engine. It deliberately gives
* the browser a useful first paint even when one or more libvirt hosts are
* slow or unavailable; live power state is layered on through the dedicated
* status endpoints after the HTML is visible.
*/
final class CloudInstancePageService
{
public static function forActor(array $actor, int $page = 1, int $perPage = 20): array
{
$page = max(1, $page);
$perPage = max(1, min(100, $perPage));
$base = self::visibleQuery($actor);
$total = (int) (clone $base)->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::stateCategory((string) ($vm['state'] ?? 'unknown'))]++;
}
// Power state is not persisted in cloud_instances. Any records outside
// the visible page are therefore unknown until the lightweight live
// status request completes; never invent a running/stopped count.
$counts['other'] += max(0, $total - count($snapshots));
$vms = $snapshots;
return [
'vms' => $vms,
'stats' => [
'total' => $total,
'running' => $counts['running'],
'stopped' => $counts['stopped'],
'other' => $counts['other'],
],
'pagination' => self::pagination($page, $perPage, $total, count($vms)),
];
}
public static function detailForActor(array $actor, $id): array
{
$instance = self::visibleInstanceQuery($actor, $id)->first(self::columns());
if ($instance === null) {
throw new CloudError('虚拟机不存在或无权访问', 404);
}
return self::snapshots(
new \Illuminate\Database\Eloquent\Collection([$instance]), $actor
)[0];
}
/** Mutable database state for the detail poll, without static VM metadata. */
public static function statusForActor(array $actor, $id): array
{
$instance = self::visibleInstanceQuery($actor, $id)->first([
'id', 'uuid', 'host_id', 'user_id', 'current_period_id', 'name',
'status', 'service_status', 'network_status', 'expires_at',
'traffic_quota_bytes', 'traffic_download_bytes',
'traffic_upload_bytes',
]);
if ($instance === null) {
throw new CloudError('虚拟机不存在或无权访问', 404);
}
$period = null;
if ($instance->current_period_id !== null) {
$period = CloudServicePeriod::where('id', $instance->current_period_id)
->where('instance_id', $instance->id)
->first(['starts_at', 'ends_at']);
}
$owner = (int) $instance->user_id === (int) $actor['user_id'];
$global = ($actor['is_admin'] ?? false)
&& ($actor['is_super_admin'] ?? false)
&& ($actor['can_manage'] ?? false);
$lifecycleActive = (string) $instance->status === 'active';
$canDelete = $lifecycleActive && ($owner || $global);
$download = max(0, (int) $instance->traffic_download_bytes);
$upload = max(0, (int) $instance->traffic_upload_bytes);
$used = $download + $upload;
$quota = max(0, (int) $instance->traffic_quota_bytes);
return [
'id' => (string) $instance->id,
'api_id' => (string) $instance->id,
'uuid' => (string) $instance->uuid,
'host_id' => (int) $instance->host_id,
'name' => (string) $instance->name,
'state' => 'unknown',
'instance_status' => (string) $instance->status,
'service_status' => (string) $instance->service_status,
'network_status' => (string) $instance->network_status,
'service_expires_at' => $instance->expires_at === null
? null : (int) $instance->expires_at,
'current_period_started_at' => $period === null ? null : (int) $period->starts_at,
'current_period_ends_at' => $period === null ? null : (int) $period->ends_at,
'traffic_download_bytes' => $download,
'traffic_upload_bytes' => $upload,
'traffic_used_bytes' => $used,
'traffic_quota_bytes' => $quota,
'traffic_remaining_bytes' => $quota === 0 ? 0 : max(0, $quota - $used),
'is_owner' => $owner,
'can_operate' => $canDelete && $instance->serviceAvailable(),
'can_delete' => $canDelete,
];
}
/**
* 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']);
$vms = [];
foreach ($records as $instance) {
$vms[] = [
'id' => (string) $instance->id,
'api_id' => (string) $instance->id,
'uuid' => (string) $instance->uuid,
'host_id' => (int) $instance->host_id,
'name' => (string) $instance->name,
'state' => 'unknown',
];
}
usort($vms, static fn (array $left, array $right): int =>
($ordered[(int) $left['id']] ?? PHP_INT_MAX)
<=> ($ordered[(int) $right['id']] ?? PHP_INT_MAX));
return $vms;
}
/** A deliberately small mutable status view merged with live engine data. */
public static function status(array $snapshot, array $live = []): array
{
$liveUuid = is_string($live['uuid'] ?? null)
? strtolower(trim($live['uuid'])) : '';
$liveMatches = $liveUuid !== '' && hash_equals(
strtolower((string) $snapshot['uuid']), $liveUuid
);
if (!$liveMatches) {
$live = [];
}
$liveStateAvailable = $liveMatches
&& is_string($live['state'] ?? null)
&& trim($live['state']) !== '';
$state = is_string($live['state'] ?? null) && trim($live['state']) !== ''
? trim($live['state']) : (string) ($snapshot['state'] ?? 'unknown');
$name = is_string($live['name'] ?? null) && trim($live['name']) !== ''
? trim($live['name']) : (string) ($snapshot['name'] ?? '');
return [
'id' => (string) $snapshot['id'],
'api_id' => (string) $snapshot['api_id'],
'uuid' => (string) $snapshot['uuid'],
'name' => $name,
'state' => $state,
'live_state_available' => $liveStateAvailable,
'instance_status' => (string) $snapshot['instance_status'],
'service_status' => (string) $snapshot['service_status'],
'network_status' => (string) $snapshot['network_status'],
'service_expires_at' => $snapshot['service_expires_at'],
'current_period_started_at' => $snapshot['current_period_started_at'],
'current_period_ends_at' => $snapshot['current_period_ends_at'],
'traffic_download_bytes' => (int) $snapshot['traffic_download_bytes'],
'traffic_upload_bytes' => (int) $snapshot['traffic_upload_bytes'],
'traffic_used_bytes' => (int) $snapshot['traffic_used_bytes'],
'traffic_quota_bytes' => (int) $snapshot['traffic_quota_bytes'],
'traffic_remaining_bytes' => (int) $snapshot['traffic_remaining_bytes'],
'is_owner' => (bool) $snapshot['is_owner'],
'can_operate' => (bool) $snapshot['can_operate'],
'can_delete' => (bool) $snapshot['can_delete'],
];
}
/** 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
);
$available = $matches && is_string($live['state'] ?? null)
&& trim($live['state']) !== '';
return [
'id' => (string) $snapshot['id'],
'api_id' => (string) $snapshot['api_id'],
'uuid' => (string) $snapshot['uuid'],
'name' => $matches && is_string($live['name'] ?? null)
&& trim($live['name']) !== ''
? trim($live['name']) : (string) $snapshot['name'],
'state' => $available ? trim($live['state']) : 'unknown',
'live_state_available' => $available,
];
}
/** 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',
'os_source', 'os_name', 'install_iso', 'public_ip_cidr', 'public_ip',
'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 [];
}
$hosts = self::hostMap($instances);
$result = [];
foreach ($instances as $instance) {
$decoded = json_decode((string) $instance->spec_json, true);
$spec = CloudInput::safeResult(is_array($decoded) ? $decoded : []);
$host = $hosts[(int) $instance->host_id] ?? null;
$region = trim((string) ($host?->region ?? ''));
if ($region === '') {
$region = trim((string) ($spec['region'] ?? $spec['location'] ?? ''));
}
$result[] = self::listItem(array_merge($spec, [
'id' => (string) $instance->id,
'api_id' => (string) $instance->id,
'uuid' => (string) $instance->uuid,
'name' => (string) $instance->name,
'state' => 'unknown',
'region' => $region,
]));
}
return $result;
}
private static function hostMap($instances): array
{
$hostIds = $instances->pluck('host_id')->map(
static fn ($id): int => (int) $id
)->unique()->values()->all();
$hosts = [];
if ($hostIds !== []) {
foreach (CloudHost::whereIn('id', $hostIds)
->get(['id', 'region', 'country_code']) as $host) {
$hosts[(int) $host->id] = $host;
}
}
return $hosts;
}
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();
$hosts = self::hostMap($instances);
$periods = [];
if ($periodIds !== []) {
foreach (CloudServicePeriod::whereIn('id', $periodIds)
->whereIn('instance_id', $instanceIds)
->get(['id', 'instance_id', 'starts_at', 'ends_at', 'status']) as $period) {
$periods[(int) $period->id] = $period;
}
}
$futurePeriods = [];
foreach (CloudServicePeriod::whereIn('instance_id', $instanceIds)
->where('status', 'scheduled')
->selectRaw('instance_id, COUNT(*) AS period_count')
->groupBy('instance_id')->get() as $row) {
$futurePeriods[(int) $row->instance_id] = (int) $row->period_count;
}
$result = [];
foreach ($instances as $instance) {
$period = $instance->current_period_id === null ? null
: ($periods[(int) $instance->current_period_id] ?? null);
if ($period !== null && (int) $period->instance_id !== (int) $instance->id) {
$period = null;
}
$result[] = self::snapshot(
$instance,
$actor,
$hosts[(int) $instance->host_id] ?? null,
$period,
(int) ($futurePeriods[(int) $instance->id] ?? 0)
);
}
return $result;
}
private static function snapshot(CloudInstance $instance, array $actor,
?CloudHost $host, ?CloudServicePeriod $period, int $futurePeriods): array
{
$decoded = json_decode((string) $instance->spec_json, true);
$spec = CloudInput::safeResult(is_array($decoded) ? $decoded : []);
$owner = (int) $instance->user_id === (int) $actor['user_id'];
$global = ($actor['is_admin'] ?? false)
&& ($actor['is_super_admin'] ?? false)
&& ($actor['can_manage'] ?? false);
$lifecycleActive = (string) $instance->status === 'active';
$canDelete = $lifecycleActive && ($owner || $global);
$canOperate = $canDelete && $instance->serviceAvailable();
$quota = max(0, (int) $instance->traffic_quota_bytes);
$download = max(0, (int) $instance->traffic_download_bytes);
$upload = max(0, (int) $instance->traffic_upload_bytes);
$used = $download + $upload;
$region = trim((string) ($host?->region ?? ''));
if ($region === '') {
$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;
$maximumFuturePeriods = max(1, min(120,
(int) Config::get('cloud_max_renewal_periods_ahead', 24)));
return array_merge($spec, [
'id' => (string) $instance->id,
'api_id' => (string) $instance->id,
'uuid' => (string) $instance->uuid,
'display_uuid' => (string) $instance->uuid,
'name' => (string) $instance->name,
// Power state is intentionally never trusted from the persisted
// specification. Operations remain disabled until a fresh,
// UUID-checked engine status response is merged by the browser.
'state' => 'unknown',
'host_id' => (int) $instance->host_id,
'user_id' => (int) $instance->user_id,
'owner_user_id' => (int) $instance->user_id,
'region' => $region,
'country_code' => strtoupper(trim((string) ($host?->country_code
?? ($spec['country_code'] ?? '')))),
'created_at' => $createdAt,
'instance_status' => (string) $instance->status,
'service_status' => (string) $instance->service_status,
'network_status' => (string) $instance->network_status,
'service_expires_at' => $instance->expires_at === null
? null : (int) $instance->expires_at,
'current_period_started_at' => $period === null ? null : (int) $period->starts_at,
'current_period_ends_at' => $period === null ? null : (int) $period->ends_at,
'prepaid_periods' => max(0, $futurePeriods),
'traffic_download_bytes' => $download,
'traffic_upload_bytes' => $upload,
'traffic_used_bytes' => $used,
'traffic_quota_bytes' => $quota,
'traffic_remaining_bytes' => $quota === 0 ? 0 : max(0, $quota - $used),
'renewal_price' => $instance->renewal_price === null
? null : (string) $instance->renewal_price,
'renewal_days' => max(0, (int) $instance->renewal_days),
'renewal_traffic_bytes' => max(0, (int) $instance->renewal_traffic_bytes),
'login_name' => (string) ($spec['login_name']
?? (($spec['os_source'] ?? '') === 'cloud_template' ? 'root' : '')),
'is_owner' => $owner,
'can_operate' => $canOperate,
'can_delete' => $canDelete,
'can_view_credential' => $owner || $global,
'can_renew' => $lifecycleActive && $owner
&& $instance->expires_at !== null
&& (int) $instance->renewal_days > 0
&& $instance->renewal_price !== null
&& $futurePeriods < $maximumFuturePeriods,
'has_initial_root_password' => ($owner || $global)
&& $instance->credential_cipher !== null,
'password_available' => ($owner || $global)
&& $instance->credential_cipher !== null,
]);
}
private static function visibleQuery(array $actor)
{
$query = CloudInstance::where('status', '<>', 'deleted');
if (!($actor['is_admin'] ?? false)) {
$query->where('user_id', (int) $actor['user_id']);
}
return $query;
}
private static function visibleInstanceQuery(array $actor, $id)
{
$query = self::visibleQuery($actor);
if (ctype_digit((string) $id)) {
return $query->where('id', (int) $id);
}
return $query->where('uuid', (string) $id);
}
private static function columns(): array
{
return [
'id', 'uuid', 'host_id', 'user_id', 'current_period_id', 'name',
'status', 'service_status', 'network_status', 'expires_at',
'renewal_price', 'renewal_days', 'renewal_traffic_bytes',
'traffic_quota_bytes', 'traffic_download_bytes',
'traffic_upload_bytes', 'spec_json', 'credential_cipher',
'created_at', 'updated_at',
];
}
private static function listColumns(): array
{
return ['id', 'uuid', 'host_id', 'name', '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';
}
}

@ -25,6 +25,11 @@ $app->group('/api/v1', function () {
'App\Controllers\CloudApiController:userIsoJob');
$this->delete('/user-isos/{id:[0-9a-f]{32}}',
'App\Controllers\CloudApiController:deleteUserIso');
// Fixed lightweight read routes must be registered before the historical
// dynamic /vms/{id} compatibility endpoint.
$this->get('/vms/page', 'App\Controllers\CloudApiController:vmPage');
$this->get('/vms/statuses', 'App\Controllers\CloudApiController:vmStatuses');
$this->get('/vms/{id:[0-9]+}/status', 'App\Controllers\CloudApiController:vmStatus');
$this->get('/vms', 'App\Controllers\CloudApiController:vms');
$this->get('/vms/{id}', 'App\Controllers\CloudApiController:vm');
$this->get('/vms/{id}/metrics', 'App\Controllers\CloudApiController:metrics');

@ -4,12 +4,22 @@ if (assetVersion) runtimeUrl.searchParams.set('v', assetVersion);
const {
VM_DETAIL_TABS, bindPageCleanup, byId, clearCredential,
clearVmMetrics, clearVmTrafficDaily, closeConsole, copyText, credential,
drawVmTrafficDaily, initializeSession, loadVm, loadVmMetrics, loadVmTrafficDaily,
renderVmDetail, renderVmMetrics, selectVmByApiId,
drawVmTrafficDaily, hydrateVmDetailBootstrap, loadVmMetrics, loadVmStatus,
loadVmTrafficDaily, renderVmDetail, renderVmMetrics,
selectedVm, setVmDetailTab, showError, state, stopVmMetrics,
stopVmTrafficDaily, toast, trafficDailyViewVisible, vmIp,
} = await import(runtimeUrl.href);
function detailBootstrap() {
const source = byId('vm-detail-bootstrap');
if (!source) throw new Error('实例详情初始数据缺失,请刷新后重试。');
try {
return JSON.parse(source.textContent || '{}');
} catch {
throw new Error('实例详情初始数据无法解析,请刷新后重试。');
}
}
function bindDetailTabs() {
document.querySelectorAll('[data-detail-tab]').forEach(button => {
button.addEventListener('click', () => {
@ -51,19 +61,19 @@ function bindConsole() {
export async function initialize() {
try {
if (!await initializeSession('detail')) return;
const vm = hydrateVmDetailBootstrap(detailBootstrap());
bindPageCleanup();
const vmId = document.body.dataset.vmId || '';
const vm = await selectVmByApiId(vmId);
const vmId = vm.api_id;
state.detailTab = VM_DETAIL_TABS.includes(new URLSearchParams(location.search).get('tab'))
? new URLSearchParams(location.search).get('tab') : 'operations';
clearVmMetrics('打开“性能监控”页签后加载监控数据。');
clearVmTrafficDaily('打开“流量信息”页签后加载最近 30 天数据。');
renderVmDetail(vm);
setVmDetailTab(state.detailTab);
byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout'));
byId('vm-detail-refresh-button')?.addEventListener('click', async () => {
await loadVm(vmId);
await loadVmStatus(vmId);
if (trafficDailyViewVisible()) await loadVmTrafficDaily(true);
});
byId('vm-detail-ip-copy')?.addEventListener('click', async () => {
@ -93,29 +103,37 @@ export async function initialize() {
}, 150);
});
let timer = null;
let stopped = false;
const poll = async () => {
timer = null;
if (stopped || document.hidden) return;
await loadVmStatus(vmId);
if (!stopped && !document.hidden) timer = window.setTimeout(poll, 20000);
};
const startPolling = () => {
if (timer !== null) window.clearInterval(timer);
timer = window.setInterval(() => {
if (!document.hidden) {
void loadVm(vmId);
if (trafficDailyViewVisible()) void loadVmTrafficDaily();
}
}, 15000);
stopped = false;
if (timer !== null) window.clearTimeout(timer);
timer = window.setTimeout(poll, 20000);
};
const stopPolling = () => {
stopped = true;
if (timer !== null) window.clearTimeout(timer);
timer = null;
};
startPolling();
void loadVmStatus(vmId);
window.addEventListener('pagehide', () => {
if (timer !== null) window.clearInterval(timer);
timer = null;
stopPolling();
});
window.addEventListener('pageshow', event => {
if (!event.persisted) return;
void loadVm(vmId);
void loadVmStatus(vmId);
setVmDetailTab(state.detailTab);
startPolling();
});
document.addEventListener('visibilitychange', () => {
if (document.hidden) { clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); }
else { void loadVm(vmId); setVmDetailTab(state.detailTab); }
if (document.hidden) { stopPolling(); clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); }
else { void loadVmStatus(vmId); setVmDetailTab(state.detailTab); startPolling(); }
});
} catch (error) { showError('cloud-page-error', error.message); }
}

@ -1,33 +1,517 @@
const runtimeUrl = new URL('/cloud/runtime.js', location.origin);
const assetVersion = new URL(import.meta.url).searchParams.get('v');
if (assetVersion) runtimeUrl.searchParams.set('v', assetVersion);
const {
bindPageCleanup, byId, initializeSession, loadVms, renderVMs, showError,
} = await import(runtimeUrl.href);
// The first twenty instances are rendered by PHP. This lightweight module only
// handles local filtering, pagination and batched live-state refreshes.
const byId = id => document.getElementById(id);
const POLL_INTERVAL = 15000;
const MAX_POLL_INTERVAL = 120000;
const state = {
vms: [],
stats: { total: 0, running: 0, stopped: 0 },
pagination: {
page: 1, per_page: 20, total: 0, total_pages: 1,
page_count: 0, has_previous: false, has_next: false, from: 0, to: 0,
},
user: {},
loading: false,
statusLoading: false,
liveStatsReady: false,
pageActive: true,
pollTimer: null,
pollFailures: 0,
};
export async function initialize() {
function showError(message = '') {
const target = byId('cloud-page-error');
if (!target) return;
target.textContent = message;
target.hidden = !message;
}
async function api(path) {
const response = await fetch(path, {
method: 'GET', headers: { Accept: 'application/json' },
credentials: 'same-origin', cache: 'no-store',
});
let payload;
try { payload = await response.json(); }
catch { throw new Error('服务返回了非 JSON 数据,请检查 PHP 及反代配置。'); }
if (response.status === 401) {
location.assign('/auth/login');
throw new Error('登录已过期。');
}
if (!response.ok || payload?.ret === 0) {
const detail = Array.isArray(payload?.detail)
? payload.detail.map(item => item.msg || '输入错误').join(';') : payload?.detail;
throw new Error(String(detail || payload?.message || payload?.msg || payload?.error
|| `请求失败 (${response.status})`));
}
return payload;
}
function makeElement(tag, className = '', content) {
const element = document.createElement(tag);
if (className) element.className = className;
if (content !== undefined) element.textContent = String(content);
return element;
}
function firstText(...values) {
for (const value of values) {
if (value !== null && value !== undefined && String(value).trim() !== '') {
return String(value).trim();
}
}
return '';
}
function normalizeVm(vm) {
const source = vm && typeof vm === 'object' ? vm : {};
return {
...source,
uuid: String(source.uuid || source.id || ''),
api_id: String(source.api_id || source.id || source.uuid || ''),
vcpu: source.vcpu ?? source.cpu_cores,
memory_mib: source.memory_mib ?? source.ram_mib,
public_ip_cidr: source.public_ip_cidr || source.public_ip || '',
};
}
function stateCategory(value) {
const normalized = String(value || 'unknown').toLowerCase().replace(/[_\s-]+/g, '');
if (normalized === 'running' || normalized === 'blocked') return 'running';
if (['shutoff', 'stopped', 'crashed'].includes(normalized)) return 'stopped';
return 'other';
}
function stateLabel(value) {
const normalized = String(value || 'unknown').toLowerCase().replace(/[_\s-]+/g, '');
const labels = {
running: '运行中', blocked: '运行中', shutoff: '已关机', stopped: '已关机',
shutdown: '关机中', crashed: '已崩溃', paused: '已暂停', pmsuspended: '已挂起',
nostate: '未知', unknown: '未知',
};
return labels[normalized] || String(value || '未知');
}
function vmRegion(vm) {
return firstText(vm.region, vm.location, '未设置');
}
function vmIp(vm) {
return firstText(vm.public_ip_cidr, vm.public_ip).split('/')[0] || '未获取';
}
function vmSystemInfo(vm) {
if (vm.os_source === 'iso') return { label: '安装镜像', value: firstText(vm.install_iso, '未识别') };
if (vm.os_source === 'cloud_template') return { label: '系统镜像', value: firstText(vm.os_name, '未识别') };
return { label: '系统', value: firstText(vm.os_name, vm.install_iso, '未识别') };
}
function diskLabel(vm) {
if (Array.isArray(vm.disks) && vm.disks.length) {
const size = vm.disks.reduce((total, disk) => {
const capacity = Number(disk?.capacity_gib ?? disk?.size_gib ?? 0);
return total + (Number.isFinite(capacity) && capacity > 0 ? capacity : 0);
}, 0);
if (size > 0) return `${Math.round(size * 100) / 100} GiB`;
}
const size = Number(vm.disk_gib);
return Number.isFinite(size) && size > 0 ? `${size} GiB` : '—';
}
function normalizeStats(value, vms = []) {
const source = value && typeof value === 'object' ? value : {};
const pageRunning = vms.filter(vm => stateCategory(vm.state) === 'running').length;
const pageStopped = vms.filter(vm => stateCategory(vm.state) === 'stopped').length;
const number = (candidate, fallback) => {
const parsed = Number(candidate);
return Number.isFinite(parsed) && parsed >= 0 ? Math.trunc(parsed) : fallback;
};
return {
total: number(source.total, vms.length),
running: number(source.running, pageRunning),
stopped: number(source.stopped, pageStopped),
};
}
function normalizePagination(value, fallbackPage = 1, fallbackTotal = 0) {
const source = value && typeof value === 'object' ? value : {};
const page = Math.max(1, Math.trunc(Number(source.page) || fallbackPage));
const totalPages = Math.max(1, Math.trunc(Number(source.total_pages) || 1));
const total = Math.max(0, Math.trunc(Number(source.total) || fallbackTotal));
return {
page,
per_page: Math.max(1, Math.trunc(Number(source.per_page) || 20)),
total,
page_count: Math.max(0, Math.trunc(Number(source.page_count) || 0)),
total_pages: totalPages,
has_previous: source.has_previous === true || page > 1,
has_next: source.has_next === true || page < totalPages,
from: Math.max(0, Math.trunc(Number(source.from) || 0)),
to: Math.max(0, Math.trunc(Number(source.to) || 0)),
};
}
function renderStats() {
if (byId('stat-total')) byId('stat-total').textContent = String(state.stats.total);
const liveValue = value => state.pagination.total === 0 || state.liveStatsReady
? String(value) : '—';
if (byId('stat-running')) byId('stat-running').textContent = liveValue(state.stats.running);
if (byId('stat-stopped')) byId('stat-stopped').textContent = liveValue(state.stats.stopped);
}
function toast(message, kind = '') {
const element = byId('toast');
if (!element) return;
element.textContent = message;
element.className = `toast ${kind}`;
element.hidden = false;
window.setTimeout(() => { element.hidden = true; }, 3000);
}
async function copyText(value) {
if (navigator.clipboard?.writeText) {
try { await navigator.clipboard.writeText(value); return; } catch {}
}
const area = document.createElement('textarea');
area.value = value;
area.style.position = 'fixed';
area.style.opacity = '0';
document.body.append(area);
area.select();
try {
if (!document.execCommand('copy')) throw new Error('浏览器无法复制,请手动选择文本。');
} finally { area.value = ''; area.remove(); }
}
function copyIconButton(value, label) {
const button = makeElement('button', 'vm-copy-icon');
button.type = 'button';
button.dataset.copyValue = value;
button.dataset.copyLabel = label;
button.title = `复制${label}`;
button.setAttribute('aria-label', `复制${label}`);
const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
icon.setAttribute('viewBox', '0 0 24 24');
icon.setAttribute('aria-hidden', 'true');
const back = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
for (const [name, valuePart] of Object.entries({ x: '8', y: '8', width: '12', height: '12', rx: '2' })) {
back.setAttribute(name, valuePart);
}
const front = document.createElementNS('http://www.w3.org/2000/svg', 'path');
front.setAttribute('d', 'M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2');
icon.append(back, front);
button.append(icon);
return button;
}
function makeCell(row, label) {
const cell = document.createElement('td');
cell.dataset.label = label;
row.append(cell);
return cell;
}
function matchingVms() {
const query = (byId('search-input')?.value || '').trim().toLocaleLowerCase();
const filter = byId('state-filter')?.value || 'all';
return state.vms.filter(vm => {
const textMatches = !query || [vm.name, vm.uuid, vm.public_ip_cidr, vm.public_ip,
vm.region, vm.location, vm.os_name, vm.install_iso]
.some(value => String(value || '').toLocaleLowerCase().includes(query));
const statusMatches = filter === 'all' || stateCategory(vm.state) === filter;
return textMatches && statusMatches;
});
}
function renderCount(filteredCount = state.vms.length) {
const target = byId('inventory-count');
if (!target) return;
const filtering = Boolean((byId('search-input')?.value || '').trim())
|| (byId('state-filter')?.value || 'all') !== 'all';
target.textContent = filtering
? `匹配 ${filteredCount} 台 · 当前页 ${state.vms.length} 台 · 共 ${state.pagination.total} 台`
: `当前页 ${state.vms.length} 台 · 共 ${state.pagination.total} 台`;
}
function renderVms(connectionError = false) {
const filtered = matchingVms();
renderCount(filtered.length);
const tbody = byId('vm-table-body');
const empty = byId('empty-state');
if (!tbody || !empty) return;
tbody.replaceChildren();
empty.hidden = filtered.length !== 0;
if (!filtered.length) {
if (connectionError) {
byId('empty-title').textContent = '无法加载实例';
byId('empty-description').textContent = '请稍后重试,或联系管理员检查服务状态。';
} else if (state.vms.length) {
byId('empty-title').textContent = '没有匹配的实例';
byId('empty-description').textContent = '尝试更换搜索词或状态筛选。';
} else {
byId('empty-title').textContent = '还没有实例';
byId('empty-description').textContent = '点击右上角“部署实例”开始。';
}
return;
}
const fragment = document.createDocumentFragment();
for (const vm of filtered) {
const row = document.createElement('tr');
row.dataset.vmId = vm.api_id;
row.dataset.vmUuid = vm.uuid;
const identity = makeElement('div', 'vm-identity');
identity.append(makeElement('div', 'vm-icon', '▣'));
const identityText = document.createElement('div');
const name = makeElement('a', 'vm-name-link', vm.name || '未命名实例');
name.href = `/user/cloud/instances/${encodeURIComponent(vm.api_id)}`;
name.dataset.vmUuid = vm.uuid;
name.setAttribute('aria-label', `管理实例 ${vm.name || vm.uuid}`);
const uuidRow = makeElement('span', 'vm-uuid-row');
const uuid = makeElement('span', 'vm-id', vm.uuid || 'UUID 未知');
if (vm.uuid) uuid.title = vm.uuid;
uuidRow.append(uuid);
if (vm.uuid) uuidRow.append(copyIconButton(vm.uuid, 'UUID'));
identityText.append(name, uuidRow);
identity.append(identityText);
makeCell(row, '实例').append(identity);
const category = stateCategory(vm.state);
const status = makeElement('span', `state-pill ${category} vm-state-pill`, stateLabel(vm.state));
makeCell(row, '状态').append(status);
makeCell(row, '地区').append(makeElement('span', 'vm-metadata', vmRegion(vm)));
const system = vmSystemInfo(vm);
makeCell(row, system.label).append(makeElement('span', 'vm-metadata', system.value));
const ip = vmIp(vm);
const ipRow = makeElement('span', 'vm-ip-copy-row');
ipRow.append(makeElement('span', 'vm-metadata vm-ip', ip));
if (ip !== '未获取') ipRow.append(copyIconButton(ip, '公网 IP'));
makeCell(row, '已配置公网 IP').append(ipRow);
const spec = makeElement('div', 'vm-spec');
spec.append(makeElement('strong', '', `${vm.vcpu ?? '—'} vCPU · ${vm.memory_mib ?? '—'} MiB`),
makeElement('small', '', '计算资源'));
makeCell(row, '规格').append(spec);
makeCell(row, '磁盘').append(makeElement('span', 'vm-spec', diskLabel(vm)));
fragment.append(row);
}
tbody.append(fragment);
}
function renderPagination() {
const navigation = byId('instances-pagination');
if (!navigation) return;
const { page, total_pages: totalPages, total, has_previous: previous, has_next: next } = state.pagination;
navigation.hidden = total === 0;
navigation.setAttribute('aria-busy', String(state.loading));
if (byId('instances-page-label')) {
byId('instances-page-label').textContent = `第 ${page} / ${totalPages} 页 · 共 ${total} 台`;
}
if (byId('instances-previous')) {
byId('instances-previous').disabled = state.loading || state.statusLoading || !previous;
}
if (byId('instances-next')) {
byId('instances-next').disabled = state.loading || state.statusLoading || !next;
}
if (byId('refresh-button')) {
byId('refresh-button').disabled = state.loading || state.statusLoading;
byId('refresh-button').setAttribute('aria-busy', String(state.loading || state.statusLoading));
}
}
function updatePageUrl(page) {
const url = new URL(location.href);
if (page > 1) url.searchParams.set('page', String(page));
else url.searchParams.delete('page');
history.replaceState(history.state, '', `${url.pathname}${url.search}${url.hash}`);
}
function stopPolling() {
if (state.pollTimer !== null) window.clearTimeout(state.pollTimer);
state.pollTimer = null;
}
function nextPollDelay() {
if (!state.pollFailures) return POLL_INTERVAL;
return Math.min(MAX_POLL_INTERVAL, POLL_INTERVAL * (2 ** Math.min(state.pollFailures, 3)));
}
function schedulePolling(delay = nextPollDelay()) {
stopPolling();
if (!state.pageActive || document.hidden || !state.vms.length) return;
state.pollTimer = window.setTimeout(() => {
state.pollTimer = null;
void refreshStatuses(true);
}, delay);
}
function statusItems(payload) {
if (Array.isArray(payload?.vms)) return payload.vms;
if (Array.isArray(payload?.statuses)) return payload.statuses;
if (Array.isArray(payload?.items)) return payload.items;
if (payload?.statuses && typeof payload.statuses === 'object') {
return Object.entries(payload.statuses).map(([id, value]) => (
value && typeof value === 'object' ? { id, ...value } : { id, state: value }
));
}
return [];
}
function vmMatchesUpdate(vm, update) {
const candidates = [update?.api_id, update?.id, update?.uuid].map(value => String(value || ''));
return candidates.includes(vm.api_id) || candidates.includes(vm.uuid);
}
function applyStatuses(payload) {
const updates = statusItems(payload);
let statusFilterChanged = false;
for (const update of updates) {
const vm = state.vms.find(item => vmMatchesUpdate(item, update));
if (!vm || !firstText(update.state, update.status)) continue;
const previousCategory = stateCategory(vm.state);
const nextState = firstText(update.state, update.status);
const nextCategory = stateCategory(nextState);
Object.assign(vm, update, { state: nextState });
if (previousCategory !== nextCategory) {
if (previousCategory === 'running') state.stats.running = Math.max(0, state.stats.running - 1);
if (previousCategory === 'stopped') state.stats.stopped = Math.max(0, state.stats.stopped - 1);
if (nextCategory === 'running') state.stats.running += 1;
if (nextCategory === 'stopped') state.stats.stopped += 1;
statusFilterChanged = true;
}
const row = Array.from(document.querySelectorAll('#vm-table-body tr[data-vm-id]'))
.find(item => item.dataset.vmId === vm.api_id || item.dataset.vmUuid === vm.uuid);
const pill = row?.querySelector('.vm-state-pill');
if (pill) {
pill.className = `state-pill ${nextCategory} vm-state-pill`;
pill.textContent = stateLabel(nextState);
}
}
if (payload?.stats && typeof payload.stats === 'object') {
state.stats = normalizeStats(payload.stats, state.vms);
}
state.liveStatsReady = state.vms.length === 0
|| state.vms.every(vm => vm.live_state_available === true);
renderStats();
if (statusFilterChanged && (byId('state-filter')?.value || 'all') !== 'all') renderVms();
}
async function refreshStatuses(scheduleNext = true) {
if (!state.pageActive || state.statusLoading || document.hidden || !state.vms.length) {
if (scheduleNext) schedulePolling();
return;
}
const ids = state.vms.map(vm => vm.api_id).filter(Boolean);
if (!ids.length) return;
state.statusLoading = true;
renderPagination();
try {
if (!await initializeSession('list')) return;
bindPageCleanup();
byId('refresh-button')?.addEventListener('click', loadVms);
byId('search-input')?.addEventListener('input', () => renderVMs());
byId('state-filter')?.addEventListener('change', () => renderVMs());
await loadVms();
let timer = null;
const startPolling = () => {
if (timer !== null) window.clearInterval(timer);
timer = window.setInterval(() => { if (!document.hidden) void loadVms(); }, 15000);
};
startPolling();
window.addEventListener('pagehide', () => {
if (timer !== null) window.clearInterval(timer);
timer = null;
});
window.addEventListener('pageshow', event => {
if (!event.persisted) return;
void loadVms();
startPolling();
});
document.addEventListener('visibilitychange', () => { if (!document.hidden) void loadVms(); });
} catch (error) { showError('cloud-page-error', error.message); }
const payload = await api(`/api/v1/vms/statuses?ids=${encodeURIComponent(ids.join(','))}`);
applyStatuses(payload);
state.pollFailures = 0;
showError();
} catch (error) {
state.pollFailures += 1;
if (state.pollFailures >= 2) {
showError(`${error?.message || '实例实时状态更新失败。'} 页面将自动重试。`);
}
} finally {
state.statusLoading = false;
renderPagination();
if (scheduleNext) schedulePolling();
}
}
async function loadPage(page = state.pagination.page, updateUrl = true) {
if (state.loading) return;
const requestedPage = Math.max(1, Math.trunc(Number(page) || 1));
state.loading = true;
state.liveStatsReady = false;
stopPolling();
renderPagination();
let pageLoaded = false;
try {
const payload = await api(`/api/v1/vms/page?page=${encodeURIComponent(requestedPage)}`);
state.vms = (Array.isArray(payload?.vms) ? payload.vms : []).map(normalizeVm);
state.pagination = normalizePagination(payload?.pagination, requestedPage, state.vms.length);
state.stats = normalizeStats(payload?.stats, state.vms);
state.pollFailures = 0;
renderStats();
renderVms();
renderPagination();
if (updateUrl) updatePageUrl(state.pagination.page);
showError();
pageLoaded = true;
} catch (error) {
showError(error?.message || '实例加载失败,请稍后重试。');
if (!state.vms.length) renderVms(true);
} finally {
state.loading = false;
renderPagination();
}
if (pageLoaded) await refreshStatuses(true);
}
function hydrate() {
const source = byId('instances-bootstrap');
if (!source) return false;
try {
const payload = JSON.parse(source.textContent || '{}');
if (!Array.isArray(payload?.vms)) return false;
state.vms = payload.vms.map(normalizeVm);
state.pagination = normalizePagination(payload.pagination, 1, state.vms.length);
state.stats = normalizeStats(payload.stats, state.vms);
state.liveStatsReady = state.vms.length === 0;
state.user = payload.user && typeof payload.user === 'object' ? payload.user : {};
renderStats();
renderPagination();
renderCount(state.vms.length);
updatePageUrl(state.pagination.page);
return true;
} catch { return false; }
}
function bindEvents() {
byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout'));
byId('refresh-button')?.addEventListener('click', () => { void loadPage(state.pagination.page, false); });
byId('search-input')?.addEventListener('input', renderVms);
byId('state-filter')?.addEventListener('change', renderVms);
byId('instances-previous')?.addEventListener('click', () => {
if (!state.loading && !state.statusLoading && state.pagination.has_previous) {
void loadPage(state.pagination.page - 1);
}
});
byId('instances-next')?.addEventListener('click', () => {
if (!state.loading && !state.statusLoading && state.pagination.has_next) {
void loadPage(state.pagination.page + 1);
}
});
byId('vm-table-body')?.addEventListener('click', event => {
const button = event.target.closest?.('[data-copy-value]');
if (!button) return;
void copyText(button.dataset.copyValue || '')
.then(() => toast(`${button.dataset.copyLabel || '内容'}已复制。`, 'success'))
.catch(error => toast(error?.message || '复制失败。', 'error'));
});
window.addEventListener('pagehide', () => {
state.pageActive = false;
stopPolling();
});
window.addEventListener('pageshow', event => {
state.pageActive = true;
if (event.persisted) void refreshStatuses(true);
});
document.addEventListener('visibilitychange', () => {
if (document.hidden) stopPolling();
else void refreshStatuses(true);
});
}
export async function initialize() {
const hydrated = hydrate();
bindEvents();
if (!hydrated) await loadPage(1, false);
else void refreshStatuses(true);
}

@ -199,6 +199,61 @@ async function loadVm(apiId = selectedVm()?.api_id || document.body.dataset.vmId
state.loadingVMs = false;
}
}
function applyCloudUser(user = {}) {
state.csrfToken = String(user.csrf_token || '');
if (!state.csrfToken) throw new Error('会话 CSRF 令牌缺失,请重新登录。');
state.userId = String(user.user_id || '');
if (!/^\d+$/.test(state.userId)) throw new Error('会话用户标识缺失,请重新登录。');
state.username = user.username || user.user_name || user.email || '用户';
state.admin = user.admin === true || user.is_admin === true || Number(user.is_admin) === 1;
if (byId('current-username')) text('current-username', state.username);
for (const id of ['cloud-admin-link', 'cloud-admin-menu-link']) {
const link = byId(id);
if (link) link.hidden = !state.admin;
}
}
function hydrateVmDetailBootstrap(payload) {
if (!payload || typeof payload !== 'object' || !payload.vm || typeof payload.vm !== 'object') {
throw new Error('实例详情初始数据缺失,请刷新后重试。');
}
state.view = 'detail';
applyCloudUser(payload.user || {});
const vm = normalizeVm(payload.vm);
if (!vm.api_id || !vm.uuid) throw new Error('实例标识缺失,请返回实例列表。');
state.vms = [vm];
state.selectedVmId = vm.uuid;
return vm;
}
async function loadVmStatus(apiId = selectedVm()?.api_id || document.body.dataset.vmId, raise = false) {
const id = String(apiId || '');
if (!id) {
const error = new Error('实例标识缺失。');
showError('cloud-page-error', error.message);
if (raise) throw error;
return null;
}
if (state.loadingVMs) return selectedVm() || null;
state.loadingVMs = true;
try {
const payload = await api(`/api/v1/vms/${encodeURIComponent(id)}/status`);
const current = selectedVm();
if (!current) throw new Error('实例初始数据已失效,请刷新页面。');
const update = payload?.vm && typeof payload.vm === 'object' ? payload.vm : payload;
if (!update || typeof update !== 'object') throw new Error('实例实时状态格式无效。');
const vm = normalizeVm({ ...current, ...update, id: current.api_id, uuid: current.uuid });
state.vms = [vm];
state.selectedVmId = vm.uuid;
showError('cloud-page-error', '');
if (state.view === 'detail') renderVmDetail(vm);
return vm;
} catch (error) {
showError('cloud-page-error', error.message);
if (raise) throw error;
return null;
} finally {
state.loadingVMs = false;
}
}
function renderVmDetail(vm) {
text('vm-detail-name', vm.name); text('vm-detail-state', stateLabel(vm.state)); byId('vm-detail-state').className = `state-pill ${stateCategory(vm.state)}`;
for (const id of ['vm-detail-region', 'vm-detail-header-region']) text(id, vmRegion(vm));
@ -209,12 +264,13 @@ function renderVmDetail(vm) {
text('vm-detail-root-password', !vm.can_view_credential ? '无权查看' : vm.password_available ? (state.credentialVisible ? state.credentialPassword : '********') : '未记录');
for (const id of ['vm-detail-password-reveal', 'vm-detail-password-copy']) byId(id).hidden = !vm.password_available;
renderVmService(vm);
const running = stateCategory(vm.state) === 'running'; const stopped = stateCategory(vm.state) === 'stopped';
const category = stateCategory(vm.state); const running = category === 'running'; const stopped = category === 'stopped';
const stateKnown = !['', 'unknown', 'nostate'].includes(String(vm.state || '').toLowerCase().replace(/[_\s-]+/g, ''));
const primary = byId('vm-detail-primary-actions'); const danger = byId('vm-detail-danger-actions'); primary.replaceChildren(); danger.replaceChildren();
danger.closest('section').hidden = !vm.can_operate && !vm.can_delete;
if (vm.can_operate) {
primary.append(actionButton('控制台', () => openConsole(vm), { disabled: !running }), actionButton('开机', () => powerAction('start'), { disabled: !stopped }), actionButton('正常关机', () => powerAction('shutdown'), { disabled: !running }), actionButton('重启', () => powerAction('reboot'), { disabled: !running }));
danger.append(actionButton('重装系统', () => navigate(vmPagePath(vm.api_id, 'reinstall')), { variant: 'danger', disabled: vm.os_source !== 'cloud_template' }), actionButton('紧急救援', () => navigate(vmPagePath(vm.api_id, 'rescue')), { variant: 'danger' }), actionButton('强制重置', () => powerAction('reset', true), { variant: 'danger', disabled: !running }), actionButton('强制断电', () => powerAction('poweroff', true), { variant: 'danger', disabled: stopped }));
danger.append(actionButton('重装系统', () => navigate(vmPagePath(vm.api_id, 'reinstall')), { variant: 'danger', disabled: !stateKnown || vm.os_source !== 'cloud_template' }), actionButton('紧急救援', () => navigate(vmPagePath(vm.api_id, 'rescue')), { variant: 'danger', disabled: !stateKnown }), actionButton('强制重置', () => powerAction('reset', true), { variant: 'danger', disabled: !running }), actionButton('强制断电', () => powerAction('poweroff', true), { variant: 'danger', disabled: !stateKnown || stopped }));
} else {
primary.append(makeElement('p', 'muted', vm.is_owner || vm.can_delete
? '实例服务已到期或正在执行策略;日常操作暂不可用。'
@ -251,7 +307,7 @@ function renderVmService(vm) {
progress.classList.remove('is-exhausted');
}
}
async function powerAction(action, dangerous = false) { const vm = selectedVm(); if (!vm?.can_operate) return toast('实例服务已到期或正在执行策略,日常操作暂不可用。', 'error'); if (state.mutationBusy) return; if (dangerous && !confirm('此操作会强制断电,可能丢失未保存的数据。确认继续?')) return; state.mutationBusy = true; setDetailBusy(true); try { const result = await api(`${vmPath()}/actions`, { method: 'POST', body: { action } }); toast('电源任务已提交,正在执行…'); if (result.job_id) await pollJob('power', result.job_id); toast('电源操作已完成。', 'success'); await loadVm(vm.api_id); } catch (error) { toast(error.message, 'error'); } finally { state.mutationBusy = false; setDetailBusy(false); } }
async function powerAction(action, dangerous = false) { const vm = selectedVm(); if (!vm?.can_operate) return toast('实例服务已到期或正在执行策略,日常操作暂不可用。', 'error'); if (state.mutationBusy) return; if (dangerous && !confirm('此操作会强制断电,可能丢失未保存的数据。确认继续?')) return; state.mutationBusy = true; setDetailBusy(true); try { const result = await api(`${vmPath()}/actions`, { method: 'POST', body: { action } }); toast('电源任务已提交,正在执行…'); if (result.job_id) await pollJob('power', result.job_id); toast('电源操作已完成。', 'success'); await loadVmStatus(vm.api_id); } catch (error) { toast(error.message, 'error'); } finally { state.mutationBusy = false; setDetailBusy(false); } }
async function deleteVm() { const vm = selectedVm(); if (!vm?.can_delete) return toast('当前账户无权删除该实例。', 'error'); if (state.mutationBusy) return; const confirmation = prompt(`永久删除“${vm.name}”及面板管理的虚拟磁盘,此操作不可恢复。请输入完整虚拟机名称确认:`); if (confirmation === null) return; if (confirmation !== vm.name) return toast('虚拟机名称不匹配,未执行删除。', 'error'); state.mutationBusy = true; setDetailBusy(true); try { const result = await api(vmPath(vm), { method: 'DELETE', body: { confirmation_name: vm.name, delete_disks: true } }); toast('删除任务已提交,正在执行…'); if (result.job_id) await pollJob('delete', result.job_id); navigate(CLOUD_PATHS.instances); } catch (error) { toast(error.message, 'error'); } finally { state.mutationBusy = false; setDetailBusy(false); } }
function setDetailBusy(busy) { if (!busy && selectedVm()) renderVmDetail(selectedVm()); else if (busy) document.querySelectorAll('#vm-detail-primary-actions button,#vm-detail-danger-actions button').forEach(button => { button.disabled = true; }); }
async function credential(copy = false) {
@ -1883,17 +1939,7 @@ async function initializeSession(view) {
state.view = view;
const session = await api('/api/v1/session');
if (session.authenticated === false) { location.assign('/auth/login'); return false; }
state.csrfToken = session.csrf_token || '';
if (!state.csrfToken) throw new Error('会话 CSRF 令牌缺失,请重新登录。');
state.userId = String(session.user_id || '');
if (!/^\d+$/.test(state.userId)) throw new Error('会话用户标识缺失,请重新登录。');
state.username = session.username || session.user_name || session.email || session.user?.email || '用户';
state.admin = session.admin === true || session.is_admin === true || Number(session.is_admin) === 1;
if (byId('current-username')) text('current-username', state.username);
for (const id of ['cloud-admin-link', 'cloud-admin-menu-link']) {
const link = byId(id);
if (link) link.hidden = !state.admin;
}
applyCloudUser(session);
byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout'));
return true;
}
@ -1918,9 +1964,9 @@ function bindPageCleanup() {
export {
CLOUD_PATHS, VM_DETAIL_TABS, api, bindPageCleanup, buy, byId, clearCredential,
clearVmMetrics, clearVmTrafficDaily, closeConsole, copyText, credential,
drawVmTrafficDaily, initializeSession, invoicePagePath,
drawVmTrafficDaily, hydrateVmDetailBootstrap, initializeSession, invoicePagePath,
loadInvoiceDetail, loadInvoices, loadKeys, loadPlanResources, loadVmMetrics, loadVmTrafficDaily,
loadVm, loadVms, navigate, openCreate, openReinstall, openRescue, reinstall,
loadVm, loadVmStatus, loadVms, navigate, openCreate, openReinstall, openRescue, reinstall,
renderVMs, renderVmDetail, renderVmMetrics, rescueAction, selectVmByApiId, selectedVm,
scheduleInvoicePoll, setVmDetailTab, showError, state, stopInvoicePoll, stopVmMetrics,
stopVmTrafficDaily, toast, trafficDailyViewVisible, vmIp,

@ -1,7 +1,7 @@
<div id="vm-workspace">
<section id="vm-detail-view" class="vm-detail-view" aria-labelledby="vm-detail-name">
<a id="vm-detail-back-button" class="button button-ghost vm-detail-back" href="/user/cloud/instances">← 返回实例列表</a>
<div class="page-heading vm-detail-heading"><div><span class="eyebrow">VIRTUAL MACHINE DETAILS</span><h1 id="vm-detail-name" tabindex="-1">虚拟机</h1><p class="vm-detail-summary"><span><span class="sr-only">服务器 IP:</span><strong id="vm-detail-header-ip">未获取</strong></span><span><span class="sr-only">区域:</span><strong id="vm-detail-header-region">未设置</strong></span><span><strong id="vm-detail-header-created-at">未记录</strong></span></p></div><div class="heading-actions"><span id="vm-detail-state" class="state-pill other">未知</span><button id="vm-detail-refresh-button" class="button button-outline" type="button"><span aria-hidden="true">↻</span> 刷新</button></div></div>
<div class="page-heading vm-detail-heading"><div><span class="eyebrow">VIRTUAL MACHINE DETAILS</span><h1 id="vm-detail-name" tabindex="-1">{$cloud_vm_view.name|default:'虚拟机'|escape:"html"}</h1><p class="vm-detail-summary"><span><span class="sr-only">服务器 IP:</span><strong id="vm-detail-header-ip">{$cloud_vm_view.ip|default:'未获取'|escape:"html"}</strong></span><span><span class="sr-only">区域:</span><strong id="vm-detail-header-region">{$cloud_vm_view.region|default:'未设置'|escape:"html"}</strong></span><span><strong id="vm-detail-header-created-at">{$cloud_vm_view.created_display|default:'未记录'|escape:"html"}</strong></span></p></div><div class="heading-actions"><span id="vm-detail-state" class="state-pill {$cloud_vm_view.state_class|default:'other'|escape:"html"}">{$cloud_vm_view.state_label|default:'正在读取'|escape:"html"}</span><button id="vm-detail-refresh-button" class="button button-outline" type="button"><span aria-hidden="true">↻</span> 刷新</button></div></div>
<div id="vm-detail-tabs" class="vm-detail-tabs" role="tablist" aria-label="虚拟机详情页面">
<button id="vm-detail-tab-operations" class="vm-detail-tab active" type="button" role="tab" aria-selected="true" aria-controls="vm-detail-operations-panel" data-detail-tab="operations">实例操作</button>
<button id="vm-detail-tab-performance" class="vm-detail-tab" type="button" role="tab" aria-selected="false" aria-controls="vm-detail-performance-panel" data-detail-tab="performance" tabindex="-1">性能监控</button>
@ -10,21 +10,21 @@
<div id="vm-detail-operations-panel" role="tabpanel" aria-labelledby="vm-detail-tab-operations">
<div class="vm-detail-grid">
<section class="inventory-panel vm-detail-panel" aria-labelledby="vm-detail-info-title">
<div class="panel-heading"><div><h2 id="vm-detail-info-title">虚拟机信息</h2><p>状态和配置每 15 秒自动更新;IP 是面板记录的配置,不代表系统已联网。</p></div></div>
<div class="panel-heading"><div><h2 id="vm-detail-info-title">虚拟机信息</h2><p>实时状态每 20 秒自动更新;IP 是面板记录的配置,不代表系统已联网。</p></div></div>
<dl class="vm-detail-facts">
<div><dt>地区</dt><dd id="vm-detail-region">未设置</dd></div><div><dt id="vm-detail-os-label">系统</dt><dd id="vm-detail-os">未识别</dd></div>
<div><dt>已配置公网 IP</dt><dd class="vm-detail-inline"><span id="vm-detail-ip">未获取</span><button id="vm-detail-ip-copy" class="vm-copy-icon" type="button" aria-label="复制公网 IP" title="复制公网 IP" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/></svg></button></dd></div><div><dt>计算规格</dt><dd id="vm-detail-spec">—</dd></div>
<div><dt>硬盘大小</dt><dd id="vm-detail-disk">—</dd></div>
<div><dt>SSH 登录名</dt><dd id="vm-detail-ssh-user">未记录</dd></div>
<div class="vm-detail-credential-row"><dt>面板记录的初始 root 密码</dt><dd class="vm-detail-inline"><code id="vm-detail-root-password" class="vm-detail-secret">未记录</code>
<button id="vm-detail-password-reveal" class="vm-copy-icon vm-credential-icon" type="button" aria-label="查看初始 root 密码" title="查看初始 root 密码" aria-controls="vm-detail-root-password" aria-pressed="false" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M2.3 12S5.8 6.5 12 6.5s9.7 5.5 9.7 5.5-3.5 5.5-9.7 5.5S2.3 12 2.3 12Z"/><circle cx="12" cy="12" r="2.6"/><path class="vm-eye-slash" d="M3 3 21 21"/></svg></button>
<button id="vm-detail-password-copy" class="vm-copy-icon vm-credential-icon" type="button" aria-label="复制初始 root 密码" title="复制初始 root 密码" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/></svg></button>
<div><dt>地区</dt><dd id="vm-detail-region">{$cloud_vm_view.region|default:'未设置'|escape:"html"}</dd></div><div><dt id="vm-detail-os-label">{$cloud_vm_view.system_label|default:'系统'|escape:"html"}</dt><dd id="vm-detail-os">{$cloud_vm_view.system_value|default:'未识别'|escape:"html"}</dd></div>
<div><dt>已配置公网 IP</dt><dd class="vm-detail-inline"><span id="vm-detail-ip">{$cloud_vm_view.ip|default:'未获取'|escape:"html"}</span><button id="vm-detail-ip-copy" class="vm-copy-icon" type="button" aria-label="复制公网 IP" title="复制公网 IP"{if $cloud_vm_view.ip|default:'未获取' == '未获取'} hidden{/if}><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/></svg></button></dd></div><div><dt>计算规格</dt><dd id="vm-detail-spec">{$cloud_vm_view.spec_display|default:'—'|escape:"html"}</dd></div>
<div><dt>硬盘大小</dt><dd id="vm-detail-disk">{$cloud_vm_view.disk_display|default:'—'|escape:"html"}</dd></div>
<div><dt>SSH 登录名</dt><dd id="vm-detail-ssh-user">{$cloud_vm_view.ssh_user|default:'未记录'|escape:"html"}</dd></div>
<div class="vm-detail-credential-row"><dt>面板记录的初始 root 密码</dt><dd class="vm-detail-inline"><code id="vm-detail-root-password" class="vm-detail-secret">{$cloud_vm_view.password_label|default:'未记录'|escape:"html"}</code>
<button id="vm-detail-password-reveal" class="vm-copy-icon vm-credential-icon" type="button" aria-label="查看初始 root 密码" title="查看初始 root 密码" aria-controls="vm-detail-root-password" aria-pressed="false"{if !$cloud_vm_view.password_available|default:false} hidden{/if}><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M2.3 12S5.8 6.5 12 6.5s9.7 5.5 9.7 5.5-3.5 5.5-9.7 5.5S2.3 12 2.3 12Z"/><circle cx="12" cy="12" r="2.6"/><path class="vm-eye-slash" d="M3 3 21 21"/></svg></button>
<button id="vm-detail-password-copy" class="vm-copy-icon vm-credential-icon" type="button" aria-label="复制初始 root 密码" title="复制初始 root 密码"{if !$cloud_vm_view.password_available|default:false} hidden{/if}><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/></svg></button>
</dd></div>
</dl>
</section>
<div class="vm-detail-operations">
<section class="inventory-panel vm-detail-panel" aria-labelledby="vm-detail-actions-title"><div class="panel-heading"><div><h2 id="vm-detail-actions-title">日常操作</h2><p>在这里管理这台虚拟机的电源和控制台。</p></div></div><div id="vm-detail-primary-actions" class="vm-detail-actions"></div></section>
<section class="inventory-panel vm-detail-panel vm-danger-panel" aria-labelledby="vm-detail-danger-title"><div class="panel-heading"><div><h2 id="vm-detail-danger-title">维护与危险操作</h2><p>救援会先预挂载 ISO,再尝试正常关机并开机;强制断电可能丢失未保存的数据,重装或删除会清除数据。</p></div></div><div id="vm-detail-danger-actions" class="vm-detail-actions"></div></section>
<section class="inventory-panel vm-detail-panel" aria-labelledby="vm-detail-actions-title"><div class="panel-heading"><div><h2 id="vm-detail-actions-title">日常操作</h2><p>在这里管理这台虚拟机的电源和控制台。</p></div></div><div id="vm-detail-primary-actions" class="vm-detail-actions"><p class="muted">正在读取实时状态…</p></div></section>
<section class="inventory-panel vm-detail-panel vm-danger-panel" aria-labelledby="vm-detail-danger-title"><div class="panel-heading"><div><h2 id="vm-detail-danger-title">维护与危险操作</h2><p>救援会先预挂载 ISO,再尝试正常关机并开机;强制断电可能丢失未保存的数据,重装或删除会清除数据。</p></div></div><div id="vm-detail-danger-actions" class="vm-detail-actions"><p class="muted">实时状态确认后才会启用操作。</p></div></section>
</div>
</div>
</div>
@ -32,15 +32,15 @@
<section class="inventory-panel vm-service-panel" aria-labelledby="vm-service-title">
<div class="panel-heading"><div><h2 id="vm-service-title">服务周期与流量</h2><p>查看当前服务、网络状态和本期流量使用情况。</p></div></div>
<dl class="vm-service-facts">
<div><dt>服务状态</dt><dd><span id="vm-detail-service-status" class="service-pill unknown">暂未提供</span></dd></div>
<div><dt>网络状态</dt><dd><span id="vm-detail-network-status" class="service-pill unknown">暂未提供</span></dd></div>
<div><dt>当前账期结束</dt><dd id="vm-detail-period-end">暂未提供</dd></div>
<div><dt>本期下载(RX)</dt><dd id="vm-detail-traffic-rx">暂未提供</dd></div>
<div><dt>本期上传(TX)</dt><dd id="vm-detail-traffic-tx">暂未提供</dd></div>
<div><dt>本期合计已用</dt><dd id="vm-detail-traffic-used">暂未提供</dd></div>
<div><dt>总流量 / 剩余流量</dt><dd id="vm-detail-traffic-total-remaining">暂未提供</dd></div>
<div><dt>服务状态</dt><dd><span id="vm-detail-service-status" class="service-pill {$cloud_vm_view.service_status_class|default:'unknown'|escape:"html"}">{$cloud_vm_view.service_status_label|default:'暂未提供'|escape:"html"}</span></dd></div>
<div><dt>网络状态</dt><dd><span id="vm-detail-network-status" class="service-pill {$cloud_vm_view.network_status_class|default:'unknown'|escape:"html"}">{$cloud_vm_view.network_status_label|default:'暂未提供'|escape:"html"}</span></dd></div>
<div><dt>当前账期结束</dt><dd id="vm-detail-period-end">{$cloud_vm_view.period_end_display|default:'暂未提供'|escape:"html"}</dd></div>
<div><dt>本期下载(RX)</dt><dd id="vm-detail-traffic-rx">{$cloud_vm_view.traffic_rx_display|default:'暂未提供'|escape:"html"}</dd></div>
<div><dt>本期上传(TX)</dt><dd id="vm-detail-traffic-tx">{$cloud_vm_view.traffic_tx_display|default:'暂未提供'|escape:"html"}</dd></div>
<div><dt>本期合计已用</dt><dd id="vm-detail-traffic-used">{$cloud_vm_view.traffic_used_display|default:'暂未提供'|escape:"html"}</dd></div>
<div><dt>总流量 / 剩余流量</dt><dd id="vm-detail-traffic-total-remaining">{$cloud_vm_view.traffic_total_remaining_display|default:'暂未提供'|escape:"html"}</dd></div>
</dl>
<div id="vm-detail-traffic-progress" class="vm-traffic-progress" role="progressbar" aria-label="套餐流量使用率" aria-valuemin="0" aria-valuemax="100" hidden><span id="vm-detail-traffic-progress-bar"></span></div>
<div id="vm-detail-traffic-progress" class="vm-traffic-progress" role="progressbar" aria-label="套餐流量使用率" aria-valuemin="0" aria-valuemax="100"{if $cloud_vm_view.traffic_ratio|default:'' == ''} hidden{else} aria-valuenow="{$cloud_vm_view.traffic_ratio|escape:"html"}"{/if}><span id="vm-detail-traffic-progress-bar"{if $cloud_vm_view.traffic_ratio|default:'' != ''} style="width:{$cloud_vm_view.traffic_ratio|escape:"html"}%"{/if}></span></div>
</section>
<section class="inventory-panel vm-traffic-daily" aria-labelledby="vm-traffic-daily-title">
<div class="panel-heading"><div><h2 id="vm-traffic-daily-title">最近 30 天每日流量</h2><p>按天统计虚拟机的下载和上传流量。</p></div></div>
@ -62,3 +62,4 @@
</section>
</section>
</div>
<script id="vm-detail-bootstrap" type="application/json">{$cloud_vm_bootstrap_json nofilter}</script>

@ -1,20 +1,41 @@
<div id="vm-workspace">
<div id="vm-list-view">
<div class="page-heading">
<div><span class="eyebrow">VIRTUAL MACHINES</span><h1 id="vm-list-title" tabindex="-1">实例管理</h1><p>查看虚拟机信息;点击名称进入管理页面执行操作。</p></div>
<div><span class="eyebrow">VIRTUAL MACHINES</span><h1 id="vm-list-title" tabindex="-1">实例管理</h1><p>查看实例信息;点击名称进入管理页面执行操作。</p></div>
<div class="heading-actions"><button id="refresh-button" class="button button-outline" type="button"><span aria-hidden="true">↻</span> 刷新</button><a id="create-button" class="button button-primary" href="/user/cloud/deploy"><span aria-hidden="true">+</span> 部署实例</a></div>
</div>
<div id="resource-warning" class="resource-warning" role="alert" hidden></div>
<div class="overview-grid" aria-label="虚拟机概览">
<section class="stat-card"><div class="stat-top"><span>虚拟机总数</span><span class="stat-icon total" aria-hidden="true">▦</span></div><strong id="stat-total">—</strong><small>我的实例</small></section>
<section class="stat-card"><div class="stat-top"><span>运行中</span><span class="stat-icon running" aria-hidden="true">▶</span></div><strong id="stat-running">—</strong><small><span class="tiny-dot green"></span> 正在提供服务</small></section>
<section class="stat-card"><div class="stat-top"><span>已关机</span><span class="stat-icon stopped" aria-hidden="true">⏻</span></div><strong id="stat-stopped">—</strong><small>可随时启动</small></section>
<div class="overview-grid" aria-label="实例概览">
<section class="stat-card"><div class="stat-top"><span>实例总数</span><span class="stat-icon total" aria-hidden="true">▦</span></div><strong id="stat-total">{$cloud_vm_stats.total|default:0|escape:"html"}</strong><small>{$cloud_vm_scope_label|default:'我的实例'|escape:"html"}</small></section>
<section class="stat-card"><div class="stat-top"><span>当前页运行中</span><span class="stat-icon running" aria-hidden="true">▶</span></div><strong id="stat-running">{if $cloud_vm_pagination.total > 0}—{else}0{/if}</strong><small><span class="tiny-dot green"></span> 实时电源状态</small></section>
<section class="stat-card"><div class="stat-top"><span>当前页已关机</span><span class="stat-icon stopped" aria-hidden="true">⏻</span></div><strong id="stat-stopped">{if $cloud_vm_pagination.total > 0}—{else}0{/if}</strong><small>实时电源状态</small></section>
</div>
<section class="inventory-panel" aria-labelledby="inventory-title">
<div class="panel-heading"><div><h2 id="inventory-title">虚拟机列表</h2><p id="inventory-count">正在加载…</p></div><div class="panel-tools"><label class="search-box"><span aria-hidden="true">⌕</span><span class="sr-only">搜索虚拟机</span><input id="search-input" type="search" placeholder="搜索名称、地区、系统或 IP" /></label><select id="state-filter" aria-label="按状态筛选"><option value="all">全部状态</option><option value="running">运行中</option><option value="stopped">已关机</option><option value="other">其他状态</option></select></div></div>
<div class="table-scroll"><table class="vm-table"><thead><tr><th>虚拟机</th><th>状态</th><th>地区</th><th>系统 / 安装镜像</th><th>已配置公网 IP</th><th>规格</th><th>磁盘</th></tr></thead><tbody id="vm-table-body"></tbody></table></div>
<div id="empty-state" class="empty-state" hidden><div class="empty-icon" aria-hidden="true">▦</div><h3 id="empty-title">还没有虚拟机</h3><p id="empty-description">点击右上角“部署实例”开始。</p></div>
<div class="panel-heading">
<div><h2 id="inventory-title">实例列表</h2><p id="inventory-count">当前页 {$cloud_vm_pagination.page_count|default:0|escape:"html"} 台 · 共 {$cloud_vm_pagination.total|escape:"html"} 台</p></div>
<div class="panel-tools"><label class="search-box"><span aria-hidden="true">⌕</span><span class="sr-only">搜索当前页实例</span><input id="search-input" type="search" placeholder="搜索当前页名称、地区、系统或 IP" /></label><select id="state-filter" aria-label="按当前页状态筛选"><option value="all">当前页全部状态</option><option value="running">运行中</option><option value="stopped">已关机</option><option value="other">其他状态</option></select></div>
</div>
<div class="table-scroll"><table class="vm-table"><thead><tr><th>实例</th><th>状态</th><th>地区</th><th>系统 / 安装镜像</th><th>已配置公网 IP</th><th>规格</th><th>磁盘</th></tr></thead><tbody id="vm-table-body">
{foreach $cloud_vm_rows as $vm}
<tr data-vm-id="{$vm.api_id|escape:"html"}" data-vm-uuid="{$vm.uuid|escape:"html"}">
<td data-label="实例"><div class="vm-identity"><div class="vm-icon" aria-hidden="true">▣</div><div><a class="vm-name-link" href="/user/cloud/instances/{$vm.api_id|escape:"url"}" data-vm-uuid="{$vm.uuid|escape:"html"}" aria-label="管理实例 {$vm.name|escape:"html"}">{$vm.name|escape:"html"}</a><span class="vm-uuid-row"><span class="vm-id" title="{$vm.uuid|escape:"html"}">{$vm.uuid|escape:"html"}</span>{if $vm.uuid != ''}<button class="vm-copy-icon" type="button" data-copy-value="{$vm.uuid|escape:"html"}" data-copy-label="UUID" title="复制 UUID" aria-label="复制 UUID"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"></rect><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"></path></svg></button>{/if}</span></div></div></td>
<td data-label="状态"><span class="state-pill {$vm.state_class|escape:"html"} vm-state-pill">{$vm.state_label|escape:"html"}</span></td>
<td data-label="地区"><span class="vm-metadata">{$vm.region|escape:"html"}</span></td>
<td data-label="{$vm.system_label|escape:"html"}"><span class="vm-metadata">{$vm.system_value|escape:"html"}</span></td>
<td data-label="已配置公网 IP"><span class="vm-ip-copy-row"><span class="vm-metadata vm-ip">{$vm.ip|escape:"html"}</span>{if $vm.has_ip}<button class="vm-copy-icon" type="button" data-copy-value="{$vm.ip|escape:"html"}" data-copy-label="公网 IP" title="复制公网 IP" aria-label="复制公网 IP"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"></rect><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"></path></svg></button>{/if}</span></td>
<td data-label="规格"><div class="vm-spec"><strong>{$vm.vcpu|default:'—'|escape:"html"} vCPU · {$vm.memory_mib|default:'—'|escape:"html"} MiB</strong><small>计算资源</small></div></td>
<td data-label="磁盘"><span class="vm-spec">{$vm.disk_label|escape:"html"}</span></td>
</tr>
{/foreach}
</tbody></table></div>
<div id="empty-state" class="empty-state"{if !empty($cloud_vm_rows)} hidden{/if}><div class="empty-icon" aria-hidden="true">▦</div><h3 id="empty-title">还没有实例</h3><p id="empty-description">点击右上角“部署实例”开始。</p></div>
</section>
<nav id="instances-pagination" class="invoice-pagination" aria-label="实例分页"{if $cloud_vm_pagination.total == 0} hidden{/if}>
<button id="instances-previous" class="button button-outline small" type="button"{if !$cloud_vm_pagination.has_previous} disabled{/if}>上一页</button>
<span id="instances-page-label" aria-live="polite">第 {$cloud_vm_pagination.page|escape:"html"} / {$cloud_vm_pagination.total_pages|escape:"html"} 页 · 共 {$cloud_vm_pagination.total|escape:"html"} 台</span>
<button id="instances-next" class="button button-outline small" type="button"{if !$cloud_vm_pagination.has_next} disabled{/if}>下一页</button>
</nav>
<div class="footer-note">状态每 15 秒自动更新 · 操作会发送至远端 libvirt 宿主机</div>
<script id="instances-bootstrap" type="application/json">{$cloud_vm_bootstrap_json nofilter}</script>
</div>
</div>

@ -1 +1 @@
{assign var=venix_asset_version value='2026092804' scope='global'}
{assign var=venix_asset_version value='2026092805' scope='global'}

@ -0,0 +1,161 @@
<?php
namespace App\Services {
final class Config
{
public static function get($name, $default = null)
{
return $name === 'cloud_max_renewal_periods_ahead' ? 24 : $default;
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudInstancePageService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('cloud_hosts', static function (Blueprint $table): void {
$table->increments('id');
$table->string('region')->default('');
$table->string('country_code')->default('');
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->string('uuid');
$table->integer('host_id');
$table->integer('user_id');
$table->integer('current_period_id')->nullable();
$table->string('name');
$table->string('status');
$table->string('service_status');
$table->string('network_status');
$table->integer('expires_at')->nullable();
$table->string('renewal_price')->nullable();
$table->integer('renewal_days')->default(0);
$table->integer('renewal_traffic_bytes')->default(0);
$table->integer('traffic_quota_bytes')->default(0);
$table->integer('traffic_download_bytes')->default(0);
$table->integer('traffic_upload_bytes')->default(0);
$table->text('spec_json');
$table->text('credential_cipher')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_service_periods', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('instance_id');
$table->integer('starts_at');
$table->integer('ends_at');
$table->string('status');
});
Capsule::table('cloud_hosts')->insert([
'id' => 7, 'region' => 'HongKong', 'country_code' => 'HK',
]);
$now = time();
$common = [
'host_id' => 7, 'current_period_id' => null, 'status' => 'active',
'service_status' => 'active', 'network_status' => 'active',
'expires_at' => $now + 86400, 'renewal_price' => '10.00',
'renewal_days' => 30, 'renewal_traffic_bytes' => 2000,
'traffic_quota_bytes' => 2000, 'traffic_download_bytes' => 300,
'traffic_upload_bytes' => 200,
'spec_json' => json_encode(['vcpu' => 2, 'memory_mib' => 2048, 'state' => 'running',
'disk_gib' => 40, 'os_source' => 'cloud_template', 'os_name' => 'AlmaLinux 10']),
'credential_cipher' => 'test-cipher', 'created_at' => $now - 60,
'updated_at' => $now,
];
Capsule::table('cloud_instances')->insert($common + [
'id' => 1, 'uuid' => '11111111-1111-4111-8111-111111111111',
'user_id' => 1, 'name' => 'owner-vm',
]);
Capsule::table('cloud_instances')->insert($common + [
'id' => 2, 'uuid' => '22222222-2222-4222-8222-222222222222',
'user_id' => 2, 'name' => 'foreign-vm',
]);
$owner = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false,
'can_manage' => false];
$admin = ['user_id' => 1, 'is_admin' => true, 'is_super_admin' => false,
'can_manage' => false];
$global = ['user_id' => 1, 'is_admin' => true, 'is_super_admin' => true,
'can_manage' => true];
Capsule::connection('default')->flushQueryLog();
Capsule::connection('default')->enableQueryLog();
$page = CloudInstancePageService::forActor($owner, 1, 20);
$pageQueryCount = count(Capsule::connection('default')->getQueryLog());
Capsule::connection('default')->disableQueryLog();
$assert($page['stats']['total'] === 1 && count($page['vms']) === 1
&& $page['pagination']['page_count'] === 1
&& $page['vms'][0]['name'] === 'owner-vm',
'Ordinary user instance first page crossed the owner boundary.');
$assert($pageQueryCount <= 3,
'Instance first page regressed beyond count, rows and host batch queries.');
$assert($page['vms'][0]['state'] === 'unknown',
'Persisted specification power state was trusted before a live UUID check.');
$assert(!array_key_exists('traffic_quota_bytes', $page['vms'][0])
&& !array_key_exists('password_available', $page['vms'][0]),
'Paginated instance rows leaked detail-only billing or credential metadata.');
$ownedDetail = CloudInstancePageService::detailForActor($owner, 1);
$assert($ownedDetail['can_operate'] && $ownedDetail['can_delete']
&& $ownedDetail['password_available'] && $ownedDetail['can_renew'],
'Owner lost expected instance capabilities.');
$assert(count(CloudInstancePageService::forActorIds($owner, [1, 2])) === 1,
'Ordinary user batch status scope disclosed a foreign instance.');
$adminPage = CloudInstancePageService::forActor($admin, 1, 20);
$assert($adminPage['stats']['total'] === 2,
'Read-only administrator lost the historical all-instance view.');
$foreign = CloudInstancePageService::detailForActor($admin, 2);
$assert(!$foreign['is_owner'] && !$foreign['can_operate']
&& !$foreign['can_delete'] && !$foreign['can_view_credential']
&& !$foreign['password_available'] && !$foreign['can_renew'],
'Read-only administrator inherited foreign instance mutation or credential access.');
$managed = CloudInstancePageService::detailForActor($global, 2);
$assert(!$managed['is_owner'] && $managed['can_operate']
&& $managed['can_delete'] && $managed['can_view_credential']
&& $managed['password_available'] && !$managed['can_renew'],
'Super administrator capabilities no longer match the legacy VM boundary.');
Capsule::connection('default')->flushQueryLog();
Capsule::connection('default')->enableQueryLog();
$mutable = CloudInstancePageService::statusForActor($global, 2);
$statusQueryCount = count(Capsule::connection('default')->getQueryLog());
Capsule::connection('default')->disableQueryLog();
$assert($statusQueryCount <= 1 && $mutable['host_id'] === 7
&& !array_key_exists('credential_cipher', $mutable)
&& !array_key_exists('renewal_price', $mutable),
'Detail status poll loaded static host, credential or renewal metadata.');
$status = CloudInstancePageService::status($managed,
['uuid' => $managed['uuid'], 'name' => 'foreign-vm', 'state' => 'running']);
$assert($status['state'] === 'running' && $status['traffic_used_bytes'] === 500
&& $status['traffic_remaining_bytes'] === 1500
&& $status['live_state_available'] === true,
'Lightweight status did not merge live state with the database billing snapshot.');
$unavailable = CloudInstancePageService::status($managed);
$assert($unavailable['state'] === 'unknown'
&& $unavailable['live_state_available'] === false,
'Unavailable hosts were presented as confirmed live power state.');
$power = CloudInstancePageService::powerStatus($managed,
['uuid' => $managed['uuid'], 'name' => 'foreign-vm', 'state' => 'running']);
$assert($power['state'] === 'running' && $power['live_state_available'] === true
&& !array_key_exists('traffic_quota_bytes', $power)
&& !array_key_exists('can_delete', $power),
'List polling returned detail-only billing or permission fields.');
echo "Cloud instance page service ownership and administrator permissions passed.\n";
}

@ -0,0 +1,111 @@
<?php
// Static regression contract for the instance list/detail hybrid SSR boundary.
// PHP and database snapshots own first paint; libvirt is consulted only by
// the small status endpoints after the page is already usable.
$root = dirname(__DIR__);
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$section = static function (string $source, string $start, string $end): string {
$offset = strpos($source, $start);
if ($offset === false) {
return '';
}
$limit = strpos($source, $end, $offset + strlen($start));
return $limit === false ? substr($source, $offset)
: substr($source, $offset, $limit - $offset);
};
$page = file_get_contents($root . '/app/Controllers/CloudPageController.php');
$api = file_get_contents($root . '/app/Controllers/CloudApiController.php');
$service = file_get_contents($root . '/app/Services/Cloud/CloudInstancePageService.php');
$middleware = file_get_contents($root . '/app/Middleware/CloudApi.php');
$routes = file_get_contents($root . '/config/routes_cloud.php');
$pageService = $section($service, 'public static function forActor(',
'public static function detailForActor(');
$assert(str_contains($service, "CloudInstance::where('status', '<>', 'deleted')")
&& str_contains($service, "if (!(\$actor['is_admin'] ?? false))")
&& str_contains($service, "->where('user_id', (int) \$actor['user_id'])")
&& str_contains($service, '->limit($perPage)')
&& str_contains($service, '->get(self::listColumns())')
&& str_contains($service, "'per_page' => \$perPage")
&& str_contains($service, "'page_count' => \$count")
&& !str_contains($service, 'CloudEngineClient'),
'Instance first-paint service must remain actor scoped, bounded and engine free.');
$assert(str_contains($pageService, 'self::listSnapshots($records)')
&& !str_contains($pageService, 'self::snapshots($records, $actor)'),
'Instance list first paint must not load detail-only billing and credential data.');
$assert(str_contains($service, "\$canDelete = \$lifecycleActive && (\$owner || \$global)")
&& str_contains($service, "'can_view_credential' => \$owner || \$global")
&& str_contains($service, "'can_renew' => \$lifecycleActive && \$owner")
&& str_contains($service, "'state' => 'unknown'"),
'Read-only administrators must not inherit owner or super-admin instance operations.');
$assert(str_contains($service, 'CloudHost::whereIn')
&& str_contains($service, 'CloudServicePeriod::whereIn')
&& str_contains($service, "->groupBy('instance_id')"),
'Instance page dependencies must remain bulk loaded instead of queried per row.');
$assert(str_contains($service, 'private static function listItem(')
&& str_contains($service, 'private static function listSnapshots(')
&& str_contains($service, "->get(['id', 'uuid', 'host_id', 'name'])")
&& str_contains($service, 'public static function powerStatus(')
&& str_contains($service, "'live_state_available'")
&& str_contains($service, "array_intersect_key"),
'Instance list bootstrap and polling payloads must remain detail-free and bounded.');
$assert(str_contains($service, 'public static function statusForActor(')
&& str_contains($service, "'traffic_upload_bytes',")
&& !str_contains($section($service, 'public static function statusForActor(',
'public static function forActorIds('), 'credential_cipher'),
'Detail status polling must load only mutable database state.');
$instances = $section($page, 'public function instances(', 'public function detail(');
$detail = $section($page, 'public function detail(', 'public function deploy(');
$assert(str_contains($instances, 'CloudAccess::actor(false)')
&& str_contains($instances, 'CloudInstancePageService::forActor')
&& str_contains($instances, "'cloud_vm_rows'")
&& str_contains($instances, "'cloud_vm_bootstrap_json'"),
'Instance list HTML must embed its owner-scoped database first page without a cloud session.');
$assert(str_contains($detail, 'CloudAccess::actor(false)')
&& str_contains($detail, 'CloudInstancePageService::detailForActor')
&& str_contains($detail, "'cloud_vm_view'")
&& str_contains($detail, "'cloud_vm_bootstrap_json'"),
'Instance detail HTML must embed a useful owner-scoped database snapshot.');
$assert(str_contains($page, 'JSON_HEX_TAG')
&& str_contains($page, "'csrf_token' => AdminCsrf::token()")
&& str_contains($page, "withHeader('Cache-Control', 'private, no-store')"),
'Embedded instance state must be script-safe, authenticated and non-cacheable.');
$pageRoute = strpos($routes, "'/vms/page'");
$statusesRoute = strpos($routes, "'/vms/statuses'");
$statusRoute = strpos($routes, "'/vms/{id:[0-9]+}/status'");
$legacyRoute = strpos($routes, "'/vms/{id}'");
$assert($pageRoute !== false && $statusesRoute !== false && $statusRoute !== false
&& $legacyRoute !== false && $pageRoute < $legacyRoute
&& $statusesRoute < $legacyRoute && $statusRoute < $legacyRoute,
'Lightweight fixed VM routes must precede the legacy dynamic VM route.');
$pageApi = $section($api, 'public function vmPage(', 'public function vmStatuses(');
$statusesApi = $section($api, 'public function vmStatuses(', 'public function vmStatus(');
$statusApi = $section($api, 'public function vmStatus(', 'public function vm(');
$assert(str_contains($pageApi, '$this->billingActor($request)')
&& str_contains($pageApi, 'CloudInstancePageService::forActor')
&& !str_contains($pageApi, 'CloudEngineClient'),
'Paginated VM rows must not create an engine session or contact libvirt.');
$assert(str_contains($statusesApi, 'CloudInstancePageService::forActorIds')
&& str_contains($statusesApi, 'CloudInstancePageService::powerStatus')
&& str_contains($statusesApi, "'GET', 'vm-states'")
&& str_contains($statusesApi, 'isset($allowed[$uuid])')
&& !str_contains($statusesApi, "'GET', 'vms'"),
'Batch VM status must intersect owner UUIDs and use only the lightweight engine resource.');
$assert(str_contains($statusApi, 'CloudInstancePageService::statusForActor')
&& str_contains($statusApi, ". '/state'")
&& str_contains($statusApi, 'hash_equals('),
'Single VM status must be owner scoped, UUID checked and avoid the full VM detail resource.');
$assert(str_contains($middleware, "\$path === '/api/v1/vms/page'")
&& str_contains($middleware, 'CloudAccess::actor(!$databaseOnly)'),
'Database-only VM pagination must not allocate a private-engine cloud session.');
echo "Instance list/detail SSR and lightweight live-status contract passed.\n";

@ -23,6 +23,9 @@ $section = static function (string $source, string $start, string $end): string
$controller = file_get_contents($root . '/app/Controllers/CloudApiController.php');
$runtime = file_get_contents($root . '/public/cloud/runtime.js');
$detail = file_get_contents($root . '/public/cloud/detail.js');
$detailTemplate = file_get_contents(
$root . '/resources/views/venix/cloud/pages/detail.tpl'
);
$contexts = $section($controller, 'private function vmListContexts(',
'private function vmData(');
@ -60,8 +63,21 @@ $assert(str_contains($loadVm, "api(`/api/v1/vms/\${encodeURIComponent(id)}`)")
$assert(str_contains($selection, 'await loadVm(apiId, true)')
&& !str_contains($selection, 'loadVms('),
'Detail selection still fetches the full VM list.');
$assert(!str_contains($detail, 'loadVms')
&& substr_count($detail, 'loadVm(vmId)') >= 4,
'Detail refresh or polling still loads every instance.');
$statusLoader = $section($runtime, 'async function loadVmStatus(',
'function renderVmDetail(');
$assert(str_contains($detail, 'hydrateVmDetailBootstrap(detailBootstrap())')
&& str_contains($detailTemplate, 'id="vm-detail-bootstrap"')
&& !str_contains($detail, 'initializeSession(')
&& !str_contains($detail, 'selectVmByApiId(')
&& !str_contains($detail, 'loadVm('),
'Detail first paint must hydrate the SSR bootstrap without session or full-VM requests.');
$assert(str_contains($statusLoader,
'api(`/api/v1/vms/${encodeURIComponent(id)}/status`)')
&& str_contains($statusLoader, 'const current = selectedVm()')
&& substr_count($detail, 'loadVmStatus(vmId)') >= 4
&& str_contains($detail, 'window.setTimeout(poll, 20000)')
&& !str_contains($detail, 'setInterval(')
&& !str_contains($detail, 'loadVms'),
'Detail refresh and non-overlapping polling must use only the lightweight status endpoint.');
echo "Cloud instance bulk-list and single-detail read paths passed.\n";

@ -107,6 +107,19 @@ namespace {
&& is_array($billingActor) && ($billingActor['session_id'] ?? null) === ''
&& CloudSession::count() === $sessionCount,
'Invoice-only API authentication created or queried an engine cloud session.');
$instancePageRequest = Request::createFromEnvironment(Environment::mock([
'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/api/v1/vms/page?page=1',
]));
$instancePageActor = null;
$instancePageNext = function ($request, $response) use (&$instancePageActor) {
$instancePageActor = $request->getAttribute('cloud_actor');
return $response;
};
$reply = $middleware($instancePageRequest, new Response(), $instancePageNext);
$assert($reply->getStatusCode() === 200
&& is_array($instancePageActor) && ($instancePageActor['session_id'] ?? null) === ''
&& CloudSession::count() === $sessionCount,
'Database-only VM pagination created or queried an engine cloud session.');
$user->isLogin = false; $called = false; $reply = $middleware($request, new Response(), $next); $assert($reply->getStatusCode() === 401 && !$called && !$reply->hasHeader('Location'), 'Guest API redirected or passed through.');
echo "Cloud cookie/Redis revocation, signed introspection, admin console isolation and JSON CSRF checks passed (crypto reference double only).\n";
}

Loading…
Cancel
Save