feat(cloud): allow same-host backup restores

go
codex 4 weeks ago
parent e9b2c8bd68
commit 4c898a2310

@ -95,7 +95,7 @@ php xcat cloudRepairInstanceMetadata --apply
后台 `/admin/object-storage` 可配置一个全局 S3 兼容对象存储应用,适用于 AWS S3、MinIO 及实现 AWS Signature Version 4 的兼容服务。该功能复用业务库已有的 `configurations` 表,不需要导入新表。Endpoint 必须是带有效证书的 HTTPS origin;MinIO 通常选择路径寻址,AWS S3 通常选择虚拟主机寻址。
Access Key ID 与 Secret Access Key 只在超级管理员提交时进入 PHP,使用 `cloud_data_key` 的独立用途密钥密封后保存,读取页面不会回显。修改任一配置或停用应用都会清除原就绪标记;必须重新执行“验证连接并启用”。连接验证只发送签名的 `HeadBucket` 请求,需要目标 Bucket 的 `s3:ListBucket` 权限,不上传、覆盖或删除对象。管理员虚拟机管理已接入完整系统盘备份和异机新实例恢复,运行账户还需要配置备份前缀范围内的 multipart 上传、`GetObject`、`HeadObject` 和 `DeleteObject` 权限;当前不包含增量链和自动保留策略,具体安全边界见 `docs/PORTABLE_VM_BACKUPS.md`。
Access Key ID 与 Secret Access Key 只在超级管理员提交时进入 PHP,使用 `cloud_data_key` 的独立用途密钥密封后保存,读取页面不会回显。修改任一配置或停用应用都会清除原就绪标记;必须重新执行“验证连接并启用”。连接验证只发送签名的 `HeadBucket` 请求,需要目标 Bucket 的 `s3:ListBucket` 权限,不上传、覆盖或删除对象。管理员虚拟机管理已接入完整系统盘备份和新实例恢复,目标可以是原宿主机或其他合格宿主机;运行账户还需要配置备份前缀范围内的 multipart 上传、`GetObject`、`HeadObject` 和 `DeleteObject` 权限。当前不包含增量链和自动保留策略,具体安全边界见 `docs/PORTABLE_VM_BACKUPS.md`。
生产环境应为面板创建独立服务账户,把权限限制到配置的 Bucket 和备份前缀。数据库备份必须与原始 `cloud_data_key` 一起保管,重新生成主密钥无法恢复全局配置及各备份冻结的对象存储凭据。

@ -1,6 +1,6 @@
# 可移植虚拟机备份与异机恢复
# 可移植虚拟机备份与新实例恢复
管理员可在虚拟机管理页为面板创建的云镜像实例生成一个完整系统盘备份,并把该备份直接上传到后台已验证的 S3 兼容对象存储。恢复不会修改或替换源实例,而是在另一台符合条件的宿主机上创建一个独立实例。
管理员可在虚拟机管理页为面板创建的云镜像实例生成一个完整系统盘备份,并把该备份直接上传到后台已验证的 S3 兼容对象存储。恢复不会修改或替换源实例,而是在选定的合格宿主机上创建一个独立实例;目标可以是原宿主机,也可以是其他宿主机。
虚拟机管理页顶部的“备份库”以备份目录自身为管理边界。即使源实例已按到期规则删除,超级管理员仍可从备份库恢复或删除对象;只读管理员只能查看。目录固定分页,浏览器响应不包含对象键、预签名 URL 或长期凭据。
@ -12,11 +12,11 @@
- 对象内容是原 qcow2 数据。传输强制 HTTPS,但当前版本不额外执行客户端加密;生产 Bucket 应启用服务端加密、版本控制、最小权限和不完整 multipart 生命周期清理。
- 系统盘内容保持不变,因此来宾系统数据、账户、SSH host key 和应用配置也保持不变。它是从备份创建新实例,不是重装一个空白操作系统。
## 异机恢复
## 恢复为新实例
恢复目标必须满足以下条件:
- 与源宿主机不同,已启用且 Agent、存储配置和 `bridge:br0` 网络均就绪;
- 已启用且 Agent、存储配置和 `bridge:br0` 网络均就绪;目标可以是原宿主机或其他宿主机;
- CPU、内存、磁盘和带宽容量足够,并且目标资源池有一个未分配的公网 IPv4;
- 目标宿主机没有同名实例。

