diff --git a/docs/PORTABLE_VM_BACKUPS.md b/docs/PORTABLE_VM_BACKUPS.md index 51d77a5f..e3d81a79 100644 --- a/docs/PORTABLE_VM_BACKUPS.md +++ b/docs/PORTABLE_VM_BACKUPS.md @@ -1,4 +1,4 @@ -# 可移植虚拟机备份与新实例恢复 +# 可移植虚拟机备份、云快照与新实例恢复 管理员可在虚拟机管理页为面板创建的云镜像实例生成一个完整系统盘备份,并把该备份直接上传到后台已验证的 S3 兼容对象存储。恢复不会修改或替换源实例,而是在选定的合格宿主机上创建一个独立实例;目标可以是原宿主机,也可以是其他宿主机。 @@ -18,7 +18,17 @@ 调度只在订阅已开启且计划执行时间落入已支付权益时运行,并在创建备份的事务内再次核对。用户可以选择每天或每周在 UTC 00:00 执行,保留上限为两份。关闭会立即停止新自动备份并从下一张续费账单移除备份费用,不退还当前周期费用,也不删除当前已付权益或已有备份;同一已付周期重新开启不重复收费。续费成功后会为新服务周期写入独立权益,历史部署快照不作为当前计费授权。 -用户只能在源实例的设置页把自动备份恢复到原实例;全局“云备份”页面可以从已有备份创建新实例。自动备份当前仍是完整系统盘对象,不是增量链。 +用户只能在源实例的设置页把自动备份恢复到原实例;全局“云备份”页面不再直接创建实例,只能把仍处恢复期限内的可用备份保存为云快照。自动备份当前仍是完整系统盘对象,不是增量链。 + +## 用户云快照 + +云快照是从一份自动备份转换出的长期部署来源。转换只在数据库中转移不可变对象的业务归属,不复制或重新上传 qcow2;转换成功后,该 backing backup 不再出现在自动备份列表,也不会被保留份数轮换或权益到期清理。每个用户最多保留两份云快照,只有用户手动删除后才会释放其对象存储数据。 + +用户不能把普通云备份编号直接提交到开通接口。从云快照创建实例必须使用本人名下的公开快照键;生成账单和余额付款时都会重新锁定快照与 backing backup,并核对对象键、大小、虚拟容量、SHA-256 和冻结存储身份。未支付或正在交付的订单,以及效果未知或最终化异常的任务,会阻止删除云快照;安全终态订单不会永久占用删除围栏。 + +云快照可以重复用于创建新的付费实例。新实例使用用户当次选择的销售方案,系统盘容量不得小于快照虚拟容量,并获得新的 UUID、MAC、公网 IP、订单、服务期和流量周期;它不继承源实例的订单、到期时间、续费价格或流量用量。 + +云快照开通时以备份系统盘中的实际密码为准,不重新注入备份时面板保存的历史密码。由于面板无法确认用户是否已在来宾系统内手工改密,新实例不显示可能失效的历史密码。已转为云快照的 backing backup 也不计入滚动自动备份的保留数,不会阻止后续自动备份。 ## 恢复为新实例 @@ -30,7 +40,7 @@ 控制面先在同一数据库事务内预留目标容量和新公网 IP,再派发恢复。Agent 校验下载对象的精确字节数和 SHA-256,创建新的 UUID、MAC、seed、NVRAM、网络过滤器和流量状态,并把新公网地址写入使用 `br0` 的 cloud-init 网络配置。它不会复用源 IP,也不会复制原 Domain XML。 -恢复实例保留备份时冻结的 CPU、内存、系统盘、带宽及系统兼容元数据,归属原用户,但不继承订单、账单、套餐、服务期、到期时间或流量周期;后台将其标记为免计费实例,后续商业化前需要另行定义计费迁移策略。 +管理员从普通备份执行“独立恢复”时,恢复实例保留备份时冻结的 CPU、内存、系统盘、带宽及系统兼容元数据,归属原用户,但不继承订单、账单、套餐、服务期、到期时间或流量周期;后台将其标记为免计费实例。用户从云快照创建实例则走正常付费开通流程,使用当次选择的套餐规格和独立服务周期。 ## 维护迁移 diff --git a/web/app/Command/CloudSetup.php b/web/app/Command/CloudSetup.php index 8a8564ca..7a4ecc30 100644 --- a/web/app/Command/CloudSetup.php +++ b/web/app/Command/CloudSetup.php @@ -8,7 +8,7 @@ use App\Services\Config; /** Initializes only the clean-break PHP business and Agent log schemas. */ final class CloudSetup { - private const SCHEMA_VERSION = 'go-agent-wss-v9-backup-utc-schedule'; + private const SCHEMA_VERSION = 'go-agent-wss-v10-deployment-snapshots'; private const MAIN_TABLES = [ 'cloud_regions', 'cloud_network_lines', 'cloud_resource_pools', 'cloud_hosts', 'cloud_host_agents', @@ -24,7 +24,7 @@ final class CloudSetup 'cloud_platform_test_policy_state', 'cloud_platform_test_policy_rules', 'cloud_instance_snapshots', 'cloud_backup_subscriptions', 'cloud_backup_period_entitlements', - 'cloud_instance_backups', + 'cloud_instance_backups', 'cloud_deployment_snapshots', 'cloud_backup_restores', 'cloud_backup_recoveries', 'cloud_instance_migrations', 'cloud_migration_bundle_artifacts', 'cloud_instance_runtime', 'cloud_orders', 'cloud_order_items', @@ -90,6 +90,15 @@ final class CloudSetup 'last_operation_id', 'error_code', 'ready_at', 'created_at', 'updated_at', ], + 'cloud_deployment_snapshots' => [ + 'id', 'snapshot_key', 'user_id', 'backup_id', + 'source_instance_id', 'name', 'state', 'idempotency_key', + 'request_hash', 'error_code', 'ready_at', 'deleted_at', + 'created_at', 'updated_at', + ], + 'cloud_orders' => [ + 'deployment_snapshot_id', + ], 'cloud_backup_restores' => [ 'id', 'restore_key', 'backup_id', 'target_host_id', 'target_instance_id', 'reservation_id', 'job_id', 'operation_id', @@ -164,6 +173,9 @@ final class CloudSetup 'chk_cloud_backup_entitlement_source', 'chk_cloud_backup_entitlement_window', ], + 'cloud_deployment_snapshots' => [ + 'chk_cloud_deployment_snapshot_state', + ], 'cloud_invoice_payments' => [ 'chk_cloud_invoice_payment_status', ], @@ -212,6 +224,16 @@ final class CloudSetup 'cloud_instance_backup_source', 'cloud_instance_backup_owner', 'cloud_instance_backup_operation', ], + 'cloud_deployment_snapshots' => [ + 'PRIMARY', 'cloud_deployment_snapshot_key', + 'cloud_deployment_snapshot_backup', + 'cloud_deployment_snapshot_request', + 'cloud_deployment_snapshot_owner', + 'cloud_deployment_snapshot_source', + ], + 'cloud_orders' => [ + 'cloud_order_deployment_snapshot', + ], 'cloud_backup_restores' => [ 'PRIMARY', 'cloud_backup_restore_key', 'cloud_backup_restore_operation', diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php index 631c168f..ae4e8e5e 100644 --- a/web/app/Controllers/CloudApiController.php +++ b/web/app/Controllers/CloudApiController.php @@ -17,6 +17,7 @@ use App\Services\Cloud\CloudAutomaticBackupBillingService; use App\Services\Cloud\CloudAutomaticBackupService; use App\Services\Cloud\CloudBackupService; use App\Services\Cloud\CloudDeploymentPageService; +use App\Services\Cloud\CloudDeploymentSnapshotService; use App\Services\Cloud\CloudAgentSettingsService; use App\Services\Cloud\CloudConsoleTicketService; use App\Services\Cloud\CloudError; @@ -1044,6 +1045,55 @@ final class CloudApiController )); } + public function cloudSnapshots($request, $response) + { + $actor = $this->actor($request); + if ($request->getMethod() === 'GET') { + return $this->json( + $response, + CloudDeploymentSnapshotService::library( + $actor, + $request->getQueryParams() + ) + ); + } + $body = CloudInput::object($request); + CloudInput::only($body, [ + 'backup_id', 'name', 'idempotency_key', + ]); + $backupId = filter_var( + $body['backup_id'] ?? null, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]] + ); + if ($backupId === false) { + throw new CloudError('请选择可用的云备份'); + } + unset($body['backup_id']); + $snapshot = CloudDeploymentSnapshotService::promote( + (int) $backupId, + $body, + $actor + ); + return $this->json($response, [ + 'snapshot' => CloudDeploymentSnapshotService::deploymentSource( + (string) $snapshot->snapshot_key, + $actor + ), + ], 201); + } + + public function deleteCloudSnapshot($request, $response, $args) + { + $snapshotKey = (string) ($args['snapshot_key'] ?? ''); + return $this->json($response, [ + 'snapshot' => CloudDeploymentSnapshotService::delete( + $snapshotKey, + $this->actor($request) + ), + ]); + } + /** Read or replace the paid instance automatic-backup policy. */ public function automaticBackup($request, $response, $args) { diff --git a/web/app/Controllers/CloudPageController.php b/web/app/Controllers/CloudPageController.php index dfe26f92..f611b946 100644 --- a/web/app/Controllers/CloudPageController.php +++ b/web/app/Controllers/CloudPageController.php @@ -7,6 +7,7 @@ use App\Services\Auth; use App\Services\Cloud\CloudAccess; use App\Services\Cloud\CloudAutomaticBackupService; use App\Services\Cloud\CloudDeploymentPageService; +use App\Services\Cloud\CloudDeploymentSnapshotService; use App\Services\Cloud\CloudError; use App\Services\Cloud\CloudInstancePageService; use App\Services\Cloud\CloudInvoiceDetailPageService; @@ -86,6 +87,28 @@ final class CloudPageController { $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); + $cloudSnapshot = null; + $snapshotKey = $request->getQueryParams()['cloud_snapshot'] ?? null; + if ($snapshotKey !== null && $snapshotKey !== '') { + if (!is_string($snapshotKey)) { + return $response->withHeader( + 'Location', '/user/cloud/cloud-snapshots' + )->withStatus(302); + } + try { + $cloudSnapshot = + CloudDeploymentSnapshotService::deploymentSource( + $snapshotKey, $actor + ); + } catch (CloudError $error) { + if (in_array($error->httpStatus, [400, 404, 409], true)) { + return $response->withHeader( + 'Location', '/user/cloud/cloud-snapshots' + )->withStatus(302); + } + throw $error; + } + } $saleCatalog = CloudDeploymentPageService::saleCatalog(); $regions = $saleCatalog['regions']; $lines = $saleCatalog['lines']; @@ -121,6 +144,7 @@ final class CloudPageController 'default_region_id' => $defaultRegionId, 'default_line_id' => $defaultLineId, 'catalog_unavailable' => $catalogUnavailable, + 'cloud_snapshot' => $cloudSnapshot, ]; return $this->render($response, 'deploy', '部署实例', '', '', [ @@ -155,6 +179,29 @@ final class CloudPageController ]); } + public function cloudSnapshots($request, $response, $args) + { + $actor = CloudAccess::actor(false); + $user = $request->getAttribute('auth_user') ?? Auth::getUser(); + $page = $this->pageNumber( + $request->getQueryParams()['page'] ?? '1' + ); + $payload = CloudDeploymentSnapshotService::library( + $actor, + ['page' => $page, 'per_page' => 20] + ); + $payload['user'] = $this->userBootstrap($user, $actor); + + return $this->render( + $response, + 'cloud-snapshots', + '云快照', + '', + '', + ['cloud_snapshot_bootstrap_json' => $this->safeJson($payload)] + ); + } + public function isoImages($request, $response, $args) { if (!CloudUserIsoFeature::enabled()) { @@ -319,6 +366,7 @@ final class CloudPageController $smarty->assign('cloud_deploy_catalog_unavailable', false); $smarty->assign('cloud_deploy_bootstrap_json', '{}'); $smarty->assign('cloud_backup_bootstrap_json', '{}'); + $smarty->assign('cloud_snapshot_bootstrap_json', '{}'); $smarty->assign('cloud_ssh_keys', []); $smarty->assign('cloud_ssh_keys_bootstrap_json', '{}'); $smarty->assign('cloud_reinstall_vm', []); diff --git a/web/app/Models/CloudDeploymentSnapshot.php b/web/app/Models/CloudDeploymentSnapshot.php new file mode 100644 index 00000000..44d8c9f1 --- /dev/null +++ b/web/app/Models/CloudDeploymentSnapshot.php @@ -0,0 +1,21 @@ + 'int', + 'user_id' => 'int', + 'backup_id' => 'int', + 'source_instance_id' => 'int', + 'ready_at' => 'int', + 'deleted_at' => 'int', + 'created_at' => 'int', + 'updated_at' => 'int', + ]; +} diff --git a/web/app/Models/CloudOrder.php b/web/app/Models/CloudOrder.php index 2ee94dab..24405b29 100644 --- a/web/app/Models/CloudOrder.php +++ b/web/app/Models/CloudOrder.php @@ -12,6 +12,7 @@ final class CloudOrder extends Model 'resource_pool_id' => 'int', 'host_id' => 'int', 'reservation_id' => 'int', + 'deployment_snapshot_id' => 'int', 'amount' => 'decimal:2', 'instance_id' => 'int', 'refunded_at' => 'int', diff --git a/web/app/Services/Cloud/CloudAutomaticBackupService.php b/web/app/Services/Cloud/CloudAutomaticBackupService.php index 8561dbf6..cf24b4c1 100644 --- a/web/app/Services/Cloud/CloudAutomaticBackupService.php +++ b/web/app/Services/Cloud/CloudAutomaticBackupService.php @@ -234,6 +234,7 @@ final class CloudAutomaticBackupService $query = CloudInstanceBackup::where('user_id', $userId) ->where('purpose', 'portable')->where('source', 'automatic') ->where('state', '<>', 'deleted'); + self::withoutDeploymentSnapshots($query); $total = (int) (clone $query)->count('id'); $pages = max(1, (int) ceil($total / $perPage)); $page = min($page, $pages); @@ -326,7 +327,9 @@ final class CloudAutomaticBackupService $pending = CloudInstanceBackup::where('source', 'automatic') ->where('purpose', 'portable') ->whereIn('state', ['deleting', 'delete_uncertain']) - ->orderBy('id')->limit($limit)->get(); + ->orderBy('id'); + self::withoutDeploymentSnapshots($pending); + $pending = $pending->limit($limit)->get(); foreach ($pending as $backup) { try { $result = CloudBackupService::delete( @@ -383,7 +386,10 @@ final class CloudAutomaticBackupService 'cloud_instance_backups.subscription_id' )->where('cloud_backup_period_entitlements.ends_at', '>', $cutoff); - })->orderBy('id')->limit($limit - $processed)->get(); + }); + self::withoutDeploymentSnapshots($expired); + $expired = $expired->orderBy('id') + ->limit($limit - $processed)->get(); foreach ($expired as $backup) { try { $result = CloudBackupService::delete( @@ -408,7 +414,11 @@ final class CloudAutomaticBackupService . 'cloud_backup_subscriptions.id ' . "AND cloud_instance_backups.source = 'automatic' " . "AND cloud_instance_backups.purpose = 'portable' " - . "AND cloud_instance_backups.state = 'ready') " + . "AND cloud_instance_backups.state = 'ready' " + . 'AND NOT EXISTS (SELECT 1 FROM cloud_deployment_snapshots ' + . 'WHERE cloud_deployment_snapshots.backup_id = ' + . 'cloud_instance_backups.id ' + . "AND cloud_deployment_snapshots.state <> 'deleted')) " . '> cloud_backup_subscriptions.retention_count' )->orderBy('id')->limit($limit - $processed)->get(); foreach ($subscriptions as $subscription) { @@ -418,8 +428,9 @@ final class CloudAutomaticBackupService $ready = CloudInstanceBackup::where( 'subscription_id', (int) $subscription->id )->where('source', 'automatic')->where('purpose', 'portable') - ->where('state', 'ready')->orderBy('scheduled_for') - ->orderBy('id')->get(); + ->where('state', 'ready'); + self::withoutDeploymentSnapshots($ready); + $ready = $ready->orderBy('scheduled_for')->orderBy('id')->get(); $excess = max(0, $ready->count() - min(self::MAX_RETENTION, max(1, (int) $subscription->retention_count))); @@ -591,7 +602,15 @@ final class CloudAutomaticBackupService 'source_instance_id', (int) $instance->id )->where('user_id', (int) $instance->user_id) ->where('purpose', 'portable')->where('source', 'automatic') - ->where('state', '<>', 'deleted')->orderByDesc('id')->get() + ->where('state', '<>', 'deleted') + ->whereNotExists(static function ($query): void { + $query->selectRaw('1')->from('cloud_deployment_snapshots') + ->whereColumn( + 'cloud_deployment_snapshots.backup_id', + 'cloud_instance_backups.id' + )->where('cloud_deployment_snapshots.state', '<>', + 'deleted'); + })->orderByDesc('id')->get() as $backup) { $items[] = self::displayBackup($backup, $instance); } @@ -629,11 +648,23 @@ final class CloudAutomaticBackupService && $instance !== null && (string) $instance->status !== 'deleted' && self::withinRecoveryGrace($backup), - 'can_create_instance' => $state === 'ready' + 'can_promote' => $state === 'ready' && self::withinRecoveryGrace($backup), ]; } + /** Exclude immutable objects now owned by the deployment-snapshot ledger. */ + private static function withoutDeploymentSnapshots($query): void + { + $query->whereNotExists(static function ($subquery): void { + $subquery->selectRaw('1')->from('cloud_deployment_snapshots') + ->whereColumn( + 'cloud_deployment_snapshots.backup_id', + 'cloud_instance_backups.id' + )->where('cloud_deployment_snapshots.state', '<>', 'deleted'); + }); + } + /** A paid period remains recoverable until three days after its end. */ public static function withinRecoveryGrace(CloudInstanceBackup $backup, ?int $now = null): bool diff --git a/web/app/Services/Cloud/CloudBackupService.php b/web/app/Services/Cloud/CloudBackupService.php index b3f9edd8..85d89433 100644 --- a/web/app/Services/Cloud/CloudBackupService.php +++ b/web/app/Services/Cloud/CloudBackupService.php @@ -6,6 +6,7 @@ use App\Models\CloudBackupRestore; use App\Models\CloudBackupRecovery; use App\Models\CloudBackupPeriodEntitlement; use App\Models\CloudBackupSubscription; +use App\Models\CloudDeploymentSnapshot; use App\Models\CloudHost; use App\Models\CloudInstance; use App\Models\CloudInstanceBackup; @@ -643,7 +644,19 @@ final class CloudBackupService } else { $usedQuery->where('source', 'automatic') ->where('subscription_id', - (int) $automaticSubscription->id); + (int) $automaticSubscription->id) + ->whereNotExists(static function ($query): void { + $query->selectRaw('1') + ->from('cloud_deployment_snapshots') + ->whereColumn( + 'cloud_deployment_snapshots.backup_id', + 'cloud_instance_backups.id' + )->where( + 'cloud_deployment_snapshots.state', + '<>', + 'deleted' + ); + }); } $used = (int) $usedQuery->count('id'); if ($maintenance === null && $automatic === null @@ -1647,6 +1660,10 @@ final class CloudBackupService })->exists()) { throw new CloudError('备份仍有关联任务,不能删除', 409); } + if (CloudDeploymentSnapshot::where('backup_id', (int) $backup->id) + ->where('state', 'ready')->exists()) { + throw new CloudError('该对象已保存为云快照,请从云快照页面删除', 409); + } } private static function markDeleteUncertain(int $backupId, diff --git a/web/app/Services/Cloud/CloudDeploymentSnapshotService.php b/web/app/Services/Cloud/CloudDeploymentSnapshotService.php new file mode 100644 index 00000000..471659f6 --- /dev/null +++ b/web/app/Services/Cloud/CloudDeploymentSnapshotService.php @@ -0,0 +1,444 @@ + $backupId, + 'name' => $requestedName, + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE + | JSON_UNESCAPED_SLASHES)); + + return (new User())->getConnection()->transaction(function () use ( + $backupId, $userId, $idempotency, $requestedName, $requestHash + ): CloudDeploymentSnapshot { + $user = User::where('id', $userId)->lockForUpdate()->first(); + if ($user === null || (int) $user->enable !== 1) { + throw new CloudError('账户不可用', 403); + } + $existing = CloudDeploymentSnapshot::where('user_id', $userId) + ->where('idempotency_key', $idempotency) + ->lockForUpdate()->first(); + if ($existing !== null) { + if (!hash_equals((string) $existing->request_hash, + $requestHash)) { + throw new CloudError( + '同一请求标识不能用于不同的云快照操作', 409 + ); + } + return $existing; + } + $backup = CloudInstanceBackup::where('id', $backupId) + ->where('user_id', $userId)->lockForUpdate()->first(); + self::assertBackingReady($backup, true, + '云备份当前不能保存为云快照'); + $alreadyPromoted = CloudDeploymentSnapshot::where( + 'backup_id', (int) $backup->id + )->where('state', '<>', 'deleted')->lockForUpdate()->first(); + if ($alreadyPromoted !== null) { + throw new CloudError('该云备份已经保存为云快照', 409); + } + $active = CloudDeploymentSnapshot::where('user_id', $userId) + ->where('state', '<>', 'deleted')->count(); + if ($active >= self::MAX_PER_USER) { + throw new CloudError( + '每个账户最多保留 ' . self::MAX_PER_USER . ' 个云快照', + 409 + ); + } + $now = time(); + $snapshot = new CloudDeploymentSnapshot(); + $snapshot->snapshot_key = bin2hex(random_bytes(16)); + $snapshot->user_id = $userId; + $snapshot->backup_id = (int) $backup->id; + $snapshot->source_instance_id = (int) $backup->source_instance_id; + $snapshot->name = $requestedName + ?? 'cloud-' . substr((string) $backup->backup_key, 0, 8); + $snapshot->state = 'ready'; + $snapshot->idempotency_key = $idempotency; + $snapshot->request_hash = $requestHash; + $snapshot->error_code = ''; + $snapshot->ready_at = $now; + $snapshot->deleted_at = null; + $snapshot->created_at = $snapshot->updated_at = $now; + $snapshot->save(); + return $snapshot; + }, 3); + } + + /** Paginated owner catalog; backing object locations and secrets stay hidden. */ + public static function library(array $actor, array $input): array + { + CloudInput::only($input, ['page', 'per_page']); + $userId = self::actorUserId($actor); + $page = self::positiveInteger($input['page'] ?? 1, 1, 1000000); + $perPage = self::positiveInteger($input['per_page'] ?? 20, 1, 50); + if (!in_array($perPage, [20, 50], true)) { + throw new CloudError('云快照库每页条数仅支持 20 或 50'); + } + $query = CloudDeploymentSnapshot::where('user_id', $userId) + ->where('state', '<>', 'deleted'); + $total = (int) (clone $query)->count('id'); + $pages = max(1, (int) ceil($total / $perPage)); + $page = min($page, $pages); + $rows = $query->orderByDesc('id') + ->offset(($page - 1) * $perPage)->limit($perPage)->get(); + $backups = []; + $instances = []; + if ($rows->isNotEmpty()) { + $backupIds = array_values(array_unique(array_map( + static fn (CloudDeploymentSnapshot $snapshot): int => + (int) $snapshot->backup_id, + $rows->all() + ))); + foreach (CloudInstanceBackup::whereIn('id', $backupIds) + ->where('user_id', $userId)->get() as $backup) { + $backups[(int) $backup->id] = $backup; + } + $instanceIds = array_values(array_unique(array_map( + static fn (CloudDeploymentSnapshot $snapshot): int => + (int) $snapshot->source_instance_id, + $rows->all() + ))); + foreach (CloudInstance::whereIn('id', $instanceIds) + ->where('user_id', $userId) + ->get(['id', 'name', 'status']) as $instance) { + $instances[(int) $instance->id] = $instance; + } + } + $items = []; + foreach ($rows as $snapshot) { + $backup = $backups[(int) $snapshot->backup_id] ?? null; + if ($backup !== null + && (int) $snapshot->source_instance_id + !== (int) $backup->source_instance_id) { + $backup = null; + } + $items[] = self::display( + $snapshot, + $backup, + $instances[(int) $snapshot->source_instance_id] ?? null + ); + } + $from = $total === 0 ? 0 : (($page - 1) * $perPage) + 1; + return [ + 'items' => $items, + 'limit' => self::MAX_PER_USER, + 'pagination' => [ + 'page' => $page, + 'per_page' => $perPage, + 'total' => $total, + 'total_pages' => $pages, + 'from' => $from, + 'to' => $from === 0 ? 0 : $from + count($items) - 1, + ], + ]; + } + + /** Lock and resolve one public snapshot key for order creation/payment. */ + public static function resolveForOrder(string $snapshotKey, int $userId): array + { + self::assertSnapshotKey($snapshotKey); + if ($userId < 1) { + throw new CloudError('请先登录', 401); + } + $snapshot = CloudDeploymentSnapshot::where( + 'snapshot_key', $snapshotKey + )->where('user_id', $userId)->lockForUpdate()->first(); + if ($snapshot === null || (string) $snapshot->state !== 'ready') { + throw new CloudError('云快照不存在或当前不可用于部署', 404); + } + $backup = CloudInstanceBackup::where('id', (int) $snapshot->backup_id) + ->where('user_id', $userId)->lockForUpdate()->first(); + self::assertBackingReady($backup, false, + '云快照不存在或当前不可用于部署'); + self::assertBinding($snapshot, $backup); + return ['snapshot' => $snapshot, 'backup' => $backup]; + } + + /** Safe read-only source projection for the deployment-page bootstrap. */ + public static function deploymentSource(string $snapshotKey, + array $actor): array + { + self::assertSnapshotKey($snapshotKey); + $userId = self::actorUserId($actor); + $snapshot = CloudDeploymentSnapshot::where( + 'snapshot_key', $snapshotKey + )->where('user_id', $userId)->first(); + if ($snapshot === null || (string) $snapshot->state !== 'ready') { + throw new CloudError('云快照不存在或当前不可用于部署', 404); + } + $backup = CloudInstanceBackup::where('id', (int) $snapshot->backup_id) + ->where('user_id', $userId)->first(); + self::assertBackingReady($backup, false, + '云快照不存在或当前不可用于部署'); + self::assertBinding($snapshot, $backup); + $instance = CloudInstance::where( + 'id', (int) $snapshot->source_instance_id + )->where('user_id', $userId)->first(); + return self::display($snapshot, $backup, $instance); + } + + /** Delete or reconcile one owner snapshot and its dedicated backing object. */ + public static function delete(string $snapshotKey, array $actor, + ?CloudObjectStorageS3Client $client = null): array + { + self::assertSnapshotKey($snapshotKey); + $userId = self::actorUserId($actor); + $prepared = (new User())->getConnection()->transaction(function () use ( + $snapshotKey, $userId + ): array { + User::where('id', $userId)->lockForUpdate()->first(); + $snapshot = CloudDeploymentSnapshot::where( + 'snapshot_key', $snapshotKey + )->where('user_id', $userId)->lockForUpdate()->first(); + if ($snapshot === null) { + throw new CloudError('云快照不存在或无权访问', 404); + } + if ((string) $snapshot->state === 'deleted') { + return ['snapshot' => $snapshot, 'backup' => null]; + } + if (self::hasBlockingUse($snapshot)) { + throw new CloudError( + '云快照仍有关联的待支付账单或创建任务,不能删除', 409 + ); + } + if (!in_array((string) $snapshot->state, + ['ready', 'deleting', 'delete_uncertain'], true)) { + throw new CloudError('当前云快照状态不允许删除', 409); + } + $backup = CloudInstanceBackup::where( + 'id', (int) $snapshot->backup_id + )->where('user_id', $userId)->lockForUpdate()->first(); + if ($backup === null) { + throw new CloudError('云快照的存储对象记录缺失', 409); + } + if ((string) $snapshot->state === 'ready') { + $snapshot->state = 'deleting'; + $snapshot->error_code = ''; + $snapshot->updated_at = time(); + $snapshot->save(); + } + return ['snapshot' => $snapshot, 'backup' => $backup]; + }, 3); + if ($prepared['backup'] === null) { + return self::display($prepared['snapshot'], null, null); + } + $systemActor = [ + 'user_id' => $userId, + 'is_admin' => true, + 'is_super_admin' => true, + 'can_manage' => true, + 'session_id' => 'deployment-snapshot-delete', + ]; + try { + $result = CloudBackupService::delete( + $prepared['backup'], $systemActor, $client + ); + } catch (\Throwable $error) { + $backingState = (string) (CloudInstanceBackup::where( + 'id', (int) $prepared['backup']->id + )->value('state') ?? ''); + $effectUnknown = in_array($backingState, + ['deleting', 'delete_uncertain', 'deleted'], true); + CloudDeploymentSnapshot::where( + 'id', (int) $prepared['snapshot']->id + )->where('state', 'deleting')->update([ + 'state' => $effectUnknown ? 'delete_uncertain' : 'ready', + 'error_code' => $effectUnknown + ? 'snapshot_delete_effect_unknown' + : 'snapshot_delete_failed', + 'updated_at' => time(), + ]); + throw $error; + } + $snapshot = (new User())->getConnection()->transaction(function () use ( + $prepared, $result + ): CloudDeploymentSnapshot { + $locked = CloudDeploymentSnapshot::where( + 'id', (int) $prepared['snapshot']->id + )->lockForUpdate()->firstOrFail(); + if (($result['deleted'] ?? false) === true) { + $locked->state = 'deleted'; + $locked->deleted_at = time(); + $locked->error_code = ''; + } elseif (($result['requires_reconciliation'] ?? false) === true) { + $locked->state = 'delete_uncertain'; + $locked->error_code = 'object_delete_uncertain'; + } else { + $locked->state = 'deleting'; + } + $locked->updated_at = time(); + $locked->save(); + return $locked; + }, 3); + return self::display( + $snapshot, + CloudInstanceBackup::find((int) $snapshot->backup_id), + null + ); + } + + public static function display(CloudDeploymentSnapshot $snapshot, + ?CloudInstanceBackup $backup = null, + ?CloudInstance $instance = null): array + { + $state = in_array((string) $snapshot->state, + ['ready', 'deleting', 'delete_uncertain', 'deleted'], true) + ? (string) $snapshot->state : 'delete_uncertain'; + $spec = $backup === null + ? null : json_decode((string) $backup->spec_json, true); + $activeInvoiceCount = (int) CloudOrder::where( + 'deployment_snapshot_id', (int) $snapshot->id + )->where('status', 'awaiting_payment')->count('id'); + $blocked = self::hasBlockingUse($snapshot); + return [ + 'snapshot_key' => (string) $snapshot->snapshot_key, + 'name' => (string) $snapshot->name, + 'state' => $state, + 'source_instance' => [ + 'id' => (string) $snapshot->source_instance_id, + 'name' => $instance === null ? '' : (string) $instance->name, + 'deleted' => $instance === null + || (string) $instance->status === 'deleted', + ], + 'consistency' => $backup !== null + && in_array((string) $backup->consistency, + ['filesystem', 'crash'], true) + ? (string) $backup->consistency : 'unknown', + 'os_name' => is_array($spec) + && is_string($spec['os_name'] ?? null) + ? trim((string) $spec['os_name']) : '', + 'object_size_bytes' => $backup === null + ? 0 : max(0, (int) $backup->object_size_bytes), + 'virtual_size_bytes' => $backup === null + ? 0 : max(0, (int) $backup->virtual_size_bytes), + 'created_at' => max(0, (int) $snapshot->created_at), + 'ready_at' => max(0, (int) $snapshot->ready_at), + 'can_create_instance' => $state === 'ready' + && $backup !== null && (string) $backup->state === 'ready', + 'can_delete' => in_array($state, + ['ready', 'deleting', 'delete_uncertain'], true) && !$blocked, + 'active_invoice_count' => $activeInvoiceCount, + 'has_blocking_use' => $blocked, + 'error' => $state === 'delete_uncertain' + ? '删除结果尚未确认;再次核对只会读取对象状态,不会重发删除请求。' + : null, + ]; + } + + private static function assertBackingReady(?CloudInstanceBackup $backup, + bool $requireRecoveryGrace, string $errorMessage): void + { + $spec = $backup === null + ? null : json_decode((string) $backup->spec_json, true); + if ($backup === null + || (string) $backup->purpose !== 'portable' + || (string) $backup->source !== 'automatic' + || $backup->subscription_id === null + || (string) $backup->state !== 'ready' + || ($requireRecoveryGrace + && !CloudAutomaticBackupService::withinRecoveryGrace($backup)) + || (int) $backup->object_size_bytes < 1 + || (int) $backup->virtual_size_bytes < 1 + || preg_match('/^[a-f0-9]{32}$/D', + (string) $backup->backup_key) !== 1 + || preg_match('/^[a-f0-9]{64}$/D', + (string) $backup->sha256) !== 1 + || !is_string($backup->sealed_storage_runtime) + || trim((string) $backup->sealed_storage_runtime) === '' + || !is_array($spec) || array_is_list($spec) + || ($spec['managed'] ?? null) !== true + || ($spec['os_source'] ?? null) !== 'cloud_template' + || !is_string($spec['os_name'] ?? null) + || trim((string) $spec['os_name']) === '' + || ($spec['login_name'] ?? null) !== 'root' + || !is_bool($spec['debian_12_network_fix'] ?? null)) { + throw new CloudError($errorMessage, 409); + } + } + + private static function hasBlockingUse( + CloudDeploymentSnapshot $snapshot + ): bool { + if (CloudOrder::where('deployment_snapshot_id', (int) $snapshot->id) + ->whereIn('status', ['awaiting_payment', 'queued'])->exists()) { + return true; + } + return CloudJob::where('backup_id', (int) $snapshot->backup_id) + ->where(static function ($query): void { + $query->where('phase', '<>', 'terminal') + ->orWhere('effect_resolution', 'unknown') + ->orWhere('finalization_incident', 1); + })->exists(); + } + + private static function assertBinding(CloudDeploymentSnapshot $snapshot, + CloudInstanceBackup $backup): void + { + if ((int) $snapshot->backup_id !== (int) $backup->id + || (int) $snapshot->user_id !== (int) $backup->user_id + || (int) $snapshot->source_instance_id + !== (int) $backup->source_instance_id) { + throw new CloudError('云快照与存储对象绑定不一致', 409); + } + } + + private static function actorUserId(array $actor): int + { + $userId = filter_var($actor['user_id'] ?? null, FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]]); + if ($userId === false) { + throw new CloudError('请先登录', 401); + } + return (int) $userId; + } + + private static function assertSnapshotKey(string $snapshotKey): void + { + if (preg_match('/^[a-f0-9]{32}$/D', $snapshotKey) !== 1) { + throw new CloudError('请选择有效的云快照'); + } + } + + private static function positiveInteger($value, int $minimum, + int $maximum): int + { + $parsed = filter_var($value, FILTER_VALIDATE_INT, + ['options' => ['min_range' => $minimum, + 'max_range' => $maximum]]); + if ($parsed === false) { + throw new CloudError('分页参数无效'); + } + return (int) $parsed; + } +} diff --git a/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php b/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php index 7bbf2aa8..8f5914ea 100644 --- a/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php +++ b/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php @@ -2,6 +2,7 @@ namespace App\Services\Cloud; +use App\Models\CloudDeploymentSnapshot; use App\Models\CloudInstance; use App\Models\CloudInstanceBackup; use App\Models\CloudInstanceMigration; @@ -509,9 +510,11 @@ final class CloudOperationRecoveryIdentity : json_decode((string) $order->spec_json, true); if ($order === null || !is_array($orderSpec) || array_is_list($orderSpec) - || ($orderSpec['source'] ?? null) !== 'backup') { + || ($orderSpec['source'] ?? null) + !== 'deployment_snapshot' + || $order->deployment_snapshot_id === null) { self::invalidPayload( - '从云备份创建实例缺少可信订单快照' + '从云快照创建实例缺少可信订单快照' ); } return self::backupProvisionIdentity( @@ -521,8 +524,7 @@ final class CloudOperationRecoveryIdentity $target, $body, $order, - $orderSpec, - $forAppliedEffect + $orderSpec ); } self::expectRequest($method, $target, 'POST', '/v1/vms'); @@ -607,8 +609,7 @@ final class CloudOperationRecoveryIdentity string $target, array $body, CloudOrder $order, - array $orderSpec, - bool $forAppliedEffect + array $orderSpec ): array { $resourceId = self::operationUuid((string) $job->operation_id); self::expectRequest( @@ -627,6 +628,10 @@ final class CloudOperationRecoveryIdentity 'platform_network_policy_snapshot', 'debian_12_network_fix', 'backup_key', 'source_url', 'source_size_bytes', 'source_sha256', ]); + $snapshot = $order->deployment_snapshot_id === null ? null + : CloudDeploymentSnapshot::find( + (int) $order->deployment_snapshot_id + ); $backup = $job->backup_id === null ? null : CloudInstanceBackup::find((int) $job->backup_id); $backupMetadata = $payload['backup_metadata'] ?? null; @@ -637,30 +642,56 @@ final class CloudOperationRecoveryIdentity FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]] ) === false) { - self::invalidPayload('从云备份创建实例的资源规格无效'); + self::invalidPayload('从云快照创建实例的资源规格无效'); } } - if ($backup === null + if ($snapshot === null || $backup === null || (int) $order->user_id !== (int) $job->user_id + || (int) $snapshot->user_id !== (int) $job->user_id || (int) $backup->user_id !== (int) $job->user_id - || (int) ($orderSpec['backup_id'] ?? 0) !== (int) $backup->id + || (string) $snapshot->state !== 'ready' + || (int) $snapshot->id + !== (int) ($orderSpec['deployment_snapshot_id'] ?? 0) + || (int) $snapshot->backup_id !== (int) $backup->id + || (int) $snapshot->source_instance_id + !== (int) $backup->source_instance_id + || !hash_equals((string) $snapshot->snapshot_key, + (string) ($orderSpec['cloud_snapshot_key'] ?? '')) + || (int) ($orderSpec['backing_backup_id'] ?? 0) + !== (int) $backup->id || !is_array($backupMetadata) || array_is_list($backupMetadata) + || (int) ($backupMetadata['deployment_snapshot_id'] ?? 0) + !== (int) $snapshot->id + || !hash_equals((string) $snapshot->snapshot_key, + (string) ($backupMetadata['cloud_snapshot_key'] ?? '')) + || (int) ($backupMetadata['backing_backup_id'] ?? 0) + !== (int) $backup->id || (int) ($backupMetadata['backup_id'] ?? 0) !== (int) $backup->id || !hash_equals((string) $backup->backup_key, - (string) ($orderSpec['backup_key'] ?? '')) + (string) ($orderSpec['backing_backup_key'] ?? '')) + || !hash_equals((string) $backup->backup_key, + (string) ($backupMetadata['backing_backup_key'] ?? '')) || !hash_equals((string) $backup->backup_key, (string) ($backupMetadata['backup_key'] ?? '')) || !hash_equals((string) $backup->backup_key, (string) ($body['backup_key'] ?? '')) || (int) $backup->object_size_bytes - !== (int) ($orderSpec['backup_size_bytes'] ?? 0) + !== (int) ($orderSpec['backing_backup_size_bytes'] ?? 0) || (int) $backup->object_size_bytes !== (int) ($body['source_size_bytes'] ?? 0) + || (int) $backup->virtual_size_bytes + !== (int) ($orderSpec[ + 'backing_backup_virtual_size_bytes' + ] ?? 0) || !hash_equals((string) $backup->sha256, - (string) ($orderSpec['backup_sha256'] ?? '')) + (string) ($orderSpec['backing_backup_sha256'] ?? '')) || !hash_equals((string) $backup->sha256, (string) ($body['source_sha256'] ?? '')) + || !hash_equals(self::backingBackupIdentity($backup), + (string) ($orderSpec['backing_backup_identity'] ?? '')) || (string) $backup->purpose !== 'portable' + || (string) $backup->source !== 'automatic' + || $backup->subscription_id === null || (string) $backup->state !== 'ready' || ($body['uuid'] ?? null) !== $resourceId || ($body['source'] ?? null) !== '' @@ -694,17 +725,37 @@ final class CloudOperationRecoveryIdentity || $job->order_id === null || array_key_exists('owner_id', $payload)) { self::invalidPayload( - '从云备份创建实例的请求与订单、备份账本不匹配' + '从云快照创建实例的请求与订单、快照账本不匹配' ); } - if ($forAppliedEffect - && (!is_string($payload['backup_sealed_credential'] ?? null) - || trim($payload['backup_sealed_credential']) === '')) { - self::invalidPayload('从云备份创建实例缺少恢复凭据快照'); - } return ['restore-backup:' . (string) $backup->backup_key, $resourceId]; } + private static function backingBackupIdentity( + CloudInstanceBackup $backup + ): string { + return hash('sha256', json_encode([ + 'id' => (int) $backup->id, + 'backup_key' => (string) $backup->backup_key, + 'source_instance_id' => (int) $backup->source_instance_id, + 'source_host_id' => (int) $backup->source_host_id, + 'user_id' => (int) $backup->user_id, + 'source_uuid' => (string) $backup->source_uuid, + 'purpose' => (string) $backup->purpose, + 'source' => (string) $backup->source, + 'subscription_id' => (int) $backup->subscription_id, + 'object_key' => (string) $backup->object_key, + 'object_size_bytes' => (int) $backup->object_size_bytes, + 'virtual_size_bytes' => (int) $backup->virtual_size_bytes, + 'sha256' => (string) $backup->sha256, + 'storage_revision' => (int) $backup->storage_revision, + 'storage_runtime_sha256' => hash( + 'sha256', + (string) $backup->sealed_storage_runtime + ), + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES)); + } + private static function assertCreateAppliedEscrow( array $payload, array $body diff --git a/web/app/Services/Cloud/CloudOrderService.php b/web/app/Services/Cloud/CloudOrderService.php index 40fd840d..aebe1e22 100644 --- a/web/app/Services/Cloud/CloudOrderService.php +++ b/web/app/Services/Cloud/CloudOrderService.php @@ -20,8 +20,13 @@ final class CloudOrderService public static function purchase(array $input, array $actor): CloudOrder { + if (array_key_exists('backup_id', $input)) { + throw new CloudError( + '云备份不能直接创建实例,请先保存为云快照' + ); + } CloudInput::only($input, [ - 'offer_id', 'source', 'template_id', 'backup_id', + 'offer_id', 'source', 'template_id', 'cloud_snapshot_key', 'guest_ssh_key_id', 'root_password', 'name', 'automatic_backup', 'idempotency_key', ]); @@ -43,35 +48,32 @@ final class CloudOrderService throw new CloudError('请选择可用的销售方案'); } $source = $input['source'] ?? 'cloud'; - if (!in_array($source, ['cloud', 'backup'], true)) { + if (!in_array($source, ['cloud', 'deployment_snapshot'], true)) { throw new CloudError('实例来源无效'); } $template = ''; - $backupId = null; + $snapshotKey = null; if ($source === 'cloud') { - if (array_key_exists('backup_id', $input)) { - throw new CloudError('云镜像部署不能携带备份标识'); + if (array_key_exists('cloud_snapshot_key', $input)) { + throw new CloudError('云镜像部署不能携带云快照标识'); } $template = CloudInput::template($input['template_id'] ?? ''); } else { if (array_key_exists('template_id', $input) || array_key_exists('guest_ssh_key_id', $input) || array_key_exists('root_password', $input)) { - throw new CloudError('从云备份创建实例不能替换镜像或登录凭据'); + throw new CloudError('从云快照创建实例不能替换镜像或登录凭据'); } - $parsedBackupId = filter_var( - $input['backup_id'] ?? null, - FILTER_VALIDATE_INT, - ['options' => ['min_range' => 1]] - ); - if ($parsedBackupId === false) { - throw new CloudError('请选择可用的云备份'); + $candidate = $input['cloud_snapshot_key'] ?? null; + if (!is_string($candidate) + || preg_match('/^[a-f0-9]{32}$/D', $candidate) !== 1) { + throw new CloudError('请选择可用的云快照'); } - $backupId = (int) $parsedBackupId; + $snapshotKey = $candidate; } ksort($input); $requestHash = hash_hmac('sha256', json_encode($input, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), CloudSecrets::key('order-request-hash')); - return (new User())->getConnection()->transaction(function () use ($input, $actor, $offerId, $source, $requestedName, $template, $backupId, $automaticBackup, $idempotency, $requestHash) { + return (new User())->getConnection()->transaction(function () use ($input, $actor, $offerId, $source, $requestedName, $template, $snapshotKey, $automaticBackup, $idempotency, $requestHash) { if ($source === 'cloud') { CloudTemplateCatalogService::assertProvisionable($template); } @@ -105,14 +107,23 @@ final class CloudOrderService || (!CloudNetworkLineFeature::enabled() && !(bool) $line->is_default)) { throw new CloudError('该销售方案的地区、线路或资源池暂不可用', 409); } + $sourceSnapshot = null; $sourceBackup = null; $backupSpec = null; - if ($source === 'backup') { - $sourceBackup = CloudInstanceBackup::where( - 'id', (int) $backupId - )->where('user_id', (int) $user->id) - ->lockForUpdate()->first(); - $backupSpec = self::assertPurchasableBackup( + if ($source === 'deployment_snapshot') { + $resolved = CloudDeploymentSnapshotService::resolveForOrder( + (string) $snapshotKey, + (int) $user->id + ); + $sourceSnapshot = $resolved['snapshot']; + $sourceBackup = $resolved['backup']; + if ((int) $sourceSnapshot->backup_id + !== (int) $sourceBackup->id + || (int) $sourceSnapshot->source_instance_id + !== (int) $sourceBackup->source_instance_id) { + throw new CloudError('云快照与存储对象绑定不一致', 409); + } + $backupSpec = self::assertDeploymentSnapshotBackup( $sourceBackup, (int) $plan->disk_gib ); @@ -180,13 +191,21 @@ final class CloudOrderService $safeSpec = CloudInput::safeResult($payload); $safeSpec['source'] = $source; if ($sourceBackup !== null) { - $safeSpec['backup_id'] = (int) $sourceBackup->id; - $safeSpec['backup_key'] = (string) $sourceBackup->backup_key; - $safeSpec['backup_size_bytes'] = + $safeSpec['deployment_snapshot_id'] = + (int) $sourceSnapshot->id; + $safeSpec['cloud_snapshot_key'] = + (string) $sourceSnapshot->snapshot_key; + $safeSpec['backing_backup_id'] = (int) $sourceBackup->id; + $safeSpec['backing_backup_key'] = + (string) $sourceBackup->backup_key; + $safeSpec['backing_backup_size_bytes'] = (int) $sourceBackup->object_size_bytes; - $safeSpec['backup_virtual_size_bytes'] = + $safeSpec['backing_backup_virtual_size_bytes'] = (int) $sourceBackup->virtual_size_bytes; - $safeSpec['backup_sha256'] = (string) $sourceBackup->sha256; + $safeSpec['backing_backup_sha256'] = + (string) $sourceBackup->sha256; + $safeSpec['backing_backup_identity'] = + self::backingBackupIdentity($sourceBackup); foreach (['os_source', 'os_name', 'login_name', 'debian_12_network_fix'] as $field) { $safeSpec[$field] = $backupSpec[$field]; @@ -220,6 +239,8 @@ final class CloudOrderService $order->resource_pool_id = $pool->id; $order->host_id = null; $order->reservation_id = null; + $order->deployment_snapshot_id = $sourceSnapshot === null + ? null : (int) $sourceSnapshot->id; $order->idempotency_key = $idempotency; $order->request_hash = $requestHash; $order->amount = CloudMoney::decimal($totalPrice); @@ -229,6 +250,8 @@ final class CloudOrderService $order->sealed_payload = CloudSecrets::encrypt(['method' => 'POST', 'request_target' => '/v1/vms', 'body' => $payload, 'credential' => $credential, + 'deployment_snapshot_id' => $sourceSnapshot === null + ? null : (int) $sourceSnapshot->id, 'backup_id' => $sourceBackup === null ? null : (int) $sourceBackup->id, ], 'order-payload'); @@ -253,7 +276,7 @@ final class CloudOrderService }, 3); } - private static function assertPurchasableBackup( + private static function assertDeploymentSnapshotBackup( ?CloudInstanceBackup $backup, int $diskGiB ): array { @@ -263,9 +286,9 @@ final class CloudOrderService ? $diskGiB * 1073741824 : 0; if ($backup === null || (string) $backup->purpose !== 'portable' + || (string) $backup->source !== 'automatic' + || $backup->subscription_id === null || (string) $backup->state !== 'ready' - || ((string) $backup->source === 'automatic' - && !CloudAutomaticBackupService::withinRecoveryGrace($backup)) || (int) $backup->object_size_bytes < 1 || (int) $backup->virtual_size_bytes < 1 || (int) $backup->virtual_size_bytes > $capacity @@ -273,8 +296,11 @@ final class CloudOrderService (string) $backup->backup_key) !== 1 || preg_match('/^[a-f0-9]{64}$/D', (string) $backup->sha256) !== 1 - || !is_string($backup->sealed_credential) - || trim($backup->sealed_credential) === '' + || !is_string($backup->object_key) + || trim((string) $backup->object_key) === '' + || !is_string($backup->sealed_storage_runtime) + || trim((string) $backup->sealed_storage_runtime) === '' + || (int) $backup->storage_revision < 1 || !is_array($spec) || array_is_list($spec) || ($spec['managed'] ?? null) !== true || ($spec['os_source'] ?? null) !== 'cloud_template' @@ -283,7 +309,7 @@ final class CloudOrderService || ($spec['login_name'] ?? null) !== 'root' || !is_bool($spec['debian_12_network_fix'] ?? null)) { throw new CloudError( - '云备份不可用,或所选套餐系统盘小于备份磁盘容量', + '云快照不可用,或所选套餐系统盘小于快照磁盘容量', 409 ); } @@ -295,6 +321,31 @@ final class CloudOrderService ]; } + private static function backingBackupIdentity( + CloudInstanceBackup $backup + ): string { + return hash('sha256', json_encode([ + 'id' => (int) $backup->id, + 'backup_key' => (string) $backup->backup_key, + 'source_instance_id' => (int) $backup->source_instance_id, + 'source_host_id' => (int) $backup->source_host_id, + 'user_id' => (int) $backup->user_id, + 'source_uuid' => (string) $backup->source_uuid, + 'purpose' => (string) $backup->purpose, + 'source' => (string) $backup->source, + 'subscription_id' => (int) $backup->subscription_id, + 'object_key' => (string) $backup->object_key, + 'object_size_bytes' => (int) $backup->object_size_bytes, + 'virtual_size_bytes' => (int) $backup->virtual_size_bytes, + 'sha256' => (string) $backup->sha256, + 'storage_revision' => (int) $backup->storage_revision, + 'storage_runtime_sha256' => hash( + 'sha256', + (string) $backup->sealed_storage_runtime + ), + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES)); + } + private static function createPurchaseItems( CloudOrder $order, Shop $plan, @@ -443,6 +494,11 @@ final class CloudOrderService $source = $orderSpec['source'] ?? null; $sourceBackup = null; if ($source === 'cloud') { + if ($order->deployment_snapshot_id !== null + || (int) ($payload['deployment_snapshot_id'] ?? 0) !== 0 + || (int) ($payload['backup_id'] ?? 0) !== 0) { + throw new CloudError('开通订单的云镜像来源不匹配', 409); + } $payload['body'] = CloudTemplateCatalogService::applyProvisioningSnapshot( $payload['body'] @@ -462,32 +518,66 @@ final class CloudOrderService // request. Only payload.body crosses the Agent boundary. $payload['template_metadata'] = $templateMetadata; $orderSpec = array_replace($orderSpec, $templateMetadata); - } elseif ($source === 'backup') { + } elseif ($source === 'deployment_snapshot') { + $snapshotId = filter_var( + $orderSpec['deployment_snapshot_id'] ?? null, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]] + ); $backupId = filter_var( - $orderSpec['backup_id'] ?? null, + $orderSpec['backing_backup_id'] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]] ); - if ($backupId === false + $snapshotKey = $orderSpec['cloud_snapshot_key'] ?? null; + if ($snapshotId === false || $backupId === false + || !is_string($snapshotKey) + || preg_match('/^[a-f0-9]{32}$/D', $snapshotKey) !== 1 + || (int) ($order->deployment_snapshot_id ?? 0) + !== (int) $snapshotId + || (int) ($payload['deployment_snapshot_id'] ?? 0) + !== (int) $snapshotId || (int) ($payload['backup_id'] ?? 0) !== (int) $backupId) { - throw new CloudError('开通订单的云备份快照不匹配', 409); + throw new CloudError('开通订单的云快照来源不匹配', 409); } - $sourceBackup = CloudInstanceBackup::where('id', (int) $backupId) - ->where('user_id', (int) $order->user_id) - ->lockForUpdate()->first(); - $metadata = self::assertPurchasableBackup( + $resolved = CloudDeploymentSnapshotService::resolveForOrder( + $snapshotKey, + (int) $order->user_id + ); + $sourceSnapshot = $resolved['snapshot']; + $sourceBackup = $resolved['backup']; + $metadata = self::assertDeploymentSnapshotBackup( $sourceBackup, (int) $plan->disk_gib ); - if (!hash_equals((string) $sourceBackup->backup_key, - (string) ($orderSpec['backup_key'] ?? '')) + if ((int) $sourceSnapshot->id !== (int) $snapshotId + || (int) $sourceSnapshot->backup_id !== (int) $backupId + || (int) $sourceSnapshot->source_instance_id + !== (int) $sourceBackup->source_instance_id + || (int) $sourceBackup->id !== (int) $backupId + || !hash_equals((string) $sourceSnapshot->snapshot_key, + $snapshotKey) + || !hash_equals((string) $sourceBackup->backup_key, + (string) ($orderSpec['backing_backup_key'] ?? '')) + || !hash_equals((string) $sourceBackup->backup_key, + (string) ($payload['body']['backup_key'] ?? '')) + || (int) $sourceBackup->object_size_bytes + !== (int) ($orderSpec['backing_backup_size_bytes'] ?? 0) || (int) $sourceBackup->object_size_bytes - !== (int) ($orderSpec['backup_size_bytes'] ?? 0) + !== (int) ($payload['body']['source_size_bytes'] ?? 0) || (int) $sourceBackup->virtual_size_bytes - !== (int) ($orderSpec['backup_virtual_size_bytes'] ?? 0) + !== (int) ($orderSpec[ + 'backing_backup_virtual_size_bytes' + ] ?? 0) + || !hash_equals((string) $sourceBackup->sha256, + (string) ($orderSpec['backing_backup_sha256'] ?? '')) || !hash_equals((string) $sourceBackup->sha256, - (string) ($orderSpec['backup_sha256'] ?? ''))) { - throw new CloudError('开通订单的云备份对象身份已变化', 409); + (string) ($payload['body']['source_sha256'] ?? '')) + || !hash_equals( + self::backingBackupIdentity($sourceBackup), + (string) ($orderSpec['backing_backup_identity'] ?? '') + )) { + throw new CloudError('开通订单的云快照存储对象身份已变化', 409); } $transfer = CloudBackupService::provisioningSource($sourceBackup); $payload['body']['source_url'] = $transfer['source_url']; @@ -496,6 +586,11 @@ final class CloudOrderService $payload['body']['source_sha256'] = (string) $sourceBackup->sha256; $payload['backup_metadata'] = [ + 'deployment_snapshot_id' => (int) $sourceSnapshot->id, + 'cloud_snapshot_key' => + (string) $sourceSnapshot->snapshot_key, + 'backing_backup_id' => (int) $sourceBackup->id, + 'backing_backup_key' => (string) $sourceBackup->backup_key, 'backup_id' => (int) $sourceBackup->id, 'backup_key' => (string) $sourceBackup->backup_key, 'os_source' => $metadata['os_source'], @@ -504,8 +599,6 @@ final class CloudOrderService 'debian_12_network_fix' => $metadata['debian_12_network_fix'], ]; - $payload['backup_sealed_credential'] = - (string) $sourceBackup->sealed_credential; unset($payload['credential']); } else { throw new CloudError('开通订单的实例来源无效', 409); diff --git a/web/app/Services/Cloud/CloudPlacementService.php b/web/app/Services/Cloud/CloudPlacementService.php index 19e09e0c..28802da5 100644 --- a/web/app/Services/Cloud/CloudPlacementService.php +++ b/web/app/Services/Cloud/CloudPlacementService.php @@ -1104,9 +1104,9 @@ final class CloudPlacementService ->lockForUpdate()->first(); $body = $payload['body'] ?? null; $orderSpec = json_decode((string) $order->spec_json, true); - $backupSource = is_array($orderSpec) + $deploymentSnapshotSource = is_array($orderSpec) && !array_is_list($orderSpec) - && ($orderSpec['source'] ?? null) === 'backup'; + && ($orderSpec['source'] ?? null) === 'deployment_snapshot'; $templateId = is_array($body) ? ($body['template_id'] ?? null) : null; $templateRevision = is_array($body) ? filter_var($body['template_revision'] ?? null, @@ -1114,11 +1114,11 @@ final class CloudPlacementService : false; $generation = is_array($body) ? ($body['template_generation_token'] ?? null) : null; - $replica = $backupSource || !is_string($templateId) + $replica = $deploymentSnapshotSource || !is_string($templateId) || $templateRevision === false || !is_string($generation) ? null : CloudTemplateReplica::query()->where('host_id', $hostId) ->where('template_id', $templateId)->lockForUpdate()->first(); - $sourceReady = $backupSource + $sourceReady = $deploymentSnapshotSource ? is_array($body) && ($body['source'] ?? null) === '' && $templateId === '' diff --git a/web/app/Services/Cloud/CloudWorkerService.php b/web/app/Services/Cloud/CloudWorkerService.php index 4e3077ba..ae04d5d5 100644 --- a/web/app/Services/Cloud/CloudWorkerService.php +++ b/web/app/Services/Cloud/CloudWorkerService.php @@ -2687,17 +2687,11 @@ final class CloudWorkerService | JSON_UNESCAPED_UNICODE ); if (isset($payload['backup_metadata'])) { - if (!is_string( - $payload['backup_sealed_credential'] ?? null - ) - || trim($payload['backup_sealed_credential']) === '') { - throw new CloudError( - '云备份开通任务缺少登录凭据快照', - 409 - ); - } - $instance->sealed_credential = - $payload['backup_sealed_credential']; + // The restored system disk is authoritative. The user may + // have changed the guest password after provisioning, so + // copying the panel's historical envelope would expose a + // password that is no longer valid. + $instance->sealed_credential = null; } else { $instance->sealed_credential = isset($payload['credential']) ? CloudSecrets::encrypt( diff --git a/web/config/routes.php b/web/config/routes.php index 0a5ae1d1..476da928 100644 --- a/web/config/routes.php +++ b/web/config/routes.php @@ -98,6 +98,7 @@ $app->group('/user', function () { $this->get('/cloud/instances/{id:[0-9]+}/reinstall', 'App\Controllers\CloudPageController:reinstall'); $this->get('/cloud/deploy', 'App\Controllers\CloudPageController:deploy'); $this->get('/cloud/backups', 'App\Controllers\CloudPageController:backups'); + $this->get('/cloud/cloud-snapshots', 'App\Controllers\CloudPageController:cloudSnapshots'); $this->get('/cloud/iso-images', 'App\Controllers\CloudPageController:isoImages'); $this->get('/cloud/ssh-keys', 'App\Controllers\CloudPageController:sshKeys'); $this->get('/cloud/invoices', 'App\Controllers\CloudPageController:invoices'); diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php index 763448d3..1f0bada7 100644 --- a/web/config/routes_cloud.php +++ b/web/config/routes_cloud.php @@ -26,6 +26,10 @@ $app->group('/api/v1', function () { $this->get('/tasks/{id:[0-9]+}', 'App\Controllers\CloudApiController:job'); $this->post('/tasks/read', 'App\Controllers\CloudApiController:readTasks'); $this->get('/backups', 'App\Controllers\CloudApiController:backups'); + $this->map(['GET', 'POST'], '/cloud-snapshots', + 'App\Controllers\CloudApiController:cloudSnapshots'); + $this->delete('/cloud-snapshots/{snapshot_key:[0-9a-f]{32}}', + 'App\Controllers\CloudApiController:deleteCloudSnapshot'); $this->get('/resources', 'App\Controllers\CloudApiController:resources'); $this->map(['GET', 'POST'], '/user-isos', 'App\Controllers\CloudApiController:userIsos'); $this->delete('/user-isos/{id:[0-9a-f]{32}}', diff --git a/web/public/cloud/app.js b/web/public/cloud/app.js index d837374f..5dec5649 100644 --- a/web/public/cloud/app.js +++ b/web/public/cloud/app.js @@ -3,6 +3,7 @@ const pageModules = Object.freeze({ detail: '/cloud/detail.js', deploy: '/cloud/deploy.js', backups: '/cloud/backups.js', + 'cloud-snapshots': '/cloud/cloud-snapshots.js', isos: '/cloud/iso-images.js', keys: '/cloud/ssh-keys.js', invoices: '/cloud/invoices.js', diff --git a/web/public/cloud/backups.js b/web/public/cloud/backups.js index a07665d8..7ba0a6f1 100644 --- a/web/public/cloud/backups.js +++ b/web/public/cloud/backups.js @@ -8,12 +8,12 @@ function versionedModuleUrl(path) { } const { - api, byId, initializeSession, readBootstrap, showError, + api, byId, initializeSession, readBootstrap, showError, toast, } = await import(versionedModuleUrl('./runtime.js')); const state = { items: [], page: 1, totalPages: 1, total: 0, loading: false, - controller: null, + controller: null, promoting: new Set(), promotionKeys: new Map(), }; function makeElement(tag, className = '', content) { @@ -83,6 +83,21 @@ function sourceInstance(backup) { }; } +function cloudSnapshot(backup) { + const value = backup?.cloud_snapshot; + if (!value || typeof value !== 'object') return null; + const key = String(value.snapshot_key ?? value.key ?? ''); + return /^[a-f0-9]{32}$/.test(key) ? { ...value, key } : null; +} + +function promotionKey(id) { + const existing = String(state.promotionKeys.get(id) || ''); + if (/^[A-Za-z0-9_.-]{16,128}$/.test(existing)) return existing; + const key = crypto.randomUUID(); + state.promotionKeys.set(id, key); + return key; +} + function render() { const container = byId('cloud-backups-list'); container.replaceChildren(); @@ -123,12 +138,18 @@ function render() { restore.href = `/user/cloud/instances/${encodeURIComponent(source.id)}?tab=settings&setting=automatic_backup`; actions.append(restore); } - if (backup.can_create_instance === true - || (backup.can_create_instance === undefined - && String(backup.state ?? backup.status).toLowerCase() === 'ready')) { - const create = makeElement('a', 'button button-primary small', '创建新实例'); - create.href = `/user/cloud/deploy?backup_id=${encodeURIComponent(id)}`; - actions.append(create); + const snapshot = cloudSnapshot(backup); + if (snapshot) { + const view = makeElement('a', 'button button-primary small', '查看云快照'); + view.href = `/user/cloud/cloud-snapshots#cloud-snapshot-${encodeURIComponent(snapshot.key)}`; + actions.append(view); + } else if (backup.can_promote === true) { + const promote = makeElement('button', 'button button-primary small', + state.promoting.has(id) ? '正在保存…' : '保存为云快照'); + promote.type = 'button'; + promote.disabled = state.loading || state.promoting.has(id); + promote.addEventListener('click', () => void promoteBackup(backup)); + actions.append(promote); } card.append(heading, facts, actions); container.append(card); @@ -139,6 +160,32 @@ function render() { byId('cloud-backups-next').disabled = state.loading || state.page >= state.totalPages; } +async function promoteBackup(backup) { + const id = String(backup?.id ?? backup?.backup_id ?? ''); + if (!/^[1-9]\d*$/.test(id) || state.loading || state.promoting.has(id)) return; + state.promoting.add(id); + render(); + const name = firstText(backup?.name, `云快照 #${id}`).slice(0, 64); + const idempotencyKey = promotionKey(id); + try { + await api('/api/v1/cloud-snapshots', { + method: 'POST', + body: { backup_id: Number(id), name, idempotency_key: idempotencyKey }, + }); + state.promotionKeys.delete(id); + toast('云快照已保存,可前往“云快照”创建新实例。', 'success'); + await load(state.page); + } catch (error) { + const status = byId('cloud-backups-status'); + status.hidden = false; + status.className = 'vm-settings-status error'; + status.textContent = error?.message || '保存云快照失败,请稍后重试。'; + } finally { + state.promoting.delete(id); + render(); + } +} + function applyPayload(payload) { state.items = normalizeItems(payload); const pagination = payload?.pagination && typeof payload.pagination === 'object' diff --git a/web/public/cloud/cloud-snapshots.js b/web/public/cloud/cloud-snapshots.js new file mode 100644 index 00000000..bc1342dc --- /dev/null +++ b/web/public/cloud/cloud-snapshots.js @@ -0,0 +1,262 @@ +const assetVersion = new URL(import.meta.url).searchParams.get('v'); + +function versionedModuleUrl(path) { + const url = new URL(path, import.meta.url); + url.search = ''; + if (assetVersion) url.searchParams.set('v', assetVersion); + return url.href; +} + +const { + api, byId, initializeSession, readBootstrap, showError, toast, +} = await import(versionedModuleUrl('./runtime.js')); + +const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options) + ?? Promise.resolve(false); + +const state = { + items: [], page: 1, totalPages: 1, total: 0, loading: false, + controller: null, deleting: new Set(), hashFocused: false, +}; + +function element(tag, className = '', content) { + const value = document.createElement(tag); + if (className) value.className = className; + if (content !== undefined) value.textContent = String(content); + return value; +} + +function firstText(...values) { + for (const value of values) { + if (value !== null && value !== undefined && String(value).trim() !== '') { + return String(value).trim(); + } + } + return ''; +} + +function formatDate(value) { + const raw = Number(value); + const timestamp = Number.isFinite(raw) && raw > 0 + ? (raw < 1e12 ? raw * 1000 : raw) : Date.parse(String(value || '')); + const date = new Date(timestamp); + return Number.isFinite(date.getTime()) + ? date.toLocaleString('zh-CN', { hour12: false }) : '时间未记录'; +} + +function formatBytes(value) { + let amount = Number(value); + if (!Number.isFinite(amount) || amount < 0) return '等待完成'; + const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']; + let index = 0; + while (amount >= 1024 && index < units.length - 1) { + amount /= 1024; + index += 1; + } + const precision = index === 0 ? 0 : amount >= 100 ? 0 : amount >= 10 ? 1 : 2; + return `${amount.toFixed(precision)} ${units[index]}`; +} + +function snapshotState(value) { + const normalized = String(value || '').toLowerCase(); + const values = { + ready: ['可用', 'running'], promoting: ['正在保存', 'warning'], + deleting: ['正在删除', 'warning'], + delete_uncertain: ['删除待核对', 'warning'], failed: ['保存失败', 'stopped'], + }; + return values[normalized] || [normalized || '状态未知', 'other']; +} + +function normalizeItems(payload) { + const values = Array.isArray(payload?.items) ? payload.items + : Array.isArray(payload?.snapshots) ? payload.snapshots : []; + return values.filter(item => item && typeof item === 'object' + && /^[a-f0-9]{32}$/.test(String(item.snapshot_key ?? item.key ?? ''))); +} + +function sourceInstance(snapshot) { + const source = snapshot?.source_instance && typeof snapshot.source_instance === 'object' + ? snapshot.source_instance : {}; + return { + id: String(source.id ?? source.instance_id ?? snapshot.source_instance_id ?? ''), + name: firstText(source.name, source.instance_name, snapshot.source_instance_name), + }; +} + +function render() { + const container = byId('cloud-snapshots-list'); + container.replaceChildren(); + if (!state.items.length) { + const empty = element('div', 'cloud-backups-empty cloud-snapshots-empty'); + empty.append(element('strong', '', '还没有云快照'), + element('span', '', '可前往“云备份”将一份可用备份保存为云快照。')); + container.append(empty); + } + for (const snapshot of state.items) { + const key = String(snapshot.snapshot_key ?? snapshot.key); + const source = sourceInstance(snapshot); + const [stateLabel, stateClass] = snapshotState(snapshot.state ?? snapshot.status); + const card = element('article', 'cloud-backup-card cloud-snapshot-card'); + card.id = `cloud-snapshot-${key}`; + const heading = element('div', 'cloud-backup-card-heading'); + const title = element('div', 'cloud-backup-title'); + const pendingInvoices = Math.max(0, Number(snapshot.active_invoice_count) || 0); + title.append(element('span', 'cloud-backup-icon cloud-snapshot-icon', '◆'), + element('div', '', firstText(snapshot.name, `云快照 ${key.slice(0, 8)}`))); + const sourceLabel = source.name || (source.id ? `实例 #${source.id}` : '来源实例未记录'); + title.lastElementChild.append(element('small', '', pendingInvoices > 0 + ? `来源:${sourceLabel} · ${pendingInvoices} 张待支付账单` + : `来源:${sourceLabel}`)); + heading.append(title, element('span', `state-pill ${stateClass}`, stateLabel)); + + const facts = element('dl', 'cloud-backup-facts cloud-snapshot-facts'); + const rows = [ + ['保存时间', formatDate(snapshot.ready_at ?? snapshot.created_at)], + ['操作系统', firstText(snapshot.os_name, '系统未记录')], + ['对象大小', formatBytes(snapshot.object_size_bytes)], + ['磁盘容量', formatBytes(snapshot.virtual_size_bytes)], + ]; + for (const [label, value] of rows) { + const row = document.createElement('div'); + row.append(element('dt', '', label), element('dd', '', value)); + facts.append(row); + } + + const actions = element('div', 'cloud-backup-actions cloud-snapshot-actions'); + if (snapshot.can_create_instance === true) { + const create = element('a', 'button button-primary small', '创建实例'); + create.href = `/user/cloud/deploy?cloud_snapshot=${encodeURIComponent(key)}`; + actions.append(create); + } + const remove = element('button', 'button button-outline small danger', + state.deleting.has(key) ? '正在处理…' : '删除'); + remove.type = 'button'; + remove.disabled = snapshot.can_delete !== true || state.deleting.has(key); + if (snapshot.can_delete !== true) { + remove.title = pendingInvoices > 0 + ? '存在待支付账单,请先支付或等待账单失效后再删除。' + : '云快照当前状态不允许删除。'; + } + remove.addEventListener('click', () => void deleteSnapshot(snapshot)); + actions.append(remove); + card.append(heading, facts, actions); + container.append(card); + } + byId('cloud-snapshots-count').textContent = `${state.total} 个`; + byId('cloud-snapshots-page').textContent = `第 ${state.page} / ${state.totalPages} 页`; + byId('cloud-snapshots-previous').disabled = state.loading || state.page <= 1; + byId('cloud-snapshots-next').disabled = state.loading || state.page >= state.totalPages; + if (!state.hashFocused && location.hash.startsWith('#cloud-snapshot-')) { + state.hashFocused = true; + requestAnimationFrame(() => document.getElementById(location.hash.slice(1)) + ?.scrollIntoView({ block: 'center' })); + } +} + +function applyPayload(payload) { + state.items = normalizeItems(payload); + const pagination = payload?.pagination && typeof payload.pagination === 'object' + ? payload.pagination : {}; + state.page = Math.max(1, Number(pagination.page ?? payload?.page) || 1); + state.totalPages = Math.max(1, + Number(pagination.total_pages ?? payload?.total_pages) || 1); + state.total = Math.max(0, + Number(pagination.total ?? payload?.total) || state.items.length); + render(); +} + +async function load(page = 1) { + if (state.loading) return; + state.loading = true; + state.controller?.abort(); + const controller = new AbortController(); + state.controller = controller; + const status = byId('cloud-snapshots-status'); + status.hidden = false; + status.className = 'vm-settings-status'; + status.textContent = '正在读取云快照…'; + render(); + try { + const payload = await api(`/api/v1/cloud-snapshots?page=${encodeURIComponent(Math.max(1, page))}&per_page=20`, { + signal: controller.signal, + }); + if (controller.signal.aborted) return; + applyPayload(payload); + status.hidden = true; + } catch (error) { + if (controller.signal.aborted) return; + status.className = 'vm-settings-status error'; + status.textContent = error?.message || '云快照读取失败,请稍后重试。'; + } finally { + if (state.controller === controller) state.controller = null; + state.loading = false; + render(); + } +} + +async function deleteSnapshot(snapshot) { + const key = String(snapshot?.snapshot_key ?? snapshot?.key ?? ''); + if (!/^[a-f0-9]{32}$/.test(key) || state.deleting.has(key)) return; + const name = firstText(snapshot?.name, `云快照 ${key.slice(0, 8)}`); + const pendingInvoices = Math.max(0, Number(snapshot?.active_invoice_count) || 0); + if (pendingInvoices > 0) { + toast('云快照存在待支付账单,请先支付或等待账单失效。', 'error'); + return; + } + const confirmed = await requestUserConfirmation({ + title: '删除云快照', + message: `确定永久删除“${name}”?删除后不能再用它创建实例,且无法恢复。`, + confirmText: '删除云快照', + tone: 'danger', + }); + if (!confirmed) return; + state.deleting.add(key); + render(); + try { + const payload = await api(`/api/v1/cloud-snapshots/${encodeURIComponent(key)}`, { + method: 'DELETE', + expectedStatus: 200, + headers: { 'Idempotency-Key': crypto.randomUUID() }, + }); + const resultState = String(payload?.snapshot?.state || '').toLowerCase(); + if (resultState === 'deleted') { + toast('云快照已删除。', 'success'); + } else if (resultState === 'delete_uncertain') { + toast('删除结果待核对,请再次点击删除;系统只会读取对象状态,不会重复发送删除请求。', 'warning'); + } else { + toast('云快照正在删除,请稍后刷新状态。', 'warning'); + } + await load(state.page); + } catch (error) { + const status = byId('cloud-snapshots-status'); + status.hidden = false; + status.className = 'vm-settings-status error'; + status.textContent = error?.message || '云快照删除失败,请稍后重试。'; + } finally { + state.deleting.delete(key); + render(); + } +} + +export async function initialize() { + try { + const bootstrap = readBootstrap('cloud-snapshots-bootstrap'); + if (!await initializeSession('cloud-snapshots', bootstrap?.user)) return; + if (Array.isArray(bootstrap?.items) || Array.isArray(bootstrap?.snapshots)) { + applyPayload(bootstrap); + byId('cloud-snapshots-status').hidden = true; + } else { + await load(1); + } + byId('cloud-snapshots-refresh')?.addEventListener('click', + () => void load(state.page)); + byId('cloud-snapshots-previous')?.addEventListener('click', + () => void load(state.page - 1)); + byId('cloud-snapshots-next')?.addEventListener('click', + () => void load(state.page + 1)); + window.addEventListener('pagehide', () => state.controller?.abort()); + } catch (error) { + showError('cloud-page-error', + error?.message || '云快照页面加载失败,请刷新后重试。'); + } +} diff --git a/web/public/cloud/runtime.js b/web/public/cloud/runtime.js index f88e33cf..8b74c515 100644 --- a/web/public/cloud/runtime.js +++ b/web/public/cloud/runtime.js @@ -23,7 +23,7 @@ const { // address, token, host credential or unrestricted create API exists in this UI. const byId = (id) => document.getElementById(id); const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options) ?? Promise.resolve(false); -const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], offers: [], regions: [], lines: [], linesEnabled: false, sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionId: '', selectedLineId: '', 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, reinstallPassword: '', reinstallPasswordDismissed: false, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, resourceController: null, mutationBusy: false, powerMutation: null, provisionIdempotency: '', provisionFingerprint: '', deployBackupId: '', rescueActive: false, rescueStaged: false }; +const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], offers: [], regions: [], lines: [], linesEnabled: false, sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionId: '', selectedLineId: '', 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, reinstallPassword: '', reinstallPasswordDismissed: false, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, resourceController: null, mutationBusy: false, powerMutation: null, provisionIdempotency: '', provisionFingerprint: '', deployCloudSnapshotKey: '', deployCloudSnapshotName: '', rescueActive: false, rescueStaged: false }; let vmStatusRequest = null; let vmStatusGeneration = 0; const activeTaskObservers = new Set(); @@ -663,26 +663,32 @@ function syncDeploymentPricing() { if (byId('create-submit')) byId('create-submit').textContent = `生成 ${formatUsd(total)} 账单`; } function applyDeploymentSource() { - const backupId = state.deployBackupId; - const source = byId('vm-backup-source'); + const snapshotKey = state.deployCloudSnapshotKey; + const source = byId('vm-cloud-snapshot-source'); const templateField = byId('vm-template-field'); const authFields = byId('vm-cloud-fields'); const template = byId('vm-template'); const password = byId('vm-root-password'); - if (byId('vm-backup-id')) byId('vm-backup-id').value = backupId; - if (source) source.hidden = !backupId; - if (templateField) templateField.hidden = Boolean(backupId); - if (authFields) authFields.hidden = Boolean(backupId); - if (template) template.disabled = Boolean(backupId) || !state.templates.some(item => item?.id); - if (password) password.disabled = Boolean(backupId); - if (byId('deploy-source-title') && backupId) byId('deploy-source-title').textContent = '备份来源'; - if (byId('vm-backup-source-name') && backupId) { - byId('vm-backup-source-name').textContent = `云备份 #${backupId},将按所选规格创建新的付费实例。`; - } -} -function initializeDeploymentOptions() { - const requestedBackup = new URLSearchParams(location.search).get('backup_id') || ''; - state.deployBackupId = /^[1-9]\d*$/.test(requestedBackup) ? requestedBackup : ''; + if (byId('vm-cloud-snapshot-key')) byId('vm-cloud-snapshot-key').value = snapshotKey; + if (source) source.hidden = !snapshotKey; + if (templateField) templateField.hidden = Boolean(snapshotKey); + if (authFields) authFields.hidden = Boolean(snapshotKey); + if (template) template.disabled = Boolean(snapshotKey) || !state.templates.some(item => item?.id); + if (password) password.disabled = Boolean(snapshotKey); + const sourceTitle = byId('deploy-source-title'); + if (sourceTitle?.firstChild) { + sourceTitle.firstChild.nodeValue = snapshotKey ? '云快照来源' : '选择系统镜像'; + } + if (byId('vm-cloud-snapshot-source-name') && snapshotKey) { + byId('vm-cloud-snapshot-source-name').textContent = `${state.deployCloudSnapshotName || `云快照 ${snapshotKey.slice(0, 8)}`},将按所选规格创建新的付费实例。`; + } +} +function initializeDeploymentOptions(bootstrap = null) { + const snapshot = bootstrap?.cloud_snapshot; + const key = String(snapshot?.snapshot_key ?? snapshot?.key ?? ''); + state.deployCloudSnapshotKey = /^[a-f0-9]{32}$/.test(key) ? key : ''; + state.deployCloudSnapshotName = state.deployCloudSnapshotKey + ? String(snapshot?.name || '').trim().slice(0, 64) : ''; const checkbox = byId('vm-automatic-backup'); if (checkbox && checkbox.dataset.bound !== 'true') { checkbox.dataset.bound = 'true'; @@ -697,7 +703,7 @@ function initializeDeploymentOptions() { } function updateCreateAvailability() { const offer = selectedSaleOffer(); - const validMedia = Boolean(state.deployBackupId || byId('vm-template')?.value); + const validMedia = Boolean(state.deployCloudSnapshotKey || byId('vm-template')?.value); if (byId('create-submit')) byId('create-submit').disabled = state.mutationBusy || !isOfferSellable(offer) || !validMedia; syncDeploymentPricing(); } @@ -859,7 +865,7 @@ async function selectOffer(offerId) { async function openCreate(bootstrap = null) { state.view = 'create'; state.selectedVmId = null; showError('create-error', ''); byId('vm-offer').value = ''; - initializeDeploymentOptions(); + initializeDeploymentOptions(bootstrap); if (bootstrap && Array.isArray(bootstrap.offers) && Array.isArray(bootstrap.regions) && Array.isArray(bootstrap.lines) && Array.isArray(bootstrap.templates)) { applySaleCatalog(bootstrap); @@ -968,8 +974,8 @@ async function existingProvisionInvoice(key) { async function buy(event) { event.preventDefault(); if (state.mutationBusy) return; const password = byId('vm-root-password').value; - if (!state.deployBackupId && !strongPassword(password)) return showError('create-error', '密码需为 12 至 128 位英文可打印字符且不能包含空格,并包含大写、小写、数字和符号。'); - if (!state.deployBackupId && !byId('vm-template').value) return showError('create-error', '请选择系统镜像版本。'); + if (!state.deployCloudSnapshotKey && !strongPassword(password)) return showError('create-error', '密码需为 12 至 128 位英文可打印字符且不能包含空格,并包含大写、小写、数字和符号。'); + if (!state.deployCloudSnapshotKey && !byId('vm-template').value) return showError('create-error', '请选择系统镜像版本。'); if (!byId('vm-offer').value) return showError('create-error', '请先选择可用实例规格。'); const selectedOffer = saleOffers().find(offer => String(offer.id) === byId('vm-offer').value); if (!selectedOffer) return showError('create-error', '地区、线路与实例规格不匹配,请重新选择。'); @@ -979,12 +985,12 @@ async function buy(event) { if (formBody) { formBody.inert = true; formBody.setAttribute('aria-busy', 'true'); } byId('create-submit').disabled = true; showError('create-error', ''); const body = { offer_id: Number(byId('vm-offer').value), name: byId('vm-name').value.trim(), - source: state.deployBackupId ? 'backup' : 'cloud', + source: state.deployCloudSnapshotKey ? 'deployment_snapshot' : 'cloud', automatic_backup: byId('vm-automatic-backup')?.checked === true }; - if (state.deployBackupId) body.backup_id = Number(state.deployBackupId); + if (state.deployCloudSnapshotKey) body.cloud_snapshot_key = state.deployCloudSnapshotKey; else body.template_id = byId('vm-template').value; - if (!state.deployBackupId && state.selectedKeys.create) body.guest_ssh_key_id = state.selectedKeys.create; - if (!state.deployBackupId && password) body.root_password = password; + if (!state.deployCloudSnapshotKey && state.selectedKeys.create) body.guest_ssh_key_id = state.selectedKeys.create; + if (!state.deployCloudSnapshotKey && password) body.root_password = password; try { const fingerprint = await provisionInvoiceFingerprint(body); const invoiceIdempotency = await pendingProvisionInvoiceKey(fingerprint); diff --git a/web/public/cloud/styles.css b/web/public/cloud/styles.css index 90af59c5..b2c1017c 100644 --- a/web/public/cloud/styles.css +++ b/web/public/cloud/styles.css @@ -271,6 +271,7 @@ body.vu-body .ssh-key-picker-manage:hover { .user-iso-delete{flex:none;color:#b94b57;border-color:#efd8dc} .user-isos-grid .host-test-status{margin:16px 0 0} .cloud-backups-notice{margin-bottom:20px}.cloud-backups-panel{padding:0;overflow:hidden}.cloud-backups-panel>.panel-heading{padding:20px 22px;border-bottom:1px solid #e8eef2}.cloud-backups-panel>#cloud-backups-status{margin:18px 22px 0}.cloud-backups-list{display:grid;gap:13px;padding:20px 22px}.cloud-backup-card{display:grid;gap:17px;padding:18px;border:1px solid #dfe8ed;border-radius:11px;background:#fff}.cloud-backup-card-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:15px}.cloud-backup-title{display:flex;align-items:center;gap:11px;min-width:0;color:#2b4358;font-size:13px;font-weight:800}.cloud-backup-title>div{display:grid;gap:3px;min-width:0;overflow-wrap:anywhere}.cloud-backup-title small{color:#8192a1;font-size:10px;font-weight:500}.cloud-backup-icon{display:grid;place-items:center;flex:0 0 38px;width:38px;height:38px;border-radius:10px;background:#eaf8f8;color:#168e97;font-size:18px}.cloud-backup-facts{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:11px;margin:0}.cloud-backup-facts>div{display:grid;gap:4px;min-width:0;padding:11px 12px;border-radius:8px;background:#f7f9fa}.cloud-backup-facts dt{color:#8998a6;font-size:9px;font-weight:700}.cloud-backup-facts dd{margin:0;color:#40566a;font-size:11px;font-weight:750;overflow-wrap:anywhere}.cloud-backup-actions{display:flex;align-items:center;justify-content:flex-end;gap:9px;flex-wrap:wrap}.cloud-backups-empty{display:grid;justify-items:center;gap:6px;padding:45px 18px;color:#8595a3;text-align:center}.cloud-backups-empty strong{color:#52697b;font-size:14px}.cloud-backups-empty span{font-size:11px}.cloud-backups-pagination{display:flex;align-items:center;justify-content:center;gap:14px;padding:16px 22px;border-top:1px solid #e8eef2;background:#fbfcfd}.cloud-backups-pagination span{min-width:100px;color:#7f909f;font-size:10px;text-align:center} +.cloud-snapshots-notice{margin-bottom:20px}.cloud-snapshots-panel>#cloud-snapshots-status{margin:18px 22px 0}.cloud-snapshot-card:target{border-color:#6bc1c7;box-shadow:0 0 0 3px rgba(24,166,176,.12)}.cloud-snapshot-icon{background:#eef1fb;color:#6176b5}.cloud-snapshot-actions .danger{color:#b94b57;border-color:#efd8dc} @media(max-width:960px){.user-isos-grid{grid-template-columns:1fr}} @media(max-width:740px){ .region-picker,.line-picker{grid-template-columns:repeat(2,minmax(0,1fr))} diff --git a/web/resources/views/venix/cloud/page.tpl b/web/resources/views/venix/cloud/page.tpl index ce144bf9..d1ead079 100644 --- a/web/resources/views/venix/cloud/page.tpl +++ b/web/resources/views/venix/cloud/page.tpl @@ -30,6 +30,8 @@ {include file='cloud/pages/deploy.tpl'} {elseif $cloud_page == 'backups'} {include file='cloud/pages/backups.tpl'} + {elseif $cloud_page == 'cloud-snapshots'} + {include file='cloud/pages/cloud-snapshots.tpl'} {elseif $cloud_page == 'isos'} {include file='cloud/pages/isos.tpl'} {elseif $cloud_page == 'keys'} diff --git a/web/resources/views/venix/cloud/pages/backups.tpl b/web/resources/views/venix/cloud/pages/backups.tpl index 30c8cf53..6bb8d026 100644 --- a/web/resources/views/venix/cloud/pages/backups.tpl +++ b/web/resources/views/venix/cloud/pages/backups.tpl @@ -1,9 +1,9 @@
-
CLOUD BACKUPS

