From 47e5841b7f4ee630aada3b6f72d062a332c1a40e Mon Sep 17 00:00:00 2001 From: codex Date: Mon, 2 Nov 2026 21:07:03 +0800 Subject: [PATCH] feat: restore and migrate across verified attachments --- docs/PRUNING_REPORT.md | 2 +- docs/VALIDATION.md | 2 +- web/app/Services/Cloud/CloudBackupService.php | 99 ++++--- .../Cloud/CloudInstanceMigrationService.php | 67 ++++- .../CloudInstanceMigrationSettlement.php | 32 +- .../Cloud/CloudOperationRecoveryIdentity.php | 98 ++++++- .../Cloud/CloudPlacementNetworkService.php | 43 ++- .../Services/Cloud/CloudPlacementService.php | 274 +++++++++--------- web/public/cloud/admin-instance-backups.js | 41 ++- web/public/cloud/admin-instance-migration.js | 22 +- web/resources/views/venix/layout_assets.tpl | 2 +- web/tests/AdminBackupLibraryBehaviorTest.mjs | 87 +++++- .../AdminInstanceMigrationBehaviorTest.mjs | 85 ++++++ web/tests/CloudFinancialWorkflowTest.php | 22 ++ ...CloudMaintenanceMigrationFinalizerTest.php | 41 ++- ...loudMaintenanceMigrationTargetSpecTest.php | 5 +- .../CloudOperationRecoveryMatrixTest.php | 119 +++++++- ...CloudPortableBackupAdminUiContractTest.php | 9 +- ...loudPortableBackupRecoveryEnvelopeTest.php | 4 +- ...CloudPortableBackupSameHostRestoreTest.php | 107 ++++++- 20 files changed, 923 insertions(+), 238 deletions(-) create mode 100644 web/tests/AdminInstanceMigrationBehaviorTest.mjs diff --git a/docs/PRUNING_REPORT.md b/docs/PRUNING_REPORT.md index 5871dfd7..ecfbbe4a 100644 --- a/docs/PRUNING_REPORT.md +++ b/docs/PRUNING_REPORT.md @@ -11,7 +11,7 @@ - 同地区 direct L3 VPC:后台地区 CIDR 池、用户 VPC/IPAM、实例冷启动连接与断开、宿主机路由投影和维护迁移保留私网 IP/MAC。VPC 不提供跨地区互联、NAT 或二层广播;独立备份恢复和云快照新建实例不继承源实例 VPC。 - 管理员工单 Telegram 通知,以及当前绑定的超级管理员对已映射通知的纯文本回复;普通用户仍只在网页处理工单。 - 公开产品落地页,以及后台统一维护、带草稿和发布历史的全局服务条款与隐私政策页面;法律内容不按域名拆分。 -- 后台全局 S3 兼容对象存储应用配置、密钥密封和只读连接验证;管理员可把受支持实例的完整系统盘备份上传到对象存储,并在原宿主机或其他合格的 `bridge:br0` 宿主机使用全新公网 IP 创建独立免计费实例。普通用户可按服务周期购买自动备份,在实例设置中选择每天或每周执行并保留最多两份;全局备份库独立于源实例生命周期,源实例删除后仍可恢复或清理对象。增量链和管理员手工备份的自动保留策略暂未接入。 +- 后台全局 S3 兼容对象存储应用配置、密钥密封和只读连接验证;管理员可把受支持实例的完整系统盘备份上传到对象存储,并在原宿主机或其他合格宿主机的指定资源池上,使用该线路当前已验证的网络接入和全新公网 IP 创建独立免计费实例。普通用户可按服务周期购买自动备份,在实例设置中选择每天或每周执行并保留最多两份;全局备份库独立于源实例生命周期,源实例删除后仍可恢复或清理对象。增量链和管理员手工备份的自动保留策略暂未接入。 ## 删除 diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 75cf4ae1..44ac9cdb 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -139,7 +139,7 @@ jq empty deploy/*.json.example - 目标分块暂存必须由 Agent 派生到第一个 `storage_path_roots` 下的 `.peer-migration-staging`,不能落在 Journal 系统盘。故障注入分块断连后应从已有偏移继续;成功导入删除暂存,过期中断会话只能由有界本地清理回收,不能删除不匹配目录。 - 目标在恢复和用户防火墙收敛期间必须保持关机;源机的运行/关机、autostart、断网状态与修改后主机名必须在独立激活步骤后保持一致。传输确定失败须同时提供续传和安全回滚,防火墙、激活、回滚、源清理的确定失败均有显式恢复出口。若源准备已存在精确成功回执但 PHP 最终化失败,只能将原准备效果收敛为 `applied` 后创建新的补偿回滚任务;Agent 明确确认源机恢复前不得释放目标预留或 IP。未知效果只能核对原 operation,不能重放。普通云备份仍只能产生单系统盘 S3 对象,PeerMigration 不得创建 S3 迁移对象。 - 维护迁移阶段注册表必须通过完整性测试:每个 Agent 任务种类只能对应一个账本字段、完成处理和不确定结果核对动作,每个人工恢复动作只能对应一个执行入口。页面必须直接使用后端返回的恢复选项和阶段进度;接口在加锁后使用同一判定重新授权。资源结算模块只能在源删除或目标接管得到明确证明后移动订单预留和公网 IP。没有持久化字节遥测时只能显示阶段进度,不能合成传输百分比。 -- 独立恢复可选择原宿主机或其他合格宿主机;无论目标是否为原宿主机,都必须单独校验并预留容量与全新公网 IP。目标使用 `bridge:br0`;校验下载对象字节数与 SHA-256,新实例 UUID、MAC、seed、NVRAM、网络过滤器和流量状态均不得复用源实例,且不得继承订单、账单、服务期、到期时间或流量周期。 +- 独立恢复可选择原宿主机或其他合格宿主机,且目标身份必须精确到宿主机与资源池;无论目标是否为原宿主机,都必须单独校验并预留容量与全新公网 IP。目标网络必须使用该资源池所属线路上、与当前 Agent 版本一致且已验证的 active attachment selector;校验下载对象字节数与 SHA-256,新实例 UUID、MAC、seed、NVRAM、网络过滤器和流量状态均不得复用源实例,且不得继承订单、账单、服务期、到期时间或流量周期。 - 对备份/恢复断连、超时和回执丢失执行故障注入:同一 Agent operation ID 只能查询收敛,不能再次派发。恢复失败只有在全部托管产物明确不存在时才能释放容量与 IP。对象删除响应未知时不得重放原 DELETE;必须用两次间隔 HEAD 证明同一大小、ETag 和 `version_id` 仍存在,才允许创建新的删除代次。验证每轮最多三次、超限转人工、手动重试重新建立稳定证据、精确版本删除、清理债务不占保留份数,并确认大量异常债务不会饿死新的保留清理。 - 清理异常工作区不得显示对象键或 `version_id`。`delete_uncertain` 必须显示下一次自动核对时间且没有人工重试按钮;`delete_attention` 必须显示停止时间,只有超级管理员可点击“重新核对”,该动作必须先执行精确对象身份检查并返回稳定核对流程,不能直接调用 DELETE。 diff --git a/web/app/Services/Cloud/CloudBackupService.php b/web/app/Services/Cloud/CloudBackupService.php index ba37fe21..36c7824c 100644 --- a/web/app/Services/Cloud/CloudBackupService.php +++ b/web/app/Services/Cloud/CloudBackupService.php @@ -136,19 +136,8 @@ final class CloudBackupService self::decodeSpec((string) $row->spec_json) ); $item['restore_targets'] = array_map( - static fn (array $target): array => [ - 'host_id' => (string) ($target['id'] ?? ''), - 'host_name' => (string) ($target['name'] ?? ''), - 'region' => (string) ($target['region'] ?? ''), - 'resource_pool' => (string) ( - $target['resource_pool'] ?? '' - ), - 'network' => 'bridge:br0', - 'available_ip_count' => max(1, - (int) ($target['available_ip_count'] ?? 1)), - 'is_source_host' => - ($target['is_source_host'] ?? false) === true, - ], + static fn (array $target): array => + self::restoreTargetDisplay($target), CloudPlacementService::backupRestoreTargets( (int) $row->source_host_id, $resources @@ -224,23 +213,10 @@ final class CloudBackupService (int) $row->source_host_id, $resources ) as $target) { - $normalized = [ - 'host_id' => (string) ($target['id'] ?? ''), - 'host_name' => (string) ($target['name'] ?? ''), - 'region' => (string) ($target['region'] ?? ''), - 'resource_pool' => (string) ( - $target['resource_pool'] ?? '' - ), - 'network' => 'bridge:br0', - 'available_ip_count' => max( - 1, - (int) ($target['available_ip_count'] ?? 1) - ), - 'is_source_host' => - ($target['is_source_host'] ?? false) === true, - ]; + $normalized = self::restoreTargetDisplay($target); $backupTargets[] = $normalized; - $targetMap[$normalized['host_id']] = $normalized; + $targetMap[$normalized['host_id'] . ':' + . $normalized['resource_pool_id']] = $normalized; } $display['restore_targets'] = $backupTargets; } @@ -265,7 +241,15 @@ final class CloudBackupService 'host_id' => (string) ($target['id'] ?? ''), 'host_name' => (string) ($target['name'] ?? ''), 'region' => (string) ($target['region'] ?? ''), + 'resource_pool_id' => (string) ( + $target['resource_pool_id'] ?? '' + ), 'resource_pool' => (string) ($target['resource_pool'] ?? ''), + 'line' => (string) ($target['line'] ?? ''), + 'network_selectors' => array_values( + is_array($target['network_selectors'] ?? null) + ? $target['network_selectors'] : [] + ), 'available_ip_count' => max( 1, (int) ($target['available_ip_count'] ?? 1) @@ -937,12 +921,21 @@ final class CloudBackupService { CloudAccess::manage($actor); CloudInput::only($input, - ['target_host_id', 'name', 'confirm_new_instance']); + ['target_host_id', 'target_resource_pool_id', 'name', + 'confirm_new_instance']); $targetHostId = filter_var($input['target_host_id'] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); + $targetResourcePoolId = filter_var( + $input['target_resource_pool_id'] ?? null, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]] + ); if ($targetHostId === false) { throw new CloudError('请选择目标宿主机'); } + if ($targetResourcePoolId === false) { + throw new CloudError('请选择目标资源池'); + } $name = CloudInput::name($input['name'] ?? null); if (($input['confirm_new_instance'] ?? false) !== true) { throw new CloudError('请确认恢复会创建免计费的独立新实例'); @@ -950,6 +943,7 @@ final class CloudBackupService $canonicalRequest = [ 'backup_id' => (int) $backup->id, 'target_host_id' => (int) $targetHostId, + 'target_resource_pool_id' => (int) $targetResourcePoolId, 'name' => $name, ]; $idempotencyTarget = '/v1/backup-restores'; @@ -1000,7 +994,8 @@ final class CloudBackupService (string) $backup->object_key, self::TRANSFER_URL_SECONDS ); return $backup->getConnection()->transaction(function () use ( - $backup, $actor, $targetHostId, $name, $sourceUrl, + $backup, $actor, $targetHostId, $targetResourcePoolId, $name, + $sourceUrl, $canonicalRequest, $idempotencyTarget, $fingerprint ): array { $locked = CloudInstanceBackup::where('id', (int) $backup->id) @@ -1049,7 +1044,10 @@ final class CloudBackupService $restore->created_at = $restore->updated_at = $now; $restore->save(); $placement = CloudPlacementService::reserveBackupRestore( - $restore, (int) $locked->user_id, $resources + $restore, + (int) $locked->user_id, + $resources, + (int) $targetResourcePoolId ); $network = $placement['network']; $instanceSpec = self::restoredSpec( @@ -1105,7 +1103,7 @@ final class CloudBackupService 'memory_mib' => $resources['memory_mib'], 'disk_gib' => $resources['disk_gib'], 'bandwidth_mbps' => $resources['bandwidth_mbps'], - 'network' => 'bridge:br0', + 'network' => (string) $network['network'], 'template_id' => '', 'template_revision' => 0, 'template_generation_token' => '', @@ -2165,6 +2163,39 @@ final class CloudBackupService 'disk_gib' => (int) $disk, 'bandwidth_mbps' => (int) $bandwidth]; } + /** @return array */ + private static function restoreTargetDisplay(array $target): array + { + $selectors = $target['network_selectors'] ?? []; + if (!is_array($selectors) || !array_is_list($selectors)) { + $selectors = []; + } + return [ + 'host_id' => (string) ($target['id'] ?? ''), + 'host_name' => (string) ($target['name'] ?? ''), + 'region_id' => (string) ($target['region_id'] ?? ''), + 'region' => (string) ($target['region'] ?? ''), + 'country_code' => (string) ($target['country_code'] ?? ''), + 'line_id' => (string) ($target['line_id'] ?? ''), + 'line' => (string) ($target['line'] ?? ''), + 'resource_pool_id' => (string) ( + $target['resource_pool_id'] ?? '' + ), + 'resource_pool' => (string) ($target['resource_pool'] ?? ''), + 'network_selectors' => array_values(array_filter( + $selectors, + static fn ($selector): bool => is_string($selector) + && $selector !== '' + )), + 'available_ip_count' => max( + 0, + (int) ($target['available_ip_count'] ?? 0) + ), + 'is_source_host' => + ($target['is_source_host'] ?? false) === true, + ]; + } + /** Freeze template-specific boot compatibility into the backup manifest. */ private static function freezeRestoreCompatibility(array $spec): array { @@ -2193,7 +2224,7 @@ final class CloudBackupService 'memory_mib' => $resources['memory_mib'], 'disk_gib' => $resources['disk_gib'], 'bandwidth_mbps' => $resources['bandwidth_mbps'], - 'network' => 'bridge:br0', + 'network' => (string) $network['network'], 'public_pool_key' => (string) $network['public_pool_key'], 'public_pool_cidr' => (string) $network['public_pool_cidr'], 'public_ip_cidr' => (string) $network['public_ip_cidr'], diff --git a/web/app/Services/Cloud/CloudInstanceMigrationService.php b/web/app/Services/Cloud/CloudInstanceMigrationService.php index 4c3039e4..e6d56736 100644 --- a/web/app/Services/Cloud/CloudInstanceMigrationService.php +++ b/web/app/Services/Cloud/CloudInstanceMigrationService.php @@ -175,14 +175,22 @@ final class CloudInstanceMigrationService ): array { CloudAccess::manage($actor); CloudInput::only($input, [ - 'target_host_id', 'cleanup_mode', 'confirm_maintenance_migration', + 'target_host_id', 'target_resource_pool_id', 'cleanup_mode', + 'confirm_maintenance_migration', ]); $targetHostId = filter_var($input['target_host_id'] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); + $targetResourcePoolId = filter_var( + $input['target_resource_pool_id'] ?? null, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]] + ); $cleanupMode = $input['cleanup_mode'] ?? null; - if ($targetHostId === false + if ($targetHostId === false || $targetResourcePoolId === false || !in_array($cleanupMode, ['retain', 'delete'], true)) { - throw new CloudError('请选择目标宿主机和源副本处理方式'); + throw new CloudError( + '请选择目标宿主机、资源池和源副本处理方式' + ); } if (($input['confirm_maintenance_migration'] ?? false) !== true) { throw new CloudError('请确认维护迁移会关闭源实例并更换公网 IP'); @@ -197,6 +205,7 @@ final class CloudInstanceMigrationService $canonical = [ 'instance_id' => (int) $instance->id, 'target_host_id' => (int) $targetHostId, + 'target_resource_pool_id' => (int) $targetResourcePoolId, 'cleanup_mode' => (string) $cleanupMode, 'confirm_maintenance_migration' => true, ]; @@ -231,6 +240,7 @@ final class CloudInstanceMigrationService $instance, $actor, $targetHostId, + $targetResourcePoolId, $cleanupMode, $sourceCapability, $target, @@ -276,6 +286,7 @@ final class CloudInstanceMigrationService self::assertStartAvailable( $locked, (int) $targetHostId, + (int) $targetResourcePoolId, $resources, CloudPeerMigrationArtifactService::additionalDiskGib($snapshots) ); @@ -305,9 +316,26 @@ final class CloudInstanceMigrationService $restore, (int) $locked->user_id, $resources, - (int) $locked->resource_pool_id, + (int) $targetResourcePoolId, CloudPeerMigrationArtifactService::additionalDiskGib($snapshots) ); + $sourceReservation = CloudResourceReservation::where( + 'id', + (int) $locked->reservation_id + )->lockForUpdate()->first(); + if ($sourceReservation === null + || (string) $sourceReservation->state !== 'committed' + || (int) $sourceReservation->host_id !== (int) $locked->host_id + || (int) $sourceReservation->instance_id !== (int) $locked->id + || (int) $sourceReservation->resource_pool_id + !== (int) $locked->resource_pool_id + || (int) ($sourceReservation->order_id ?? 0) + !== (int) $locked->order_id) { + throw new CloudRecoveryInstanceStateConflict( + 'PeerMigration 源资源预留与实例所属资源池不一致', + 409 + ); + } $reservation = $placement['reservation']; $reservation->instance_id = (int) $locked->id; $reservation->updated_at = time(); @@ -400,6 +428,7 @@ final class CloudInstanceMigrationService public static function assertStartAvailable( CloudInstance $instance, int $targetHostId, + int $targetResourcePoolId, array $resources, int $snapshotDiskGib = 0, ?int $excludeMigrationId = null @@ -418,6 +447,9 @@ final class CloudInstanceMigrationService || (int) ($instance->resource_pool_id ?? 0) < 1) { throw new CloudError('只有具备完整订单和资源预留的实例可以维护迁移', 409); } + if ($targetResourcePoolId !== (int) $instance->resource_pool_id) { + throw new CloudError('维护迁移必须保持原资源池身份', 409); + } $query = CloudInstanceMigration::where( 'instance_id', (int) $instance->id )->whereIn('state', array_merge( @@ -438,10 +470,12 @@ final class CloudInstanceMigrationService ), static fn (array $target): bool => (int) ($target['id'] ?? 0) === $targetHostId + && (int) ($target['resource_pool_id'] ?? 0) + === $targetResourcePoolId ); if ($allowed === []) { throw new CloudError( - '目标宿主机必须位于同一资源池并具备可用容量、br0 和公网 IP', + '目标宿主机必须具备原资源池的活动成员关系、可用容量、已验证网络接入和公网 IP', 409 ); } @@ -452,6 +486,9 @@ final class CloudInstanceMigrationService { $state = (string) $migration->state; $action = (string) $migration->recovery_action; + $targetReservation = CloudResourceReservation::find( + (int) $migration->target_reservation_id + ); $hasAbortEvidence = self::hasAbortPrepareEvidence($migration); $recoveryOptions = CloudInstanceMigrationWorkflow::recoveryOptions( $migration, @@ -463,6 +500,8 @@ final class CloudInstanceMigrationService 'cleanup_mode' => (string) $migration->cleanup_mode, 'source_host_id' => (string) $migration->source_host_id, 'target_host_id' => (string) $migration->target_host_id, + 'target_resource_pool_id' => $targetReservation === null + ? null : (string) $targetReservation->resource_pool_id, 'source_retained' => $state === 'source_retained', 'can_cleanup' => $state === 'source_retained' && $action !== 'reconcile_cleanup', @@ -1216,6 +1255,16 @@ final class CloudInstanceMigrationService ); $reservation = $placement['reservation']; $network = $placement['network']; + if ((int) $reservation->resource_pool_id + !== (int) $instance->resource_pool_id + || (int) ($network['resource_pool_id'] ?? 0) + !== (int) $instance->resource_pool_id + || !CloudNetworkSelector::isValid($network['network'] ?? null)) { + throw new CloudRecoveryInstanceStateConflict( + 'PeerMigration 目标资源池或网络接入身份不一致', + 409 + ); + } $policy = $spec['platform_network_policy_snapshot'] ?? []; if (!is_array($policy) || array_is_list($policy)) { $policy = []; @@ -1246,7 +1295,7 @@ final class CloudInstanceMigrationService 'memory_mib' => $resources['memory_mib'], 'disk_gib' => $resources['disk_gib'], 'bandwidth_mbps' => $resources['bandwidth_mbps'], - 'network' => 'bridge:br0', + 'network' => (string) $network['network'], 'template_id' => '', 'template_revision' => 0, 'template_generation_token' => '', @@ -1412,6 +1461,10 @@ final class CloudInstanceMigrationService || (int) $target->disk_gib !== $expectedTargetClaim || (string) $source->state !== 'committed' || (int) $source->host_id !== (int) $migration->source_host_id + || (int) $source->resource_pool_id + !== (int) $instance->resource_pool_id + || (int) $target->resource_pool_id + !== (int) $source->resource_pool_id || (int) $source->instance_id !== (int) $instance->id || (int) $source->disk_gib !== (int) $rootDiskGib || (int) $instance->host_id !== (int) $migration->source_host_id @@ -2535,7 +2588,7 @@ final class CloudInstanceMigrationService $publicIpCidr = $value['public_ip_cidr'] ?? null; $gateway = $value['gateway'] ?? null; $dns = $value['dns_servers'] ?? null; - if ($network !== 'bridge:br0' + if (!CloudNetworkSelector::isValid($network) || !is_string($poolKey) || preg_match('/^[a-f0-9]{32}$/D', $poolKey) !== 1 || !is_string($poolCidr) diff --git a/web/app/Services/Cloud/CloudInstanceMigrationSettlement.php b/web/app/Services/Cloud/CloudInstanceMigrationSettlement.php index 4914c10e..e374ff73 100644 --- a/web/app/Services/Cloud/CloudInstanceMigrationSettlement.php +++ b/web/app/Services/Cloud/CloudInstanceMigrationSettlement.php @@ -50,12 +50,26 @@ final class CloudInstanceMigrationSettlement || !hash_equals(strtolower((string) $instance->uuid), strtolower((string) $migration->target_uuid)) || (int) $instance->reservation_id !== (int) $target->id + || (int) $instance->resource_pool_id + !== (int) $source->resource_pool_id + || (int) $target->resource_pool_id + !== (int) $source->resource_pool_id + || (int) $source->host_id !== (int) $migration->source_host_id + || (int) $target->host_id !== (int) $migration->target_host_id || (int) $source->order_id !== (int) $order->id + || (int) $order->resource_pool_id + !== (int) $source->resource_pool_id || $source->backup_restore_id !== null || (int) $target->backup_restore_id !== (int) $migration->restore_id || $target->order_id !== null || (string) $source->state !== 'committed' || (string) $target->state !== 'committed' + || (int) $sourceIp->host_id !== (int) $source->host_id + || (int) $targetIp->host_id !== (int) $target->host_id + || (int) $sourceIp->public_ip_pool_id + !== (int) $source->public_ip_pool_id + || (int) $targetIp->public_ip_pool_id + !== (int) $target->public_ip_pool_id || (int) $sourceIp->reservation_id !== (int) $source->id || (int) $targetIp->reservation_id !== (int) $target->id) { throw new CloudRecoveryInstanceStateConflict( @@ -124,7 +138,9 @@ final class CloudInstanceMigrationSettlement && (int) $instance->reservation_id === (int) $target->id && $target->order_id !== null && $target->backup_restore_id === null - && (int) $target->host_id === (int) $migration->target_host_id; + && (int) $target->host_id === (int) $migration->target_host_id + && (int) $target->resource_pool_id + === (int) $instance->resource_pool_id; } /** Source deletion is proven; transfer its order-linked reservation. */ @@ -155,10 +171,24 @@ final class CloudInstanceMigrationSettlement || !hash_equals(strtolower((string) $instance->uuid), strtolower((string) $migration->target_uuid)) || (int) $instance->reservation_id !== (int) $target->id + || (int) $instance->resource_pool_id + !== (int) $source->resource_pool_id + || (int) $target->resource_pool_id + !== (int) $source->resource_pool_id + || (int) $source->host_id !== (int) $migration->source_host_id + || (int) $target->host_id !== (int) $migration->target_host_id || (int) $source->order_id !== (int) $order->id + || (int) $order->resource_pool_id + !== (int) $source->resource_pool_id || (string) $source->state !== 'committed' || (int) $target->backup_restore_id !== (int) $migration->restore_id || (string) $target->state !== 'committed' + || (int) $sourceIp->host_id !== (int) $source->host_id + || (int) $targetIp->host_id !== (int) $target->host_id + || (int) $sourceIp->public_ip_pool_id + !== (int) $source->public_ip_pool_id + || (int) $targetIp->public_ip_pool_id + !== (int) $target->public_ip_pool_id || (int) $sourceIp->reservation_id !== (int) $source->id || (int) $targetIp->reservation_id !== (int) $target->id) { throw new CloudRecoveryInstanceStateConflict( diff --git a/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php b/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php index 82589014..a7246c42 100644 --- a/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php +++ b/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php @@ -12,10 +12,13 @@ use App\Models\CloudPeerMigrationArtifact; use App\Models\CloudBackupRestore; use App\Models\CloudBackupRecovery; use App\Models\CloudHostStorageConfiguration; +use App\Models\CloudHostNetworkAttachment; use App\Models\CloudJob; use App\Models\CloudOrder; use App\Models\CloudPublicIp; +use App\Models\CloudPublicIpPool; use App\Models\CloudResourceReservation; +use App\Models\CloudResourcePool; use App\Models\CloudRescueTemplate; use App\Models\CloudRescueTemplateReplica; use App\Models\CloudTemplate; @@ -681,6 +684,14 @@ final class CloudOperationRecoveryIdentity ); $ip = $reservation === null ? null : CloudPublicIp::find((int) $reservation->public_ip_id); + $attachment = $reservation === null ? null + : CloudHostNetworkAttachment::find( + (int) $reservation->network_attachment_id + ); + $resourcePool = $reservation === null ? null + : CloudResourcePool::find((int) $reservation->resource_pool_id); + $publicPool = $reservation === null ? null + : CloudPublicIpPool::find((int) $reservation->public_ip_pool_id); $prepare = CloudJob::find((int) $migration->source_prepare_job_id); try { $preparePayload = $prepare === null ? null : CloudSecrets::decrypt( @@ -705,15 +716,24 @@ final class CloudOperationRecoveryIdentity $spec['guest_hostname'] ?? $instance->name )) : ''; $sourceEndpoints = $body['source_endpoints'] ?? null; + $publicPoolDns = $publicPool === null ? null : json_decode( + (string) $publicPool->dns_servers_json, + true + ); $encodedEndpoints = is_array($sourceEndpoints) && array_is_list($sourceEndpoints) ? json_encode($sourceEndpoints, JSON_UNESCAPED_SLASHES) : false; if ($restore === null || $reservation === null || $ip === null + || $attachment === null || $resourcePool === null + || $publicPool === null + || !is_array($publicPoolDns) || !array_is_list($publicPoolDns) || !is_array($prepareBody) || array_is_list($prepareBody) || !is_array($spec) || array_is_list($spec) || (int) $job->backup_restore_id !== (int) $restore->id || (int) $restore->target_host_id !== (int) $job->host_id || (int) $restore->reservation_id !== (int) $reservation->id + || (int) $migration->target_reservation_id + !== (int) $reservation->id || !hash_equals((string) $restore->operation_id, (string) $job->operation_id) || $restore->backup_id !== null @@ -721,10 +741,23 @@ final class CloudOperationRecoveryIdentity || (int) $reservation->backup_restore_id !== (int) $restore->id || (int) $reservation->instance_id !== (int) $instance->id || (int) $reservation->host_id !== (int) $job->host_id + || (int) $reservation->resource_pool_id + !== (int) $instance->resource_pool_id + || (int) $attachment->host_id !== (int) $job->host_id + || (int) $attachment->line_id !== (int) $resourcePool->line_id + || (int) $reservation->network_attachment_id + !== (int) $attachment->id + || (int) $publicPool->host_id !== (int) $job->host_id + || (int) $publicPool->network_attachment_id + !== (int) $attachment->id + || (int) $reservation->public_ip_pool_id + !== (int) $publicPool->id || !in_array((string) $reservation->state, ['held', 'uncertain', 'committed'], true) || (int) $reservation->disk_gib !== $expectedDisk + || (int) $ip->host_id !== (int) $job->host_id || (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id + || (int) $ip->public_ip_pool_id !== (int) $publicPool->id || !hash_equals((string) $reservation->operation_id, (string) ($ip->operation_id ?? '')) || ($body['migration_id'] ?? null) @@ -750,7 +783,24 @@ final class CloudOperationRecoveryIdentity || ($body['startup_script'] ?? null) !== '' || ($body['guest_ssh_public_key'] ?? null) !== '' || ($body['root_password'] ?? null) !== '' - || ($body['network'] ?? null) !== 'bridge:br0' + || !CloudNetworkSelector::isValid($body['network'] ?? null) + || !hash_equals( + (string) $attachment->network_selector, + (string) ($body['network'] ?? '') + ) + || !hash_equals( + (string) $publicPool->pool_key, + (string) ($body['public_pool_key'] ?? '') + ) + || !hash_equals( + (string) $publicPool->cidr, + (string) ($body['public_pool_cidr'] ?? '') + ) + || !hash_equals( + (string) $publicPool->gateway, + (string) ($body['gateway'] ?? '') + ) + || ($body['dns_servers'] ?? null) !== $publicPoolDns || !hash_equals((string) $instance->name, (string) ($body['name'] ?? '')) || !hash_equals($expectedHostname, @@ -1563,6 +1613,14 @@ final class CloudOperationRecoveryIdentity : CloudResourceReservation::find((int) $reservationId); $ip = $reservation === null ? null : CloudPublicIp::find((int) $reservation->public_ip_id); + $attachment = $reservation === null ? null + : CloudHostNetworkAttachment::find( + (int) $reservation->network_attachment_id + ); + $resourcePool = $reservation === null ? null + : CloudResourcePool::find((int) $reservation->resource_pool_id); + $publicPool = $reservation === null ? null + : CloudPublicIpPool::find((int) $reservation->public_ip_pool_id); $instanceSpec = json_decode((string) $instance->spec_json, true); $backupSpec = $backup === null ? null : json_decode((string) $backup->spec_json, true); @@ -1570,8 +1628,15 @@ final class CloudOperationRecoveryIdentity $expectedReservationId = (int) $instance->reservation_id; $expectedUuid = strtolower((string) $instance->uuid); $expectedReservationDisk = (int) ($body['disk_gib'] ?? 0); + $publicPoolDns = $publicPool === null ? null : json_decode( + (string) $publicPool->dns_servers_json, + true + ); if ($restore === null || $backup === null || $reservation === null || $ip === null + || $attachment === null || $resourcePool === null + || $publicPool === null + || !is_array($publicPoolDns) || !array_is_list($publicPoolDns) || (int) $restore->backup_id !== (int) $backup->id || (int) $restore->target_instance_id !== (int) $instance->id || (int) $restore->target_host_id !== (int) $job->host_id @@ -1581,9 +1646,21 @@ final class CloudOperationRecoveryIdentity || (int) $reservation->instance_id !== (int) $instance->id || (int) $reservation->host_id !== (int) $job->host_id || (int) $reservation->user_id !== (int) $instance->user_id + || (int) $reservation->resource_pool_id + !== (int) $instance->resource_pool_id + || (int) $attachment->host_id !== (int) $job->host_id + || (int) $attachment->line_id !== (int) $resourcePool->line_id + || (int) $reservation->network_attachment_id + !== (int) $attachment->id + || (int) $publicPool->host_id !== (int) $job->host_id + || (int) $publicPool->network_attachment_id + !== (int) $attachment->id + || (int) $reservation->public_ip_pool_id + !== (int) $publicPool->id || !in_array((string) $reservation->state, ['held', 'uncertain', 'committed'], true) || (int) $ip->host_id !== (int) $job->host_id + || (int) $ip->public_ip_pool_id !== (int) $publicPool->id || (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id || !hash_equals((string) $reservation->operation_id, (string) ($ip->operation_id ?? '')) @@ -1597,7 +1674,24 @@ final class CloudOperationRecoveryIdentity || ($body['backup_key'] ?? null) !== $key || strtolower((string) ($body['uuid'] ?? '')) !== $expectedUuid || ($body['source'] ?? null) !== '' - || ($body['network'] ?? null) !== 'bridge:br0' + || !CloudNetworkSelector::isValid($body['network'] ?? null) + || !hash_equals( + (string) $attachment->network_selector, + (string) ($body['network'] ?? '') + ) + || !hash_equals( + (string) $publicPool->pool_key, + (string) ($body['public_pool_key'] ?? '') + ) + || !hash_equals( + (string) $publicPool->cidr, + (string) ($body['public_pool_cidr'] ?? '') + ) + || !hash_equals( + (string) $publicPool->gateway, + (string) ($body['gateway'] ?? '') + ) + || ($body['dns_servers'] ?? null) !== $publicPoolDns || !is_array($instanceSpec) || array_is_list($instanceSpec) || !is_array($backupSpec) || array_is_list($backupSpec) || !is_bool($backupSpec['debian_12_network_fix'] ?? null) diff --git a/web/app/Services/Cloud/CloudPlacementNetworkService.php b/web/app/Services/Cloud/CloudPlacementNetworkService.php index b9aa6601..dde4ff0f 100644 --- a/web/app/Services/Cloud/CloudPlacementNetworkService.php +++ b/web/app/Services/Cloud/CloudPlacementNetworkService.php @@ -42,6 +42,29 @@ final class CloudPlacementNetworkService /** @return array> keyed by host ID then line ID. */ public static function advisoryAvailableHostLines($candidateRows): array { + $details = self::advisoryAvailableHostLineDetails($candidateRows); + $available = []; + foreach ($details as $hostId => $lines) { + foreach ($lines as $lineId => $detail) { + if (($detail['available_ip_count'] ?? 0) > 0) { + $available[(int) $hostId][(int) $lineId] = true; + } + } + } + return $available; + } + + /** + * Non-locking inventory for exact host/line restore target presentation. + * Admission must still repeat every predicate through lockedCandidates() + * and lockAvailableSelection(). + * + * @return array}>> + */ + public static function advisoryAvailableHostLineDetails( + $candidateRows + ): array { $hostLines = []; foreach ($candidateRows as $candidate) { $hostId = (int) ($candidate->id ?? 0); @@ -134,8 +157,26 @@ final class CloudPlacementNetworkService )) { continue; } - $available[$hostId][$lineId] = true; + if (!isset($available[$hostId][$lineId])) { + $available[$hostId][$lineId] = [ + 'available_ip_count' => 0, + 'network_selectors' => [], + ]; + } + $available[$hostId][$lineId]['available_ip_count']++; + $available[$hostId][$lineId]['network_selectors'][ + (string) $row->network_selector + ] = true; + } + foreach ($available as &$lines) { + foreach ($lines as &$detail) { + $selectors = array_keys($detail['network_selectors']); + sort($selectors, SORT_STRING); + $detail['network_selectors'] = $selectors; + } + unset($detail); } + unset($lines); return $available; } diff --git a/web/app/Services/Cloud/CloudPlacementService.php b/web/app/Services/Cloud/CloudPlacementService.php index b9622c82..56f70535 100644 --- a/web/app/Services/Cloud/CloudPlacementService.php +++ b/web/app/Services/Cloud/CloudPlacementService.php @@ -368,75 +368,99 @@ final class CloudPlacementService array $resources): array { $resources = self::upgradeResources($resources); + $candidates = CloudHost::query()->join( + 'cloud_host_resource_pool_memberships as restore_membership', + 'restore_membership.host_id', '=', 'cloud_hosts.id' + )->join( + 'cloud_resource_pools as restore_resource_pool', + 'restore_resource_pool.id', '=', + 'restore_membership.resource_pool_id' + )->join( + 'cloud_network_lines as restore_line', + 'restore_line.id', '=', 'restore_resource_pool.line_id' + )->join( + 'cloud_regions as restore_region', + 'restore_region.id', '=', 'restore_line.region_id' + )->join( + 'cloud_host_capacity_policies as restore_capacity', + 'restore_capacity.host_id', '=', 'cloud_hosts.id' + )->join( + 'cloud_host_agents as restore_agent', + 'restore_agent.host_id', '=', 'cloud_hosts.id' + )->join( + 'cloud_host_storage_configurations as restore_storage', + 'restore_storage.host_id', '=', 'cloud_hosts.id' + )->where('cloud_hosts.enabled', 1) + ->where('restore_membership.scheduler_state', 'active') + ->where('restore_resource_pool.status', 'active') + ->where('restore_line.status', 'active') + ->where('restore_region.status', 'active') + ->where('restore_agent.enabled', 1) + ->where('restore_agent.last_test_status', 'healthy') + ->where('restore_agent.tested_revision', '>', 0) + ->whereColumn( + 'restore_agent.tested_revision', + 'restore_agent.revision' + )->where('restore_storage.state', 'applied') + ->where('restore_capacity.configured_cpu_cores', '>', 0) + ->where('restore_capacity.configured_memory_mib', '>', 0) + ->where('restore_capacity.configured_disk_gib', '>', 0) + ->orderBy('cloud_hosts.id') + ->orderBy('restore_resource_pool.id') + ->get([ + 'cloud_hosts.id', + 'cloud_hosts.name', + 'restore_resource_pool.id as resource_pool_id', + 'restore_resource_pool.name as resource_pool_name', + 'restore_line.id as resource_pool_line_id', + 'restore_line.name as line_name', + 'restore_region.id as region_id', + 'restore_region.name as region_name', + 'restore_region.country_code', + 'restore_capacity.configured_cpu_cores', + 'restore_capacity.configured_memory_mib', + 'restore_capacity.configured_disk_gib', + 'restore_capacity.safety_cpu_cores', + 'restore_capacity.safety_memory_mib', + 'restore_capacity.safety_disk_gib', + 'restore_capacity.max_instances', + ]); + $pendingByHost = self::pendingUsageByHost($candidates); + $networkByHostLine = CloudPlacementNetworkService:: + advisoryAvailableHostLineDetails($candidates); $result = []; - $hosts = CloudHost::where('enabled', 1) - ->orderBy('id')->get(); - foreach ($hosts as $host) { - if ((string) $host->default_network !== 'bridge:br0') { - continue; - } - $memberships = CloudHostResourcePoolMembership::where( - 'host_id', (int) $host->id - )->where('scheduler_state', 'active')->orderBy('id')->get(); - $membership = $memberships->count() === 1 - ? $memberships->first() : null; - $pool = $membership === null ? null - : CloudResourcePool::find((int) $membership->resource_pool_id); - $line = $pool === null ? null - : CloudNetworkLine::find((int) $pool->line_id); - $region = $line === null ? null - : CloudRegion::find((int) $line->region_id); - $policy = CloudHostCapacityPolicy::find((int) $host->id); - $agent = CloudHostAgent::find((int) $host->id); - $storage = CloudHostStorageConfiguration::find((int) $host->id); - if ($pool === null || $line === null || $region === null - || (string) $pool->status !== 'active' - || (string) $line->status !== 'active' - || (string) $region->status !== 'active' - || $policy === null || $agent === null || !$agent->isReady() - || $storage === null || !$storage->isApplied() + foreach ($candidates as $candidate) { + $hostId = (int) $candidate->id; + $lineId = (int) $candidate->resource_pool_line_id; + $network = $networkByHostLine[$hostId][$lineId] ?? null; + if (!is_array($network) + || (int) ($network['available_ip_count'] ?? 0) < 1 || !self::hasCapacity( - $policy, - CloudPanelUsageService::forHost((int) $host->id), + $candidate, + $pendingByHost[$hostId] ?? self::emptyUsage(), $resources )) { continue; } - $attachmentIds = CloudHostNetworkAttachment::where( - 'host_id', (int) $host->id - )->where('line_id', (int) $line->id) - ->where('network_selector', 'bridge:br0') - ->where('state', 'active')->where('sync_state', 'applied') - ->whereColumn('observed_revision', '>=', 'desired_revision') - ->pluck('id')->all(); - if ($attachmentIds === []) { - continue; - } - $availableIpCount = CloudPublicIp::query() - ->join('cloud_public_ip_pools as restore_pool', - 'restore_pool.id', '=', 'cloud_public_ips.public_ip_pool_id') - ->where('cloud_public_ips.host_id', (int) $host->id) - ->whereIn('restore_pool.network_attachment_id', $attachmentIds) - ->where('restore_pool.state', 'active') - ->where('restore_pool.sync_state', 'applied') - ->whereColumn('restore_pool.observed_revision', '>=', - 'restore_pool.desired_revision') - ->where('cloud_public_ips.state', 'available') - ->whereNull('cloud_public_ips.reservation_id') - ->whereNull('cloud_public_ips.instance_id') - ->whereNull('cloud_public_ips.operation_id')->count(); - if ((int) $availableIpCount < 1) { - continue; - } $result[] = [ - 'id' => (string) $host->id, - 'name' => (string) $host->name, - 'region' => (string) $region->name, - 'resource_pool_id' => (string) $pool->id, - 'resource_pool' => (string) $pool->name, - 'network' => 'bridge:br0', - 'available_ip_count' => (int) $availableIpCount, - 'is_source_host' => (int) $host->id === $sourceHostId, + 'id' => (string) $hostId, + 'name' => (string) $candidate->name, + 'region_id' => (string) $candidate->region_id, + 'region' => (string) $candidate->region_name, + 'country_code' => strtoupper( + (string) $candidate->country_code + ), + 'line_id' => (string) $lineId, + 'line' => (string) $candidate->line_name, + 'resource_pool_id' => + (string) $candidate->resource_pool_id, + 'resource_pool' => + (string) $candidate->resource_pool_name, + 'network_selectors' => + array_values($network['network_selectors'] ?? []), + 'available_ip_count' => + (int) $network['available_ip_count'], + 'is_source_host' => $hostId === $sourceHostId, ]; } return $result; @@ -471,32 +495,33 @@ final class CloudPlacementService * public_ip:CloudPublicIp,network:array} */ public static function reserveBackupRestore(CloudBackupRestore $restore, - int $userId, array $resources, - ?int $requiredResourcePoolId = null, + int $userId, array $resources, int $requiredResourcePoolId, int $additionalDiskGib = 0): array { $resources = self::upgradeResources($resources); $capacityResources = $resources; $capacityResources['disk_gib'] += max(0, $additionalDiskGib); $hostId = (int) $restore->target_host_id; - $host = CloudHost::where('id', $hostId)->lockForUpdate()->first(); - $memberships = CloudHostResourcePoolMembership::where('host_id', $hostId) - ->orderBy('id')->lockForUpdate()->get(); - $membership = $memberships->first(static fn ($row): bool => - (string) $row->scheduler_state === 'active'); - if ($memberships->filter(static fn ($row): bool => - (string) $row->scheduler_state === 'active')->count() !== 1) { - $membership = null; - } - $pool = $membership === null ? null - : CloudResourcePool::where('id', (int) $membership->resource_pool_id) + if ($hostId < 1 || $requiredResourcePoolId < 1) { + throw new CloudError('备份恢复目标身份无效', 409); + } + $poolRef = CloudResourcePool::find($requiredResourcePoolId); + $lineRef = $poolRef === null ? null + : CloudNetworkLine::find((int) $poolRef->line_id); + $region = $lineRef === null ? null + : CloudRegion::where('id', (int) $lineRef->region_id) ->lockForUpdate()->first(); - $line = $pool === null ? null - : CloudNetworkLine::where('id', (int) $pool->line_id) + $line = $lineRef === null ? null + : CloudNetworkLine::where('id', (int) $lineRef->id) ->lockForUpdate()->first(); - $region = $line === null ? null - : CloudRegion::where('id', (int) $line->region_id) + $pool = $poolRef === null ? null + : CloudResourcePool::where('id', (int) $poolRef->id) ->lockForUpdate()->first(); + $host = CloudHost::where('id', $hostId)->lockForUpdate()->first(); + $membership = CloudHostResourcePoolMembership::where( + 'host_id', $hostId + )->where('resource_pool_id', $requiredResourcePoolId) + ->lockForUpdate()->first(); $policy = CloudHostCapacityPolicy::where('host_id', $hostId) ->lockForUpdate()->first(); $storage = CloudHostStorageConfiguration::where('host_id', $hostId) @@ -508,32 +533,24 @@ final class CloudPlacementService || $storage === null || !$storage->isApplied() || $agent === null || !$agent->isReady() || !(bool) $host->enabled - || (string) $host->default_network !== 'bridge:br0' + || (string) $membership->scheduler_state !== 'active' + || (int) $membership->resource_pool_id !== $requiredResourcePoolId + || (int) $pool->id !== $requiredResourcePoolId + || (int) $pool->line_id !== (int) $line->id + || (int) $line->region_id !== (int) $region->id || (string) $pool->status !== 'active' || (string) $line->status !== 'active' || (string) $region->status !== 'active') { throw new CloudError('所选目标宿主机暂不支持备份恢复', 409); } - if ($requiredResourcePoolId !== null - && (int) $pool->id !== $requiredResourcePoolId) { - throw new CloudError('维护迁移只能选择同一资源池的宿主机', 409); + $networkCandidates = CloudPlacementNetworkService::lockedCandidates( + $hostId, + (int) $line->id, + $agent + ); + if ($networkCandidates === []) { + throw new CloudError('目标宿主机的线路网络接入尚未就绪', 409); } - - $attachments = CloudHostNetworkAttachment::where('host_id', $hostId) - ->where('line_id', (int) $line->id) - ->where('network_selector', 'bridge:br0') - ->where('state', 'active')->where('sync_state', 'applied') - ->whereColumn('observed_revision', '>=', 'desired_revision') - ->orderBy('id')->lockForUpdate()->get(); - if ($attachments->isEmpty()) { - throw new CloudError('目标宿主机的 br0 网络接入尚未就绪', 409); - } - $attachmentById = $attachments->keyBy('id'); - $pools = CloudPublicIpPool::where('host_id', $hostId) - ->whereIn('network_attachment_id', $attachments->pluck('id')->all()) - ->where('state', 'active')->where('sync_state', 'applied') - ->whereColumn('observed_revision', '>=', 'desired_revision') - ->orderBy('id')->lockForUpdate()->get(); $reservations = CloudResourceReservation::where('host_id', $hostId) ->whereIn('state', ['held', 'uncertain', 'committed']) ->orderBy('id')->lockForUpdate()->get(); @@ -545,35 +562,16 @@ final class CloudPlacementService throw new CloudError('目标宿主机没有足够的可用容量', 409); } - $selectedPool = null; - $ip = null; - foreach ($pools as $candidatePool) { - if (preg_match('/^[a-f0-9]{32}$/D', - (string) $candidatePool->pool_key) !== 1) { - continue; - } - foreach (self::availablePublicIpQuery( - $hostId, - (int) $candidatePool->id, - (int) $candidatePool->guest_prefix_length - )->limit(self::MAX_PUBLIC_IPS_PER_POOL + 1) - ->lockForUpdate()->get() as $candidateIp) { - if (self::publicIpBelongsToPool($candidateIp, $candidatePool)) { - $selectedPool = $candidatePool; - $ip = $candidateIp; - break 2; - } - } - } - if ($selectedPool === null || $ip === null) { - throw new CloudError('目标宿主机没有可分配的公网 IP', 409); - } - $attachment = $attachmentById->get( - (int) $selectedPool->network_attachment_id + $network = CloudPlacementNetworkService::lockAvailableSelection( + $hostId, + $networkCandidates ); - if ($attachment === null) { - throw new CloudError('目标宿主机公网地址池关系不完整', 409); + if ($network === null) { + throw new CloudError('目标宿主机没有可分配的公网 IP', 409); } + $attachment = $network['attachment']; + $selectedPool = $network['public_pool']; + $ip = $network['public_ip']; $dns = self::poolDnsServers($selectedPool); $reservation = new CloudResourceReservation(); $reservation->reservation_key = bin2hex(random_bytes(16)); @@ -612,7 +610,7 @@ final class CloudPlacementService 'host' => $host, 'public_ip' => $ip, 'network' => [ - 'network' => 'bridge:br0', + 'network' => (string) $attachment->network_selector, 'public_pool_key' => (string) $selectedPool->pool_key, 'public_pool_cidr' => (string) $selectedPool->cidr, 'public_ip_cidr' => (string) $ip->address . '/' @@ -661,13 +659,27 @@ final class CloudPlacementService 'id', (int) $reservation->network_attachment_id )->lockForUpdate()->first(); + $resourcePool = $reservation === null ? null + : CloudResourcePool::find((int) $reservation->resource_pool_id); + $membership = $reservation === null ? null + : CloudHostResourcePoolMembership::where( + 'host_id', + (int) $reservation->host_id + )->where( + 'resource_pool_id', + (int) $reservation->resource_pool_id + )->first(); if ($reservation === null || $ip === null || $pool === null - || $attachment === null + || $attachment === null || $resourcePool === null + || $membership === null || (int) $restore->reservation_id !== (int) $reservation->id || (int) $restore->target_host_id !== (int) $reservation->host_id || (int) $reservation->backup_restore_id !== (int) $restore->id || (int) $reservation->instance_id !== $instanceId || (string) $reservation->state !== 'held' + || (string) $membership->scheduler_state !== 'active' + || (int) $attachment->host_id !== (int) $reservation->host_id + || (int) $attachment->line_id !== (int) $resourcePool->line_id || (int) $pool->host_id !== (int) $reservation->host_id || (int) $pool->network_attachment_id !== (int) $attachment->id || (int) $ip->host_id !== (int) $reservation->host_id @@ -685,7 +697,9 @@ final class CloudPlacementService ) || preg_match('/^[a-f0-9]{32}$/D', (string) $pool->pool_key) !== 1 - || (string) $attachment->network_selector !== 'bridge:br0') { + || !CloudNetworkSelector::isValid( + (string) $attachment->network_selector + )) { throw new CloudRecoveryInstanceStateConflict( '维护迁移目标预留在源实例停机后发生变化', 409 @@ -694,7 +708,7 @@ final class CloudPlacementService return [ 'reservation' => $reservation, 'network' => [ - 'network' => 'bridge:br0', + 'network' => (string) $attachment->network_selector, 'public_pool_key' => (string) $pool->pool_key, 'public_pool_cidr' => (string) $pool->cidr, 'public_ip_cidr' => (string) $ip->address . '/' diff --git a/web/public/cloud/admin-instance-backups.js b/web/public/cloud/admin-instance-backups.js index f474716a..e350f976 100644 --- a/web/public/cloud/admin-instance-backups.js +++ b/web/public/cloud/admin-instance-backups.js @@ -56,7 +56,8 @@ function backupTargets(payload, backup) { : (Array.isArray(payload?.restore_targets) ? payload.restore_targets : (Array.isArray(payload?.target_hosts) ? payload.target_hosts : [])); return values.filter(value => value && typeof value === 'object' - && /^[1-9][0-9]*$/.test(String(value.host_id ?? value.id ?? ''))); + && /^[1-9][0-9]*$/.test(String(value.host_id ?? value.id ?? '')) + && /^[1-9][0-9]*$/.test(String(value.resource_pool_id ?? ''))); } export function createAdminInstanceBackups({ @@ -248,17 +249,23 @@ export function createAdminInstanceBackups({ const form = el('form', 'mt-3'); form.noValidate = true; const grid = el('div', 'row g-2'); const hostLabel = el('label', 'col-12 col-lg-6'); - hostLabel.append(el('span', 'form-label d-block', '恢复到宿主机')); - const host = el('select', 'form-select'); host.name = 'target_host_id'; host.required = true; - host.append(new Option(targets.length ? '请选择目标宿主机' : '暂无符合条件的宿主机', '')); + hostLabel.append(el('span', 'form-label d-block', '恢复到宿主机与资源池')); + const host = el('select', 'form-select'); host.name = 'target_identity'; host.required = true; + host.append(new Option(targets.length ? '请选择目标宿主机与资源池' : '暂无符合条件的目标', '')); for (const target of targets) { const id = String(target.host_id ?? target.id); + const resourcePoolId = String(target.resource_pool_id); const name = text(target.host_name, target.name, `宿主机 #${id}`); const region = String(target.region || target.region_name || '').trim(); + const line = String(target.line || '').trim(); + const resourcePool = String(target.resource_pool || `资源池 #${resourcePoolId}`).trim(); const available = Number(target.available_ip_count ?? target.available_count); const suffix = Number.isFinite(available) ? ` · ${available} 个可用 IP` : ''; const source = target.is_source_host === true ? ' · 原宿主机' : ''; - host.append(new Option(`${name}${region ? ` · ${region}` : ''}${source}${suffix}`, id)); + host.append(new Option( + `${name}${region ? ` · ${region}` : ''}${line ? ` · ${line}` : ''} · ${resourcePool}${source}${suffix}`, + `${id}:${resourcePoolId}`, + )); } host.disabled = mutationBlocked || targets.length === 0; hostLabel.append(host); const nameLabel = el('label', 'col-12 col-lg-6'); @@ -273,7 +280,7 @@ export function createAdminInstanceBackups({ confirm.type = 'checkbox'; confirm.name = 'confirm_new_instance'; confirm.disabled = mutationBlocked || targets.length === 0; confirmLabel.append(confirm, document.createTextNode( - '我确认这会创建一台免计费的独立新实例,使用 br0 并分配全新公网 IP;不会继承原 IP、账单、到期时间或流量周期。')); + '我确认这会创建一台免计费的独立新实例,使用所选资源池线路中已验证的网络接入并分配全新公网 IP;不会继承原 IP、账单、到期时间或流量周期。')); form.append(confirmLabel); const resultFeedback = el('p', 'text-muted fs-13 mb-2'); resultFeedback.dataset.restoreFeedback = ''; resultFeedback.hidden = true; @@ -285,23 +292,31 @@ export function createAdminInstanceBackups({ form.addEventListener('submit', async event => { event.preventDefault(); if (state.mutationRequest || mutationBlocked) return; - const targetHostId = String(host.value || ''); const instanceName = String(name.value || '').trim(); + const targetIdentity = String(host.value || ''); const instanceName = String(name.value || '').trim(); const show = (message, tone = 'danger') => { resultFeedback.hidden = false; resultFeedback.className = `text-${tone} fs-13 mb-2`; resultFeedback.textContent = message; }; - if (!/^[1-9][0-9]*$/.test(targetHostId)) return show('请选择目标宿主机。'); + const targetMatch = /^([1-9][0-9]*):([1-9][0-9]*)$/.exec(targetIdentity); + if (!targetMatch) return show('请选择目标宿主机与资源池。'); + const targetHostId = Number(targetMatch[1]); + const targetResourcePoolId = Number(targetMatch[2]); if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/.test(instanceName)) { return show('新实例名称需为 1 至 63 位英文、数字、点、下划线或连字符,并以英文或数字开头。'); } - if (!confirm.checked) return show('请确认新实例、br0 和全新公网 IP 的恢复规则。'); + if (!confirm.checked) return show('请确认新实例、目标网络接入和全新公网 IP 的恢复规则。'); for (const control of form.querySelectorAll('input, select, button')) control.disabled = true; show('正在预留目标资源并创建恢复任务,请勿重复提交…', 'muted'); try { const receipt = await submitTask({ vmId, path: mutationUrl(vmId, backup.id, 'restore', library), - body: { target_host_id: Number(targetHostId), name: instanceName, confirm_new_instance: true }, + body: { + target_host_id: targetHostId, + target_resource_pool_id: targetResourcePoolId, + name: instanceName, + confirm_new_instance: true, + }, title: '备份恢复', library, }); show(`恢复任务 #${receipt.task_id || '—'} 已接收。`, 'muted'); @@ -324,7 +339,7 @@ export function createAdminInstanceBackups({ const panel = byId('instance-panel-backups'); panel.replaceChildren(); const intro = el('div', 'alert alert-info'); intro.append(el('strong', 'd-block mb-1', '可移植系统盘备份'), - document.createTextNode('备份上传到已验证的对象存储,不修改源实例。恢复会在所选宿主机创建独立实例;可选择原宿主机或其他合格宿主机,并统一接入 br0、分配全新公网 IP。')); + document.createTextNode('备份上传到已验证的对象存储,不修改源实例。恢复会在所选宿主机与资源池创建独立实例,使用该线路中当前已验证的网络接入并分配全新公网 IP。')); panel.append(intro, migration.render(payload, vmId)); const create = el('section', 'card mb-3'); const createBody = el('div', 'card-body'); createBody.append(el('h3', 'h6 fw-semibold', '创建备份')); @@ -434,7 +449,7 @@ export function createAdminInstanceBackups({ if (targets.length) cardBody.append(restoreForm(vmId, backup, targets, payload?.can_restore === false || payload?.active_job?.blocks_mutation === true)); else cardBody.append(el('p', 'text-warning fs-13 mb-0', - '暂无满足容量、存储、br0 网络和可用公网 IP 条件的宿主机。')); + '暂无满足容量、存储、已验证线路网络和可用公网 IP 条件的目标。')); } if (['ready', 'failed'].includes(backup.state) && backup.can_delete === true) { const deleteActions = el('div', 'd-flex justify-content-end mt-3'); @@ -504,7 +519,7 @@ export function createAdminInstanceBackups({ if (backup.state === 'ready') { if (targets.length) cardBody.append(restoreForm(vmId, backup, targets, !canManage, true)); else cardBody.append(el('p', 'text-warning fs-13', - '暂无满足容量、存储、br0 网络和可用公网 IP 条件的宿主机。')); + '暂无满足容量、存储、已验证线路网络和可用公网 IP 条件的目标。')); } if (backup.can_delete === true) { const actions = el('div', 'd-flex justify-content-end mt-3'); diff --git a/web/public/cloud/admin-instance-migration.js b/web/public/cloud/admin-instance-migration.js index 935ae9ae..9fbf67df 100644 --- a/web/public/cloud/admin-instance-migration.js +++ b/web/public/cloud/admin-instance-migration.js @@ -44,7 +44,7 @@ export function createAdminInstanceMigration({ const stateLabel = text(progress.label, '状态未知'); body.append(infoList([ ['状态', stateLabel], - ['迁移方向', `宿主机 #${text(migration.source_host_id)} → #${text(migration.target_host_id)}`], + ['迁移方向', `宿主机 #${text(migration.source_host_id)} → #${text(migration.target_host_id)} · 资源池 #${text(migration.target_resource_pool_id)}`], ['源副本策略', migration.cleanup_mode === 'delete' ? '目标验证后自动清理' : '保留并由管理员稍后清理'], ['切换时间', date(migration.cutover_at)], ['完成时间', date(migration.completed_at)], @@ -165,9 +165,13 @@ export function createAdminInstanceMigration({ hostLabel.append(el('span', 'form-label d-block', '目标宿主机')); const host = el('select', 'form-select'); host.required = true; host.append(new Option(targets.length ? '请选择同资源池宿主机' : '暂无可迁移宿主机', '')); - targets.forEach(target => host.append(new Option( - `${text(target.host_name, `宿主机 #${target.host_id}`)}${target.region ? ` · ${target.region}` : ''} · ${Number(target.available_ip_count) || 1} 个可用 IP`, - String(target.host_id)))); + targets.forEach(target => { + const option = new Option( + `${text(target.host_name, `宿主机 #${target.host_id}`)}${target.region ? ` · ${target.region}` : ''}${target.line ? ` · ${target.line}` : ''} · ${Number(target.available_ip_count) || 1} 个可用 IP`, + String(target.host_id)); + option.dataset.resourcePoolId = String(target.resource_pool_id || ''); + host.append(option); + }); hostLabel.append(host); const modeLabel = el('label', 'col-12 col-lg-5'); modeLabel.append(el('span', 'form-label d-block', '目标验证后的源副本')); @@ -191,7 +195,7 @@ export function createAdminInstanceMigration({ feedback.hidden = false; feedback.className = 'text-warning fs-13 mb-0 mt-2'; feedback.textContent = targets.length ? text(payload?.create_block_reason, '当前实例不能开始维护迁移。') - : '暂无同资源池且具备容量、br0 和可用公网 IP 的其他宿主机。'; + : '暂无具备原资源池活动成员关系、可用容量、已验证网络接入和公网 IP 的其他宿主机。'; } form.addEventListener('submit', async event => { event.preventDefault(); @@ -200,6 +204,11 @@ export function createAdminInstanceMigration({ feedback.hidden = false; feedback.className = 'text-danger fs-13 mb-0 mt-2'; feedback.textContent = '请选择目标宿主机。'; return; } + const targetResourcePoolId = host.selectedOptions[0]?.dataset.resourcePoolId || ''; + if (!/^[1-9][0-9]*$/.test(targetResourcePoolId)) { + feedback.hidden = false; feedback.className = 'text-danger fs-13 mb-0 mt-2'; + feedback.textContent = '目标宿主机缺少原资源池身份,请刷新后重试。'; return; + } if (!confirm.checked) { feedback.hidden = false; feedback.className = 'text-danger fs-13 mb-0 mt-2'; feedback.textContent = '请确认冷迁移、原服务账本和新公网 IP 规则。'; return; @@ -211,7 +220,8 @@ export function createAdminInstanceMigration({ const receipt = await submitTask({ vmId, path: `/api/v1/admin/instances/${encodeURIComponent(vmId)}/maintenance-migrations`, - body: { target_host_id: Number(host.value), cleanup_mode: mode.value, + body: { target_host_id: Number(host.value), + target_resource_pool_id: Number(targetResourcePoolId), cleanup_mode: mode.value, confirm_maintenance_migration: true }, title: '维护迁移', }); diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index a01707cf..e5ef7dc3 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026110205' scope='global'} +{assign var=venix_asset_version value='2026110206' scope='global'} diff --git a/web/tests/AdminBackupLibraryBehaviorTest.mjs b/web/tests/AdminBackupLibraryBehaviorTest.mjs index ff9bd61e..f4c116c9 100644 --- a/web/tests/AdminBackupLibraryBehaviorTest.mjs +++ b/web/tests/AdminBackupLibraryBehaviorTest.mjs @@ -1,12 +1,32 @@ import assert from 'node:assert/strict'; import { createAdminInstanceBackups } from '../public/cloud/admin-instance-backups.js'; -function node() { - return { open: false, value: '', children: [], handlers: {}, - append(...children) { this.children.push(...children); }, - replaceChildren(...children) { this.children = children; }, - setAttribute() {}, addEventListener(name, handler) { this.handlers[name] = handler; }, - removeEventListener() {}, querySelector() { return null; } }; +class FakeNode { + constructor(tag = 'div') { + this.tagName = String(tag).toLowerCase(); this.open = false; + this.value = ''; this.children = []; this.handlers = {}; + this.dataset = {}; this.disabled = false; this.hidden = false; + this.checked = false; this.textContent = ''; + } + append(...children) { this.children.push(...children); } + replaceChildren(...children) { this.children = children; } + setAttribute() {} + addEventListener(name, handler) { this.handlers[name] = handler; } + removeEventListener() {} + querySelector() { return null; } + querySelectorAll(selector) { + const tags = new Set(selector.split(',').map(value => value.trim())); + return descendants(this).filter(child => tags.has(child.tagName)); + } +} +function node(tag = 'div') { return new FakeNode(tag); } +function descendants(root) { + const found = []; + for (const child of root.children || []) { + if (!(child instanceof FakeNode)) continue; + found.push(child, ...descendants(child)); + } + return found; } const ids = new Map(['backup-library', 'backup-library-filter', 'backup-library-items', 'backup-library-notice', 'backup-library-page', 'backup-library-previous', @@ -14,15 +34,28 @@ const ids = new Map(['backup-library', 'backup-library-filter', 'backup-library- const controls = new Map(['q', 'state', 'user_id', 'instance_id', 'host_id'].map(key => [key, node()])); const form = ids.get('backup-library-filter'); form.elements = { namedItem: key => controls.get(key) }; +globalThis.Node = FakeNode; +globalThis.Option = class extends FakeNode { + constructor(label, value) { + super('option'); this.textContent = String(label); this.value = String(value); + } +}; globalThis.document = { createElement: node, + createTextNode(value) { + const text = node('#text'); text.textContent = String(value); return text; + }, body: { style: { setProperty() {}, removeProperty() {} } }, documentElement: { classList: { add() {}, remove() {} } } }; globalThis.window = { addEventListener() {}, removeEventListener() {}, VenixDrawerMotion: { openDrawerWithMotion(dialog) { dialog.open = true; } } }; const requests = []; +const mutations = []; const backups = createAdminInstanceBackups({ byId: id => ids.get(id), createMigration: () => ({}), - actions: { enqueue() {}, read(path, controller) { + actions: { enqueue(path, body) { + mutations.push({ path, body }); + return Promise.resolve({ task_id: '77', url: '/tasks/77' }); + }, watch() { return { url: '/tasks/77', stop() {} }; }, read(path, controller) { return new Promise(resolve => requests.push({ path, controller, resolve })); } }, }); @@ -58,4 +91,44 @@ assert.equal(resetUrl.searchParams.get('user_id'), null); assert.equal(resetUrl.searchParams.get('page'), '1'); assert.equal(controls.get('state').value, ''); await settle(3, payload(1, 0)); await resetPromise; + +const compositeLoad = backups.openLibrary(null); +await settle(4, { + can_manage: true, + items: [{ + id: '19', name: 'portable-backup', state: 'ready', consistency: 'crash', + can_delete: false, + restore_targets: [{ + host_id: '8', host_name: 'HKG-A', region: 'Hong Kong', + line: 'International', resource_pool_id: '31', + resource_pool: 'HKG International', available_ip_count: 2, + is_source_host: true, + }], + source: { instance_id: '999', host_id: '8', user_id: '77' }, + }], + pagination: { page: 1, total_pages: 1, total: 1 }, +}); +await compositeLoad; +const rendered = descendants(ids.get('backup-library-items')); +const restoreSelect = rendered.find(child => child.tagName === 'select' + && child.name === 'target_identity'); +assert.ok(restoreSelect, 'Restore target selector was not rendered.'); +assert.equal(restoreSelect.children[1].value, '8:31', + 'Restore target did not preserve the composite host/resource-pool identity.'); +restoreSelect.value = '8:31'; +const restoreForm = rendered.find(child => child.tagName === 'form' + && typeof child.handlers.submit === 'function'); +assert.ok(restoreForm, 'Restore form was not rendered.'); +const restoreInputs = descendants(restoreForm); +restoreInputs.find(child => child.tagName === 'input' + && child.name === 'name').value = 'restored-vm'; +restoreInputs.find(child => child.tagName === 'input' + && child.name === 'confirm_new_instance').checked = true; +await restoreForm.handlers.submit({ preventDefault() {} }); +assert.deepEqual(mutations.at(-1)?.body, { + target_host_id: 8, + target_resource_pool_id: 31, + name: 'restored-vm', + confirm_new_instance: true, +}, 'Restore request lost the exact host/resource-pool target identity.'); console.log('Administrator backup library filtering, paging and stale response protection passed.'); diff --git a/web/tests/AdminInstanceMigrationBehaviorTest.mjs b/web/tests/AdminInstanceMigrationBehaviorTest.mjs new file mode 100644 index 00000000..b6d6003f --- /dev/null +++ b/web/tests/AdminInstanceMigrationBehaviorTest.mjs @@ -0,0 +1,85 @@ +import assert from 'node:assert/strict'; +import { createAdminInstanceMigration } from '../public/cloud/admin-instance-migration.js'; + +class Element { + constructor(tag = 'div') { + this.tag = tag; this.children = []; this.listeners = new Map(); + this.dataset = {}; this.value = ''; this.checked = false; + this.disabled = false; this.hidden = false; this.textContent = ''; + } + append(...children) { this.children.push(...children); } + addEventListener(name, listener) { this.listeners.set(name, listener); } + querySelectorAll(selector) { + const tags = selector.split(',').map(value => value.trim()); + const descendants = this.children.flatMap(child => child instanceof Element + ? [child, ...child.querySelectorAll(selector)] : []); + return descendants.filter(child => tags.includes(child.tag)); + } + get selectedOptions() { + return this.tag === 'select' + ? this.children.filter(child => child instanceof Element + && child.tag === 'option' && String(child.value) === String(this.value)) + : []; + } +} + +globalThis.document = { + createElement: tag => new Element(tag), + createTextNode: value => ({ textContent: String(value) }), +}; +globalThis.Option = class extends Element { + constructor(label = '', value = '') { + super('option'); this.textContent = String(label); this.value = String(value); + } +}; + +const submissions = []; +const migration = createAdminInstanceMigration({ + isBusy: () => false, + async submitTask(value) { + submissions.push(value); + return { task_id: '42' }; + }, + notice() {}, + refresh() {}, +}); +const section = migration.render({ + can_migrate: true, + migration_targets: [{ + host_id: '9', host_name: 'HKG-B', region: 'Hong Kong', line: 'Premium', + resource_pool_id: '77', available_ip_count: 3, + }], +}, '123'); +const form = section.querySelectorAll('form')[0]; +const selects = form.querySelectorAll('select'); +const confirm = section.querySelectorAll('input')[0]; +assert.equal(selects[0].children[1].dataset.resourcePoolId, '77'); +assert.match(selects[0].children[1].textContent, /Premium/); +selects[0].value = '9'; +selects[1].value = 'delete'; +confirm.checked = true; +await form.listeners.get('submit')({ preventDefault() {} }); +assert.equal(submissions.length, 1); +assert.deepEqual(submissions[0].body, { + target_host_id: 9, + target_resource_pool_id: 77, + cleanup_mode: 'delete', + confirm_maintenance_migration: true, +}); + +const invalid = migration.render({ + can_migrate: true, + migration_targets: [{ + host_id: '10', host_name: 'Broken target', resource_pool_id: '', + available_ip_count: 1, + }], +}, '123'); +const invalidForm = invalid.querySelectorAll('form')[0]; +const invalidSelects = invalidForm.querySelectorAll('select'); +invalidSelects[0].value = '10'; +invalid.querySelectorAll('input')[0].checked = true; +await invalidForm.listeners.get('submit')({ preventDefault() {} }); +assert.equal(submissions.length, 1, + 'A target without its exact resource-pool identity reached the API.'); + +console.log('Administrator maintenance-migration target identity behavior passed.'); diff --git a/web/tests/CloudFinancialWorkflowTest.php b/web/tests/CloudFinancialWorkflowTest.php index 33a585d5..c58f3f67 100644 --- a/web/tests/CloudFinancialWorkflowTest.php +++ b/web/tests/CloudFinancialWorkflowTest.php @@ -1099,9 +1099,26 @@ namespace { $sourceBackup->sha256 = $originalBackingSha256; $sourceBackup->updated_at = time(); $sourceBackup->save(); + // Cloud-snapshot provisioning must select from the paid offer's exact + // resource-pool line and current Agent evidence. default_network and the + // attachment sync projection are not placement authorities. + $host->default_network = 'public'; + $host->save(); + $attachment->state = 'draining'; + $attachment->save(); CloudInvoiceService::payBalance(CloudInvoice::where('order_id', $failed->id)->first(), $actor, 'provision-balance-test-0002'); $failedJob = CloudJob::where('order_id', $failed->id)->first(); + $snapshotReservation = CloudResourceReservation::where( + 'order_id', (int) $failed->id + )->first(); + $assert($snapshotReservation !== null + && (int) $snapshotReservation->resource_pool_id === (int) $pool->id + && (int) $snapshotReservation->network_attachment_id + === (int) $targetAttachment->id + && (int) $snapshotReservation->public_ip_pool_id + === (int) $targetPublicPool->id, + 'Cloud snapshot payment did not freeze the exact offer pool and verified attachment.'); $beforeBackupDispatch = count($history); $mock->append(new Response(422, [], json_encode(['error' => [ 'code' => 'invalid_request', @@ -1131,8 +1148,13 @@ namespace { ) && ($backupAgentBody['source'] ?? null) === '' && ($backupAgentBody['root_password'] ?? null) === '' + && ($backupAgentBody['network'] ?? null) === 'bridge:br1' && (int) $failedJob->backup_id === (int) $sourceBackup->id, 'Paid backup-origin create lost its signed object identity or used the cloud-template endpoint.'); + $host->default_network = 'bridge:br0'; + $host->save(); + $attachment->state = 'active'; + $attachment->save(); $instance->spec_json = $originalSourceSpec; $instance->save(); $subscription->enabled = false; diff --git a/web/tests/CloudMaintenanceMigrationFinalizerTest.php b/web/tests/CloudMaintenanceMigrationFinalizerTest.php index 24148f8d..10a11808 100644 --- a/web/tests/CloudMaintenanceMigrationFinalizerTest.php +++ b/web/tests/CloudMaintenanceMigrationFinalizerTest.php @@ -109,8 +109,21 @@ $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'); }); +$schema->create('cloud_resource_pools', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('line_id'); + }); +$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_public_ip_pools', static function (Blueprint $table): void { $table->increments('id'); @@ -174,7 +187,7 @@ $targetUuid = '22222222-2222-4222-8222-222222222222'; $capsule->table('cloud_instances')->insert([ 'id' => 11, 'uuid' => $targetUuid, 'host_id' => 2, 'user_id' => 9, 'order_id' => 21, 'plan_id' => 31, 'offer_id' => 41, - 'resource_pool_id' => 102, 'reservation_id' => 62, + 'resource_pool_id' => 101, 'reservation_id' => 62, 'current_period_id' => 71, 'expires_at' => $now + 86400, 'renewal_price' => '19.95', 'renewal_days' => 30, 'renewal_traffic_bytes' => 2_000_000, @@ -209,7 +222,7 @@ $capsule->table('cloud_resource_reservations')->insert([ 'id' => 62, 'reservation_key' => str_repeat('c', 32), 'operation_id' => str_repeat('d', 32), 'order_id' => null, 'backup_restore_id' => 51, 'offer_id' => null, - 'resource_pool_id' => 102, 'host_id' => 2, 'user_id' => 9, + 'resource_pool_id' => 101, 'host_id' => 2, 'user_id' => 9, 'instance_id' => 11, 'network_attachment_id' => 82, 'public_ip_pool_id' => 92, 'public_ip_id' => 102, 'cpu_cores' => 2, 'memory_mib' => 2048, 'disk_gib' => 40, @@ -273,9 +286,9 @@ $order = $capsule->table('cloud_orders')->find(21); $assert($before === $after, 'Maintenance migration modified identity, billing, expiry, period, or traffic ownership fields.'); $assert((int) $instance->reservation_id === 61 - && (int) $instance->resource_pool_id === 102 + && (int) $instance->resource_pool_id === 101 && (int) $source->host_id === 2 - && (int) $source->resource_pool_id === 102 + && (int) $source->resource_pool_id === 101 && (int) $source->public_ip_id === 102 && (int) $source->network_attachment_id === 82 && (int) $source->disk_gib === 40 @@ -295,7 +308,7 @@ $assert((string) $target->state === 'released' === 'maintenance_migration_transferred', 'Temporary restore reservation remained billable after placement transfer.'); $assert((int) $order->host_id === 2 - && (int) $order->resource_pool_id === 102 + && (int) $order->resource_pool_id === 101 && (int) $order->reservation_id === 61 && (int) $order->plan_id === 31 && (int) $order->offer_id === 41 @@ -369,7 +382,7 @@ $assert((string) $rolledBack->state === 'rolled_back' $capsule->table('cloud_instances')->insert([ 'id' => 13, 'uuid' => $targetUuid, 'host_id' => 2, 'user_id' => 9, 'order_id' => 23, 'plan_id' => 31, 'offer_id' => 41, - 'resource_pool_id' => 102, 'reservation_id' => 65, + 'resource_pool_id' => 101, 'reservation_id' => 65, 'current_period_id' => 73, 'expires_at' => $now + 86400, 'renewal_price' => '19.95', 'renewal_days' => 30, 'renewal_traffic_bytes' => 2_000_000, @@ -404,7 +417,7 @@ $capsule->table('cloud_resource_reservations')->insert([ 'id' => 65, 'reservation_key' => str_repeat('8', 32), 'operation_id' => str_repeat('9', 32), 'order_id' => null, 'backup_restore_id' => 53, 'offer_id' => null, - 'resource_pool_id' => 102, 'host_id' => 2, 'user_id' => 9, + 'resource_pool_id' => 101, 'host_id' => 2, 'user_id' => 9, 'instance_id' => 13, 'network_attachment_id' => 82, 'public_ip_pool_id' => 92, 'public_ip_id' => 104, 'cpu_cores' => 2, 'memory_mib' => 2048, 'disk_gib' => 40, @@ -486,7 +499,7 @@ $capsule->table('cloud_resource_reservations')->insert([ 'id' => 67, 'reservation_key' => str_repeat('5', 32), 'operation_id' => $previousTransferOperation, 'order_id' => null, 'backup_restore_id' => 54, 'offer_id' => null, - 'resource_pool_id' => 102, 'host_id' => 2, 'user_id' => 9, + 'resource_pool_id' => 101, 'host_id' => 2, 'user_id' => 9, 'instance_id' => 13, 'network_attachment_id' => 82, 'public_ip_pool_id' => 92, 'public_ip_id' => 105, 'cpu_cores' => 2, 'memory_mib' => 2048, 'disk_gib' => 40, @@ -528,8 +541,16 @@ $prepareAbortUuid = '33333333-3333-4333-8333-333333333333'; $prepareAbortTargetUuid = '44444444-4444-4444-8444-444444444444'; $prepareAbortOperation = str_repeat('a', 32); $capsule->table('cloud_hosts')->insert(['id' => 2]); +$capsule->table('cloud_resource_pools')->insert([ + 'id' => 101, 'line_id' => 501, +]); +$capsule->table('cloud_host_resource_pool_memberships')->insert([ + 'host_id' => 2, 'resource_pool_id' => 101, + 'scheduler_state' => 'active', +]); $capsule->table('cloud_host_network_attachments')->insert([ - 'id' => 83, 'host_id' => 2, 'network_selector' => 'bridge:br0', + 'id' => 83, 'host_id' => 2, 'line_id' => 501, + 'network_selector' => 'bridge:migration', ]); $capsule->table('cloud_public_ip_pools')->insert([ 'id' => 93, 'host_id' => 2, 'network_attachment_id' => 83, @@ -560,7 +581,7 @@ $capsule->table('cloud_resource_reservations')->insert([ 'id' => 69, 'reservation_key' => str_repeat('c', 32), 'operation_id' => $prepareAbortOperation, 'order_id' => null, 'backup_restore_id' => 55, 'offer_id' => null, - 'resource_pool_id' => 102, 'host_id' => 2, 'user_id' => 9, + 'resource_pool_id' => 101, 'host_id' => 2, 'user_id' => 9, 'instance_id' => 14, 'network_attachment_id' => 83, 'public_ip_pool_id' => 93, 'public_ip_id' => 107, 'cpu_cores' => 2, 'memory_mib' => 2048, 'disk_gib' => 40, diff --git a/web/tests/CloudMaintenanceMigrationTargetSpecTest.php b/web/tests/CloudMaintenanceMigrationTargetSpecTest.php index fefc87c3..09425dfe 100644 --- a/web/tests/CloudMaintenanceMigrationTargetSpecTest.php +++ b/web/tests/CloudMaintenanceMigrationTargetSpecTest.php @@ -28,7 +28,7 @@ $source = [ ]; $body = [ 'vcpu' => 4, 'memory_mib' => 8192, 'disk_gib' => 80, - 'bandwidth_mbps' => 500, 'network' => 'bridge:br0', + 'bandwidth_mbps' => 500, 'network' => 'bridge:line-b', 'public_pool_key' => str_repeat('b', 32), 'public_pool_cidr' => '203.0.113.0/24', 'public_ip_cidr' => '203.0.113.20/24', @@ -54,7 +54,7 @@ $assert(($spec['billing_marker'] ?? null) === 'preserved' && ($spec['ram_mib'] ?? null) === 8192 && ($spec['disk_gib'] ?? null) === 80 && ($spec['bandwidth_mbps'] ?? null) === 500 - && ($spec['network'] ?? null) === 'bridge:br0' + && ($spec['network'] ?? null) === 'bridge:line-b' && ($spec['public_pool_key'] ?? null) === str_repeat('b', 32) && ($spec['public_pool_cidr'] ?? null) === '203.0.113.0/24' && ($spec['public_ip_cidr'] ?? null) === '203.0.113.20/24' @@ -70,6 +70,7 @@ foreach ([ 'public_pool_cidr' => '203.0.114.0/24', 'gateway' => '203.0.113.2', 'dns_servers' => ['8.8.8.8'], + 'network' => 'network:other-line', ] as $field => $different) { $mismatched = array_replace($vm, [$field => $different]); $rejected = false; diff --git a/web/tests/CloudOperationRecoveryMatrixTest.php b/web/tests/CloudOperationRecoveryMatrixTest.php index d791f0f6..5419ceaf 100644 --- a/web/tests/CloudOperationRecoveryMatrixTest.php +++ b/web/tests/CloudOperationRecoveryMatrixTest.php @@ -176,6 +176,7 @@ namespace { $table->string('uuid'); $table->integer('host_id'); $table->integer('user_id'); + $table->integer('resource_pool_id')->default(7001); $table->integer('reservation_id')->nullable(); $table->string('name'); $table->string('status'); @@ -381,6 +382,9 @@ namespace { $table->integer('backup_restore_id'); $table->integer('host_id'); $table->integer('user_id'); + $table->integer('resource_pool_id')->nullable(); + $table->integer('network_attachment_id')->nullable(); + $table->integer('public_ip_pool_id')->nullable(); $table->string('operation_id'); $table->integer('public_ip_id'); $table->integer('instance_id')->nullable(); @@ -398,6 +402,7 @@ namespace { static function (Blueprint $table): void { $table->increments('id'); $table->integer('host_id'); + $table->integer('public_ip_pool_id')->nullable(); $table->string('address'); $table->integer('prefix_length'); $table->string('state'); @@ -407,6 +412,28 @@ namespace { $table->integer('created_at'); $table->integer('updated_at'); }); + $schema->create('cloud_resource_pools', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('line_id'); + }); + $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'); + }); + $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('pool_key'); + $table->string('cidr'); + $table->string('gateway'); + $table->text('dns_servers_json'); + }); $schema->create('cloud_instance_firewall_versions', static function (Blueprint $table): void { $table->increments('id'); @@ -833,6 +860,30 @@ namespace { $migrationArtifactId = str_repeat('c', 32); $migrationArtifactDigest = str_repeat('f', 64); $migrationTargetUuid = '123e4567-e89b-42d3-a456-426614174099'; + $migrationResourcePoolId = 7001; + $migrationLineId = 7101; + $migrationAttachmentId = 7201; + $migrationPublicPoolId = 7301; + $migrationNetworkSelector = 'bridge:migration-wan'; + Capsule::table('cloud_resource_pools')->insert([ + 'id' => $migrationResourcePoolId, + 'line_id' => $migrationLineId, + ]); + Capsule::table('cloud_host_network_attachments')->insert([ + 'id' => $migrationAttachmentId, + 'host_id' => $hostId, + 'line_id' => $migrationLineId, + 'network_selector' => $migrationNetworkSelector, + ]); + Capsule::table('cloud_public_ip_pools')->insert([ + 'id' => $migrationPublicPoolId, + 'host_id' => $hostId, + 'network_attachment_id' => $migrationAttachmentId, + 'pool_key' => str_repeat('b', 32), + 'cidr' => '203.0.113.0/24', + 'gateway' => '203.0.113.1', + 'dns_servers_json' => '["1.1.1.1"]', + ]); $migrationArtifact = [ 'id' => $migrationArtifactId, 'role' => 'root', @@ -889,7 +940,7 @@ namespace { 'memory_mib' => 2048, 'disk_gib' => 20, 'bandwidth_mbps' => 100, - 'network' => 'bridge:br0', + 'network' => $migrationNetworkSelector, 'template_id' => '', 'template_revision' => 0, 'template_generation_token' => '', @@ -1077,6 +1128,9 @@ namespace { 'backup_restore_id' => 9002, 'host_id' => $hostId, 'user_id' => $ownerId, + 'resource_pool_id' => $migrationResourcePoolId, + 'network_attachment_id' => $migrationAttachmentId, + 'public_ip_pool_id' => $migrationPublicPoolId, 'operation_id' => $migrationTransfer['operation_id'], 'public_ip_id' => 9007, 'instance_id' => $instanceId, @@ -1093,6 +1147,7 @@ namespace { Capsule::table('cloud_public_ips')->insert([ 'id' => 9007, 'host_id' => $hostId, + 'public_ip_pool_id' => $migrationPublicPoolId, 'address' => '203.0.113.30', 'prefix_length' => 24, 'state' => 'uncertain', @@ -2412,6 +2467,9 @@ namespace { $restoreName = 'matrix-restored-vm'; $restoreIp = '203.0.113.31'; $restorePoolKey = str_repeat('7', 32); + $restoreAttachmentId = 7202; + $restorePublicPoolId = 7302; + $restoreNetworkSelector = 'bridge:restore-wan'; $restoreSha256 = str_repeat('8', 64); $restoreSpec = [ 'managed' => true, @@ -2422,7 +2480,7 @@ namespace { 'memory_mib' => 2048, 'disk_gib' => 40, 'bandwidth_mbps' => 100, - 'network' => 'bridge:br0', + 'network' => $restoreNetworkSelector, 'public_pool_key' => $restorePoolKey, 'public_ip_cidr' => $restoreIp . '/24', 'debian_12_network_fix' => true, @@ -2438,6 +2496,7 @@ namespace { $restoreKey, $restoreReservationId, $restoreSha256, + $restoreNetworkSelector, $ownerId ): array { return [ @@ -2454,7 +2513,7 @@ namespace { 'memory_mib' => 2048, 'disk_gib' => 40, 'bandwidth_mbps' => 100, - 'network' => 'bridge:br0', + 'network' => $restoreNetworkSelector, 'template_id' => 'debian-12', 'template_revision' => 1, 'template_generation_token' => str_repeat('9', 32), @@ -2533,9 +2592,25 @@ namespace { 'created_at' => $now - 180, 'updated_at' => $now - 20, ]); + Capsule::table('cloud_host_network_attachments')->insert([ + 'id' => $restoreAttachmentId, + 'host_id' => $hostId, + 'line_id' => $migrationLineId, + 'network_selector' => $restoreNetworkSelector, + ]); + Capsule::table('cloud_public_ip_pools')->insert([ + 'id' => $restorePublicPoolId, + 'host_id' => $hostId, + 'network_attachment_id' => $restoreAttachmentId, + 'pool_key' => $restorePoolKey, + 'cidr' => '203.0.113.0/24', + 'gateway' => '203.0.113.1', + 'dns_servers_json' => '["1.1.1.1"]', + ]); Capsule::table('cloud_public_ips')->insert([ 'id' => $restoreIpId, 'host_id' => $hostId, + 'public_ip_pool_id' => $restorePublicPoolId, 'address' => $restoreIp, 'prefix_length' => 24, 'state' => 'reserved', @@ -2550,6 +2625,9 @@ namespace { 'backup_restore_id' => $restoreId, 'host_id' => $hostId, 'user_id' => $ownerId, + 'resource_pool_id' => $migrationResourcePoolId, + 'network_attachment_id' => $restoreAttachmentId, + 'public_ip_pool_id' => $restorePublicPoolId, 'operation_id' => $restoreRecord['operation_id'], 'public_ip_id' => $restoreIpId, 'instance_id' => $restoreInstanceId, @@ -2776,6 +2854,41 @@ namespace { $migrationTransfer['job'], $migrationTransfer['payload'] ); + Capsule::table('cloud_host_network_attachments') + ->where('id', $migrationAttachmentId)->update([ + 'network_selector' => 'bridge:tampered', + ]); + $selectorTamperRejected = false; + try { + CloudOperationRecoveryIdentity::expectedFromPayload( + $migrationTransfer['job'], + $migrationTransfer['payload'] + ); + } catch (CloudError $error) { + $selectorTamperRejected = $error->httpStatus === 409; + } + $assert($selectorTamperRejected, + 'PeerMigration recovery identity accepted a changed target attachment selector.'); + Capsule::table('cloud_host_network_attachments') + ->where('id', $migrationAttachmentId)->update([ + 'network_selector' => $migrationNetworkSelector, + 'line_id' => $migrationLineId + 1, + ]); + $lineTamperRejected = false; + try { + CloudOperationRecoveryIdentity::expectedFromPayload( + $migrationTransfer['job'], + $migrationTransfer['payload'] + ); + } catch (CloudError $error) { + $lineTamperRejected = $error->httpStatus === 409; + } + $assert($lineTamperRejected, + 'PeerMigration recovery identity accepted an attachment from the wrong line.'); + Capsule::table('cloud_host_network_attachments') + ->where('id', $migrationAttachmentId)->update([ + 'line_id' => $migrationLineId, + ]); $cleanupInspection = $inspectionMethod->invoke(null, [ 'operation_id' => $migrationTransfer['operation_id'], 'action' => $transferIdentity['action'], diff --git a/web/tests/CloudPortableBackupAdminUiContractTest.php b/web/tests/CloudPortableBackupAdminUiContractTest.php index e449a9f1..f3a71e2f 100644 --- a/web/tests/CloudPortableBackupAdminUiContractTest.php +++ b/web/tests/CloudPortableBackupAdminUiContractTest.php @@ -68,6 +68,7 @@ $assert(str_contains($runtime, 'export function createAdminInstanceMigration(') && str_contains($runtime, "import(versionedModuleUrl('./admin-instance-migration.js'))") && str_contains($runtime, 'confirm_maintenance_migration: true') + && str_contains($runtime, 'target_resource_pool_id: Number(') && str_contains($runtime, 'confirm_source_cleanup: true') && str_contains($runtime, '原账单、到期时间和流量周期') && str_contains( @@ -78,6 +79,7 @@ $assert(str_contains($runtime, 'export function createAdminInstanceMigration(') && str_contains($migration, "'reconcile_cleanup'") && str_contains($migration, "'managed_artifacts_absent'") && str_contains($migration, 'reserveBackupRestore(') + && str_contains($migration, "'target_resource_pool_id'") && str_contains($migration, 'preparedBackupRestorePlacement(') && str_contains($migration, '$restore->target_instance_id = null;') && str_contains($jobService, @@ -160,13 +162,14 @@ $assert(str_contains($runtime, "await commit(") && str_contains($runtime, 'requires_reconciliation'), 'Backup deletion UI must expose bounded stable-evidence reconciliation after unknown effect.'); -$assert(str_contains($runtime, '统一接入 br0、分配全新公网 IP') +$assert(str_contains($runtime, '使用该线路中当前已验证的网络接入') && str_contains($runtime, '不会继承原 IP、账单、到期时间或流量周期') && str_contains($runtime, '临时工作区仍待清理') && str_contains($runtime, '清理不会重复上传或修改备份对象') && str_contains($runtime, 'target_host_id') + && str_contains($runtime, 'target_resource_pool_id') && str_contains($runtime, 'available_ip_count'), - 'The restore UI must describe and collect the independent br0/new-IP target intent.'); + 'The restore UI must collect exact host/pool identity and describe the verified attachment/new-IP intent.'); $assert(str_contains($placement, "'is_source_host'") && !str_contains($placement, "->where('id', '<>', \$sourceHostId)") @@ -177,7 +180,7 @@ $assert(str_contains($placement, "'is_source_host'") $assert(!str_contains($validationGuide, '恢复必须选择不同宿主机') && str_contains($validationGuide, '原宿主机或其他合格宿主机') && !str_contains($pruningReport, '并在另一台 `bridge:br0` 宿主机') - && str_contains($pruningReport, '原宿主机或其他合格的 `bridge:br0` 宿主机'), + && str_contains($pruningReport, '原宿主机或其他合格宿主机'), 'Portable-backup documentation must allow an independently reserved same-host restore.'); $assert(str_contains($service, diff --git a/web/tests/CloudPortableBackupRecoveryEnvelopeTest.php b/web/tests/CloudPortableBackupRecoveryEnvelopeTest.php index b3abf008..6742b7c0 100644 --- a/web/tests/CloudPortableBackupRecoveryEnvelopeTest.php +++ b/web/tests/CloudPortableBackupRecoveryEnvelopeTest.php @@ -72,7 +72,7 @@ $restorePayload = [ 'memory_mib' => 8192, 'disk_gib' => 80, 'bandwidth_mbps' => 500, - 'network' => 'bridge:br0', + 'network' => 'bridge:restore-wan', 'public_ip_cidr' => '203.0.113.19/24', 'public_pool_key' => str_repeat('1', 32), 'public_pool_cidr' => '203.0.113.0/24', @@ -90,7 +90,7 @@ $assert(($restoreCompact['body'] ?? null) === [ 'memory_mib' => 8192, 'disk_gib' => 80, 'bandwidth_mbps' => 500, - 'network' => 'bridge:br0', + 'network' => 'bridge:restore-wan', 'public_ip_cidr' => '203.0.113.19/24', 'public_pool_key' => str_repeat('1', 32), 'public_pool_cidr' => '203.0.113.0/24', diff --git a/web/tests/CloudPortableBackupSameHostRestoreTest.php b/web/tests/CloudPortableBackupSameHostRestoreTest.php index fb0efe9a..489c54f8 100644 --- a/web/tests/CloudPortableBackupSameHostRestoreTest.php +++ b/web/tests/CloudPortableBackupSameHostRestoreTest.php @@ -37,6 +37,7 @@ $schema->create('cloud_regions', static function (Blueprint $table): void { $schema->create('cloud_network_lines', static function (Blueprint $table): void { $table->increments('id'); $table->integer('region_id'); + $table->string('name'); $table->string('status'); }); $schema->create('cloud_resource_pools', static function (Blueprint $table): void { @@ -70,6 +71,7 @@ $schema->create('cloud_host_agents', static function (Blueprint $table): void { $table->integer('revision'); $table->integer('tested_revision'); $table->string('last_test_status'); + $table->text('network_selectors_json'); }); $schema->create('cloud_host_storage_configurations', static function (Blueprint $table): void { @@ -83,6 +85,10 @@ $schema->create('cloud_host_network_attachments', $table->integer('line_id'); $table->string('network_selector'); $table->string('state'); + $table->integer('priority'); + $table->string('verification_state'); + $table->integer('verified_agent_revision'); + $table->integer('last_verified_at'); $table->string('sync_state'); $table->integer('observed_revision'); $table->integer('desired_revision'); @@ -96,6 +102,7 @@ $schema->create('cloud_public_ip_pools', $table->string('sync_state'); $table->integer('observed_revision'); $table->integer('desired_revision'); + $table->integer('priority'); $table->integer('guest_prefix_length'); $table->string('pool_key'); $table->string('cidr'); @@ -168,16 +175,22 @@ $capsule->table('cloud_regions')->insert([ 'status' => 'active', ]); $capsule->table('cloud_network_lines')->insert([ - 'id' => 1, 'region_id' => 1, 'status' => 'active', + ['id' => 1, 'region_id' => 1, 'name' => 'International', + 'status' => 'active'], + ['id' => 2, 'region_id' => 1, 'name' => 'Premium', + 'status' => 'active'], ]); $capsule->table('cloud_resource_pools')->insert([ - 'id' => 1, 'line_id' => 1, 'name' => 'HKG', 'status' => 'active', + ['id' => 1, 'line_id' => 1, 'name' => 'HKG International', + 'status' => 'active'], + ['id' => 2, 'line_id' => 2, 'name' => 'HKG Premium', + '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', + 'default_network' => 'bridge:retired', ]); $capsule->table('cloud_host_resource_pool_memberships')->insert([ 'host_id' => $hostId, 'resource_pool_id' => 1, @@ -196,6 +209,12 @@ foreach ([1 => 'source-host', 2 => 'other-host'] as $hostId => $name) { $capsule->table('cloud_host_agents')->insert([ 'host_id' => $hostId, 'enabled' => 1, 'revision' => 1, 'tested_revision' => 1, 'last_test_status' => 'healthy', + 'network_selectors_json' => json_encode( + $hostId === 1 + ? ['bridge:restore-a', 'bridge:restore-c'] + : ['bridge:restore-b'], + JSON_THROW_ON_ERROR + ), ]); $capsule->table('cloud_host_storage_configurations')->insert([ 'host_id' => $hostId, 'state' => 'applied', @@ -204,7 +223,11 @@ foreach ([1 => 'source-host', 2 => 'other-host'] as $hostId => $name) { $poolId = $hostId; $capsule->table('cloud_host_network_attachments')->insert([ 'id' => $attachmentId, 'host_id' => $hostId, 'line_id' => 1, - 'network_selector' => 'bridge:br0', 'state' => 'active', + 'network_selector' => $hostId === 1 + ? 'bridge:restore-a' : 'bridge:restore-b', + 'state' => 'active', 'priority' => 0, + 'verification_state' => 'verified', + 'verified_agent_revision' => 1, 'last_verified_at' => 1700000000, 'sync_state' => 'applied', 'observed_revision' => 1, 'desired_revision' => 1, ]); @@ -212,7 +235,8 @@ foreach ([1 => 'source-host', 2 => 'other-host'] as $hostId => $name) { 'id' => $poolId, 'host_id' => $hostId, 'network_attachment_id' => $attachmentId, 'state' => 'active', 'sync_state' => 'applied', 'observed_revision' => 1, - 'desired_revision' => 1, 'guest_prefix_length' => 24, + 'desired_revision' => 1, 'priority' => 0, + 'guest_prefix_length' => 24, 'pool_key' => str_repeat((string) $hostId, 32), 'cidr' => '203.0.' . $hostId . '.0/24', 'gateway' => '203.0.' . $hostId . '.1', @@ -228,6 +252,36 @@ foreach ([1 => 'source-host', 2 => 'other-host'] as $hostId => $name) { ]); } +// The same physical host is an active member of a second commercial line. +// Restore inventory must expose both exact host/pool identities without +// duplicating host-global capacity accounting or trusting default_network. +$capsule->table('cloud_host_resource_pool_memberships')->insert([ + 'host_id' => 1, 'resource_pool_id' => 2, 'scheduler_state' => 'active', +]); +$capsule->table('cloud_host_network_attachments')->insert([ + 'id' => 3, 'host_id' => 1, 'line_id' => 2, + 'network_selector' => 'bridge:restore-c', 'state' => 'active', + 'priority' => 0, 'verification_state' => 'verified', + 'verified_agent_revision' => 1, 'last_verified_at' => 1700000000, + 'sync_state' => 'never', 'observed_revision' => 0, + 'desired_revision' => 7, +]); +$capsule->table('cloud_public_ip_pools')->insert([ + 'id' => 3, 'host_id' => 1, 'network_attachment_id' => 3, + 'state' => 'active', 'sync_state' => 'applied', + 'observed_revision' => 1, 'desired_revision' => 1, 'priority' => 0, + 'guest_prefix_length' => 24, 'pool_key' => str_repeat('3', 32), + 'cidr' => '198.51.100.0/24', 'gateway' => '198.51.100.1', + 'dns_servers_json' => '["9.9.9.9"]', 'reserved_ips_json' => '[]', +]); +$capsule->table('cloud_public_ips')->insert([ + 'id' => 3, 'host_id' => 1, 'public_ip_pool_id' => 3, + 'address' => '198.51.100.20', 'prefix_length' => 24, + 'state' => 'available', 'reservation_id' => null, + 'instance_id' => null, 'operation_id' => null, + 'created_at' => 1700000000, 'updated_at' => 1700000000, +]); + // 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([ @@ -240,21 +294,41 @@ $capsule->table('cloud_instances')->insert([ $targets = CloudPlacementService::backupRestoreTargets(1, [ 'cpu_cores' => 2, 'memory_mib' => 2048, 'disk_gib' => 20, ]); -$byId = []; +$byIdentity = []; foreach ($targets as $target) { - $byId[(int) $target['id']] = $target; + $byIdentity[(int) $target['id'] . ':' + . (int) $target['resource_pool_id']] = $target; } -$assert(isset($byId[1]), +$assert(isset($byIdentity['1:1']), 'The original host was excluded from eligible manual restore targets.'); -$assert(($byId[1]['is_source_host'] ?? null) === true, +$assert(($byIdentity['1: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, +$assert(isset($byIdentity['1:2']) + && ($byIdentity['1:2']['network_selectors'] ?? null) + === ['bridge:restore-c'], + 'A second exact host/pool restore identity was overwritten or lost.'); +$assert(isset($byIdentity['2:1']) + && ($byIdentity['2:1']['is_source_host'] ?? null) === false, 'A different eligible host was lost or misidentified.'); -$assert((int) $byId[1]['available_ip_count'] === 1, +$assert((int) $byIdentity['1:1']['available_ip_count'] === 1, 'The original host did not retain its independent IP capacity check.'); +$capsule->table('cloud_host_network_attachments')->where('id', 3)->update([ + 'last_verified_at' => 0, +]); +$staleTargets = CloudPlacementService::backupRestoreTargets(1, [ + 'cpu_cores' => 2, 'memory_mib' => 2048, 'disk_gib' => 20, +]); +$assert(!in_array('2', array_map( + static fn (array $target): string => (string) $target['resource_pool_id'], + array_filter($staleTargets, static fn (array $target): bool => + (int) $target['id'] === 1) +), true), 'Stale attachment evidence remained eligible for restore.'); +$capsule->table('cloud_host_network_attachments')->where('id', 3)->update([ + 'last_verified_at' => 1700000000, +]); + $restore = new CloudBackupRestore(); $restore->target_host_id = 1; $restore->reservation_id = null; @@ -263,11 +337,15 @@ $restore->save(); $placement = CloudPlacementService::reserveBackupRestore($restore, 77, [ 'cpu_cores' => 2, 'memory_mib' => 2048, 'disk_gib' => 20, -]); +], 1); $reservation = $placement['reservation']; $publicIp = $placement['public_ip']; $assert($placement['network']['dns_servers'] === ['1.1.1.1', '8.8.8.8'], 'A valid pool DNS list could not reach the restore placement payload.'); +$assert($placement['network']['network'] === 'bridge:restore-a' + && (int) $reservation->resource_pool_id === 1 + && (int) $reservation->network_attachment_id === 1, + 'Restore placement did not freeze the selected exact pool and attachment.'); $assert((int) $reservation->backup_restore_id === (int) $restore->id && (int) $reservation->public_ip_id === (int) $publicIp->id && (string) $reservation->state === 'held' @@ -286,6 +364,7 @@ $prepared = CloudPlacementService::preparedBackupRestorePlacement( 99 ); $assert($prepared['network']['dns_servers'] === ['1.1.1.1', '8.8.8.8'] + && $prepared['network']['network'] === 'bridge:restore-a' && (int) $prepared['reservation']->id === (int) $reservation->id, 'Maintenance migration did not preserve the pre-reserved pool DNS data.'); @@ -315,7 +394,7 @@ $invalidRestore->save(); try { CloudPlacementService::reserveBackupRestore($invalidRestore, 77, [ 'cpu_cores' => 2, 'memory_mib' => 2048, 'disk_gib' => 20, - ]); + ], 1); throw new RuntimeException('A malformed pool DNS list was accepted.'); } catch (CloudError $error) { $assert($error->httpStatus === 409