@ -123,6 +123,8 @@ final class CloudBackupService
'network' => 'bridge:br0',
'available_ip_count' => max(1,
(int) ($target['available_ip_count'] ?? 1)),
'is_source_host' =>
($target['is_source_host'] ?? false) === true,
],
CloudPlacementService::backupRestoreTargets(
(int) $row->source_host_id,
@ -203,6 +205,8 @@ final class CloudBackupService
1,
(int) ($target['available_ip_count'] ?? 1)
),
'is_source_host' =>
($target['is_source_host'] ?? false) === true,
];
$backupTargets[] = $normalized;
$targetMap[$normalized['host_id']] = $normalized;
@ -638,9 +642,6 @@ final class CloudBackupService
return ['restore' => self::displayRestore($restore),
'job' => $prior];
}
if ((int) $locked->source_host_id === (int) $targetHostId) {
throw new CloudError('请选择与源宿主机不同的目标宿主机', 409);
}
if (CloudInstance::where('host_id', (int) $targetHostId)
->where('name', $name)->where('status', '<>', 'deleted')
->exists()) {

@ -24,8 +24,8 @@ final class CloudOperationCatalog
'snapshot_create' => '创建快照',
'snapshot_restore' => '恢复快照',
'snapshot_delete' => '删除快照',
'backup_create' => '创建异机备份',
'backup_restore' => '异机恢复实例',
'backup_create' => '创建可移植备份',
'backup_restore' => '从备份创建实例',
'firewall_apply' => '应用防火墙',
'service_suspend' => '到期停用',
'network_suspend' => '限制网络',

@ -902,11 +902,11 @@ final class CloudOperationRecoveryIdentity
|| !str_starts_with($upload['complete_url'], 'https://')
|| !str_starts_with($upload['abort_url'], 'https://')
|| !str_starts_with($upload['verify_url'], 'https://')) {
self::invalidPayload('创建异机备份请求无效');
self::invalidPayload('创建可移植备份请求无效');
}
foreach ($upload['part_urls'] as $url) {
if (!is_string($url) || !str_starts_with($url, 'https://')) {
self::invalidPayload('创建异机备份请求无效');
self::invalidPayload('创建可移植备份请求无效');
}
}
return 'create-backup:' . $key . ':' . $mode;
@ -1023,7 +1023,7 @@ final class CloudOperationRecoveryIdentity
$body['source_sha256']) !== 1
|| !hash_equals((string) $backup->sha256,
(string) $body['source_sha256'])) {
self::invalidPayload('异机恢复请求无效');
self::invalidPayload('备份恢复请求无效');
}
return 'restore-backup:' . $key;
}

@ -369,7 +369,7 @@ final class CloudPlacementService
$resources = self::upgradeResources($resources);
$result = [];
$hosts = CloudHost::where('enabled', 1)
->where('id', '<>', $sourceHostId)->orderBy('id')->get();
->orderBy('id')->get();
foreach ($hosts as $host) {
if ((string) $host->default_network !== 'bridge:br0') {
continue;
@ -434,6 +434,7 @@ final class CloudPlacementService
'resource_pool' => (string) $pool->name,
'network' => 'bridge:br0',
'available_ip_count' => (int) $availableIpCount,
'is_source_host' => (int) $host->id === $sourceHostId,
];
}
return $result;

