feat: add durable cloud snapshot deployment flow

go
codex 3 weeks ago
parent 2c28497775
commit 3ad0a97ecd

@ -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、内存、系统盘、带宽及系统兼容元数据,归属原用户,但不继承订单、账单、套餐、服务期、到期时间或流量周期;后台将其标记为免计费实例。用户从云快照创建实例则走正常付费开通流程,使用当次选择的套餐规格和独立服务周期。
## 维护迁移

@ -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',

@ -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)
{

@ -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', []);

@ -0,0 +1,21 @@
<?php
namespace App\Models;
/** User-owned durable deployment source promoted from one cloud backup. */
final class CloudDeploymentSnapshot extends Model
{
protected $connection = 'default';
protected $table = 'cloud_deployment_snapshots';
protected $hidden = ['request_hash'];
protected $casts = [
'id' => 'int',
'user_id' => 'int',
'backup_id' => 'int',
'source_instance_id' => 'int',
'ready_at' => 'int',
'deleted_at' => 'int',
'created_at' => 'int',
'updated_at' => 'int',
];
}

@ -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',

@ -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

@ -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,

@ -0,0 +1,444 @@
<?php
namespace App\Services\Cloud;
use App\Models\CloudDeploymentSnapshot;
use App\Models\CloudInstance;
use App\Models\CloudInstanceBackup;
use App\Models\CloudJob;
use App\Models\CloudOrder;
use App\Models\User;
/** Durable user deployment sources promoted from automatic cloud backups. */
final class CloudDeploymentSnapshotService
{
public const MAX_PER_USER = 2;
/** Promote one immutable automatic backup without copying its S3 object. */
public static function promote(int $backupId, array $input,
array $actor): CloudDeploymentSnapshot
{
CloudInput::only($input, ['name', 'idempotency_key']);
$userId = self::actorUserId($actor);
$idempotency = $input['idempotency_key'] ?? null;
if (!is_string($idempotency)
|| preg_match('/^[A-Za-z0-9_.-]{16,128}$/D',
$idempotency) !== 1) {
throw new CloudError('请提供 16 至 128 字符的请求幂等标识');
}
$requestedName = $input['name'] ?? null;
if ($requestedName !== null && $requestedName !== '') {
$requestedName = CloudInput::snapshotName($requestedName);
} else {
$requestedName = null;
}
$requestHash = hash('sha256', json_encode([
'backup_id' => $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;
}
}

@ -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

@ -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);

@ -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 === ''

@ -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(

@ -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');

@ -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}}',

@ -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',

@ -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'

@ -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 || '云快照页面加载失败,请刷新后重试。');
}
}

@ -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);

@ -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))}

@ -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'}

@ -1,9 +1,9 @@
<div id="cloud-backups-workspace">
<div class="page-heading">
<div><span class="eyebrow">CLOUD BACKUPS</span><h1>云备份</h1><p>集中查看当前账户的云备份,并选择可用备份创建新的付费实例。</p></div>
<div><span class="eyebrow">CLOUD BACKUPS</span><h1>云备份</h1><p>集中查看当前账户的云备份,恢复原实例或保存为长期保留的云快照。</p></div>
<button id="cloud-backups-refresh" class="button button-outline" type="button"><span aria-hidden="true">↻</span> 刷新</button>
</div>
<div class="vm-settings-notice cloud-backups-notice"><strong>恢复入口说明</strong><span>此页面只用于从备份创建新实例。将已有实例恢复到某个备份,只能在该实例详情的“实例设置 → 自动备份”中执行。</span></div>
<div class="vm-settings-notice cloud-backups-notice"><strong>备份用途说明</strong><span>云备份用于恢复原实例,也可保存为长期保留的云快照;创建新实例请前往“云快照”。</span></div>
<section class="inventory-panel cloud-backups-panel" aria-labelledby="cloud-backups-list-title">
<div class="panel-heading"><div><h2 id="cloud-backups-list-title">全部备份</h2><p>只显示属于当前账户的普通云备份,不包含管理员维护迁移的临时数据。</p></div><span id="cloud-backups-count" class="state-pill other">0 个</span></div>
<p id="cloud-backups-status" class="vm-settings-status" role="status" aria-live="polite">正在读取云备份…</p>
@ -14,6 +14,6 @@
<button id="cloud-backups-next" class="button button-outline small" type="button" disabled>下一页</button>
</nav>
</section>
<noscript><p class="resource-warning">查看云备份和创建新实例需要启用 JavaScript。</p></noscript>
<noscript><p class="resource-warning">查看云备份和保存云快照需要启用 JavaScript。</p></noscript>
</div>
<script id="cloud-backups-bootstrap" type="application/json">{$cloud_backup_bootstrap_json|default:'{}' nofilter}</script>

@ -0,0 +1,18 @@
<div id="cloud-snapshots-workspace">
<div class="page-heading"><div><span class="eyebrow">CLOUD SNAPSHOTS</span><h1>云快照</h1><p>长期保存由云备份转换而来的系统盘,并用于创建新的实例。</p></div>
<button id="cloud-snapshots-refresh" class="button button-outline" type="button"><span aria-hidden="true">↻</span> 刷新</button>
</div>
<div class="vm-settings-notice cloud-snapshots-notice"><strong>与在线快照不同</strong><span>云快照独立存放在对象存储中,不随源实例或自动备份轮换删除;只有手动删除后才会释放其存储对象。</span></div>
<section class="inventory-panel cloud-backups-panel cloud-snapshots-panel" aria-labelledby="cloud-snapshots-list-title">
<div class="panel-heading"><div><h2 id="cloud-snapshots-list-title">全部云快照</h2><p>从云快照创建的新实例会使用新的 UUID、网络标识和公网 IP。</p></div><span id="cloud-snapshots-count" class="state-pill other">0 个</span></div>
<p id="cloud-snapshots-status" class="vm-settings-status" role="status" aria-live="polite">正在读取云快照…</p>
<div id="cloud-snapshots-list" class="cloud-backups-list cloud-snapshots-list" aria-live="polite"></div>
<nav class="cloud-backups-pagination cloud-snapshots-pagination" aria-label="云快照分页">
<button id="cloud-snapshots-previous" class="button button-outline small" type="button" disabled>上一页</button>
<span id="cloud-snapshots-page">第 1 / 1 页</span>
<button id="cloud-snapshots-next" class="button button-outline small" type="button" disabled>下一页</button>
</nav>
</section>
<noscript><p class="resource-warning">查看、创建实例和删除云快照需要启用 JavaScript。</p></noscript>
</div>
<script id="cloud-snapshots-bootstrap" type="application/json">{$cloud_snapshot_bootstrap_json|default:'{}' nofilter}</script>

@ -60,11 +60,11 @@
</section>
<section id="vm-source-step" class="deployment-step" aria-labelledby="deploy-source-title" aria-disabled="false">
<div class="deployment-step-heading"><span>{if !empty($cloud_deploy_lines_enabled)}4{else}3{/if}</span><h2 id="deploy-source-title">选择系统镜像<span class="deployment-required-mark" aria-hidden="true">*</span><span class="sr-only">(必选)</span></h2></div>
<input id="vm-backup-id" type="hidden" value="" />
<div id="vm-backup-source" class="deployment-backup-source" hidden>
<input id="vm-cloud-snapshot-key" type="hidden" value="" />
<div id="vm-cloud-snapshot-source" class="deployment-backup-source" hidden>
<span class="deployment-backup-source-icon" aria-hidden="true"><i class="mdi mdi-cloud-check-outline"></i></span>
<div><strong>从云备份创建新实例</strong><small id="vm-backup-source-name">正在核对备份…</small></div>
<a class="button button-outline small" href="/user/cloud/backups">重新选择</a>
<div><strong>从云快照创建新实例</strong><small id="vm-cloud-snapshot-source-name">正在核对云快照…</small></div>
<a class="button button-outline small" href="/user/cloud/cloud-snapshots">重新选择</a>
</div>
<div class="field full" id="vm-template-field"><input id="vm-template" name="template_id" type="hidden" value=""{if empty($cloud_deploy_template_groups)} disabled{/if} /><div id="vm-template-catalog" class="template-catalog" role="group" aria-labelledby="deploy-source-title" aria-required="true">
{if empty($cloud_deploy_template_groups)}