云备份

集中查看当前账户的云备份,并选择可用备份创建新的付费实例。

+
CLOUD BACKUPS

云备份

集中查看当前账户的云备份,恢复原实例或保存为长期保留的云快照。

-
恢复入口说明此页面只用于从备份创建新实例。将已有实例恢复到某个备份,只能在该实例详情的“实例设置 → 自动备份”中执行。
+
备份用途说明云备份用于恢复原实例,也可保存为长期保留的云快照;创建新实例请前往“云快照”。

全部备份

只显示属于当前账户的普通云备份,不包含管理员维护迁移的临时数据。

0 个

正在读取云备份…

@@ -14,6 +14,6 @@
- +
diff --git a/web/resources/views/venix/cloud/pages/cloud-snapshots.tpl b/web/resources/views/venix/cloud/pages/cloud-snapshots.tpl new file mode 100644 index 00000000..7ae45203 --- /dev/null +++ b/web/resources/views/venix/cloud/pages/cloud-snapshots.tpl @@ -0,0 +1,18 @@ +
+
CLOUD SNAPSHOTS

云快照

长期保存由云备份转换而来的系统盘,并用于创建新的实例。

+ +
+
与在线快照不同云快照独立存放在对象存储中,不随源实例或自动备份轮换删除;只有手动删除后才会释放其存储对象。
+
+

全部云快照

从云快照创建的新实例会使用新的 UUID、网络标识和公网 IP。

0 个
+

正在读取云快照…

+
+ +
+ +
+ diff --git a/web/resources/views/venix/cloud/pages/deploy.tpl b/web/resources/views/venix/cloud/pages/deploy.tpl index b54b3bce..04c5e923 100644 --- a/web/resources/views/venix/cloud/pages/deploy.tpl +++ b/web/resources/views/venix/cloud/pages/deploy.tpl @@ -60,11 +60,11 @@
{if !empty($cloud_deploy_lines_enabled)}4{else}3{/if}

选择系统镜像(必选)

- -