@ -867,7 +867,8 @@ function restoreForm(vmId, backup, targets, mutationBlocked, library = false) {
const region = String(target.region || target.region_name || '').trim();
const available = Number(target.available_ip_count ?? target.available_count);
const suffix = Number.isFinite(available) ? ` · ${available} 个可用 IP` : '';
host.append(new Option(`${name}${region ? ` · ${region}` : ''}${suffix}`, id));
const source = target.is_source_host === true ? ' · 原宿主机' : '';
host.append(new Option(`${name}${region ? ` · ${region}` : ''}${source}${suffix}`, id));
});
host.disabled = mutationBlocked || targets.length === 0;
hostLabel.append(host);
@ -919,8 +920,8 @@ function restoreForm(vmId, backup, targets, mutationBlocked, library = false) {
);
show(`恢复任务 #${receipt.task_id || '—'} 已接收。`, 'muted');
backupSurfaceNotice('恢复任务已接收;目标资源会保持预留,直到任务得到明确结果。', false, library);
if (library) watchLibraryBackupTask(receipt, '异机恢复');
else watchBackupTask(vmId, receipt, '异机恢复');
if (library) watchLibraryBackupTask(receipt, '备份恢复');
else watchBackupTask(vmId, receipt, '备份恢复');
refreshBackupSurface(vmId, library);
} catch (error) {
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
@ -944,7 +945,7 @@ function renderBackups(payload, vmId) {
panel.replaceChildren();
const intro = el('div', 'alert alert-info');
intro.append(el('strong', 'd-block mb-1', '可移植系统盘备份'),
document.createTextNode('备份上传到已验证的对象存储,不修改源实例。恢复会在所选其他宿主机创建独立实例,统一接入 br0 并分配全新公网 IP。'));
document.createTextNode('备份上传到已验证的对象存储,不修改源实例。恢复会在所选宿主机创建独立实例;可选择原宿主机或其他合格宿主机,并统一接入 br0、分配全新公网 IP。'));
panel.append(intro);
const create = el('section', 'card mb-3');
@ -1061,7 +1062,7 @@ function renderBackups(payload, vmId) {
if (targets.length) body.append(restoreForm(vmId, backup, targets,
payload?.can_restore === false || payload?.active_job?.blocks_mutation === true));
else body.append(el('p', 'text-warning fs-13 mb-0',
'暂无满足容量、存储、br0 网络和可用公网 IP 条件的其他宿主机。'));
'暂无满足容量、存储、br0 网络和可用公网 IP 条件的宿主机。'));
}
if (['ready', 'failed'].includes(backup.state) && backup.can_delete === true) {
const deleteActions = el('div', 'd-flex justify-content-end mt-3');
@ -1136,7 +1137,7 @@ function renderBackupLibrary(payload) {
]));
if (source.deleted === true) {
body.append(el('p', 'alert alert-warning fs-13',
'源实例已删除;该备份仍由独立目录保留,可恢复到其他宿主机或确认删除。'));
'源实例已删除;该备份仍由独立目录保留,可恢复为新实例或确认删除。'));
}
if (backup.cleanup_pending === true) {
body.append(el('p', 'text-warning fs-13',
@ -1149,7 +1150,7 @@ function renderBackupLibrary(payload) {
body.append(restoreForm(vmId, backup, targets, !canManage, true));
} else {
body.append(el('p', 'text-warning fs-13',
'暂无满足容量、存储、br0 网络和可用公网 IP 条件的其他宿主机。'));
'暂无满足容量、存储、br0 网络和可用公网 IP 条件的宿主机。'));
}
}
if (backup.can_delete === true) {

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

@ -16,6 +16,7 @@ $template = $read('resources/views/venix/admin/cloud/instances.tpl');
$runtime = $read('public/cloud/admin-instances.js');
$assets = $read('resources/views/venix/layout_assets.tpl');
$service = $read('app/Services/Cloud/CloudBackupService.php');
$placement = $read('app/Services/Cloud/CloudPlacementService.php');
$assert(str_contains($routes,
"['GET', 'POST'], '/admin/instances/{id:[0-9]+}/backups'")
@ -63,7 +64,7 @@ $assert(str_contains($runtime, "method: 'DELETE'")
&& str_contains($runtime, 'requires_reconciliation'),
'Backup deletion UI must expose non-replaying read-only reconciliation after unknown effect.');
$assert(str_contains($runtime, '统一接入 br0 并分配全新公网 IP')
$assert(str_contains($runtime, '统一接入 br0、分配全新公网 IP')
&& str_contains($runtime, '不会继承原 IP、账单、到期时间或流量周期')
&& str_contains($runtime, '临时快照清理仍需管理员核对')
&& str_contains($runtime, '系统不会重复上传')
@ -71,6 +72,12 @@ $assert(str_contains($runtime, '统一接入 br0 并分配全新公网 IP')
&& str_contains($runtime, 'available_ip_count'),
'The restore UI must describe and collect the independent br0/new-IP target intent.');
$assert(str_contains($placement, "'is_source_host'")
&& !str_contains($placement, "->where('id', '<>', \$sourceHostId)")
&& !str_contains($service, '请选择与源宿主机不同的目标宿主机')
&& str_contains($runtime, '原宿主机'),
'Manual restore must offer an eligible original host while preserving an explicit UI label.');
$assert(str_contains($service,
"is_bool(\$spec['debian_12_network_fix'] ?? null)")
&& str_contains($service, '实例缺少创建时冻结的网络兼容快照'),

@ -0,0 +1,210 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudPlacementService;
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);
}
};
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite', 'database' => ':memory:',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('cloud_hosts', static function (Blueprint $table): void {
$table->increments('id');
$table->string('name');
$table->boolean('enabled');
$table->string('default_network');
});
$schema->create('cloud_regions', static function (Blueprint $table): void {
$table->increments('id');
$table->string('name');
$table->string('status');
});
$schema->create('cloud_network_lines', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('region_id');
$table->string('status');
});
$schema->create('cloud_resource_pools', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('line_id');
$table->string('name');
$table->string('status');
});
$schema->create('cloud_host_resource_pool_memberships',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('host_id');
$table->integer('resource_pool_id');
$table->string('scheduler_state');
});
$schema->create('cloud_host_capacity_policies',
static function (Blueprint $table): void {
$table->integer('host_id')->primary();
$table->integer('configured_cpu_cores');
$table->integer('configured_memory_mib');
$table->integer('configured_disk_gib');
$table->integer('safety_cpu_cores');
$table->integer('safety_memory_mib');
$table->integer('safety_disk_gib');
$table->integer('max_instances');
});
$schema->create('cloud_host_agents', static function (Blueprint $table): void {
$table->integer('host_id')->primary();
$table->boolean('enabled');
$table->integer('revision');
$table->integer('tested_revision');
$table->string('last_test_status');
});
$schema->create('cloud_host_storage_configurations',
static function (Blueprint $table): void {
$table->integer('host_id')->primary();
$table->string('state');
});
$schema->create('cloud_host_network_attachments',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('host_id');
$table->integer('line_id');
$table->string('network_selector');
$table->string('state');
$table->string('sync_state');
$table->integer('observed_revision');
$table->integer('desired_revision');
});
$schema->create('cloud_public_ip_pools',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('host_id');
$table->integer('network_attachment_id');
$table->string('state');
$table->string('sync_state');
$table->integer('observed_revision');
$table->integer('desired_revision');
$table->integer('guest_prefix_length');
});
$schema->create('cloud_public_ips', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('host_id');
$table->integer('public_ip_pool_id');
$table->string('address');
$table->integer('prefix_length');
$table->string('state');
$table->integer('reservation_id')->nullable();
$table->integer('instance_id')->nullable();
$table->string('operation_id')->nullable();
});
$schema->create('cloud_resource_reservations',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('host_id');
$table->string('state');
$table->integer('instance_id')->nullable();
$table->integer('cpu_cores');
$table->integer('memory_mib');
$table->integer('disk_gib');
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('host_id');
$table->string('status');
$table->text('spec_json');
});
$capsule->table('cloud_regions')->insert([
'id' => 1, 'name' => 'Hong Kong', 'status' => 'active',
]);
$capsule->table('cloud_network_lines')->insert([
'id' => 1, 'region_id' => 1, 'status' => 'active',
]);
$capsule->table('cloud_resource_pools')->insert([
'id' => 1, 'line_id' => 1, 'name' => 'HKG', 'status' => 'active',
]);
foreach ([1 => 'source-host', 2 => 'other-host'] as $hostId => $name) {
$capsule->table('cloud_hosts')->insert([
'id' => $hostId, 'name' => $name, 'enabled' => 1,
'default_network' => 'bridge:br0',
]);
$capsule->table('cloud_host_resource_pool_memberships')->insert([
'host_id' => $hostId, 'resource_pool_id' => 1,
'scheduler_state' => 'active',
]);
$capsule->table('cloud_host_capacity_policies')->insert([
'host_id' => $hostId,
'configured_cpu_cores' => 16,
'configured_memory_mib' => 32768,
'configured_disk_gib' => 1000,
'safety_cpu_cores' => 0,
'safety_memory_mib' => 0,
'safety_disk_gib' => 0,
'max_instances' => 20,
]);
$capsule->table('cloud_host_agents')->insert([
'host_id' => $hostId, 'enabled' => 1, 'revision' => 1,
'tested_revision' => 1, 'last_test_status' => 'healthy',
]);
$capsule->table('cloud_host_storage_configurations')->insert([
'host_id' => $hostId, 'state' => 'applied',
]);
$attachmentId = $hostId;
$poolId = $hostId;
$capsule->table('cloud_host_network_attachments')->insert([
'id' => $attachmentId, 'host_id' => $hostId, 'line_id' => 1,
'network_selector' => 'bridge:br0', 'state' => 'active',
'sync_state' => 'applied', 'observed_revision' => 1,
'desired_revision' => 1,
]);
$capsule->table('cloud_public_ip_pools')->insert([
'id' => $poolId, 'host_id' => $hostId,
'network_attachment_id' => $attachmentId, 'state' => 'active',
'sync_state' => 'applied', 'observed_revision' => 1,
'desired_revision' => 1, 'guest_prefix_length' => 24,
]);
$capsule->table('cloud_public_ips')->insert([
'host_id' => $hostId, 'public_ip_pool_id' => $poolId,
'address' => '203.0.' . $hostId . '.20', 'prefix_length' => 24,
'state' => 'available', 'reservation_id' => null,
'instance_id' => null, 'operation_id' => null,
]);
}
// The source VM consumes capacity on its current host. A same-host restore
// must still reserve a second, independent resource and IP allocation.
$capsule->table('cloud_instances')->insert([
'id' => 1, 'host_id' => 1, 'status' => 'active',
'spec_json' => json_encode([
'vcpu' => 2, 'memory_mib' => 2048, 'disk_gib' => 20,
], JSON_THROW_ON_ERROR),
]);
$targets = CloudPlacementService::backupRestoreTargets(1, [
'cpu_cores' => 2, 'memory_mib' => 2048, 'disk_gib' => 20,
]);
$byId = [];
foreach ($targets as $target) {
$byId[(int) $target['id']] = $target;
}
$assert(isset($byId[1]),
'The original host was excluded from eligible manual restore targets.');
$assert(($byId[1]['is_source_host'] ?? null) === true,
'The original host target was not explicitly identified.');
$assert(isset($byId[2])
&& ($byId[2]['is_source_host'] ?? null) === false,
'A different eligible host was lost or misidentified.');
$assert((int) $byId[1]['available_ip_count'] === 1,
'The original host did not retain its independent IP capacity check.');
echo "Portable backup same-host restore target behavior passed.\n";

