diff --git a/web/app/Controllers/CloudAdminController.php b/web/app/Controllers/CloudAdminController.php index b8198651..27db631a 100644 --- a/web/app/Controllers/CloudAdminController.php +++ b/web/app/Controllers/CloudAdminController.php @@ -3,6 +3,7 @@ namespace App\Controllers; use App\Models\CloudHost; use App\Services\Cloud\CloudAccess; +use App\Services\Cloud\CloudDeploymentPageService; use App\Services\Cloud\CloudEngineClient; use App\Services\Cloud\CloudError; use App\Services\Cloud\CloudInput; @@ -182,9 +183,13 @@ final class CloudAdminController if (isset($args['job_id'])) { $path .= '/import-jobs/' . rawurlencode($args['job_id']); } - return $response->withJson( - (new CloudEngineClient())->request($method, $path, $actor, $body) - ); + $result = (new CloudEngineClient())->request($method, $path, $actor, $body); + if ($method === 'GET' && !isset($args['job_id']) && !isset($args['id'])) { + CloudDeploymentPageService::rememberTemplateCatalog($result); + } elseif (is_array($result['template'] ?? null)) { + CloudDeploymentPageService::rememberTemplate($result['template']); + } + return $response->withJson($result); } // Rescue ISOs remain deliberately scoped to one host and its separate diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php index 0e544014..baf2226d 100644 --- a/web/app/Controllers/CloudApiController.php +++ b/web/app/Controllers/CloudApiController.php @@ -14,6 +14,7 @@ use App\Services\Auth; use App\Services\AdminCsrf; use App\Services\Config; use App\Services\Cloud\CloudAccess; +use App\Services\Cloud\CloudDeploymentPageService; use App\Services\Cloud\CloudEngineClient; use App\Services\Cloud\CloudError; use App\Services\Cloud\CloudInput; @@ -130,30 +131,7 @@ final class CloudApiController public function plans($request, $response) { - $plans = []; - $available = Shop::where('status', 1)->orderBy('sort')->orderBy('id')->get(); - $hostIds = $available->pluck('host_id')->map(static fn ($id) => (int) $id) - ->filter(static fn ($id) => $id > 0)->unique()->values()->all(); - $hosts = $hostIds === [] ? collect() : CloudHost::whereIn('id', $hostIds) - ->where('enabled', 1)->get()->keyBy('id'); - foreach ($available as $plan) { - if ((int) $plan->stock === 0) { - continue; - } - $host = $hosts->get((int) $plan->host_id); - if ($host !== null) { - $plans[] = ['id' => (int) $plan->id, 'name' => $plan->name, 'price' => (string) $plan->price, - 'cpu_cores' => (int) $plan->cpu_cores, 'memory_mib' => (int) $plan->memory_mib, - 'bandwidth_mbps' => (int) $plan->bandwidth_mbps, 'disk_gib' => (int) $plan->disk_gib, - 'validity_days' => (int) $plan->validity_days, - 'traffic_quota_bytes' => (int) $plan->traffic_quota_bytes, - 'traffic_gib' => $plan->trafficGiB(), - 'stock' => (int) $plan->stock, 'host_id' => (int) $host->id, - 'host_name' => $host->name, 'country_code' => strtoupper((string) ($host->country_code ?? '')), - 'region' => $host->region]; - } - } - return $this->json($response, ['plans' => $plans]); + return $this->json($response, ['plans' => CloudDeploymentPageService::plans()]); } public function orders($request, $response) @@ -861,9 +839,9 @@ final class CloudApiController $key->save(); return $this->json($response, ['id' => (int) $key->id, 'name' => $key->name, 'fingerprint' => $key->fingerprint], 201); } - $keys = CloudSSHKey::where('user_id', $actor['user_id'])->orderBy('id')->get()->map(fn ($key) => - ['id' => (int) $key->id, 'name' => $key->name, 'fingerprint' => $key->fingerprint, 'created_at' => (int) $key->created_at])->all(); - return $this->json($response, ['keys' => $keys]); + return $this->json($response, [ + 'keys' => CloudDeploymentPageService::sshKeys((int) $actor['user_id']), + ]); } public function deleteKey($request, $response, $args) @@ -881,7 +859,7 @@ final class CloudApiController // Cloud images are a panel-wide catalog. Host-specific replication is // owned by the private engine and must not make the browser reload or // replace the catalog whenever a customer changes region or plan. - $catalog = $engine->request('GET', '/internal/v1/vm-templates', $actor); + $catalog = CloudDeploymentPageService::freshTemplateCatalog($actor); $templatePayload = [ 'templates' => is_array($catalog['templates'] ?? null) ? $catalog['templates'] : [], diff --git a/web/app/Controllers/CloudPageController.php b/web/app/Controllers/CloudPageController.php index 318164d0..3a7184f1 100644 --- a/web/app/Controllers/CloudPageController.php +++ b/web/app/Controllers/CloudPageController.php @@ -5,6 +5,7 @@ namespace App\Controllers; use App\Services\AdminCsrf; use App\Services\Auth; use App\Services\Cloud\CloudAccess; +use App\Services\Cloud\CloudDeploymentPageService; use App\Services\Cloud\CloudError; use App\Services\Cloud\CloudInstancePageService; use App\Services\Cloud\CloudInvoicePageService; @@ -72,7 +73,36 @@ final class CloudPageController public function deploy($request, $response, $args) { - return $this->render($response, 'deploy', '部署实例'); + $actor = CloudAccess::actor(false); + $user = $request->getAttribute('auth_user') ?? Auth::getUser(); + $plans = CloudDeploymentPageService::publicPagePlans(); + $regions = CloudDeploymentPageService::regions($plans); + $catalog = CloudDeploymentPageService::templateCatalogForPage($actor); + $templates = is_array($catalog['templates'] ?? null) + ? $catalog['templates'] : []; + $catalogUnavailable = ($catalog['catalog_unavailable'] ?? false) === true; + $keys = $this->sshKeyOptions((int) $actor['user_id']); + $defaultHostId = $regions === [] ? 0 : (int) $regions[0]['host_id']; + $bootstrapRegions = array_map(static fn (array $region): array => + array_diff_key($region, ['plans' => true]), $regions); + $payload = [ + 'user' => $this->userBootstrap($user, $actor), + 'plans' => $plans, + 'regions' => $bootstrapRegions, + 'templates' => $templates, + 'ssh_keys' => $keys, + 'default_host_id' => $defaultHostId, + 'catalog_unavailable' => $catalogUnavailable, + ]; + + return $this->render($response, 'deploy', '部署实例', '', '', [ + 'cloud_deploy_regions' => $regions, + 'cloud_deploy_template_groups' => CloudDeploymentPageService::templateGroups($templates), + 'cloud_deploy_ssh_keys' => $keys, + 'cloud_deploy_default_host_id' => $defaultHostId, + 'cloud_deploy_catalog_unavailable' => $catalogUnavailable, + 'cloud_deploy_bootstrap_json' => $this->safeJson($payload), + ]); } public function isoImages($request, $response, $args) @@ -124,7 +154,42 @@ final class CloudPageController public function reinstall($request, $response, $args) { - return $this->renderVmPage($response, $args, 'reinstall', '重装系统'); + $vmId = $this->vmId($args); + if ($vmId === null) { + return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302); + } + $actor = CloudAccess::actor(false); + $user = $request->getAttribute('auth_user') ?? Auth::getUser(); + try { + $vm = CloudInstancePageService::detailForActor($actor, $vmId); + } catch (CloudError $error) { + if ($error->httpStatus === 404) { + return $response->withHeader('Location', '/user/cloud/instances') + ->withStatus(302); + } + throw $error; + } + $vm = $this->reinstallVm($vm); + $catalog = CloudDeploymentPageService::templateCatalogForPage($actor); + $templates = is_array($catalog['templates'] ?? null) + ? $catalog['templates'] : []; + $catalogUnavailable = ($catalog['catalog_unavailable'] ?? false) === true; + $keys = $this->sshKeyOptions((int) $actor['user_id']); + $payload = [ + 'user' => $this->userBootstrap($user, $actor), + 'vm' => $vm, + 'templates' => $templates, + 'ssh_keys' => $keys, + 'catalog_unavailable' => $catalogUnavailable, + ]; + + return $this->render($response, 'reinstall', '重装系统', $vmId, '', [ + 'cloud_reinstall_vm' => $vm, + 'cloud_reinstall_template_groups' => CloudDeploymentPageService::templateGroups($templates), + 'cloud_reinstall_ssh_keys' => $keys, + 'cloud_reinstall_catalog_unavailable' => $catalogUnavailable, + 'cloud_reinstall_bootstrap_json' => $this->safeJson($payload), + ]); } public function rescue($request, $response, $args) @@ -139,8 +204,8 @@ final class CloudPageController private function renderVmPage($response, $args, $page, $title) { - $vmId = isset($args['id']) ? (string) $args['id'] : ''; - if (!preg_match('/^[1-9][0-9]*$/', $vmId)) { + $vmId = $this->vmId($args); + if ($vmId === null) { return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302); } @@ -173,6 +238,17 @@ final class CloudPageController $smarty->assign('cloud_vm_view', []); $smarty->assign('cloud_vm_scope_label', '我的实例'); $smarty->assign('cloud_vm_bootstrap_json', '{}'); + $smarty->assign('cloud_deploy_regions', []); + $smarty->assign('cloud_deploy_template_groups', []); + $smarty->assign('cloud_deploy_ssh_keys', []); + $smarty->assign('cloud_deploy_default_host_id', 0); + $smarty->assign('cloud_deploy_catalog_unavailable', false); + $smarty->assign('cloud_deploy_bootstrap_json', '{}'); + $smarty->assign('cloud_reinstall_vm', []); + $smarty->assign('cloud_reinstall_template_groups', []); + $smarty->assign('cloud_reinstall_ssh_keys', []); + $smarty->assign('cloud_reinstall_catalog_unavailable', false); + $smarty->assign('cloud_reinstall_bootstrap_json', '{}'); foreach ($values as $name => $value) { $smarty->assign($name, $value); } @@ -260,6 +336,35 @@ final class CloudPageController return $json === false ? '{}' : $json; } + private function vmId(array $args): ?string + { + $vmId = isset($args['id']) ? (string) $args['id'] : ''; + return preg_match('/^[1-9][0-9]*$/D', $vmId) === 1 ? $vmId : null; + } + + /** Deployment forms need only opaque key identifiers and user labels. */ + private function sshKeyOptions(int $userId): array + { + return array_map(static fn (array $key): array => [ + 'id' => $key['id'], + 'name' => $key['name'], + ], CloudDeploymentPageService::sshKeys($userId)); + } + + /** Keep reinstall bootstrap small and free of internal host identifiers. */ + private function reinstallVm(array $vm): array + { + $keys = [ + 'id', 'api_id', 'uuid', 'name', 'state', 'public_ip_cidr', 'public_ip', + 'instance_status', 'service_status', 'network_status', 'can_operate', + 'can_delete', 'is_owner', + ]; + $result = array_intersect_key($vm, array_flip($keys)); + $address = trim((string) ($result['public_ip_cidr'] ?? $result['public_ip'] ?? '')); + $result['public_ip'] = $address === '' ? '' : (explode('/', $address, 2)[0] ?: ''); + return $result; + } + private function vmListRow(array $vm): array { [$stateLabel, $stateClass] = $this->vmState((string) ($vm['state'] ?? 'unknown')); diff --git a/web/app/Services/Cloud/CloudDeploymentPageService.php b/web/app/Services/Cloud/CloudDeploymentPageService.php new file mode 100644 index 00000000..68dbca67 --- /dev/null +++ b/web/app/Services/Cloud/CloudDeploymentPageService.php @@ -0,0 +1,382 @@ +orderBy('sort')->orderBy('id')->get(); + $hostIds = $available->pluck('host_id')->map(static fn ($id): int => (int) $id) + ->filter(static fn (int $id): bool => $id > 0)->unique()->values()->all(); + $hosts = $hostIds === [] ? collect() : CloudHost::whereIn('id', $hostIds) + ->where('enabled', 1)->get(['id', 'name', 'country_code', 'region'])->keyBy('id'); + + foreach ($available as $plan) { + if ((int) $plan->stock === 0) { + continue; + } + $host = $hosts->get((int) $plan->host_id); + if ($host === null) { + continue; + } + $plans[] = [ + 'id' => (int) $plan->id, + 'name' => (string) $plan->name, + 'price' => (string) $plan->price, + 'cpu_cores' => (int) $plan->cpu_cores, + 'memory_mib' => (int) $plan->memory_mib, + 'bandwidth_mbps' => (int) $plan->bandwidth_mbps, + 'disk_gib' => (int) $plan->disk_gib, + 'validity_days' => (int) $plan->validity_days, + 'traffic_quota_bytes' => (int) $plan->traffic_quota_bytes, + 'traffic_gib' => $plan->trafficGiB(), + 'stock' => (int) $plan->stock, + 'host_id' => (int) $host->id, + 'host_name' => (string) $host->name, + 'country_code' => strtoupper(trim((string) ($host->country_code ?? ''))), + 'region' => trim((string) $host->region), + ]; + } + + return $plans; + } + + /** Plans embedded in user HTML omit the administrator-facing host label. */ + public static function publicPagePlans(): array + { + return array_map(static function (array $plan): array { + unset($plan['host_name']); + return $plan; + }, self::plans()); + } + + public static function regions(array $plans): array + { + $regions = []; + foreach ($plans as $plan) { + $hostId = max(0, (int) ($plan['host_id'] ?? 0)); + if ($hostId === 0) { + continue; + } + if (!isset($regions[$hostId])) { + $countryCode = strtoupper(trim((string) ($plan['country_code'] ?? ''))); + $regions[$hostId] = [ + 'host_id' => $hostId, + 'country_code' => $countryCode, + 'flag' => self::countryFlag($countryCode), + 'region' => trim((string) ($plan['region'] ?? '')) ?: '地区未设置', + 'plans' => [], + ]; + } + $regions[$hostId]['plans'][] = $plan; + } + + return array_values($regions); + } + + public static function sshKeys(int $userId): array + { + return CloudSSHKey::where('user_id', $userId)->orderBy('id')->get([ + 'id', 'name', 'fingerprint', 'created_at', + ])->map(static fn ($key): array => [ + 'id' => (int) $key->id, + 'name' => (string) $key->name, + 'fingerprint' => (string) $key->fingerprint, + 'created_at' => (int) $key->created_at, + ])->all(); + } + + /** + * Return a complete public catalog for SSR. A durable last-known snapshot + * avoids an engine dependency on every page view. On a fresh installation + * the first request waits briefly for the loopback engine and still returns + * one complete HTML response instead of an empty browser shell. + */ + public static function templateCatalogForPage(array $actor): array + { + $snapshot = self::templateSnapshot(); + if ($snapshot !== null + && time() - (int) $snapshot['checked_at'] < self::TEMPLATE_SNAPSHOT_REFRESH_SECONDS) { + return self::pageCatalog($snapshot); + } + + try { + return self::freshTemplateCatalog($actor, 2.0); + } catch (CloudError $error) { + error_log('Unable to refresh the public cloud template catalog: ' + . get_class($error)); + $snapshot ??= [ + 'version' => self::TEMPLATE_SNAPSHOT_VERSION, + 'updated_at' => 0, + 'templates' => [], + ]; + $snapshot['checked_at'] = time(); + $snapshot['refresh_failed'] = true; + self::saveTemplateSnapshot($snapshot); + return self::pageCatalog($snapshot); + } + } + + /** Fetch the authoritative engine-global catalog and refresh the snapshot. */ + public static function freshTemplateCatalog(array $actor, float $timeoutSeconds = 20.0): array + { + $payload = (new CloudEngineClient(null, $timeoutSeconds))->request( + 'GET', '/internal/v1/vm-templates', $actor + ); + $payload['templates'] = self::sanitizeTemplates($payload['templates'] ?? []); + self::rememberTemplateCatalog($payload); + return $payload; + } + + /** Persist only the public subset needed to draw an image picker. */ + public static function rememberTemplateCatalog(array $payload): void + { + $templates = self::sanitizeTemplates($payload['templates'] ?? []); + $snapshot = [ + 'version' => self::TEMPLATE_SNAPSHOT_VERSION, + 'updated_at' => time(), + 'checked_at' => time(), + 'refresh_failed' => false, + 'templates' => array_map(static fn (array $template): array => [ + 'id' => $template['id'], + 'name' => $template['name'], + 'os_family' => $template['os_family'], + 'os_version' => $template['os_version'], + ], $templates), + ]; + self::saveTemplateSnapshot($snapshot); + } + + private static function saveTemplateSnapshot(array $snapshot): void + { + $json = json_encode($snapshot, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES + | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR); + // configurations.value is TEXT. Refuse an accidental oversized write + // instead of truncating the JSON into a misleading partial catalog. + if (strlen($json) > 60000) { + error_log('Public cloud template catalog snapshot exceeds the storage limit'); + return; + } + + try { + $row = Configurations::where('name', self::TEMPLATE_SNAPSHOT_KEY)->first(); + if ($row === null) { + $row = new Configurations(); + $row->name = self::TEMPLATE_SNAPSHOT_KEY; + } + $row->value = $json; + $row->save(); + } catch (\Throwable $error) { + // A public API read must not fail merely because its optional + // first-paint snapshot could not be refreshed. + error_log('Unable to save the public cloud template catalog snapshot: ' + . get_class($error)); + } + } + + /** Update a cached rename/import result without ever fabricating a catalog. */ + public static function rememberTemplate(array $template): void + { + $snapshot = self::templateSnapshot(); + $records = self::sanitizeTemplates([$template]); + if ($snapshot === null || $records === []) { + return; + } + $replacement = $records[0]; + $templates = []; + $found = false; + foreach ($snapshot['templates'] as $existing) { + if ((string) $existing['id'] === (string) $replacement['id']) { + $templates[] = $replacement; + $found = true; + } else { + $templates[] = $existing; + } + } + if (!$found) { + $templates[] = $replacement; + } + self::rememberTemplateCatalog(['templates' => $templates]); + } + + public static function templateGroups(array $templates): array + { + $groups = []; + foreach (self::sanitizeTemplates($templates) as $template) { + [$family, $version] = self::templateSystem($template); + if (!isset($groups[$family])) { + $groups[$family] = [ + 'family' => $family, + 'icon_path' => self::templateIcon($family), + 'templates' => [], + ]; + } + $template['display_version'] = $version; + $groups[$family]['templates'][] = $template; + } + foreach ($groups as &$group) { + usort($group['templates'], static function (array $left, array $right): int { + $version = version_compare( + (string) ($right['display_version'] ?? '0'), + (string) ($left['display_version'] ?? '0') + ); + return $version !== 0 ? $version + : strnatcasecmp((string) $left['name'], (string) $right['name']); + }); + } + unset($group); + $order = ['AlmaLinux' => 0, 'Debian' => 1, 'CentOS Stream' => 2, 'Ubuntu' => 3]; + uasort($groups, static fn (array $left, array $right): int => + ($order[$left['family']] ?? 100) <=> ($order[$right['family']] ?? 100) + ?: strcasecmp($left['family'], $right['family'])); + + return array_values($groups); + } + + private static function templateSnapshot(): ?array + { + try { + $raw = Configurations::where('name', self::TEMPLATE_SNAPSHOT_KEY)->value('value'); + } catch (\Throwable $error) { + return null; + } + if (!is_string($raw) || $raw === '' || strlen($raw) > 65535) { + return null; + } + $decoded = json_decode($raw, true); + if (!is_array($decoded) || (int) ($decoded['version'] ?? 0) !== self::TEMPLATE_SNAPSHOT_VERSION + || !is_array($decoded['templates'] ?? null)) { + return null; + } + $templates = self::sanitizeTemplates($decoded['templates']); + // Do not accept a partially corrupted non-empty snapshot as an empty + // authoritative catalog; recover it from the engine instead. + if ($decoded['templates'] !== [] && $templates === []) { + return null; + } + return [ + 'version' => self::TEMPLATE_SNAPSHOT_VERSION, + 'updated_at' => max(0, (int) ($decoded['updated_at'] ?? 0)), + 'checked_at' => max(0, (int) ($decoded['checked_at'] + ?? $decoded['updated_at'] ?? 0)), + 'refresh_failed' => ($decoded['refresh_failed'] ?? false) === true, + 'templates' => $templates, + ]; + } + + private static function pageCatalog(array $snapshot): array + { + $templates = is_array($snapshot['templates'] ?? null) + ? $snapshot['templates'] : []; + $failed = ($snapshot['refresh_failed'] ?? false) === true; + return [ + 'templates' => $templates, + 'catalog_stale' => $failed && $templates !== [], + 'catalog_unavailable' => $failed && $templates === [], + ]; + } + + private static function sanitizeTemplates($values): array + { + if (!is_array($values)) { + return []; + } + $templates = []; + foreach (array_slice($values, 0, 256) as $value) { + if (!is_array($value)) { + continue; + } + $id = $value['id'] ?? null; + $name = $value['name'] ?? null; + $family = $value['os_family'] ?? ''; + $version = $value['os_version'] ?? ''; + if (!is_string($id) + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D', $id) !== 1 + || !self::plainLabel($name, 64) + || !self::plainLabel($family, 40) + || !is_string($version) + || preg_match('/^[0-9]{1,4}(?:\.[0-9]{1,4}){0,2}$/D', $version) !== 1) { + continue; + } + $templates[$id] = [ + 'id' => $id, + 'name' => trim($name), + 'os_family' => trim($family), + 'os_version' => $version, + ]; + } + return array_values($templates); + } + + private static function plainLabel($value, int $maximum): bool + { + return is_string($value) && trim($value) !== '' && mb_strlen($value) <= $maximum + && preg_match('//u', $value) === 1 + && preg_match('/[\x00-\x1F\x7F]/u', $value) !== 1; + } + + private static function templateSystem(array $template): array + { + $familyKey = strtolower((string) preg_replace( + '/[\s_-]+/', '', (string) ($template['os_family'] ?? '') + )); + $family = [ + 'alma' => 'AlmaLinux', 'almalinux' => 'AlmaLinux', + 'debian' => 'Debian', 'centos' => 'CentOS Stream', + 'centosstream' => 'CentOS Stream', 'ubuntu' => 'Ubuntu', + ][$familyKey] ?? ''; + $idVersion = ''; + if (preg_match('/^(alma|debian|ubuntu|centosstream)([0-9]{1,4})-/i', + (string) $template['id'], $match) === 1) { + $family = $family ?: [ + 'alma' => 'AlmaLinux', 'debian' => 'Debian', + 'ubuntu' => 'Ubuntu', 'centosstream' => 'CentOS Stream', + ][strtolower($match[1])]; + $idVersion = $match[2]; + if (strtolower($match[1]) === 'ubuntu' && strlen($idVersion) === 4) { + $idVersion = substr($idVersion, 0, 2) . '.' . substr($idVersion, 2); + } + } + return [ + $family ?: '其他系统', + (string) ($template['os_version'] ?: $idVersion), + ]; + } + + private static function templateIcon(string $family): string + { + return [ + 'AlmaLinux' => '/cloud/almalinux-icon.svg', + 'Debian' => '/cloud/debian-icon.svg', + 'CentOS Stream' => '/cloud/centos-icon.svg', + 'Ubuntu' => '/cloud/ubuntu-icon.svg', + ][$family] ?? ''; + } + + private static function countryFlag(string $countryCode): string + { + if (preg_match('/^[A-Z]{2}$/D', $countryCode) !== 1) { + return '🌐'; + } + return mb_chr(127397 + ord($countryCode[0]), 'UTF-8') + . mb_chr(127397 + ord($countryCode[1]), 'UTF-8'); + } +} diff --git a/web/public/cloud/deploy.js b/web/public/cloud/deploy.js index a69457cd..f2436eb5 100644 --- a/web/public/cloud/deploy.js +++ b/web/public/cloud/deploy.js @@ -3,14 +3,15 @@ const assetVersion = new URL(import.meta.url).searchParams.get('v'); if (assetVersion) runtimeUrl.searchParams.set('v', assetVersion); const { bindPageCleanup, buy, byId, initializeSession, openCreate, - showError, + readBootstrap, showError, } = await import(runtimeUrl.href); export async function initialize() { try { - if (!await initializeSession('create')) return; + const bootstrap = readBootstrap('deploy-bootstrap'); + if (!await initializeSession('create', bootstrap?.user)) return; bindPageCleanup(); byId('create-form')?.addEventListener('submit', buy); - await openCreate(); + await openCreate(bootstrap); } catch (error) { showError('cloud-page-error', error.message); } } diff --git a/web/public/cloud/reinstall.js b/web/public/cloud/reinstall.js index c5407d0f..d269494d 100644 --- a/web/public/cloud/reinstall.js +++ b/web/public/cloud/reinstall.js @@ -3,15 +3,16 @@ const assetVersion = new URL(import.meta.url).searchParams.get('v'); if (assetVersion) runtimeUrl.searchParams.set('v', assetVersion); const { bindPageCleanup, byId, initializeSession, openReinstall, reinstall, - selectVmByApiId, showError, + readBootstrap, selectVmByApiId, showError, } = await import(runtimeUrl.href); export async function initialize() { try { - if (!await initializeSession('reinstall')) return; + const bootstrap = readBootstrap('reinstall-bootstrap'); + if (!await initializeSession('reinstall', bootstrap?.user)) return; bindPageCleanup(); - const vm = await selectVmByApiId(document.body.dataset.vmId || ''); + const vm = await selectVmByApiId(document.body.dataset.vmId || '', bootstrap?.vm); byId('reinstall-form')?.addEventListener('submit', reinstall); - await openReinstall(vm); + await openReinstall(vm, bootstrap); } catch (error) { showError('cloud-page-error', error.message); } } diff --git a/web/public/cloud/runtime.js b/web/public/cloud/runtime.js index 73086dc8..bd260556 100644 --- a/web/public/cloud/runtime.js +++ b/web/public/cloud/runtime.js @@ -1,7 +1,7 @@ // PHP owns authentication, authorisation, ownership and purchasing. No engine // address, token, host credential or unrestricted create API exists in this UI. const byId = (id) => document.getElementById(id); -const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], plans: [], sshKeys: [], templates: [], resources: null, selectedRegionHostId: '', invoices: [], invoicePage: 1, invoicePagination: { page: 1, per_page: 10, total: 0, total_pages: 1, has_previous: false, has_next: false, from: 0, to: 0 }, invoiceLoading: false, invoiceLoadPromise: null, invoicePaymentMethods: [], invoiceBalance: '0.00', selectedInvoice: null, selectedInvoicePaymentMethod: '', invoiceJobProgress: new Map(), invoicePollTimers: new Map(), view: 'list', selectedVmId: null, detailTab: 'operations', metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, trafficDailyPayload: null, trafficDailyVmId: '', trafficDailyRequest: null, trafficDailyResizeTimer: null, trafficDailyLoadedAt: 0, credentialPassword: '', credentialVisible: false, credentialTimer: null, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, resourceController: null, mutationBusy: false, provisionIdempotency: '', provisionFingerprint: '', rescueActive: false, rescueStaged: false }; +const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], plans: [], regions: [], sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionHostId: '', invoices: [], invoicePage: 1, invoicePagination: { page: 1, per_page: 10, total: 0, total_pages: 1, has_previous: false, has_next: false, from: 0, to: 0 }, invoiceLoading: false, invoiceLoadPromise: null, invoicePaymentMethods: [], invoiceBalance: '0.00', selectedInvoice: null, selectedInvoicePaymentMethod: '', invoiceJobProgress: new Map(), invoicePollTimers: new Map(), view: 'list', selectedVmId: null, detailTab: 'operations', metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, trafficDailyPayload: null, trafficDailyVmId: '', trafficDailyRequest: null, trafficDailyResizeTimer: null, trafficDailyLoadedAt: 0, credentialPassword: '', credentialVisible: false, credentialTimer: null, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, resourceController: null, mutationBusy: false, provisionIdempotency: '', provisionFingerprint: '', rescueActive: false, rescueStaged: false }; // Keep the historical storage key so an interrupted deployment made just // before an online update can still reconcile to the same opening invoice. const PROVISION_INVOICE_STORAGE_PREFIX = 'virt-cloud:pending-order:'; @@ -17,6 +17,19 @@ const invoicePagePath = (id) => `${CLOUD_PATHS.invoices}/${encodeURIComponent(St const navigate = (path) => location.assign(path); const text = (id, value) => { byId(id).textContent = value ?? '—'; }; const items = (payload) => Array.isArray(payload) ? payload : Array.isArray(payload?.items) ? payload.items : Array.isArray(payload?.plans) ? payload.plans : Array.isArray(payload?.templates) ? payload.templates : Array.isArray(payload?.keys) ? payload.keys : Array.isArray(payload?.vms) ? payload.vms : []; +function readBootstrap(id) { + const source = byId(id); + if (!source) return null; + let payload; + try { payload = JSON.parse(source.textContent || '{}'); } + catch { throw new Error('页面初始数据无效,请刷新后重试。'); } + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error('页面初始数据缺失,请刷新后重试。'); + return payload; +} +function bootstrapItems(payload, ...names) { + for (const name of names) if (Array.isArray(payload?.[name])) return payload[name]; + return []; +} function showError(id, message) { text(id, message); byId(id).hidden = !message; } let toastTimer; function toast(message, kind = '') { const element = byId('toast'); element.textContent = message; element.className = `toast ${kind}`; element.hidden = false; clearTimeout(toastTimer); toastTimer = setTimeout(() => { element.hidden = true; }, 5000); } @@ -340,6 +353,15 @@ function flagForCountry(code) { } function saleRegions() { const regions = new Map(); + for (const region of state.regions) { + const hostId = String(region?.host_id ?? region?.id ?? ''); + if (!/^\d+$/.test(hostId) || regions.has(hostId)) continue; + regions.set(hostId, { + hostId, + countryCode: String(region.country_code || '').trim().toUpperCase(), + region: String(region.region || region.name || '地区未设置').trim() || '地区未设置', + }); + } for (const plan of state.plans) { const hostId = String(plan?.host_id || ''); if (!/^\d+$/.test(hostId) || regions.has(hostId)) continue; @@ -477,9 +499,39 @@ async function selectPlan(planId) { showError('create-error', ''); updateCreateAvailability(); } -async function openCreate() { +async function openCreate(bootstrap = null) { state.view = 'create'; state.selectedVmId = null; showError('create-error', ''); - state.selectedRegionHostId = ''; byId('vm-region-host').value = ''; byId('vm-plan').value = ''; + byId('vm-plan').value = ''; + if (bootstrap && Array.isArray(bootstrap.plans) && Array.isArray(bootstrap.templates)) { + state.regions = bootstrapItems(bootstrap, 'regions'); + state.plans = bootstrapItems(bootstrap, 'plans'); + if (!state.plans.length) state.plans = state.regions.flatMap(region => Array.isArray(region?.plans) ? region.plans : []); + state.templates = bootstrapItems(bootstrap, 'templates', 'cloud_templates'); + state.templateCatalogUnavailable = bootstrap.catalog_unavailable === true; + state.sshKeys = bootstrapItems(bootstrap, 'ssh_keys', 'keys'); + state.resources = { templates: state.templates }; + state.selectedKeys.create = ''; + const regions = saleRegions(); + const requestedDefault = bootstrap.default_host_id ?? bootstrap.default_region?.host_id ?? bootstrap.default_region; + const requestedHostId = String(requestedDefault ?? ''); + state.selectedRegionHostId = regions.some(region => region.hostId === requestedHostId) + ? requestedHostId : (regions[0]?.hostId || ''); + byId('vm-region-host').value = state.selectedRegionHostId; + renderRegionPicker(); + renderPlanPicker(); + renderTemplateCatalog('vm-template'); + renderKeyCards('create'); + byId('vm-template').disabled = !state.templates.some(item => item?.id); + byId('vm-name').disabled = false; + byId('vm-root-password').disabled = false; + setDeploymentStepEnabled('vm-plan-step', Boolean(state.selectedRegionHostId)); + setDeploymentStepEnabled('vm-source-step', true); + setDeploymentStepEnabled('vm-config-step', true); + updateCreateAvailability(); + return; + } + state.regions = []; + state.selectedRegionHostId = ''; byId('vm-region-host').value = ''; setDeploymentStepEnabled('vm-plan-step', false); resetInstallChoices(); const results = await Promise.allSettled([ api('/api/v1/plans').then(plans => { state.plans = items(plans); renderRegionPicker(); }), @@ -499,6 +551,7 @@ async function loadGlobalTemplates() { const resources = await api('/api/v1/resources', { signal: controller.signal }); if (controller !== state.resourceController) return; state.resources = resources; + state.templateCatalogUnavailable = false; state.templates = items(resources.templates || resources.cloud_templates); renderTemplateCatalog('vm-template'); byId('vm-template').disabled = !state.templates.some(item => item?.id); @@ -1184,9 +1237,27 @@ async function loadInvoices(page = state.invoicePage) { renderInvoicePagination(); } } -async function openReinstall(vm) { - if (!vm?.can_operate) return toast('实例服务已到期或正在执行策略,日常操作暂不可用。', 'error'); +async function openReinstall(vm, bootstrap = null) { state.view = 'reinstall'; text('reinstall-subtitle', `${vm.name} · 保留原有公网网络参数,重新创建系统盘。`); text('reinstall-public-ip', vmIp(vm)); byId('reinstall-confirm-name').value = ''; byId('reinstall-root-password').value = ''; byId('reinstall-template').value = ''; showError('reinstall-error', ''); byId('reinstall-progress').hidden = true; byId('reinstall-result').hidden = true; byId('reinstall-fields').hidden = false; + if (!vm?.can_operate) { + byId('reinstall-fields').inert = true; + byId('reinstall-fields').setAttribute('aria-disabled', 'true'); + byId('reinstall-submit').disabled = true; + showError('reinstall-error', '实例服务已到期或正在执行策略,当前不能重装系统。'); + return; + } + byId('reinstall-fields').inert = false; + byId('reinstall-fields').removeAttribute('aria-disabled'); + byId('reinstall-submit').disabled = false; + if (bootstrap && Array.isArray(bootstrap.templates)) { + state.templates = bootstrapItems(bootstrap, 'templates', 'cloud_templates'); + state.templateCatalogUnavailable = bootstrap.catalog_unavailable === true; + state.sshKeys = bootstrapItems(bootstrap, 'ssh_keys', 'keys'); + state.selectedKeys.reinstall = ''; + renderTemplateCatalog('reinstall-template'); + renderKeyCards('reinstall'); + return; + } try { const resources = await api(`/api/v1/resources?vm_id=${encodeURIComponent(vm.api_id)}`); state.templates = items(resources.templates || resources.cloud_templates); renderTemplateCatalog('reinstall-template'); await loadKeys(); } catch (error) { showError('reinstall-error', error.message); } } async function pollJob(kind, id, phaseId, errorId) { @@ -1922,9 +1993,12 @@ function renderTemplateCatalog(inputId) { } if (!groups.size) { input.value = ""; - container.replaceChildren(makeElement("p", "template-catalog-empty", state.admin - ? "暂无云镜像,请先到“云镜像模板”页面导入。" - : "暂无可用云镜像,请联系管理员导入模板。")); + container.replaceChildren(makeElement("p", "template-catalog-empty", + state.templateCatalogUnavailable + ? "系统镜像目录暂时无法读取,请稍后刷新。" + : state.admin + ? "暂无云镜像,请先到“云镜像模板”页面导入。" + : "暂无可用云镜像,请联系管理员导入模板。")); return; } if (!state.templates.some((item) => String(item.id) === input.value)) input.value = ""; @@ -1965,8 +2039,14 @@ function renderTemplateCatalog(inputId) { } container.replaceChildren(...cards); } -async function initializeSession(view) { +async function initializeSession(view, bootstrapUser = null) { state.view = view; + if (bootstrapUser && typeof bootstrapUser === 'object') { + if (bootstrapUser.authenticated === false) { location.assign('/auth/login'); return false; } + applyCloudUser(bootstrapUser); + byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout')); + return true; + } const session = await api('/api/v1/session'); if (session.authenticated === false) { location.assign('/auth/login'); return false; } applyCloudUser(session); @@ -1974,7 +2054,14 @@ async function initializeSession(view) { return true; } -async function selectVmByApiId(apiId) { +async function selectVmByApiId(apiId, bootstrapVm = null) { + if (bootstrapVm && typeof bootstrapVm === 'object') { + const vm = normalizeVm(bootstrapVm); + if (!vm.api_id || String(vm.api_id) !== String(apiId || '')) throw new Error('实例初始数据与当前地址不匹配,请刷新后重试。'); + state.vms = [vm]; + state.selectedVmId = vm.uuid; + return vm; + } const vm = await loadVm(apiId, true); if (!vm) throw new Error('虚拟机不存在或当前账户无权访问。'); return vm; @@ -1997,7 +2084,7 @@ export { drawVmTrafficDaily, hydrateVmDetailBootstrap, initializeSession, invoicePagePath, loadGlobalTemplates, loadInvoiceDetail, loadInvoices, loadKeys, loadVmMetrics, loadVmTrafficDaily, loadVm, loadVmStatus, loadVms, navigate, openCreate, openReinstall, openRescue, reinstall, - renderVMs, renderVmDetail, renderVmMetrics, rescueAction, selectVmByApiId, selectedVm, + readBootstrap, renderVMs, renderVmDetail, renderVmMetrics, rescueAction, selectVmByApiId, selectedVm, scheduleInvoicePoll, setVmDetailTab, showError, state, stopInvoicePoll, stopVmMetrics, stopVmTrafficDaily, toast, trafficDailyViewVisible, vmIp, vmPagePath, diff --git a/web/resources/views/venix/cloud/pages/deploy.tpl b/web/resources/views/venix/cloud/pages/deploy.tpl index 2e5c8bf0..f7df7eeb 100644 --- a/web/resources/views/venix/cloud/pages/deploy.tpl +++ b/web/resources/views/venix/cloud/pages/deploy.tpl @@ -6,23 +6,73 @@
暂无可部署地区,请联系管理员配置在售商品。
+ {else} + {foreach $cloud_deploy_regions as $region} + + {/foreach} + {/if} +请先选择地区。
当前地区暂无可用实例规格。
{/if} +{if !empty($cloud_deploy_catalog_unavailable)}系统镜像目录暂时无法读取,请稍后刷新。{else}暂无可用云镜像,请联系管理员导入模板。{/if}
+ {else} + {foreach $cloud_deploy_template_groups as $group} +保留原有公网网络参数,重新创建系统盘。
{$cloud_reinstall_vm.name|default:'实例'|escape:"html"} · 保留原有公网网络参数,重新创建系统盘。