@ -178,7 +178,7 @@
<div class="vm-settings-actions"><button id="vm-automatic-backup-save" class="button button-primary" type="submit" disabled>保存备份计划</button></div>
<p id="vm-automatic-backup-error" class="form-error" role="alert" hidden></p>
</form>
<div class="vm-automatic-backup-list-heading"><div><h4>此实例的备份</h4><small>在“云备份”页面可使用这些备份创建新实例。</small></div><a class="button button-outline small" href="/user/cloud/backups">查看全部备份</a></div>
<div class="vm-automatic-backup-list-heading"><div><h4>此实例的备份</h4><small>可在“云备份”页面保存为云快照,再从“云快照”创建新实例。</small></div><a class="button button-outline small" href="/user/cloud/backups">查看全部备份</a></div>
<div id="vm-automatic-backup-list" class="vm-automatic-backup-list" aria-live="polite"></div>
</section>
<section id="vm-settings-section-snapshots" class="vm-settings-section" role="tabpanel" aria-labelledby="vm-settings-nav-snapshots" data-instance-setting-panel="snapshots" hidden>

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026102606' scope='global'}
{assign var=venix_asset_version value='2026102607' scope='global'}

@ -23,6 +23,9 @@
<a class="sidebar-link{if $panel_cloud_active_key == 'backups'} active{/if}" href="/user/cloud/backups">
<i class="mdi mdi-cloud-upload-outline nav-icon" aria-hidden="true"></i><span>云备份</span>
</a>
<a class="sidebar-link{if $panel_cloud_active_key == 'cloud-snapshots'} active{/if}" href="/user/cloud/cloud-snapshots">
<i class="mdi mdi-layers-triple-outline nav-icon" aria-hidden="true"></i><span>云快照</span>
</a>
{if !empty($user_iso_enabled)}
<a class="sidebar-link{if $panel_cloud_active_key == 'isos'} active{/if}" href="/user/cloud/iso-images">
<i class="mdi mdi-disc nav-icon" aria-hidden="true"></i><span>ISO 上传</span>