@ -73,7 +73,7 @@ $assert(str_contains($auth, "Config::get('tos_reg') === 'true'")
'Legal consent is only client-side and can be bypassed.');
$assets = $read('web/resources/views/venix/layout_assets.tpl');
$assert(str_contains($assets, "value='2026102503'")
$assert(str_contains($assets, "value='2026102504'")
&& str_contains($admin, '?v={$venix_asset_version}')
&& str_contains($read('web/resources/views/venix/home/layout_header.tpl'), '?v={$venix_asset_version}'),
'Shared browser asset version was not coupled to the new assets.');

@ -80,7 +80,7 @@ $assert(preg_match('/\.landing-site-header\s*\{[^}]*position:\s*fixed;/s', $css)
&& str_contains($accountCss, 'padding-top: 88px;')
&& str_contains($accountCss, 'padding-top: 76px;'),
'Persistent desktop or mobile public-navigation styling is incomplete.');
$assert(str_contains($read('web/resources/views/venix/layout_assets.tpl'), "value='2026102503'"),
$assert(str_contains($read('web/resources/views/venix/layout_assets.tpl'), "value='2026102504'"),
'The shared browser asset version was not advanced with the navigation styles.');
echo "Public page locale and shared-layout contract tests passed.\n";

@ -69,7 +69,7 @@ foreach ($templates as $template) {
}
$assets = $read('web/resources/views/venix/layout_assets.tpl');
$assert(str_contains($assets, "value='2026102503'"),
$assert(str_contains($assets, "value='2026102504'"),
'The shared asset version was not updated for the canonical logo.');
echo "Shared site-brand contract passed across public, auth, user, cloud and admin layouts.\n";

Loading…
Cancel
Save