@ -616,6 +616,34 @@ CREATE TABLE cloud_instance_backups (
KEY cloud_instance_backup_owner (user_id, id),
KEY cloud_instance_backup_operation (last_operation_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- A user-owned, durable deployment source promoted from one automatic cloud
-- backup. The backing backup row remains the sole owner of the immutable S3
-- object in this first schema; user backup rotation and listing must exclude
-- a backup while an active deployment snapshot references it.
CREATE TABLE cloud_deployment_snapshots (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
snapshot_key CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
user_id BIGINT UNSIGNED NOT NULL,
backup_id BIGINT UNSIGNED NOT NULL,
source_instance_id BIGINT UNSIGNED NOT NULL,
name VARCHAR(64) NOT NULL,
state VARCHAR(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'ready',
idempotency_key VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
request_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
error_code VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '',
ready_at BIGINT UNSIGNED NOT NULL,
deleted_at BIGINT UNSIGNED DEFAULT NULL,
created_at BIGINT UNSIGNED NOT NULL,
updated_at BIGINT UNSIGNED NOT NULL,
UNIQUE KEY cloud_deployment_snapshot_key (snapshot_key),
UNIQUE KEY cloud_deployment_snapshot_backup (backup_id),
UNIQUE KEY cloud_deployment_snapshot_request (user_id, idempotency_key),
KEY cloud_deployment_snapshot_owner (user_id, state, id),
KEY cloud_deployment_snapshot_source (source_instance_id, state, id),
CONSTRAINT chk_cloud_deployment_snapshot_state CHECK (
state IN ('ready','deleting','delete_uncertain','deleted')
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- An ordinary restore creates a separate administrator-managed VM and does not
-- copy billing state. Maintenance migration also uses this table for its
-- hidden, pre-reserved target, but keeps target_instance_id NULL and preserves
@ -760,6 +788,7 @@ CREATE TABLE cloud_orders (
resource_pool_id BIGINT UNSIGNED DEFAULT NULL,
host_id BIGINT UNSIGNED DEFAULT NULL,
reservation_id BIGINT UNSIGNED DEFAULT NULL,
deployment_snapshot_id BIGINT UNSIGNED DEFAULT NULL,
idempotency_key VARCHAR(128) NOT NULL,
request_hash CHAR(64) NOT NULL,
amount DECIMAL(12,2) NOT NULL,
@ -780,7 +809,8 @@ CREATE TABLE cloud_orders (
KEY cloud_order_placement (resource_pool_id, host_id, status),
KEY cloud_order_admin_created (created_at, id),
KEY cloud_order_admin_status (status, created_at, id),
KEY cloud_order_admin_user (user_id, created_at, id)
KEY cloud_order_admin_user (user_id, created_at, id),
KEY cloud_order_deployment_snapshot (deployment_snapshot_id, status, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE cloud_order_items (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,

@ -20,9 +20,7 @@ namespace {
use App\Models\CloudInstanceBackup;
use App\Services\Config;
use App\Services\Cloud\CloudAutomaticBackupService;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudObjectStorageS3Client;
use App\Services\Cloud\CloudOrderService;
use App\Services\Cloud\CloudSecrets;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
@ -114,6 +112,13 @@ namespace {
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_deployment_snapshots', static function (
Blueprint $table
): void {
$table->increments('id');
$table->integer('backup_id')->unique();
$table->string('state');
});
foreach (['cloud_backup_restores', 'cloud_backup_recoveries'] as $tableName) {
$schema->create($tableName, static function (Blueprint $table): void {
$table->increments('id');
@ -208,44 +213,39 @@ namespace {
$insideGrace = $newBackup($newSubscription(12, [$now - 3 * 86400 + 1]), 'inside-grace');
$expired = $newBackup($newSubscription(13, [$now - 3 * 86400]), 'expired');
$renewed = $newBackup($newSubscription(14, [$now - 4 * 86400, $now + 20 * 86400]), 'renewed');
$ordinaryExpired = $newBackup(
$newSubscription(15, [$now - 3 * 86400]),
'ordinary-expired'
);
$capsule->table('cloud_deployment_snapshots')->insert([
'backup_id' => (int) $expired->id,
'state' => 'ready',
]);
$assert(CloudAutomaticBackupService::withinRecoveryGrace($paid, $now)
&& CloudAutomaticBackupService::withinRecoveryGrace($insideGrace, $now)
&& !CloudAutomaticBackupService::withinRecoveryGrace($expired, $now)
&& CloudAutomaticBackupService::withinRecoveryGrace($renewed, $now),
'Recovery eligibility did not follow the paid period plus three-day grace.');
$purchasable = new ReflectionMethod(
CloudOrderService::class, 'assertPurchasableBackup'
);
$metadata = $purchasable->invoke(null, $paid, 1);
$assert(($metadata['os_name'] ?? null) === 'Debian 13',
'A retained paid automatic backup could not create a new instance.');
$expiredRejected = false;
try {
$purchasable->invoke(null, $expired, 1);
} catch (CloudError $error) {
$expiredRejected = $error->httpStatus === 409;
}
$assert($expiredRejected,
'An expired automatic backup remained purchasable after grace.');
$history = [];
$stack = HandlerStack::create(new MockHandler([new Response(204)]));
$stack->push(Middleware::history($history));
$client = new CloudObjectStorageS3Client(new Client(['handler' => $stack]));
$removed = CloudAutomaticBackupService::pruneRetention(10, $now, $client);
foreach ([$paid, $insideGrace, $expired, $renewed] as $backup) {
foreach ([$paid, $insideGrace, $expired, $renewed, $ordinaryExpired]
as $backup) {
$backup->refresh();
}
$assert($removed === 1
&& (string) $paid->state === 'ready'
&& (string) $insideGrace->state === 'ready'
&& (string) $expired->state === 'deleted'
&& (string) $expired->state === 'ready'
&& (string) $renewed->state === 'ready'
&& (string) $ordinaryExpired->state === 'deleted'
&& count($history) === 1
&& $history[0]['request']->getMethod() === 'DELETE',
'Automatic backups were not retained until exactly three days after the last paid entitlement ended.');
'Automatic backups were not retained through grace or were pruned after promotion to a cloud snapshot.');
echo "Automatic backup entitlement grace retention tests passed.\n";
}

@ -97,6 +97,12 @@ $schema->create('cloud_instance_backups',
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_deployment_snapshots',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('backup_id')->unique();
$table->string('state');
});
$instance = new CloudInstance();
$instance->id = 1;

@ -203,11 +203,15 @@ $assert($selectRegion !== '' && $selectLine !== '' && $selectOffer !== ''
&& !str_contains($selectOffer, 'loadGlobalTemplates(')
&& str_contains($buy, 'offer_id: Number(byId(\'vm-offer\').value)')
&& str_contains($buy, "automatic_backup: byId('vm-automatic-backup')?.checked === true")
&& str_contains($buy, 'body.backup_id = Number(state.deployBackupId)')
&& str_contains($buy,
'body.cloud_snapshot_key = state.deployCloudSnapshotKey')
&& str_contains($buy,
"source: state.deployCloudSnapshotKey ? 'deployment_snapshot' : 'cloud'")
&& !str_contains($buy, 'body.backup_id =')
&& !str_contains($buy, 'plan_id:')
&& str_contains($buy, 'provisionInvoiceFingerprint(body)')
&& str_contains($buy, 'pendingProvisionInvoiceKey(fingerprint)'),
'Changing a region, line or offer must preserve the source and purchasing must keep backup-aware offer idempotency.');
'Changing a region, line or offer must preserve the source and purchasing must keep cloud-snapshot-aware offer idempotency.');
$assert(!str_contains($buy, 'confirm(')
&& !str_contains($buy, 'toast(')
&& !str_contains($buy, 'purchaseSummary')

@ -0,0 +1,124 @@
<?php
$root = dirname(__DIR__);
$read = static function (string $path) use ($root): string {
$full = $root . '/' . $path;
return is_file($full) ? (string) file_get_contents($full) : '';
};
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$section = static function (string $source, string $start,
string $end): string {
$offset = strpos($source, $start);
if ($offset === false) {
return '';
}
$finish = strpos($source, $end, $offset + strlen($start));
return $finish === false ? substr($source, $offset)
: substr($source, $offset, $finish - $offset);
};
$schema = $read('sql/cloud.sql');
$orders = $read('app/Services/Cloud/CloudOrderService.php');
$backups = $read('app/Services/Cloud/CloudBackupService.php');
$recovery = $read(
'app/Services/Cloud/CloudOperationRecoveryIdentity.php'
);
$placement = $read('app/Services/Cloud/CloudPlacementService.php');
$worker = $read('app/Services/Cloud/CloudWorkerService.php');
$catalog = $read('app/Services/Cloud/CloudDeploymentSnapshotService.php')
. $read('app/Services/Cloud/CloudDeploymentSnapshotCatalog.php');
$purchase = $section($orders, 'public static function purchase(',
'private static function createPurchaseItems(');
$payment = $section($orders, 'public static function queuePaidProvision(',
'/** Release a finite plan reservation exactly once. */');
$assert($purchase !== ''
&& str_contains($purchase, "['cloud', 'deployment_snapshot']")
&& str_contains($purchase, "'cloud_snapshot_key'")
&& str_contains($purchase, "'deployment_snapshot'")
&& str_contains($purchase, "array_key_exists('backup_id', \$input)")
&& !str_contains($purchase, "['cloud', 'backup']")
&& !str_contains($purchase, "\$source === 'backup'"),
'Public provisioning must accept a cloud snapshot key and must not accept a cloud backup as an instance source.');
$assert(str_contains($schema, 'CREATE TABLE cloud_deployment_snapshots')
&& str_contains($schema,
'deployment_snapshot_id BIGINT UNSIGNED DEFAULT NULL')
&& str_contains($schema, 'cloud_order_deployment_snapshot')
&& str_contains($orders, '$order->deployment_snapshot_id')
&& str_contains($orders, '$sourceSnapshot->id'),
'Provisioning orders must persist the selected deployment snapshot instead of relying on a request-only source key.');
$assert(str_contains($purchase, "'deployment_snapshot_id'")
&& str_contains($purchase, "'cloud_snapshot_key'")
&& str_contains($purchase, "'backing_backup_id'")
&& str_contains($purchase, "'backing_backup_key'")
&& str_contains($purchase, "'backing_backup_size_bytes'")
&& str_contains($purchase, "'backing_backup_virtual_size_bytes'")
&& str_contains($purchase, "'backing_backup_sha256'")
&& str_contains($purchase, "'backing_backup_identity'"),
'The safe order snapshot must freeze both the public cloud snapshot and its immutable backing object identity.');
$jobBound = str_contains($schema,
'deployment_snapshot_id BIGINT UNSIGNED DEFAULT NULL')
&& str_contains($schema, 'cloud_job_deployment_snapshot')
&& str_contains($orders, '$job->deployment_snapshot_id')
|| (str_contains($orders, '$job->backup_id')
&& str_contains($payment, 'backing_backup_id'));
$assert($jobBound,
'Provisioning jobs must remain audibly bound to the deployment snapshot or its frozen backing backup.');
$assert(str_contains($recovery, "!== 'deployment_snapshot'")
&& !str_contains($recovery, "!== 'backup'")
&& str_contains($placement, "=== 'deployment_snapshot'")
&& !str_contains($placement, "=== 'backup'"),
'Placement and operation recovery must use the cloud snapshot source contract while preserving the internal restore-backup protocol.');
$assert(!str_contains($orders, 'backup_sealed_credential')
&& !str_contains($recovery, 'backup_sealed_credential')
&& str_contains($worker, '$instance->sealed_credential = null;'),
'Cloud-snapshot provisioning must preserve the system-disk password and must not expose the historical panel credential as current.');
$assert($catalog !== ''
&& substr_count($catalog, 'lockForUpdate()') >= 2
&& str_contains($catalog, "'ready'")
&& str_contains($catalog, 'sha256')
&& str_contains($catalog, 'object_size_bytes')
&& str_contains($catalog, 'virtual_size_bytes')
&& str_contains($purchase, 'CloudDeploymentSnapshot')
&& str_contains($payment, 'CloudDeploymentSnapshot'),
'Purchase and paid provisioning must both re-lock a ready snapshot and validate the immutable object identity.');
$automaticCapacity = $section($backups,
'$usedQuery = CloudInstanceBackup::where(',
'$used = (int) $usedQuery->count');
$assert(str_contains($automaticCapacity, 'whereNotExists')
&& str_contains($automaticCapacity, 'cloud_deployment_snapshots')
&& str_contains($automaticCapacity, 'cloud_deployment_snapshots.state')
&& str_contains($automaticCapacity, "'deleted'"),
'Promoted snapshot backings must not consume the rolling automatic-backup retention capacity.');
$assert(str_contains($catalog, 'CloudOrder')
&& str_contains($catalog, 'deployment_snapshot_id')
&& str_contains($catalog, "'awaiting_payment'")
&& str_contains($catalog, "'queued'")
&& str_contains($catalog, 'effect_resolution')
&& str_contains($catalog, "'unknown'")
&& str_contains($catalog, 'finalization_incident'),
'Snapshot deletion must remain fenced by unpaid, queued, and unknown-effect provisioning references.');
$assert(!preg_match(
"/whereIn\\('status',\\s*\\[[^]]*'succeeded'[^]]*\\]\\)/s",
$catalog
)
&& !preg_match(
"/whereIn\\('status',\\s*\\[[^]]*'expired'[^]]*\\]\\)/s",
$catalog
),
'Terminal safe and expired provisioning orders must not permanently block manual snapshot deletion.');
echo "Cloud deployment snapshot order and deletion contracts passed.\n";

@ -0,0 +1,460 @@
<?php
namespace App\Services {
final class Config
{
public static string $dataKey = '';
public static function get($name, $default = null)
{
return $name === 'cloud_data_key' ? self::$dataKey : $default;
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudInstanceBackup;
use App\Services\Config;
use App\Services\Cloud\CloudDeploymentSnapshotService;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudObjectStorageS3Client;
use App\Services\Cloud\CloudSecrets;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$expect = static function (int $status, callable $callback) use (
$assert
): void {
try {
$callback();
} catch (CloudError $error) {
$assert($error->httpStatus === $status,
'Cloud snapshot failure returned the wrong status.');
return;
}
throw new RuntimeException('Expected cloud snapshot failure.');
};
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite', 'database' => ':memory:',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('user', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('enable');
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
$table->string('name');
$table->string('status');
});
$schema->create('cloud_backup_subscriptions',
static function (Blueprint $table): void {
$table->increments('id');
});
$schema->create('cloud_backup_period_entitlements',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('subscription_id');
$table->integer('ends_at');
});
$schema->create('cloud_instance_backups',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('backup_key')->unique();
$table->integer('source_instance_id');
$table->integer('source_host_id');
$table->integer('user_id');
$table->string('source_uuid');
$table->string('name');
$table->string('purpose');
$table->string('source');
$table->integer('subscription_id')->nullable();
$table->integer('scheduled_for')->nullable();
$table->string('state');
$table->string('consistency');
$table->string('object_key')->unique();
$table->integer('object_size_bytes');
$table->integer('virtual_size_bytes');
$table->string('sha256');
$table->text('spec_json');
$table->text('sealed_storage_runtime');
$table->text('sealed_credential')->nullable();
$table->integer('storage_revision');
$table->integer('active_job_id')->nullable();
$table->string('last_operation_id')->nullable();
$table->string('error_code');
$table->integer('ready_at')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_deployment_snapshots',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('snapshot_key')->unique();
$table->integer('user_id');
$table->integer('backup_id')->unique();
$table->integer('source_instance_id');
$table->string('name');
$table->string('state');
$table->string('idempotency_key');
$table->string('request_hash');
$table->string('error_code');
$table->integer('ready_at');
$table->integer('deleted_at')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
$table->unique(['user_id', 'idempotency_key']);
});
$schema->create('cloud_orders', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
$table->integer('deployment_snapshot_id')->nullable();
$table->string('status');
});
$schema->create('cloud_backup_restores',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('backup_id');
$table->string('state');
});
$schema->create('cloud_backup_recoveries',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('backup_id');
$table->string('state');
});
$schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('backup_id')->nullable();
$table->string('phase');
$table->string('effect_resolution');
$table->integer('finalization_incident')->default(0);
});
$now = time();
$capsule->table('user')->insert([
['id' => 7, 'enable' => 1],
['id' => 8, 'enable' => 1],
]);
$capsule->table('cloud_instances')->insert([
'id' => 50, 'user_id' => 7, 'name' => 'source-vm',
'status' => 'active',
]);
foreach ([1, 2, 3, 4] as $subscriptionId) {
$capsule->table('cloud_backup_subscriptions')->insert([
'id' => $subscriptionId,
]);
}
$capsule->table('cloud_backup_period_entitlements')->insert([
['subscription_id' => 1, 'ends_at' => $now + 86400],
['subscription_id' => 2, 'ends_at' => $now - 4 * 86400],
['subscription_id' => 3, 'ends_at' => $now + 86400],
['subscription_id' => 4, 'ends_at' => $now + 86400],
]);
Config::$dataKey = base64_encode(str_repeat('d', 32));
$sealedRuntime = function_exists(
'sodium_crypto_aead_xchacha20poly1305_ietf_encrypt'
) ? CloudSecrets::encrypt([
'config' => [
'endpoint' => 'https://objects.example.com',
'region' => 'us-east-1',
'bucket' => 'backup-bucket',
'prefix' => 'virt',
'path_style' => true,
],
'credentials' => [
'access_key_id' => 'SNAPSHOTACCESS',
'secret_access_key' => 'snapshot-secret-value',
],
'revision' => 1,
], 'object-storage-backup-runtime') : 'sealed-runtime-test-double';
$newBackup = static function (int $id, int $userId, int $subscriptionId,
string $state = 'ready') use ($now, $sealedRuntime): CloudInstanceBackup {
$backup = new CloudInstanceBackup();
$backup->id = $id;
$backup->backup_key = str_pad(dechex($id), 32, '0', STR_PAD_LEFT);
$backup->source_instance_id = 50;
$backup->source_host_id = 3;
$backup->user_id = $userId;
$backup->source_uuid = '11111111-1111-4111-8111-111111111111';
$backup->name = 'backup-' . $id;
$backup->purpose = 'portable';
$backup->source = 'automatic';
$backup->subscription_id = $subscriptionId;
$backup->scheduled_for = $now - 60;
$backup->state = $state;
$backup->consistency = 'filesystem';
$backup->object_key = 'virt/vm-backups/' . $id . '/system.qcow2';
$backup->object_size_bytes = 1024;
$backup->virtual_size_bytes = 2048;
$backup->sha256 = str_repeat(dechex(($id % 15) + 1), 64);
$backup->spec_json = json_encode([
'managed' => true,
'os_source' => 'cloud_template',
'os_name' => 'Debian 13',
'login_name' => 'root',
'debian_12_network_fix' => false,
], JSON_THROW_ON_ERROR);
$backup->sealed_storage_runtime = $sealedRuntime;
$backup->sealed_credential = 'sealed-credential';
$backup->storage_revision = 1;
$backup->active_job_id = null;
$backup->last_operation_id = null;
$backup->error_code = '';
$backup->ready_at = $now;
$backup->created_at = $backup->updated_at = $now;
$backup->save();
return $backup;
};
$actor = ['user_id' => 7];
$good = $newBackup(11, 7, 1);
$good->sealed_credential = null;
$good->save();
$snapshot = CloudDeploymentSnapshotService::promote(11, [
'name' => '生产恢复点',
'idempotency_key' => 'snapshot-promote-0001',
], $actor);
$replayed = CloudDeploymentSnapshotService::promote(11, [
'name' => '生产恢复点',
'idempotency_key' => 'snapshot-promote-0001',
], $actor);
$assert((int) $snapshot->id === (int) $replayed->id
&& preg_match('/^[a-f0-9]{32}$/D',
(string) $snapshot->snapshot_key) === 1,
'Cloud backup promotion was not idempotent.');
$expect(409, static fn () =>
CloudDeploymentSnapshotService::promote(11, [
'name' => '不同名称',
'idempotency_key' => 'snapshot-promote-0001',
], $actor));
$library = CloudDeploymentSnapshotService::library($actor, [
'page' => 1, 'per_page' => 20,
]);
$item = $library['items'][0] ?? [];
$assert(($library['pagination']['total'] ?? 0) === 1
&& ($item['snapshot_key'] ?? '') === (string) $snapshot->snapshot_key
&& ($item['name'] ?? '') === '生产恢复点'
&& ($item['os_name'] ?? '') === 'Debian 13'
&& ($item['source_instance']['name'] ?? '') === 'source-vm'
&& !array_key_exists('backup_id', $item)
&& !array_key_exists('object_key', $item)
&& !array_key_exists('sha256', $item)
&& !array_key_exists('sealed_storage_runtime', $item),
'Cloud snapshot library leaked backing identity or omitted display data.');
$capsule->table('cloud_backup_period_entitlements')
->where('subscription_id', 1)->update(['ends_at' => $now - 5 * 86400]);
$resolved = CloudDeploymentSnapshotService::resolveForOrder(
(string) $snapshot->snapshot_key, 7
);
$assert((int) $resolved['backup']->id === (int) $good->id,
'A promoted cloud snapshot incorrectly followed later backup entitlement expiry.');
$deploymentSource = CloudDeploymentSnapshotService::deploymentSource(
(string) $snapshot->snapshot_key, $actor
);
$assert(($deploymentSource['snapshot_key'] ?? '')
=== (string) $snapshot->snapshot_key
&& ($deploymentSource['can_create_instance'] ?? false) === true
&& !array_key_exists('object_key', $deploymentSource),
'Deployment bootstrap did not resolve a safe owner snapshot projection.');
$capsule->table('cloud_instance_backups')->where('id', (int) $good->id)
->update(['state' => 'failed']);
foreach ([
static fn () => CloudDeploymentSnapshotService::resolveForOrder(
(string) $snapshot->snapshot_key, 7
),
static fn () => CloudDeploymentSnapshotService::deploymentSource(
(string) $snapshot->snapshot_key, $actor
),
] as $invalidDeploymentSource) {
try {
$invalidDeploymentSource();
throw new RuntimeException(
'Invalid backing unexpectedly remained deployable.'
);
} catch (CloudError $error) {
$assert($error->getMessage()
=== '云快照不存在或当前不可用于部署',
'Deployment used the backup-promotion error vocabulary.');
}
}
$capsule->table('cloud_instance_backups')->where('id', (int) $good->id)
->update(['state' => 'ready']);
$capsule->table('cloud_deployment_snapshots')
->where('id', (int) $snapshot->id)
->update(['source_instance_id' => 999]);
$expect(409, static fn () =>
CloudDeploymentSnapshotService::resolveForOrder(
(string) $snapshot->snapshot_key, 7
));
$expect(409, static fn () =>
CloudDeploymentSnapshotService::deploymentSource(
(string) $snapshot->snapshot_key, $actor
));
$capsule->table('cloud_deployment_snapshots')
->where('id', (int) $snapshot->id)
->update(['source_instance_id' => (int) $good->source_instance_id]);
$wrongOwner = $newBackup(12, 8, 3);
$expect(409, static fn () =>
CloudDeploymentSnapshotService::promote((int) $wrongOwner->id, [
'idempotency_key' => 'snapshot-promote-0002',
], $actor));
$failed = $newBackup(13, 7, 3, 'failed');
$expect(409, static fn () =>
CloudDeploymentSnapshotService::promote((int) $failed->id, [
'idempotency_key' => 'snapshot-promote-0003',
], $actor));
$expired = $newBackup(14, 7, 2);
$expect(409, static fn () =>
CloudDeploymentSnapshotService::promote((int) $expired->id, [
'idempotency_key' => 'snapshot-promote-0004',
], $actor));
$capsule->table('cloud_orders')->insert([
'id' => 91,
'user_id' => 7,
'deployment_snapshot_id' => (int) $snapshot->id,
'status' => 'awaiting_payment',
]);
$expect(409, static fn () => CloudDeploymentSnapshotService::delete(
(string) $snapshot->snapshot_key, $actor
));
$capsule->table('cloud_orders')->where('id', 91)
->update(['status' => 'expired']);
$capsule->table('cloud_jobs')->insert([
'id' => 81,
'backup_id' => (int) $good->id,
'phase' => 'accepted',
'effect_resolution' => 'not_applicable',
'finalization_incident' => 0,
]);
$expect(409, static fn () => CloudDeploymentSnapshotService::delete(
(string) $snapshot->snapshot_key, $actor
));
$capsule->table('cloud_jobs')->where('id', 81)->update([
'phase' => 'terminal',
'effect_resolution' => 'applied',
]);
$capsule->table('cloud_jobs')->insert([
'id' => 82,
'backup_id' => (int) $good->id,
'phase' => 'terminal',
'effect_resolution' => 'unknown',
'finalization_incident' => 0,
]);
$expect(409, static fn () => CloudDeploymentSnapshotService::delete(
(string) $snapshot->snapshot_key, $actor
));
$capsule->table('cloud_jobs')->where('id', 82)->update([
'effect_resolution' => 'not_applied',
]);
$capsule->table('cloud_jobs')->insert([
'id' => 83,
'backup_id' => (int) $good->id,
'phase' => 'terminal',
'effect_resolution' => 'applied',
'finalization_incident' => 1,
]);
$expect(409, static fn () => CloudDeploymentSnapshotService::delete(
(string) $snapshot->snapshot_key, $actor
));
$capsule->table('cloud_jobs')->where('id', 83)->update([
'finalization_incident' => 0,
]);
if (function_exists('sodium_crypto_aead_xchacha20poly1305_ietf_encrypt')) {
$client = static function (array $responses,
array &$history): CloudObjectStorageS3Client {
$stack = HandlerStack::create(new MockHandler($responses));
$stack->push(Middleware::history($history));
return new CloudObjectStorageS3Client(new Client([
'handler' => $stack,
]));
};
$history = [];
$deleted = CloudDeploymentSnapshotService::delete(
(string) $snapshot->snapshot_key,
$actor,
$client([new Response(204)], $history)
);
$good->refresh();
$assert(($deleted['state'] ?? '') === 'deleted'
&& (string) $good->state === 'deleted'
&& count($history) === 1
&& $history[0]['request']->getMethod() === 'DELETE',
'Cloud snapshot deletion did not converge its backing object.');
$uncertainBackup = $newBackup(15, 7, 3);
$uncertainSnapshot = CloudDeploymentSnapshotService::promote(15, [
'idempotency_key' => 'snapshot-promote-0005',
], $actor);
$uncertainHistory = [];
$uncertain = CloudDeploymentSnapshotService::delete(
(string) $uncertainSnapshot->snapshot_key,
$actor,
$client([new ConnectException(
'timeout', new Request('DELETE', 'https://objects.example.com')
)], $uncertainHistory)
);
$assert(($uncertain['state'] ?? '') === 'delete_uncertain'
&& count($uncertainHistory) === 1
&& $uncertainHistory[0]['request']->getMethod() === 'DELETE',
'Unknown object deletion was not reflected by the cloud snapshot.');
$reconcileHistory = [];
$reconciled = CloudDeploymentSnapshotService::delete(
(string) $uncertainSnapshot->snapshot_key,
$actor,
$client([new Response(404)], $reconcileHistory)
);
$assert(($reconciled['state'] ?? '') === 'deleted'
&& count($reconcileHistory) === 1
&& $reconcileHistory[0]['request']->getMethod() === 'HEAD',
'Cloud snapshot reconciliation replayed DeleteObject.');
} else {
$capsule->table('cloud_deployment_snapshots')
->where('id', (int) $snapshot->id)->update([
'state' => 'deleted', 'deleted_at' => $now,
]);
$capsule->table('cloud_instance_backups')
->where('id', (int) $good->id)->update(['state' => 'deleted']);
}
$second = $newBackup(16, 7, 3);
CloudDeploymentSnapshotService::promote((int) $second->id, [
'idempotency_key' => 'snapshot-promote-0006',
], $actor);
$third = $newBackup(17, 7, 4);
CloudDeploymentSnapshotService::promote((int) $third->id, [
'idempotency_key' => 'snapshot-promote-0007',
], $actor);
$fourth = $newBackup(18, 7, 4);
$expect(409, static fn () =>
CloudDeploymentSnapshotService::promote((int) $fourth->id, [
'idempotency_key' => 'snapshot-promote-0008',
], $actor));
echo "Cloud deployment snapshot service tests passed.\n";
}

@ -92,6 +92,7 @@ namespace {
use App\Models\CloudHostNetworkAttachment;
use App\Models\CloudHostResourcePoolMembership;
use App\Models\CloudBackupSubscription;
use App\Models\CloudDeploymentSnapshot;
use App\Models\CloudInstanceBackup;
use App\Models\CloudBackupRestore;
use App\Models\CloudInstance;
@ -253,11 +254,12 @@ namespace {
$schema->create('cloud_template_replicas', function (Blueprint $t) { $t->integer('host_id'); $t->string('template_id'); $t->integer('job_id')->nullable(); $t->integer('revision'); $t->string('generation_token'); $t->string('state')->default('pending'); $t->integer('image_bytes')->default(0); $t->string('sha256')->default(''); $t->string('operation_id')->default(''); $t->string('error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); $t->primary(['host_id', 'template_id']); });
$schema->create('cloud_platform_test_policy_state', function (Blueprint $t) { $t->integer('id')->primary(); $t->integer('revision')->default(0); $t->integer('updated_by')->nullable(); $t->integer('updated_at')->default(0); });
$schema->create('cloud_platform_test_policy_rules', function (Blueprint $t) { $t->increments('id'); $t->string('rule_key', 32)->unique(); $t->string('service', 120); $t->string('protocol', 8); $t->integer('port_from'); $t->integer('port_to'); $t->string('direction', 8); $t->string('reason', 500); $t->integer('created_by'); $t->integer('updated_by'); $t->integer('deleted_by')->nullable(); $t->integer('deleted_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_orders', function (Blueprint $t) { $t->increments('id'); foreach (['user_id', 'plan_id', 'offer_id', 'resource_pool_id'] as $v) { $t->integer($v); } $t->integer('host_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->string('currency')->default('USD'); $t->string('status'); $t->text('spec_json'); $t->text('sealed_payload')->nullable(); $t->integer('instance_id')->nullable(); $t->integer('refunded_at')->nullable(); $t->integer('stock_reserved_at')->nullable(); $t->integer('stock_released_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); });
$schema->create('cloud_orders', function (Blueprint $t) { $t->increments('id'); foreach (['user_id', 'plan_id', 'offer_id', 'resource_pool_id'] as $v) { $t->integer($v); } $t->integer('host_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->integer('deployment_snapshot_id')->nullable(); $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->string('currency')->default('USD'); $t->string('status'); $t->text('spec_json'); $t->text('sealed_payload')->nullable(); $t->integer('instance_id')->nullable(); $t->integer('refunded_at')->nullable(); $t->integer('stock_reserved_at')->nullable(); $t->integer('stock_released_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); });
$schema->create('cloud_order_items', function (Blueprint $t) { $t->increments('id'); $t->integer('order_id'); $t->string('code'); $t->string('label'); $t->string('amount'); $t->string('currency')->default('USD'); $t->text('snapshot_json'); $t->integer('created_at'); $t->unique(['order_id', 'code']); });
$schema->create('cloud_resource_reservations', function (Blueprint $t) { $t->increments('id'); $t->string('reservation_key')->unique(); $t->string('operation_id')->unique(); $t->integer('order_id')->nullable(); $t->integer('backup_restore_id')->nullable(); $t->integer('offer_id')->nullable(); foreach (['resource_pool_id', 'host_id', 'user_id'] as $v) { $t->integer($v); } $t->integer('instance_id')->nullable(); $t->integer('network_attachment_id')->nullable(); $t->integer('public_ip_pool_id')->nullable(); $t->integer('public_ip_id')->nullable(); foreach (['cpu_cores', 'memory_mib', 'disk_gib'] as $v) { $t->integer($v); } $t->string('state'); $t->integer('expires_at')->nullable(); $t->integer('released_at')->nullable(); $t->string('release_reason')->default(''); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); $t->unique('backup_restore_id'); });
$schema->create('cloud_backup_restores', function (Blueprint $t) { $t->increments('id'); $t->string('restore_key')->unique(); $t->integer('backup_id'); $t->integer('target_host_id'); $t->integer('target_instance_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->integer('job_id')->nullable(); $t->string('operation_id')->unique(); $t->string('new_uuid'); $t->string('new_name'); $t->string('state'); $t->string('error_code')->default(''); $t->integer('ready_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_instance_backups', function (Blueprint $t) { $t->increments('id'); $t->string('backup_key')->unique(); $t->integer('source_instance_id'); $t->integer('source_host_id'); $t->integer('user_id'); $t->string('source_uuid'); $t->string('name'); $t->string('purpose')->default('portable'); $t->string('source')->default('manual'); $t->integer('subscription_id')->nullable(); $t->integer('scheduled_for')->nullable(); $t->string('state')->default('creating'); $t->string('consistency'); $t->string('object_key')->unique(); $t->integer('object_size_bytes')->default(0); $t->integer('virtual_size_bytes')->default(0); $t->string('sha256')->default(''); $t->text('spec_json'); $t->text('sealed_storage_runtime'); $t->text('sealed_credential')->nullable(); $t->integer('storage_revision'); $t->integer('active_job_id')->nullable(); $t->string('last_operation_id')->nullable(); $t->string('error_code')->default(''); $t->integer('ready_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['subscription_id', 'scheduled_for']); });
$schema->create('cloud_deployment_snapshots', function (Blueprint $t) { $t->increments('id'); $t->string('snapshot_key')->unique(); $t->integer('user_id'); $t->integer('backup_id')->unique(); $t->integer('source_instance_id'); $t->string('name'); $t->string('state')->default('ready'); $t->string('idempotency_key'); $t->string('request_hash'); $t->string('error_code')->default(''); $t->integer('ready_at'); $t->integer('deleted_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); });
$schema->create('cloud_jobs', function (Blueprint $t) {
$t->increments('id');
$t->string('operation_id')->unique();
@ -921,17 +923,124 @@ namespace {
$sourceBackup->ready_at = time();
$sourceBackup->created_at = $sourceBackup->updated_at = time();
$sourceBackup->save();
$orderCountBeforeDirectBackupRequest = CloudOrder::count();
try {
CloudOrderService::purchase([
'offer_id' => (int) $offer->id,
'source' => 'backup',
'backup_id' => (int) $sourceBackup->id,
'name' => 'forbidden-backup-source',
'automatic_backup' => false,
'idempotency_key' => 'test-direct-backup-source-0001',
], $actor);
throw new RuntimeException(
'A cloud backup was accepted as a public deployment source.'
);
} catch (CloudError $error) {
$assert(str_contains($error->getMessage(), '云快照'),
'Direct backup deployment did not direct the user to cloud snapshots.');
}
$assert(CloudOrder::count() === $orderCountBeforeDirectBackupRequest,
'Rejected direct backup deployment created finance state.');
// The guest system disk is authoritative. A restored source may no longer
// have a trustworthy panel credential envelope and must still be usable
// as a cloud snapshot deployment source.
$sourceBackup->sealed_credential = null;
$sourceBackup->updated_at = time();
$sourceBackup->save();
$deploymentSnapshot = new CloudDeploymentSnapshot();
$deploymentSnapshot->snapshot_key = str_repeat('e', 32);
$deploymentSnapshot->user_id = 1;
$deploymentSnapshot->backup_id = (int) $sourceBackup->id;
$deploymentSnapshot->source_instance_id = (int) $instance->id;
$deploymentSnapshot->name = 'deployment-snapshot-fixture';
$deploymentSnapshot->state = 'ready';
$deploymentSnapshot->idempotency_key =
'snapshot-promotion-test-0001';
$deploymentSnapshot->request_hash = str_repeat('f', 64);
$deploymentSnapshot->error_code = '';
$deploymentSnapshot->ready_at = time();
$deploymentSnapshot->created_at =
$deploymentSnapshot->updated_at = time();
$deploymentSnapshot->save();
$failed = CloudOrderService::purchase([
'offer_id' => (int) $offer->id,
'source' => 'backup',
'backup_id' => (int) $sourceBackup->id,
'source' => 'deployment_snapshot',
'cloud_snapshot_key' => $deploymentSnapshot->snapshot_key,
'name' => 'vm-two',
'automatic_backup' => false,
'idempotency_key' => 'test-request-key-0002',
], $actor);
$failedSpec = json_decode(
(string) $failed->spec_json,
true,
64,
JSON_THROW_ON_ERROR
);
$assert((int) $failed->deployment_snapshot_id
=== (int) $deploymentSnapshot->id
&& ($failedSpec['source'] ?? null) === 'deployment_snapshot'
&& (int) ($failedSpec['deployment_snapshot_id'] ?? 0)
=== (int) $deploymentSnapshot->id
&& ($failedSpec['cloud_snapshot_key'] ?? null)
=== $deploymentSnapshot->snapshot_key
&& (int) ($failedSpec['backing_backup_id'] ?? 0)
=== (int) $sourceBackup->id
&& ($failedSpec['backing_backup_key'] ?? null)
=== $sourceBackup->backup_key,
'Cloud snapshot purchase did not freeze its snapshot and backing object identity.');
$assert(User::find(1)->money === '90.01'
&& CloudJob::where('order_id', $failed->id)->count() === 0,
'A second unpaid deployment charged or entered the worker queue.');
$deploymentSnapshot->state = 'deleting';
$deploymentSnapshot->updated_at = time();
$deploymentSnapshot->save();
try {
CloudInvoiceService::payBalance(
CloudInvoice::where('order_id', $failed->id)->first(),
$actor,
'snapshot-not-ready-payment-0001'
);
throw new RuntimeException(
'A non-ready cloud snapshot entered the worker queue.'
);
} catch (CloudError $error) {
$assert($error->httpStatus === 404,
'A non-ready cloud snapshot returned the wrong payment error.');
}
$assert(User::find(1)->money === '90.01'
&& CloudJob::where('order_id', $failed->id)->count() === 0
&& (string) CloudOrder::find($failed->id)->status
=== 'awaiting_payment',
'Rejected cloud snapshot payment changed money or finance state.');
$deploymentSnapshot->state = 'ready';
$deploymentSnapshot->updated_at = time();
$deploymentSnapshot->save();
$originalBackingSha256 = (string) $sourceBackup->sha256;
$sourceBackup->sha256 = str_repeat('b', 64);
$sourceBackup->updated_at = time();
$sourceBackup->save();
try {
CloudInvoiceService::payBalance(
CloudInvoice::where('order_id', $failed->id)->first(),
$actor,
'snapshot-identity-payment-0001'
);
throw new RuntimeException(
'A changed cloud snapshot backing object entered the worker queue.'
);
} catch (CloudError $error) {
$assert($error->httpStatus === 409,
'A changed cloud snapshot backing object returned the wrong payment error.');
}
$assert(User::find(1)->money === '90.01'
&& CloudJob::where('order_id', $failed->id)->count() === 0
&& (string) CloudOrder::find($failed->id)->status
=== 'awaiting_payment',
'Backing identity rejection changed money or finance state.');
$sourceBackup->sha256 = $originalBackingSha256;
$sourceBackup->updated_at = time();
$sourceBackup->save();
CloudInvoiceService::payBalance(CloudInvoice::where('order_id', $failed->id)->first(),
$actor, 'provision-balance-test-0002');
$failedJob = CloudJob::where('order_id', $failed->id)->first();

@ -22,7 +22,7 @@ $assert(stripos($schema, 'compatibility import') === false
$assert(!preg_match('/\bengine_[A-Za-z0-9_]*\b/', $schema),
'cloud.sql retained an engine-prefixed identifier.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v9-backup-utc-schedule'")
"SCHEMA_VERSION = 'go-agent-wss-v10-deployment-snapshots'")
&& !str_contains($setup, "SCHEMA_VERSION = 'go-v1'"),
'Outbound Agent schema must reject the incompatible earlier Go database.');
$assert(str_contains($schema,
@ -34,6 +34,7 @@ foreach (['cloud_host_agents', 'cloud_templates', 'cloud_hosts', 'cloud_instance
'cloud_orders', 'cloud_invoices', 'cloud_jobs',
'cloud_agent_completion_events', 'cloud_console_tickets',
'cloud_rescue_template_imports', 'cloud_instance_backups',
'cloud_deployment_snapshots',
'cloud_backup_subscriptions', 'cloud_backup_period_entitlements',
'cloud_backup_restores',
'cloud_backup_recoveries', 'cloud_order_items', 'cloud_invoice_items',
@ -115,6 +116,25 @@ $assert(str_contains($schema,
&& str_contains($setup,
"'chk_cloud_backup_entitlement_window',"),
'Fresh schema is missing immutable paid automatic-backup period entitlements.');
$assert(str_contains($schema, 'CREATE TABLE cloud_deployment_snapshots (')
&& str_contains($schema,
'snapshot_key CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL')
&& str_contains($schema,
'UNIQUE KEY cloud_deployment_snapshot_backup (backup_id)')
&& str_contains($schema,
'UNIQUE KEY cloud_deployment_snapshot_request (user_id, idempotency_key)')
&& str_contains($schema,
'KEY cloud_deployment_snapshot_owner (user_id, state, id)')
&& str_contains($schema,
'CONSTRAINT chk_cloud_deployment_snapshot_state CHECK (')
&& str_contains($schema,
'deployment_snapshot_id BIGINT UNSIGNED DEFAULT NULL')
&& str_contains($schema,
'KEY cloud_order_deployment_snapshot (deployment_snapshot_id, status, id)')
&& str_contains($setup, "'cloud_deployment_snapshots'")
&& str_contains($setup, "'cloud_deployment_snapshot_key'")
&& str_contains($setup, "'chk_cloud_deployment_snapshot_state'"),
'Fresh schema is missing durable cloud deployment snapshots.');
$assert(str_contains($schema, 'CREATE TABLE cloud_instance_migrations (')
&& str_contains($schema, 'purpose VARCHAR(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT \'portable\'')
&& str_contains($schema, 'CREATE TABLE cloud_migration_bundle_artifacts (')

@ -87,6 +87,12 @@ namespace {
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_deployment_snapshots',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('backup_id')->unique();
$table->string('state');
});
$schema->create('cloud_backup_restores',
static function (Blueprint $table): void {
$table->increments('id');

@ -11,13 +11,19 @@ $read = static fn (string $path): string => file_get_contents($root . '/' . $pat
$deploy = $read('resources/views/venix/cloud/pages/deploy.tpl');
$detail = $read('resources/views/venix/cloud/pages/detail.tpl');
$backupPage = $read('resources/views/venix/cloud/pages/backups.tpl');
$snapshotPage = $read('resources/views/venix/cloud/pages/cloud-snapshots.tpl');
$runtime = $read('public/cloud/runtime.js');
$detailScript = $read('public/cloud/detail.js');
$backupScript = $read('public/cloud/backups.js');
$snapshotScript = $read('public/cloud/cloud-snapshots.js');
$app = $read('public/cloud/app.js');
$shell = $read('resources/views/venix/cloud/page.tpl');
$sidebar = $read('resources/views/venix/user/panel_sidebar.tpl');
$styles = $read('public/cloud/styles.css');
$pageController = $read('app/Controllers/CloudPageController.php');
$apiController = $read('app/Controllers/CloudApiController.php');
$routes = $read('config/routes.php');
$apiRoutes = $read('config/routes_cloud.php');
$assert(str_contains($deploy, 'id="vm-automatic-backup"')
&& str_contains($deploy, 'id="vm-order-instance-price"')
@ -31,13 +37,17 @@ $assert(str_contains($runtime, 'const backupAvailable = Boolean(offer);')
&& !str_contains($runtime, 'backup_available')
&& str_contains($runtime, 'Number(offer.backup_price)')
&& str_contains($runtime, "automatic_backup: byId('vm-automatic-backup')?.checked === true")
&& str_contains($runtime, "new URLSearchParams(location.search).get('backup_id')")
&& str_contains($runtime, 'body.backup_id = Number(state.deployBackupId)')
&& str_contains($runtime, "source: state.deployBackupId ? 'backup' : 'cloud'")
&& str_contains($runtime,
'if (!state.deployBackupId && !strongPassword(password))')
"source: state.deployCloudSnapshotKey ? 'deployment_snapshot' : 'cloud'")
&& str_contains($runtime,
'body.cloud_snapshot_key = state.deployCloudSnapshotKey')
&& !str_contains($runtime,
"new URLSearchParams(location.search).get('backup_id')")
&& !str_contains($runtime, 'body.backup_id =')
&& str_contains($runtime,
'if (!state.deployCloudSnapshotKey && !strongPassword(password))')
&& str_contains($runtime, 'provisionInvoiceFingerprint(body)'),
'Deployment pricing and idempotency must include the backup purchase and optional backup source.');
'Deployment pricing and idempotency must include the automatic-backup purchase and optional cloud-snapshot source.');
$assert(str_contains($detail, 'data-instance-setting-tab="automatic_backup"')
&& str_contains($detail, 'id="vm-automatic-backup-service"')
@ -89,17 +99,53 @@ $assert(str_contains($detailScript,
$assert(str_contains($sidebar, 'href="/user/cloud/backups"')
&& str_contains($sidebar, '>云备份</span>')
&& str_contains($sidebar, 'href="/user/cloud/cloud-snapshots"')
&& str_contains($sidebar, '>云快照</span>')
&& str_contains($shell, "cloud_page == 'backups'")
&& str_contains($shell, "cloud_page == 'cloud-snapshots'")
&& str_contains($app, "backups: '/cloud/backups.js'")
&& str_contains($app,
"'cloud-snapshots': '/cloud/cloud-snapshots.js'")
&& str_contains($backupPage, 'id="cloud-backups-list"')
&& str_contains($snapshotPage, 'id="cloud-snapshots-list"')
&& str_contains($backupScript, "api(`/api/v1/backups?page=")
&& str_contains($backupScript, "`/user/cloud/deploy?backup_id=\${encodeURIComponent(id)}`")
&& str_contains($backupScript, "api('/api/v1/cloud-snapshots'")
&& str_contains($backupScript,
'body: { backup_id: Number(id), name, idempotency_key: idempotencyKey }')
&& !str_contains($backupScript, '/user/cloud/deploy?backup_id=')
&& str_contains($backupScript,
"`/user/cloud/instances/\${encodeURIComponent(source.id)}?tab=settings&setting=automatic_backup`")
&& str_contains($backupScript, 'backup?.source_instance')
&& !str_contains($backupScript, "method: 'POST'"),
'The global backup library must create new instances or link to instance settings, never restore the source directly.');
&& str_contains($snapshotScript,
"api(`/api/v1/cloud-snapshots?page=")
&& str_contains($snapshotScript,
'`/user/cloud/deploy?cloud_snapshot=${encodeURIComponent(key)}`')
&& str_contains($snapshotScript,
"`/api/v1/cloud-snapshots/\${encodeURIComponent(key)}`")
&& str_contains($snapshotScript, "resultState === 'deleted'")
&& str_contains($snapshotScript, "resultState === 'delete_uncertain'")
&& str_contains($snapshotScript, '请先支付或等待账单失效后再删除')
&& str_contains($snapshotScript, 'window.VenixDialog?.confirm?.')
&& !str_contains($snapshotScript, 'confirm('),
'Cloud backups must only restore or promote, while the separate cloud-snapshot library owns new-instance and delete actions.');
$assert(str_contains($routes,
"'/cloud/cloud-snapshots', 'App\\Controllers\\CloudPageController:cloudSnapshots'")
&& str_contains($apiRoutes, "'/cloud-snapshots'")
&& str_contains($apiRoutes,
"'/cloud-snapshots/{snapshot_key:[0-9a-f]{32}}'")
&& str_contains($pageController,
'CloudDeploymentSnapshotService::deploymentSource(')
&& str_contains($pageController,
"'cloud_snapshot' => \$cloudSnapshot")
&& str_contains($apiController,
'CloudDeploymentSnapshotService::promote(')
&& str_contains($apiController,
'CloudDeploymentSnapshotService::delete('),
'Cloud-snapshot page, API, promotion, deletion and owner-scoped SSR deployment routes must form one reachable contract.');
$assert(str_contains($styles, '.cloud-backups-list')
&& str_contains($styles, '.cloud-snapshot-card:target')
&& str_contains($styles,
'.cloud-snapshots-panel>#cloud-snapshots-status')
&& str_contains($styles, '.vm-automatic-backup-grid')
&& str_contains($styles,
'.vm-automatic-backup-grid>.vm-settings-field{align-content:start}')

@ -82,17 +82,18 @@ $assert(str_contains($service, 'final class CloudUserIsoService')
'User ISO service lost its one-shot child dispatch, terminal aggregate, result validation or quota boundary.');
$runtime = file_get_contents($root . '/public/cloud/runtime.js');
$assert(str_contains($orders, "if (!in_array(\$source, ['cloud', 'backup'], true))")
$assert(str_contains($orders,
"if (!in_array(\$source, ['cloud', 'deployment_snapshot'], true))")
&& str_contains($orders, '实例来源无效')
&& !str_contains($orders, "'iso_id'")
&& !str_contains($orders, "\$payload['user_iso_id']")
&& !str_contains($orders, 'iso_path')
&& str_contains($runtime,
"source: state.deployBackupId ? 'backup' : 'cloud'")
"source: state.deployCloudSnapshotKey ? 'deployment_snapshot' : 'cloud'")
&& !str_contains($runtime, 'body.iso_id')
&& !str_contains($runtime, "byId('vm-iso')")
&& !str_contains($runtime, 'body.iso_path ='),
'VM provisioning must remain limited to cloud templates and portable backups while personal ISOs stay a separate owner library.');
'VM provisioning must remain limited to cloud templates and deployment snapshots while personal ISOs stay a separate owner library.');
$assert(str_contains($schema, 'CREATE TABLE cloud_user_isos')
&& str_contains($schema, 'sealed_source_url LONGTEXT NOT NULL')

@ -236,7 +236,11 @@ $assert($regionPosition !== false && $linePosition > $regionPosition
&& str_contains($clientScript, 'function renderRegionPicker()')
&& str_contains($clientScript, 'function renderLinePicker()')
&& str_contains($clientScript, 'function renderOfferPicker()')
&& str_contains($clientScript, "source: state.deployBackupId ? 'backup' : 'cloud'")
&& str_contains($clientScript,
"source: state.deployCloudSnapshotKey ? 'deployment_snapshot' : 'cloud'")
&& str_contains($clientScript,
'body.cloud_snapshot_key = state.deployCloudSnapshotKey')
&& !str_contains($clientScript, 'body.backup_id =')
&& str_contains($clientScript, "offer_id: Number(byId('vm-offer').value)")
&& str_contains($clientScript, "automatic_backup: byId('vm-automatic-backup')?.checked === true")
&& !str_contains($deployTemplate, 'host_id')
@ -610,7 +614,8 @@ $availabilityEnd = $availabilityStart === false ? false
$availability = $availabilityStart === false || $availabilityEnd === false ? ''
: substr($runtimeDeployScript, $availabilityStart, $availabilityEnd - $availabilityStart);
$assert(str_contains($availability, 'const offer = selectedSaleOffer()')
&& str_contains($availability, "const validMedia = Boolean(state.deployBackupId || byId('vm-template')?.value)")
&& str_contains($availability,
"const validMedia = Boolean(state.deployCloudSnapshotKey || byId('vm-template')?.value)")
&& !str_contains($availability, 'state.resources'),
'Deployment submission must require a matching region/line/offer and selected global image.');
$assert(str_contains($baseStyles, '.deployment-step')

Loading…
Cancel
Save