feat: settle dual-stack maintenance migrations

go
codex 2 weeks ago
parent acc5523c0f
commit 8c76dd2ddb

@ -160,7 +160,7 @@ libvirt 的持久 pool 定义就是 Agent 后续使用的映射,不另写存
公网网络接入在宿主机的“网络接入”中按资源池线路独立配置,可使用 `bridge:br0`、其他 Linux 网桥或 `network:default` 这样的 libvirt network。名称以字母或数字开头,后续只能包含字母、数字、点、下划线和短横线,bridge 名称为 1~15 字符,libvirt network 名称为 1~64 字符。宿主机上的公网网桥或 libvirt network 必须由运维预先准备。Agent 只发现、验证和使用现有公网网络,不创建公网网桥、不启动 libvirt network,也不修改公网地址、上游网关或挂载。`cloud_hosts.default_network` 仅保留为兼容展示值,不参与 Agent 就绪、调度、恢复、迁移或换 IP 决策;真正的运行时权威是资源池线路、当前 Agent 代次已验证的网络接入,以及绑定该接入的公网地址池。VPC 使用下述独立的 Agent 受管 bridge 和 L3 路由,不改变这一公网边界。
全新公网账本 schema 版本为 `go-agent-wss-v33-portable-restore-attempts`。每个资源预留的当前公网权威只来自 `cloud_resource_reservation_ips.active_claim = 1` 的一组 IPv4+IPv6 精确声明;两族允许具有各自的 generation 和 operation ID,但必须绑定同一资源预留和网络接入,并各自与具体 IP、地址池、宿主机、实例状态双向一致。`cloud_resource_reservations` 中旧的单地址列只保留审计形态,不参与当前地址读取、释放或管理员投影。释放时历史声明保留并把 `active_claim` 置空,具体 IP 同时清空 claim、operation、reservation 和 instance 归属。独立恢复只允许 `cloud_backup_restore_attempts` 拥有、携带合法 `attempt_key` 且通过完整双栈信封校验的新任务;旧 `CloudPlacementService` 单地址恢复、缺少或损坏 attempt 身份的任务仍会在派发 CAS 前拒绝。尚未迁移到双栈账本的普通换 IP 与维护迁移继续保持关闭,不能通过旧单地址写入路径绕过门禁。
全新公网账本 schema 版本为 `go-agent-wss-v33-portable-restore-attempts`。每个资源预留的当前公网权威只来自 `cloud_resource_reservation_ips.active_claim = 1` 的一组 IPv4+IPv6 精确声明;两族允许具有各自的 generation 和 operation ID,但必须绑定同一资源预留和网络接入,并各自与具体 IP、地址池、宿主机、实例状态双向一致。`cloud_resource_reservations` 中旧的单地址列只保留审计形态,不参与当前地址读取、释放或管理员投影。释放时历史声明保留并把 `active_claim` 置空,具体 IP 同时清空 claim、operation、reservation 和 instance 归属。普通换 IP、独立恢复和维护迁移分别只允许 transition ledger、restore attempt 与 migration source debt 所有的完整双栈流程;旧 `CloudPlacementService` 单地址恢复、旧换 IP writer,以及缺少或损坏冻结身份的任务仍会在派发 CAS 前拒绝,不能绕过新账本。
Agent 的 capabilities 响应仍使用 `network_selectors` 字段,但它是自动发现的当前可用 `bridge:<名称>` / `network:<名称>` 列表,排序去重且最多 64 项,不再来自配置文件。Linux 网桥必须有 sysfs bridge 目录且接口为 UP;libvirt network 必须处于 active 状态。完整 Agent 测试保存当前代次的候选列表,但不要求某个宿主机全局默认值必须存在。管理员只能从该代次已测试列表创建网络接入,并必须对每个接入执行精确验证;创建、恢复、迁移、重装和换 IP 会在锁内再次核对本次资源池线路、接入、公网池与 Agent 代次。修改兼容 `default_network` 不会撤销 Agent 就绪结果,修改或失效真实网络接入则由接入自身的验证状态阻止运行时使用。

@ -44,20 +44,20 @@
## 维护迁移
维护迁移是独立恢复之外的管理员流程,只允许选择同一资源池内的其他宿主机。它使用独立的 `PeerMigration V3` 冷迁移协议,不经过面板、Gateway 或对象存储传输磁盘,也不改变普通云备份的单系统盘格式。控制面先冻结当前全部已就绪快照目录,并按系统盘加全部快照容量锁定目标资源和新公网 IP;任何未就绪、目录漂移或不完整回执都会阻止切换。
维护迁移是独立恢复之外的管理员流程,只允许选择同一资源池内的其他宿主机。它使用独立的 `PeerMigration V3` 冷迁移协议,不经过面板、Gateway 或对象存储传输磁盘,也不改变普通云备份的单系统盘格式。控制面先冻结当前全部已就绪快照目录,并按系统盘加全部快照容量锁定目标资源和同一接入下全新的公网 IPv4+IPv6;任何未就绪、目录漂移、单族地址不足或不完整回执都会阻止切换。
源 Agent 先把原运行状态和 autostart 写入本地持久恢复意图,再正常关闭实例并禁用 autostart。实例完全停机后,Agent 对稳定系统盘和全部快照卷计算大小、虚拟容量和 SHA-256,发布一个不含宿主机路径的短期只读清单。每台 Agent 首次启动时在私有状态目录自动生成并持久化独立 TLS 1.3 身份;面板通过已认证控制通道把源身份的精确 SHA-256 锁定值交给目标。目标只能用该锁定身份和控制面生成的 32 字节随机票据读取本次迁移,票据不进入 URL,清单和每个工件都不能泄露本机路径。
目标 Agent 主动从源 Agent 的 HTTPS 地址目录拉取数据,优先选择目标本机同网段的地址,再回退公网地址;因此当前可使用公网,后续增加物理内网地址时无需改面板配置。传输使用固定 8 MiB HTTP Range 分块、`.partial` 断点续传和完整 SHA-256 校验。暂存目录由 Agent 自动派生为第一个 `storage_path_roots` 下的 `.peer-migration-staging`,不会落入 Agent Journal 所在目录。导入完成并重建全部快照元数据后,目标只定义关机且禁用 autostart 的 Domain。控制面确认新 UUID、新公网 IP、系统盘摘要、每个快照回执和资源预留后,才切换原 `cloud_instances` 记录及快照宿主机归属。迁移不会创建第二份账单实例,也不会改动原订单、套餐、服务期、到期时间、续费参数或当前流量周期。
目标 Agent 主动从源 Agent 的 HTTPS 地址目录拉取数据,优先选择目标本机同网段的地址,再回退公网地址;因此当前可使用公网,后续增加物理内网地址时无需改面板配置。传输使用固定 8 MiB HTTP Range 分块、`.partial` 断点续传和完整 SHA-256 校验。暂存目录由 Agent 自动派生为第一个 `storage_path_roots` 下的 `.peer-migration-staging`,不会落入 Agent Journal 所在目录。导入完成并重建全部快照元数据后,目标只定义关机且禁用 autostart 的 Domain。控制面确认新 UUID、新公网 IPv4+IPv6、系统盘摘要、每个快照回执和资源预留后,才在一个数据库事务内切换原 `cloud_instances` 记录及快照宿主机归属。迁移不会创建第二份账单实例,也不会改动原订单、套餐、服务期、到期时间、续费参数或当前流量周期。
目标使用已冻结的目标资源池线路、该线路当前 Agent 已验证的网络接入和新公网 IPv4。原累计流量作为新 Agent 计数器世代的基数继续单调累计,不能因宿主机和 UUID 改变而清零或重复计费。修改过的来宾主机名从备份时冻结的 `guest_hostname` 生成新 seed,不回退为实例显示名。目标保持源实例的服务状态、网络状态和电源状态;源网络已因流量或到期被限制时,目标持久网卡从定义开始就是 `link down`。
目标使用已冻结的目标资源池线路、该线路当前 Agent 已验证的网络接入和新公网 IPv4+IPv6,并同时建立两族防伪身份。原累计流量作为新 Agent 计数器世代的基数继续单调累计,不能因宿主机和 UUID 改变而清零或重复计费。迁移不重新注入主机名、密码或 SSH 公钥,来宾磁盘中的当前值保持不变;面板保存的 `guest_hostname` 只随实例规格元数据迁移。目标保持源实例的服务状态、网络状态和电源状态;源网络已因流量或到期被限制时,目标持久网卡从定义开始就是 `link down`。
目标在整个恢复和防火墙阶段保持关机。若实例启用了用户防火墙,控制面必须先在关机目标上重新应用并确认同一策略;没有策略或策略已禁用时也必须完成恢复终结。只有这些步骤完成后,独立的目标激活任务才恢复原 autostart 和运行/关机状态,随后才允许进入源副本清理。因此目标不会在用户防火墙生效前短暂联网启动。
管理员可在开始时选择两种源副本策略:
- “目标验证后自动清理”会在目标恢复及防火墙收敛后删除源 Domain 和面板托管磁盘,只有 Agent 同时确认 Domain 与全部托管产物均不存在时,才释放原公网 IP 和源容量。
- “保留源副本”会保持源 Domain 关机且禁用 autostart,并继续锁定原公网 IP 和源容量;管理员稍后可从同一页面显式发起清理。
- “目标验证后自动清理”会在目标恢复及防火墙收敛后删除源 Domain 和面板托管磁盘,只有 Agent 同时确认 Domain 与全部托管产物均不存在时,才释放原公网 IPv4、IPv6 和源容量。
- “保留源副本”会保持源 Domain 关机且禁用 autostart,并通过独立 source-debt 账本继续锁定原公网 IPv4、IPv6 和源容量;管理员稍后可从同一页面显式发起清理。
- 在源副本清理或异常核对完成前,面板会阻止普通实例变更和套餐升级;到期策略仍可断网,但不会只删除目标实例而遗留源副本。
任何派发后的超时、断连或回执丢失都进入原 operation 的只读核对,系统不会重放源停机、目标创建或源删除,也不会提前释放资源。传输明确失败且目标创建被证明没有发生时,管理员可以“重试传输”并从已有分块继续,或“中止传输”恢复源机原电源/autostart 状态并释放目标预留。防火墙、目标激活和源回滚的确定失败分别提供同阶段重试;源清理失败回到 `source_retained`,允许再次显式清理。只有不确定效果仍由任务安全核对栅栏阻止重放,因此业务状态不会依靠一个无出口的永久软件锁。

@ -138,7 +138,7 @@ jq empty deploy/*.json.example
- `PeerMigration V3` 必须验证当前全部快照都进入同一不可变清单、任一快照缺失或回执漂移即拒绝切换、目标恢复后快照目录整体改绑。源 Agent 自动生成持久 TLS 1.3 身份并发布本机地址目录,目标必须精确锁定源证书 SHA-256 并携带一次性 Bearer 票据;公开清单、任务结果和浏览器响应均不得出现宿主机路径、私钥或票据。目标必须优先尝试同网段地址并可回退公网地址,按固定 8 MiB Range 分块续传、复用合法 `.partial` 并在导入前核对每个完整 SHA-256。
- 目标分块暂存必须由 Agent 派生到第一个 `storage_path_roots` 下的 `.peer-migration-staging`,不能落在 Journal 系统盘。故障注入分块断连后应从已有偏移继续;成功导入删除暂存,过期中断会话只能由有界本地清理回收,不能删除不匹配目录。
- 目标在恢复和用户防火墙收敛期间必须保持关机;源机的运行/关机、autostart、断网状态与修改后主机名必须在独立激活步骤后保持一致。传输确定失败须同时提供续传和安全回滚,防火墙、激活、回滚、源清理的确定失败均有显式恢复出口。若源准备已存在精确成功回执但 PHP 最终化失败,只能将原准备效果收敛为 `applied` 后创建新的补偿回滚任务;Agent 明确确认源机恢复前不得释放目标预留或 IP。未知效果只能核对原 operation,不能重放。普通云备份仍只能产生单系统盘 S3 对象,PeerMigration 不得创建 S3 迁移对象。
- 维护迁移阶段注册表必须通过完整性测试:每个 Agent 任务种类只能对应一个账本字段、完成处理和不确定结果核对动作,每个人工恢复动作只能对应一个执行入口。页面必须直接使用后端返回的恢复选项和阶段进度;接口在加锁后使用同一判定重新授权。资源结算模块只能在源删除或目标接管得到明确证明后移动订单预留和公网 IP。没有持久化字节遥测时只能显示阶段进度,不能合成传输百分比。
- 维护迁移阶段注册表必须通过完整性测试:每个 Agent 任务种类只能对应一个账本字段、完成处理和不确定结果核对动作,每个人工恢复动作只能对应一个执行入口。页面必须直接使用后端返回的恢复选项和阶段进度;接口在加锁后使用同一判定重新授权。目标接管得到明确证明后,目标 reservation 才能原位接管订单及目标双栈 claims,源 reservation 同时原位转成 source-debt;reservation、claim 和具体地址 ID 均不得在源与目标之间交换。源删除只有在 Agent 明确确认 Domain 与托管磁盘都不存在后才释放原 IPv4+IPv6;未知效果必须保留同一 cleanup operation、两族地址和源容量,晚到成功回执才能终结债务。没有持久化字节遥测时只能显示阶段进度,不能合成传输百分比。
- 独立恢复可选择原宿主机或其他合格宿主机,且目标身份必须精确到宿主机与资源池;无论目标是否为原宿主机,都必须单独校验并预留容量,以及同一已验证 active attachment 下全新的 IPv4+IPv6。校验下载对象字节数与 SHA-256;新实例 UUID、MAC、seed、NVRAM、网络过滤器、两族防伪身份和流量状态均不得复用源实例,且不得继承订单、账单、服务期、到期时间或流量周期。
- 独立恢复还必须故障注入 attempt/payload 不一致、预签名失败和本地信封失败:这些故障不得联系 Agent;存在确定 `not_dispatched` 证据时必须原子释放容量、IPv4、IPv6 和两族 claims,账本损坏或派发效果未知时则必须保留完整双栈 reservation、claims 与 operation 围栏。后续只能查询原 operation,或使用已经持久化的精确回执执行 PHP-only finalization,绝不重放原 mutation。预签名 URL 只能存在于单次 wire payload,不得进入数据库任务、回执、浏览器响应或恢复信封。
- 公网地址池批量替换只能选择同宿主机、同线路、当前 Agent revision 已验证 attachment 上的 active/applied 目标池。启动事务必须同时将源池转为 `draining`、为全部实例冻结不重复的目标 IP、建立父任务及全部子任务。验收全成功停用源池、全部明确未应用恢复源池、已知部分成功保持排空、任一未知效果保持 active claim 和 IP 围栏。管理员只能核对原子任务,不得批量重放。

@ -27,7 +27,6 @@ final class CloudInstanceMigrationService
CloudJob $receiveJob,
array $inspection
): bool {
CloudPublicNetworkTransitionGate::assertMigrationReady();
$cleanup = $inspection['cleanup'] ?? null;
$planId = is_array($cleanup) ? ($cleanup['plan_id'] ?? null) : null;
$steps = is_array($cleanup) ? ($cleanup['steps'] ?? null) : null;
@ -174,7 +173,6 @@ final class CloudInstanceMigrationService
array $input
): array {
CloudAccess::manage($actor);
CloudPublicNetworkTransitionGate::assertMigrationReady();
CloudInput::only($input, [
'target_host_id', 'target_resource_pool_id', 'cleanup_mode',
'confirm_maintenance_migration',
@ -194,7 +192,9 @@ final class CloudInstanceMigrationService
);
}
if (($input['confirm_maintenance_migration'] ?? false) !== true) {
throw new CloudError('请确认维护迁移会关闭源实例并更换公网 IP');
throw new CloudError(
'请确认维护迁移会关闭源实例并更换公网 IPv4 和 IPv6'
);
}
$requestKey = $actor['request_idempotency_key'] ?? null;
if (!is_string($requestKey) || $requestKey === '') {
@ -722,7 +722,11 @@ final class CloudInstanceMigrationService
$action = 'abort_prepare';
}
if ((string) $stage['key'] === 'cleanup') {
CloudInstanceMigrationSettlement::retainSourceLocked($migration);
CloudInstanceMigrationSettlement::markCleanupAttentionLocked(
$migration,
$job,
'finalization_incident'
);
self::setState($migration, 'source_retained',
'finalization_incident', $action);
return;
@ -874,7 +878,6 @@ final class CloudInstanceMigrationService
array $input
): CloudJob {
CloudAccess::manage($actor);
CloudPublicNetworkTransitionGate::assertMigrationReady();
CloudInput::only($input, ['action', 'confirm_recovery']);
$action = $input['action'] ?? null;
if (!is_string($action)
@ -1030,7 +1033,6 @@ final class CloudInstanceMigrationService
array $input
): CloudJob {
CloudAccess::manage($actor);
CloudPublicNetworkTransitionGate::assertMigrationReady();
CloudInput::only($input, ['confirm_source_cleanup']);
if (($input['confirm_source_cleanup'] ?? false) !== true) {
throw new CloudError('请确认删除源宿主机上的旧副本');
@ -1530,14 +1532,36 @@ final class CloudInstanceMigrationService
if ($rootDiskGib === false) {
throw new CloudError('目标 Agent 的系统盘容量回执无效', 502);
}
$committedNetwork = CloudPublicNetworkAllocationService::commitBundle(
(int) $target->id,
(int) $instance->id,
(string) $restore->operation_id
$sourceHint = CloudResourceReservation::find(
(int) $migration->source_reservation_id
);
if ($sourceHint === null
|| preg_match('/^[a-f0-9]{32}$/D',
(string) $sourceHint->operation_id) !== 1) {
throw new CloudRecoveryInstanceStateConflict(
'PeerMigration 源双栈网络操作身份无效', 409
);
}
$handoff = CloudPublicNetworkAllocationService::
handoffMigrationBundles(
(int) $sourceHint->id,
(int) $target->id,
(int) $instance->id,
(string) $sourceHint->operation_id,
(string) $restore->operation_id
);
$sourceClaimSet = $handoff['source'] ?? null;
$committedTargetClaimSet = $handoff['target'] ?? null;
if (!$sourceClaimSet instanceof CloudActivePublicNetworkClaimSet
|| !$committedTargetClaimSet
instanceof CloudActivePublicNetworkClaimSet) {
throw new CloudRecoveryInstanceStateConflict(
'PeerMigration 双栈网络切换回执无效', 409
);
}
if (!hash_equals(
$targetClaimSet->publicNetwork()->fingerprint(),
$committedNetwork->fingerprint()
$committedTargetClaimSet->publicNetwork()->fingerprint()
)) {
throw new CloudRecoveryInstanceStateConflict(
'PeerMigration 目标双栈公网提交身份发生变化', 409
@ -1554,19 +1578,18 @@ final class CloudInstanceMigrationService
);
$expectedTargetClaim = (int) $rootDiskGib + $snapshotDiskGib;
if ($target === null || $source === null
|| !in_array((string) $target->state,
['held', 'uncertain'], true)
|| $target->instance_id !== null
|| (string) $target->state !== 'committed'
|| (int) $target->instance_id !== (int) $instance->id
|| !hash_equals((string) $restore->operation_id,
(string) $target->operation_id)
|| (int) $target->disk_gib !== $expectedTargetClaim
|| (string) $source->state !== 'committed'
|| (string) $source->state !== 'held'
|| (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
|| $source->instance_id !== null
|| (int) $source->disk_gib !== (int) $rootDiskGib
|| (int) $instance->host_id !== (int) $migration->source_host_id
|| !hash_equals(strtolower((string) $instance->uuid),
@ -1592,11 +1615,6 @@ final class CloudInstanceMigrationService
$source->disk_gib = $expectedTargetClaim;
$source->updated_at = $now;
$source->save();
$target->state = 'committed';
$target->instance_id = (int) $instance->id;
$target->expires_at = null;
$target->released_at = null;
$target->release_reason = '';
$target->updated_at = $now;
$target->save();
@ -1632,6 +1650,18 @@ final class CloudInstanceMigrationService
$instance->traffic_synced_at = 0;
$instance->updated_at = $now;
$instance->save();
CloudInstanceMigrationSettlement::settleCutoverLocked(
$migration,
$sourceClaimSet
);
$restore = CloudBackupRestore::where(
'id', (int) $restore->id
)->lockForUpdate()->first();
if ($restore === null || $restore->reservation_id !== null) {
throw new CloudRecoveryInstanceStateConflict(
'PeerMigration 目标恢复预留未完成结算', 409
);
}
$restore->state = 'ready';
$restore->error_code = '';
$restore->ready_at = $now;
@ -2413,7 +2443,7 @@ final class CloudInstanceMigrationService
]);
return;
}
CloudInstanceMigrationSettlement::retainSourceLocked($migration);
CloudInstanceMigrationSettlement::markRetainedLocked($migration);
self::setState($migration, 'source_retained', '');
}
@ -2462,6 +2492,7 @@ final class CloudInstanceMigrationService
$job->backup_restore_id = (int) $migration->restore_id;
$job->save();
$migration->cleanup_job_id = (int) $job->id;
CloudInstanceMigrationSettlement::bindCleanupLocked($migration, $job);
self::setState($migration, 'cleanup_running', '');
return $job;
}
@ -2485,13 +2516,21 @@ final class CloudInstanceMigrationService
return;
}
if ($status === 'uncertain') {
CloudInstanceMigrationSettlement::retainSourceLocked($migration);
CloudInstanceMigrationSettlement::markCleanupAttentionLocked(
$migration,
$job,
'operation_effect_unknown'
);
self::setState($migration, 'source_retained',
'operation_effect_unknown', 'reconcile_cleanup');
return;
}
if ($status === 'failed') {
CloudInstanceMigrationSettlement::retainSourceLocked($migration);
CloudInstanceMigrationSettlement::markCleanupFailedLocked(
$migration,
$job,
'migration_cleanup_failed'
);
self::setState($migration, 'source_retained',
'migration_cleanup_failed');
return;
@ -2503,15 +2542,10 @@ final class CloudInstanceMigrationService
'源 Agent 未确认实例和托管磁盘均已删除', 502
);
}
if (CloudInstanceMigrationSettlement::isSettled($migration)) {
CloudInstanceMigrationSettlement::releaseRetainedSourceLocked(
$migration
);
} else {
CloudInstanceMigrationSettlement::finalizeSourceDeletionLocked(
$migration
);
}
CloudInstanceMigrationSettlement::releaseSourceLocked(
$migration,
$job
);
self::setState($migration, 'completed', '');
$migration->completed_at = time();
$migration->save();

File diff suppressed because it is too large Load Diff

@ -6,6 +6,7 @@ use App\Models\CloudDeploymentSnapshot;
use App\Models\CloudInstance;
use App\Models\CloudInstanceBackup;
use App\Models\CloudInstanceMigration;
use App\Models\CloudInstanceMigrationSourceDebt;
use App\Models\CloudInstanceFirewallVersion;
use App\Models\CloudInstanceSnapshot;
use App\Models\CloudPeerMigrationArtifact;
@ -655,6 +656,22 @@ final class CloudOperationRecoveryIdentity
409
);
}
$sourceDebt = CloudInstanceMigrationSourceDebt::where(
'migration_id', (int) $migration->id
)->first();
if ($sourceDebt === null
|| !in_array((string) $sourceDebt->state,
['cleanup_running', 'attention', 'released'], true)
|| (int) $sourceDebt->cleanup_job_id !== (int) $job->id
|| !hash_equals(
(string) $sourceDebt->cleanup_operation_id,
(string) $job->operation_id
)) {
throw new CloudRecoveryInstanceStateConflict(
'维护迁移源清理任务与资源债务不一致',
409
);
}
$uuid = strtolower((string) $migration->source_uuid);
$base = '/v1/vms/' . rawurlencode($uuid);
self::expectRequest($method, $target, 'POST',

@ -1817,7 +1817,8 @@ final class CloudPlacementService
CloudBackupRestore $restore
): void {
if ($restore->backup_id === null) {
CloudPublicNetworkTransitionGate::assertMigrationReady();
CloudPublicNetworkTransitionGate::
assertLegacyMigrationWriterRetired();
}
CloudPublicNetworkTransitionGate::assertPortableRestoreReady();
}

@ -377,6 +377,280 @@ final class CloudPublicNetworkAllocationService
});
}
/**
* Atomically hand one migration instance from its source bundle to target.
*
* Both hosts and every network row are locked in a single deterministic
* order. Claim and address identities never move between reservations.
*
* @return array{source:CloudActivePublicNetworkClaimSet,
* target:CloudActivePublicNetworkClaimSet}
*/
public static function handoffMigrationBundles(
int $sourceReservationId,
int $targetReservationId,
int $instanceId,
string $sourceOperationId,
string $targetOperationId
): array {
self::assertIdentity($sourceReservationId, $sourceOperationId);
self::assertIdentity($targetReservationId, $targetOperationId);
if ($instanceId < 1) {
throw new CloudError('实例网络归属无效', 409);
}
if ($sourceReservationId === $targetReservationId) {
throw new CloudError('迁移源和目标资源预留必须不同', 409);
}
return self::connection()->transaction(static function () use (
$sourceReservationId,
$targetReservationId,
$instanceId,
$sourceOperationId,
$targetOperationId
): array {
$reservationIds = [$sourceReservationId, $targetReservationId];
sort($reservationIds, SORT_NUMERIC);
$reservationHints = DB::table('cloud_resource_reservations')
->whereIn('id', $reservationIds)->orderBy('id')->get()->all();
if (count($reservationHints) !== 2) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$reservationHintsById = [];
$hostIds = [];
foreach ($reservationHints as $hint) {
$reservationHintsById[(int) $hint->id] = $hint;
$hostIds[(int) $hint->host_id] = true;
}
if (!isset($reservationHintsById[$sourceReservationId],
$reservationHintsById[$targetReservationId])
|| count($hostIds) !== 2) {
throw new CloudError('迁移双栈网络宿主机边界无效', 409);
}
$hostIds = array_keys($hostIds);
sort($hostIds, SORT_NUMERIC);
$hosts = DB::table('cloud_hosts')->whereIn('id', $hostIds)
->orderBy('id')->lockForUpdate()->get()->all();
if (count($hosts) !== 2) {
throw new CloudError('公网网络宿主机不存在', 409);
}
$claimHints = DB::table('cloud_resource_reservation_ips')
->whereIn('reservation_id', $reservationIds)
->where('active_claim', 1)->orderBy('reservation_id')
->orderBy('address_family')->orderBy('id')->get()->all();
if (count($claimHints) !== 4) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$attachmentIds = [];
$poolIds = [];
foreach ($claimHints as $claim) {
$attachmentIds[(int) $claim->network_attachment_id] = true;
$poolIds[(int) $claim->public_ip_pool_id] = true;
}
$attachmentIds = array_keys($attachmentIds);
$poolIds = array_keys($poolIds);
sort($attachmentIds, SORT_NUMERIC);
sort($poolIds, SORT_NUMERIC);
DB::table('cloud_host_network_attachments')
->whereIn('id', $attachmentIds)->orderBy('id')
->lockForUpdate()->get();
DB::table('cloud_public_ip_pools')->whereIn('id', $poolIds)
->orderBy('id')->lockForUpdate()->get();
$lockedReservations = DB::table('cloud_resource_reservations')
->whereIn('id', $reservationIds)->orderBy('id')
->lockForUpdate()->get()->all();
$reservations = [];
foreach ($lockedReservations as $reservation) {
$reservations[(int) $reservation->id] = $reservation;
}
$source = $reservations[$sourceReservationId] ?? null;
$target = $reservations[$targetReservationId] ?? null;
self::assertReservation(
$source,
(int) $reservationHintsById[$sourceReservationId]->host_id,
$sourceOperationId,
['committed']
);
self::assertReservation(
$target,
(int) $reservationHintsById[$targetReservationId]->host_id,
$targetOperationId,
['held', 'uncertain']
);
if ((int) ($source->instance_id ?? 0) !== $instanceId
|| $target->instance_id !== null) {
throw new CloudError('迁移双栈网络归属不一致', 409);
}
$lockedClaims = DB::table('cloud_resource_reservation_ips')
->whereIn('reservation_id', $reservationIds)
->where('active_claim', 1)->orderBy('reservation_id')
->orderBy('address_family')->orderBy('id')->lockForUpdate()
->get()->all();
$claimIdentity = static function (object $claim): array {
return [
(int) $claim->id,
(int) $claim->reservation_id,
(string) $claim->address_family,
(int) $claim->network_attachment_id,
(int) $claim->public_ip_pool_id,
(int) $claim->public_ip_id,
(string) $claim->operation_id,
(int) $claim->claim_generation,
(string) $claim->state,
];
};
if (array_map($claimIdentity, $claimHints)
!== array_map($claimIdentity, $lockedClaims)) {
// The network context was selected from the unlocked hints.
// A changed claim could otherwise introduce a late attachment
// or pool lock and break the canonical global lock order.
throw new CloudError('迁移双栈网络账本已变化,请重新核对', 409);
}
$claimsByReservation = [
$sourceReservationId => [],
$targetReservationId => [],
];
foreach ($lockedClaims as $claim) {
$claimsByReservation[(int) $claim->reservation_id][] = $claim;
}
$sourceClaims = $claimsByReservation[$sourceReservationId];
$targetClaims = $claimsByReservation[$targetReservationId];
$targetClaimState = self::claimStateForReservation($target);
self::assertClaimSet(
$sourceClaims,
$sourceOperationId,
['committed']
);
self::assertClaimSet(
$targetClaims,
$targetOperationId,
[$targetClaimState]
);
$sourceSelection = self::lockClaimNetworkContext(
$sourceClaims,
(int) $source->host_id
);
$targetSelection = self::lockClaimNetworkContext(
$targetClaims,
(int) $target->host_id
);
self::assertClaimsUseSelection($sourceClaims, $sourceSelection);
self::assertClaimsUseSelection($targetClaims, $targetSelection);
$addresses = self::lockClaimAddresses($lockedClaims);
self::assertClaimAddresses(
$sourceClaims,
$addresses,
$sourceSelection,
$sourceOperationId,
['committed' => ['assigned']],
$instanceId
);
self::assertClaimAddresses(
$targetClaims,
$addresses,
$targetSelection,
$targetOperationId,
[
'reserved' => ['reserved'],
'uncertain' => ['uncertain'],
]
);
$sourceClaimSet = self::claimSet(
$sourceClaims,
'committed',
$instanceId,
(int) $source->host_id
);
$now = time();
foreach ($sourceClaims as $claim) {
$ipUpdated = DB::table('cloud_public_ips')
->where('id', (int) $claim->public_ip_id)
->where('reservation_id', $sourceReservationId)
->where('reservation_ip_claim_id', (int) $claim->id)
->where('operation_id', $sourceOperationId)
->where('instance_id', $instanceId)
->where('state', 'assigned')->update([
'state' => 'reserved',
'instance_id' => null,
'updated_at' => $now,
]);
$claimUpdated = DB::table('cloud_resource_reservation_ips')
->where('id', (int) $claim->id)
->where('active_claim', 1)
->where('operation_id', $sourceOperationId)
->where('state', 'committed')->update([
'state' => 'reserved',
'updated_at' => $now,
]);
if ($ipUpdated !== 1 || $claimUpdated !== 1) {
throw new CloudError('迁移源双栈地址未精确转为清理债务', 409);
}
}
foreach ($targetClaims as $claim) {
$ipUpdated = DB::table('cloud_public_ips')
->where('id', (int) $claim->public_ip_id)
->where('reservation_id', $targetReservationId)
->where('reservation_ip_claim_id', (int) $claim->id)
->where('operation_id', $targetOperationId)
->whereNull('instance_id')
->where('state', $targetClaimState)->update([
'state' => 'assigned',
'instance_id' => $instanceId,
'updated_at' => $now,
]);
$claimUpdated = DB::table('cloud_resource_reservation_ips')
->where('id', (int) $claim->id)
->where('active_claim', 1)
->where('operation_id', $targetOperationId)
->where('state', $targetClaimState)->update([
'state' => 'committed',
'updated_at' => $now,
]);
if ($ipUpdated !== 1 || $claimUpdated !== 1) {
throw new CloudError('迁移目标双栈地址未精确提交', 409);
}
}
$sourceUpdated = DB::table('cloud_resource_reservations')
->where('id', $sourceReservationId)
->where('operation_id', $sourceOperationId)
->where('instance_id', $instanceId)
->where('state', 'committed')->update([
'state' => 'held',
'instance_id' => null,
'expires_at' => null,
'updated_at' => $now,
]);
$targetUpdated = DB::table('cloud_resource_reservations')
->where('id', $targetReservationId)
->where('operation_id', $targetOperationId)
->whereNull('instance_id')
->where('state', (string) $target->state)->update([
'state' => 'committed',
'instance_id' => $instanceId,
'expires_at' => null,
'released_at' => null,
'release_reason' => '',
'updated_at' => $now,
]);
if ($sourceUpdated !== 1 || $targetUpdated !== 1) {
throw new CloudError('迁移源资源预留未精确转为清理债务', 409);
}
$targetClaimSet = self::claimSet(
self::lockedClaims($targetReservationId),
'committed',
$instanceId,
(int) $target->host_id
);
return [
'source' => $sourceClaimSet,
'target' => $targetClaimSet,
];
});
}
public static function fenceBundle(int $reservationId,
string $operationId): void
{
@ -901,16 +1175,11 @@ final class CloudPublicNetworkAllocationService
}
private static function assertPoolLedger(object $pool,
CloudPublicIpPoolContract $contract, array $rows,
array $retainedSourceEvidence): void
CloudPublicIpPoolContract $contract, array $rows): void
{
foreach ($rows as $row) {
self::assertConcreteAddress($row, $pool, $contract);
self::assertAddressOwnership(
$row,
$pool,
$retainedSourceEvidence
);
self::assertAddressOwnership($row);
}
}
@ -974,8 +1243,7 @@ final class CloudPublicNetworkAllocationService
}
}
private static function assertAddressOwnership(object $row,
?object $pool = null, array $retainedSourceEvidence = []): void
private static function assertAddressOwnership(object $row): void
{
$reservationId = $row->reservation_id === null
? null : (int) $row->reservation_id;
@ -995,14 +1263,9 @@ final class CloudPublicNetworkAllocationService
&& $claimId !== null && $claimId > 0
&& $instanceId === null && $validOperation,
'assigned' => $reservationId !== null && $reservationId > 0
&& $claimId !== null && $claimId > 0 && $validOperation && (
($instanceId !== null && $instanceId > 0)
|| self::matchesRetainedSourceEvidence(
$row,
$pool,
$retainedSourceEvidence
)
),
&& $claimId !== null && $claimId > 0
&& $instanceId !== null && $instanceId > 0
&& $validOperation,
'changing', 'uncertain' => $reservationId !== null
&& $reservationId > 0 && $claimId !== null && $claimId > 0
&& ($instanceId === null || $instanceId > 0)
@ -1014,37 +1277,6 @@ final class CloudPublicNetworkAllocationService
}
}
private static function matchesRetainedSourceEvidence(object $row,
?object $pool, array $evidenceByPublicIpId): bool
{
if ($pool === null || $row->instance_id !== null) {
return false;
}
$evidence = $evidenceByPublicIpId[(int) ($row->id ?? 0)] ?? null;
return is_array($evidence)
&& in_array(
$evidence['migration_state'] ?? null,
['source_retained', 'cleanup_running'],
true
)
&& (int) ($evidence['reservation_id'] ?? 0)
=== (int) ($row->reservation_id ?? 0)
&& (int) ($evidence['host_id'] ?? 0) === (int) $row->host_id
&& (int) ($evidence['host_id'] ?? 0) === (int) $pool->host_id
&& (int) ($evidence['network_attachment_id'] ?? 0)
=== (int) $pool->network_attachment_id
&& (int) ($evidence['public_ip_pool_id'] ?? 0)
=== (int) $row->public_ip_pool_id
&& (int) ($evidence['public_ip_pool_id'] ?? 0)
=== (int) $pool->id
&& (int) ($evidence['public_ip_id'] ?? 0) === (int) $row->id
&& is_string($evidence['operation_id'] ?? null)
&& hash_equals(
(string) $evidence['operation_id'],
(string) ($row->operation_id ?? '')
);
}
private static function assertClaimAddresses(array $claims,
array $addresses, array $selection, ?string $operationId,
array $allowedPairs, ?int $instanceId = null): void
@ -1229,17 +1461,10 @@ final class CloudPublicNetworkAllocationService
if (!$complete) {
throw new CloudError('宿主机双栈公网地址池目录不完整', 409);
}
$poolIds = array_map(
static fn (object $pool): int => (int) $pool->id,
$poolRows
);
$retainedSourceEvidence = CloudInstanceMigrationSettlement::
lockRetainedSourcePublicIpEvidence($hostId, $poolIds);
return [
'attachments' => $eligible,
'pools' => $pools,
'contracts' => $contracts,
'retained_source_evidence' => $retainedSourceEvidence,
];
}
@ -1270,12 +1495,7 @@ final class CloudPublicNetworkAllocationService
if (!$contract instanceof CloudPublicIpPoolContract) {
throw new CloudError('公网地址池合同缺失', 409);
}
self::assertPoolLedger(
$pool,
$contract,
$rowsByPool[$poolId],
$catalog['retained_source_evidence'] ?? []
);
self::assertPoolLedger($pool, $contract, $rowsByPool[$poolId]);
}
if ($constraint !== null) {

@ -24,10 +24,10 @@ final class CloudPublicNetworkTransitionGate
);
}
public static function assertMigrationReady(): void
public static function assertLegacyMigrationWriterRetired(): void
{
throw new CloudError(
'维护迁移正在升级为双栈公网网络流程,暂不可提交',
'旧维护迁移公网写入口已停用',
409
);
}
@ -68,7 +68,7 @@ final class CloudPublicNetworkTransitionGate
return;
}
if ((int) ($reservation->migration_source_debt_id ?? 0) > 0) {
self::assertMigrationReady();
self::assertLegacyMigrationWriterRetired();
}
throw new CloudError('实例资源预留来源无法确认', 409);
}

@ -437,7 +437,17 @@ final class CloudWorkerService
(string) $job->kind,
'instance_migration_'
)) {
CloudPublicNetworkTransitionGate::assertMigrationReady();
// Canonical PeerMigration rows carry an exact recoverable
// identity. Reject stale scalar-IP or torn ledger jobs before
// the dispatch CAS so they can never contact an Agent. This
// must validate the live request directly: expected() also
// accepts a post-effect recovery escrow, which is never a
// valid shape for an accepted, not-yet-dispatched job.
CloudOperationRecoveryIdentity::expectedFromPayload(
$job,
$payload,
false
);
} elseif (in_array(
(string) $job->kind,
['delete', 'delete_force', 'expiry_delete'],
@ -1728,13 +1738,8 @@ final class CloudWorkerService
'memory_mib' => $body['memory_mib'] ?? null,
'disk_gib' => $body['disk_gib'] ?? null,
'bandwidth_mbps' => $body['bandwidth_mbps'] ?? null,
'network' => $body['network'] ?? null,
'public_ip_cidr' => $body['public_ip_cidr'] ?? null,
'public_pool_key' => $body['public_pool_key'] ?? null,
'public_pool_cidr' =>
$body['public_pool_cidr'] ?? null,
'gateway' => $body['gateway'] ?? null,
'dns_servers' => $body['dns_servers'] ?? null,
'public_network' => $body['public_network'] ?? null,
'vpc_port' => $body['vpc_port'] ?? null,
],
];
}

@ -89,7 +89,7 @@ export function createAdminInstanceMigration({
? 'alert alert-danger fs-13' : 'alert alert-warning fs-13',
migration.recovery_action === 'reconcile_cleanup'
? '源副本删除效果正在按原操作编号核对,资源保持占用且不会盲目重放删除。'
: '目标实例已经接管原账单、到期时间和流量周期;源宿主机副本及原公网 IP 仍被保留并占用资源。'));
: '目标实例已经接管原账单、到期时间和流量周期;源宿主机副本及原公网 IPv4、IPv6 仍被保留并占用资源。'));
}
const recoveryOptions = Array.isArray(migration.recovery_options)
? migration.recovery_options.filter(option => option && typeof option === 'object'
@ -211,7 +211,7 @@ export function createAdminInstanceMigration({
}
if (!confirm.checked) {
feedback.hidden = false; feedback.className = 'text-danger fs-13 mb-0 mt-2';
feedback.textContent = '请确认冷迁移、原服务账本和新公网 IP 规则。'; return;
feedback.textContent = '请确认冷迁移、原服务账本和新公网 IPv4、IPv6 规则。'; return;
}
for (const control of form.querySelectorAll('input, select, button')) control.disabled = true;
feedback.hidden = false; feedback.className = 'text-muted fs-13 mb-0 mt-2';

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

@ -1533,6 +1533,7 @@ CREATE TABLE cloud_instance_migration_source_debts (
AND resolved_at IS NULL)
OR (state = 'attention'
AND active_debt IS NOT NULL AND active_debt = 1
AND cleanup_operation_id IS NOT NULL AND cleanup_job_id IS NOT NULL
AND resolved_at IS NULL)
OR (state = 'released' AND active_debt IS NULL
AND cleanup_operation_id IS NOT NULL AND cleanup_job_id IS NOT NULL

@ -3082,6 +3082,80 @@ namespace {
&& (int) $legacyWorkerJob->fresh()->dispatch_attempts === 0,
'Legacy network task was replayed after local rejection.');
// A stale migration row that still carries the retired scalar public-IP
// request shape must fail before the accepted-to-dispatching CAS. The
// immutable migration/instance/reservation ledgers are the only authority
// for a PeerMigration receive request.
$legacyMigrationJob = new CloudJob();
$legacyMigrationJob->operation_id = bin2hex(random_bytes(16));
$legacyMigrationJob->request_idempotency_key =
'legacy-migration-worker-gate-0001';
$legacyMigrationJob->request_fingerprint = hash(
'sha256',
'legacy-migration-worker-gate-0001'
);
$legacyMigrationJob->instance_id = (int) $legacyNetworkInstance->id;
$legacyMigrationJob->user_id = (int) $legacyNetworkInstance->user_id;
$legacyMigrationJob->host_id = (int) $legacyNetworkInstance->host_id;
$legacyMigrationJob->kind = 'instance_migration_transfer';
$legacyMigrationJob->execution_mode = 'agent';
$legacyMigrationJob->status = 'queued';
$legacyMigrationStoredIdentity = [
'version' => 1,
'action' => 'peer-migration-receive',
'resource_id' => 'migration:987654',
'request_fingerprint' => str_repeat('a', 64),
];
$legacyMigrationJob->sealed_payload =
\App\Services\Cloud\CloudSecrets::encrypt([
\App\Services\Cloud\CloudOperationRecoveryIdentity::payloadKey()
=> $legacyMigrationStoredIdentity,
'_operation_recovery' => [
'version' => 1,
'kind' => 'instance_migration_transfer',
'prepared_marker' => 'prepared:test:legacy-migration',
'operation' => [
'operation_id' =>
(string) $legacyMigrationJob->operation_id,
'action' => $legacyMigrationStoredIdentity['action'],
'resource_id' =>
$legacyMigrationStoredIdentity['resource_id'],
'request_fingerprint' =>
$legacyMigrationStoredIdentity[
'request_fingerprint'
],
],
],
'method' => 'POST',
'request_target' => '/v1/vms/'
. rawurlencode((string) $legacyNetworkInstance->uuid)
. '/peer-migration/receive',
'body' => [
'operation_id' => (string) $legacyMigrationJob->operation_id,
'public_ip_cidr' => '9.9.9.10/24',
'gateway' => '9.9.9.1',
],
'maintenance_migration_id' => 987654,
'owner_id' => (int) $legacyNetworkInstance->user_id,
'can_manage' => false,
], 'job-payload');
$legacyMigrationJob->available_at = $legacyMigrationJob->created_at =
$legacyMigrationJob->updated_at = time();
$legacyMigrationJob->save();
$beforeLegacyMigration = count($history);
$assert($worker->tick(),
'Legacy migration task was not consumed by local admission.');
$legacyMigrationJob->refresh();
$assert(count($history) === $beforeLegacyMigration
&& (int) $legacyMigrationJob->dispatch_attempts === 0
&& $legacyMigrationJob->phase === 'terminal'
&& $legacyMigrationJob->outcome === 'failed',
'Legacy migration task reached the Agent or remained claimable.');
$worker->tick();
$assert(count($history) === $beforeLegacyMigration
&& (int) $legacyMigrationJob->fresh()->dispatch_attempts === 0,
'Legacy migration task was replayed after local rejection.');
// The ordinary job enqueue path is permanently closed to legacy scalar
// network changes. Canonical transitions have their own durable workflow
// and are tested in the dedicated begin/finalization behavior suites.

@ -289,10 +289,11 @@ $assert(substr_count($serviceSource,
'$field = match ((string) $job->kind)')
&& str_contains($serviceSource,
'CloudInstanceMigrationWorkflow::recoveryActions(')
&& !str_contains($serviceSource,
"'maintenance_migration_transferred'")
&& str_contains($settlementSource,
"'maintenance_migration_transferred'")
"'maintenance_migration_source_removed'")
&& str_contains($settlementSource,
'migration_source_debt_id')
&& !str_contains($settlementSource, 'CloudPublicIp')
&& str_contains($serviceSource,
'CloudVpcPortService::migrationPortIdLocked(')
&& str_contains($serviceSource,

File diff suppressed because it is too large Load Diff

@ -140,7 +140,9 @@ $assert($transferOutcome !== ''
&& str_contains($transferOutcome,
'CloudPublicNetworkAllocationService::fenceBundle(')
&& str_contains($transferOutcome,
'CloudPublicNetworkAllocationService::commitBundle(')
'handoffMigrationBundles(')
&& str_contains($transferOutcome,
'CloudInstanceMigrationSettlement::settleCutoverLocked(')
&& str_contains($transferOutcome, 'verifiedTargetBundle(')
&& !str_contains($transferOutcome, '$requestedIp'),
'Transfer outcomes are not committed or fenced as one dual-stack bundle.');

@ -39,11 +39,14 @@ namespace {
use App\Services\Cloud\CloudAdminOperationRecoveryService;
use App\Services\Cloud\CloudAgentError;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudFrozenPublicNetworkIdentity;
use App\Services\Cloud\CloudInstanceMigrationService;
use App\Services\Cloud\CloudOperationCompletionService;
use App\Services\Cloud\CloudOperationRecoveryContract;
use App\Services\Cloud\CloudOperationRecoveryIdentity;
use App\Services\Cloud\CloudOperationRecoveryPolicy;
use App\Services\Cloud\CloudPortableRestoreCompatibility;
use App\Services\Cloud\CloudPublicNetworkAllocationService;
use App\Services\Cloud\CloudRecoveryInstanceStateConflict;
use App\Services\Cloud\CloudSecrets;
use App\Services\Cloud\CloudVpcProjection;
@ -103,6 +106,9 @@ namespace {
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('cloud_hosts', static function (Blueprint $table): void {
$table->increments('id');
});
$schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->increments('id');
$table->string('operation_id')->unique();
@ -385,8 +391,11 @@ namespace {
$schema->create('cloud_resource_reservations',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('reservation_key')->nullable();
$table->integer('order_id')->nullable();
$table->integer('backup_restore_id')->nullable();
$table->string('backup_restore_attempt_key')->nullable();
$table->integer('migration_source_debt_id')->nullable();
$table->integer('offer_id')->nullable();
$table->integer('host_id');
$table->integer('user_id');
@ -421,15 +430,36 @@ namespace {
$table->increments('id');
$table->integer('host_id');
$table->integer('public_ip_pool_id')->nullable();
$table->integer('address_family')->nullable();
$table->string('address');
$table->binary('address_binary')->nullable();
$table->integer('prefix_length');
$table->string('state');
$table->integer('reservation_id')->nullable();
$table->integer('reservation_ip_claim_id')->nullable();
$table->integer('instance_id')->nullable();
$table->string('operation_id')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_resource_reservation_ips', static function (
Blueprint $table
): void {
$table->increments('id');
$table->integer('reservation_id');
$table->integer('address_family');
$table->integer('claim_generation')->default(1);
$table->integer('active_claim')->nullable()->default(1);
$table->integer('network_attachment_id');
$table->integer('public_ip_pool_id');
$table->integer('public_ip_id');
$table->string('operation_id');
$table->string('state');
$table->integer('released_at')->nullable();
$table->string('release_reason')->default('');
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_resource_pools',
static function (Blueprint $table): void {
$table->increments('id');
@ -448,10 +478,42 @@ namespace {
$table->integer('host_id');
$table->integer('network_attachment_id');
$table->string('pool_key');
$table->integer('address_family')->nullable();
$table->string('cidr');
$table->string('gateway');
$table->boolean('gateway_on_link')->default(0);
$table->integer('guest_prefix_length')->nullable();
$table->text('dns_servers_json');
$table->text('reserved_ips_json')->default('[]');
$table->string('allocation_start')->nullable();
$table->string('allocation_end')->nullable();
$table->string('allocation_cursor')->nullable();
$table->integer('max_allocations')->default(0);
});
$schema->create('cloud_instance_migration_source_debts', static function (
Blueprint $table
): void {
$table->increments('id');
$table->string('debt_key');
$table->integer('migration_id');
$table->integer('source_reservation_id');
$table->integer('source_host_id');
$table->string('source_uuid');
$table->integer('source_network_attachment_id');
$table->text('source_identity_json');
$table->string('source_identity_sha256');
$table->string('source_claim_set_sha256');
$table->text('source_public_network_json');
$table->string('source_public_network_sha256');
$table->string('cleanup_operation_id')->nullable();
$table->integer('cleanup_job_id')->nullable();
$table->string('state');
$table->integer('active_debt')->nullable();
$table->string('last_error_code')->default('');
$table->integer('resolved_at')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_instance_firewall_versions',
static function (Blueprint $table): void {
$table->increments('id');
@ -574,6 +636,7 @@ namespace {
$instanceId = 1;
$instanceUuid = '123e4567-e89b-42d3-a456-426614174000';
Capsule::table('user')->insert(['id' => $ownerId]);
Capsule::table('cloud_hosts')->insert(['id' => $hostId]);
Capsule::table('cloud_instances')->insert([
'id' => $instanceId,
'uuid' => $instanceUuid,
@ -882,7 +945,9 @@ namespace {
$migrationLineId = 7101;
$migrationAttachmentId = 7201;
$migrationPublicPoolId = 7301;
$migrationIpv6PublicPoolId = 7306;
$migrationNetworkSelector = 'bridge:migration-wan';
$migrationSourceOperationId = str_repeat('7', 32);
Capsule::table('cloud_resource_pools')->insert([
'id' => $migrationResourcePoolId,
'line_id' => $migrationLineId,
@ -894,13 +959,40 @@ namespace {
'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"]',
[
'id' => $migrationPublicPoolId,
'host_id' => $hostId,
'network_attachment_id' => $migrationAttachmentId,
'pool_key' => str_repeat('b', 32),
'address_family' => 4,
'cidr' => '8.8.30.0/24',
'gateway' => '8.8.30.1',
'gateway_on_link' => 0,
'guest_prefix_length' => 24,
'dns_servers_json' => '["1.1.1.1"]',
'reserved_ips_json' => '[]',
'allocation_start' => null,
'allocation_end' => null,
'allocation_cursor' => null,
'max_allocations' => 0,
],
[
'id' => $migrationIpv6PublicPoolId,
'host_id' => $hostId,
'network_attachment_id' => $migrationAttachmentId,
'pool_key' => str_repeat('c', 32),
'address_family' => 6,
'cidr' => '2404:c140:156:30::/64',
'gateway' => '2404:c140:156:30::1',
'gateway_on_link' => 0,
'guest_prefix_length' => 64,
'dns_servers_json' => '["2606:4700:4700::1111"]',
'reserved_ips_json' => '[]',
'allocation_start' => '2404:c140:156:30::100',
'allocation_end' => '2404:c140:156:30::1ff',
'allocation_cursor' => null,
'max_allocations' => 100,
],
]);
$migrationArtifact = [
'id' => $migrationArtifactId,
@ -958,27 +1050,21 @@ namespace {
'memory_mib' => 2048,
'disk_gib' => 20,
'bandwidth_mbps' => 100,
'network' => $migrationNetworkSelector,
'public_network' => [],
'template_id' => '',
'template_revision' => 0,
'template_generation_token' => '',
'startup_script' => '',
'hostname' => 'matrix-vm',
'hostname' => '',
'guest_ssh_public_key' => '',
'root_password' => '',
'public_pool_key' => str_repeat('b', 32),
'public_pool_cidr' => '203.0.113.0/24',
'public_ip_cidr' => '203.0.113.30/24',
'gateway' => '203.0.113.1',
'dns_servers' => ['1.1.1.1'],
'platform_network_policy_snapshot' => [
'schema_version' => 1,
],
'platform_network_policy_snapshot' => [],
],
'owner_id' => $ownerId,
'can_manage' => true,
'reservation_id' => 9004,
'maintenance_migration_id' => 1,
'migration_target' => [],
],
$instanceId,
null,
@ -1142,36 +1228,207 @@ namespace {
'updated_at' => $now - 20,
]);
Capsule::table('cloud_resource_reservations')->insert([
'id' => 9004,
[
'id' => 9003,
'reservation_key' => str_repeat('3', 32),
'backup_restore_id' => null,
'backup_restore_attempt_key' => null,
'migration_source_debt_id' => 1,
'host_id' => $hostId,
'user_id' => $ownerId,
'resource_pool_id' => $migrationResourcePoolId,
'network_attachment_id' => null,
'public_ip_pool_id' => null,
'operation_id' => $migrationSourceOperationId,
'public_ip_id' => null,
'instance_id' => null,
'cpu_cores' => 2,
'memory_mib' => 2048,
'disk_gib' => 20,
'state' => 'held',
'expires_at' => null,
'released_at' => null,
'release_reason' => '',
'created_at' => $now - 300,
'updated_at' => $now - 20,
],
[
'id' => 9004,
'reservation_key' => str_repeat('4', 32),
'backup_restore_id' => 9002,
'backup_restore_attempt_key' => null,
'migration_source_debt_id' => null,
'host_id' => $hostId,
'user_id' => $ownerId,
'resource_pool_id' => $migrationResourcePoolId,
'network_attachment_id' => null,
'public_ip_pool_id' => null,
'operation_id' => $migrationTransfer['operation_id'],
'public_ip_id' => null,
'instance_id' => null,
'cpu_cores' => 2,
'memory_mib' => 2048,
'disk_gib' => 20,
'state' => 'uncertain',
'expires_at' => null,
'released_at' => null,
'release_reason' => '',
'created_at' => $now - 300,
'updated_at' => $now - 20,
],
]);
$insertMigrationClaim = static function (
int $claimId,
int $ipId,
int $reservationId,
int $family,
int $poolId,
string $address,
string $operationId,
string $state
) use ($hostId, $migrationAttachmentId, $now): void {
Capsule::table('cloud_public_ips')->insert([
'id' => $ipId,
'host_id' => $hostId,
'public_ip_pool_id' => $poolId,
'address_family' => $family,
'address' => $address,
'address_binary' => inet_pton($address),
'prefix_length' => $family === 4 ? 24 : 64,
'state' => $state === 'reserved' ? 'reserved' : 'uncertain',
'reservation_id' => $reservationId,
'reservation_ip_claim_id' => $claimId,
'instance_id' => null,
'operation_id' => $operationId,
'created_at' => $now - 300,
'updated_at' => $now - 20,
]);
Capsule::table('cloud_resource_reservation_ips')->insert([
'id' => $claimId,
'reservation_id' => $reservationId,
'address_family' => $family,
'claim_generation' => 1,
'active_claim' => 1,
'network_attachment_id' => $migrationAttachmentId,
'public_ip_pool_id' => $poolId,
'public_ip_id' => $ipId,
'operation_id' => $operationId,
'state' => $state,
'released_at' => null,
'release_reason' => '',
'created_at' => $now - 300,
'updated_at' => $now - 20,
]);
};
$insertMigrationClaim(
9201,
9007,
9004,
4,
$migrationPublicPoolId,
'8.8.30.30',
$migrationTransfer['operation_id'],
'uncertain'
);
$insertMigrationClaim(
9202,
9008,
9004,
6,
$migrationIpv6PublicPoolId,
'2404:c140:156:30::130',
$migrationTransfer['operation_id'],
'uncertain'
);
$insertMigrationClaim(
9203,
9009,
9003,
4,
$migrationPublicPoolId,
'8.8.30.29',
$migrationSourceOperationId,
'reserved'
);
$insertMigrationClaim(
9204,
9010,
9003,
6,
$migrationIpv6PublicPoolId,
'2404:c140:156:30::129',
$migrationSourceOperationId,
'reserved'
);
$migrationTargetClaims =
CloudPublicNetworkAllocationService::currentClaimSet(
9004,
'uncertain'
);
$migrationTargetIdentity = CloudFrozenPublicNetworkIdentity::fromClaimSet(
$migrationTargetUuid,
$migrationTargetClaims
);
$migrationSourceClaims =
CloudPublicNetworkAllocationService::currentClaimSet(9003, 'held');
$migrationSourceIdentity = CloudFrozenPublicNetworkIdentity::fromClaimSet(
$instanceUuid,
$migrationSourceClaims
);
$migrationTransfer['payload']['body']['public_network'] =
$migrationTargetIdentity->publicNetwork()->toArray();
$migrationTransfer['payload']['migration_target'] = [
'contract' => 1,
'backup_restore_id' => 9002,
'reservation_id' => 9004,
'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,
'cpu_cores' => 2,
'memory_mib' => 2048,
'disk_gib' => 20,
'state' => 'uncertain',
'expires_at' => null,
'released_at' => null,
'release_reason' => '',
'created_at' => $now - 300,
'updated_at' => $now - 20,
]);
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',
'reservation_id' => 9004,
'instance_id' => null,
'operation_id' => $migrationTransfer['operation_id'],
'target_uuid' => strtolower($migrationTargetUuid),
'target_agent_revision' => 3,
'target_agent_contract_sha256' =>
CloudPortableRestoreCompatibility::supported()->sha256(),
'target_identity_json' => $migrationTargetIdentity->identityJson(),
'target_identity_sha256' =>
$migrationTargetIdentity->identitySha256(),
'target_claim_set_sha256' =>
$migrationTargetIdentity->claimSetSha256(),
'target_public_network_json' =>
$migrationTargetIdentity->publicNetworkJson(),
'target_public_network_sha256' =>
$migrationTargetIdentity->publicNetworkSha256(),
'vpc_port' => null,
];
$migrationTransferPayload = CloudSecrets::encrypt(
$migrationTransfer['payload'],
'job-payload'
);
Capsule::table('cloud_jobs')->where('id', $migrationTransfer['id'])
->update(['sealed_payload' => $migrationTransferPayload]);
$migrationTransfer['job']->sealed_payload = $migrationTransferPayload;
Capsule::table('cloud_instance_migration_source_debts')->insert([
'id' => 1,
'debt_key' => str_repeat('5', 32),
'migration_id' => 1,
'source_reservation_id' => 9003,
'source_host_id' => $hostId,
'source_uuid' => strtolower($instanceUuid),
'source_network_attachment_id' => $migrationAttachmentId,
'source_identity_json' => $migrationSourceIdentity->identityJson(),
'source_identity_sha256' =>
$migrationSourceIdentity->identitySha256(),
'source_claim_set_sha256' =>
$migrationSourceIdentity->claimSetSha256(),
'source_public_network_json' =>
$migrationSourceIdentity->publicNetworkJson(),
'source_public_network_sha256' =>
$migrationSourceIdentity->publicNetworkSha256(),
'cleanup_operation_id' => $migrationCleanup['operation_id'],
'cleanup_job_id' => $migrationCleanup['id'],
'state' => 'attention',
'active_debt' => 1,
'last_error_code' => 'operation_effect_unknown',
'resolved_at' => null,
'created_at' => $now - 300,
'updated_at' => $now - 20,
]);
@ -3325,6 +3582,24 @@ namespace {
'uuid' => $instanceUuid,
'reservation_id' => 9003,
]);
Capsule::table('cloud_instance_migration_source_debts')
->where('migration_id', 1)->delete();
Capsule::table('cloud_resource_reservations')->where('id', 9003)->update([
'migration_source_debt_id' => null,
'instance_id' => $instanceId,
'state' => 'committed',
'updated_at' => $now,
]);
Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', 9003)->update([
'state' => 'committed',
'updated_at' => $now,
]);
Capsule::table('cloud_public_ips')->where('reservation_id', 9003)->update([
'state' => 'assigned',
'instance_id' => $instanceId,
'updated_at' => $now,
]);
Capsule::table('cloud_instance_migrations')->where('id', 1)->update([
'target_receive_job_id' => null,
'firewall_job_id' => null,
@ -3352,15 +3627,20 @@ namespace {
]);
Capsule::table('cloud_resource_reservations')->where('id', 9004)->update([
'operation_id' => $abortTargetOperation,
'instance_id' => $instanceId,
'instance_id' => null,
'state' => 'held',
'released_at' => null,
'release_reason' => '',
'updated_at' => $now,
]);
Capsule::table('cloud_public_ips')->where('id', 9007)->update([
Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', 9004)->update([
'state' => 'reserved',
'operation_id' => $abortTargetOperation,
'updated_at' => $now,
]);
Capsule::table('cloud_public_ips')->where('reservation_id', 9004)->update([
'state' => 'reserved',
'reservation_id' => 9004,
'instance_id' => null,
'operation_id' => $abortTargetOperation,
'updated_at' => $now,
@ -3565,7 +3845,8 @@ namespace {
. '/peer-migration/receive',
'body' => [
'operation_id' => $operationId,
'public_ip_cidr' => '203.0.113.30/24',
'public_network' =>
$migrationTargetIdentity->publicNetwork()->toArray(),
],
'owner_id' => $ownerId,
'can_manage' => true,
@ -3635,11 +3916,17 @@ namespace {
->update([
'backup_restore_id' => 9012,
'operation_id' => $residueTransfer['operation_id'],
'instance_id' => $instanceId,
'instance_id' => null,
'state' => 'uncertain',
'updated_at' => $now,
]);
Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', 9004)->update([
'state' => 'uncertain',
'operation_id' => $residueTransfer['operation_id'],
'updated_at' => $now,
]);
Capsule::table('cloud_public_ips')->where('id', 9007)->update([
Capsule::table('cloud_public_ips')->where('reservation_id', 9004)->update([
'state' => 'uncertain',
'instance_id' => null,
'operation_id' => $residueTransfer['operation_id'],

@ -73,14 +73,16 @@ $assert(str_contains($runtime, 'export function createAdminInstanceMigration(')
&& str_contains($runtime, '原账单、到期时间和流量周期')
&& str_contains(
$migrationSettlement,
"'maintenance_migration_transferred'"
"'maintenance_migration_source_removed'"
)
&& str_contains($migrationSettlement, 'settleCutoverLocked(')
&& str_contains($migrationSettlement, 'migration_source_debt_id')
&& str_contains($migration, "'traffic_counter_generation'")
&& str_contains($migration, "'reconcile_cleanup'")
&& str_contains($migration, "'managed_artifacts_absent'")
&& str_contains($migration, 'reserveBackupRestore(')
&& str_contains($migration, 'reserveMaintenanceMigrationTarget(')
&& str_contains($migration, "'target_resource_pool_id'")
&& str_contains($migration, 'preparedBackupRestorePlacement(')
&& str_contains($migration, 'preparedMaintenanceMigrationTarget(')
&& str_contains($migration, '$restore->target_instance_id = null;')
&& str_contains($jobService,
'CloudInstanceMigrationService::assertInstanceMutationAvailable(')
@ -110,7 +112,7 @@ $assert(str_contains($peerArtifacts,
&& str_contains($migration, 'queueActivationLocked(')
&& strpos($migration, 'queueMaintenanceMigrationReapplyLocked(')
< strpos($migration, 'queueActivationLocked(')
&& str_contains($migration, "\$spec['guest_hostname'] ?? \$instance->name")
&& str_contains($migration, "'hostname' => ''")
&& str_contains($migrationWorkflow, "'label' => '恢复目标电源状态'")
&& str_contains($migrationWorkflow, "'label' => '重试目标状态恢复'")
&& str_contains($migrationWorkflow,

@ -102,4 +102,75 @@ $assert(($restoreCompact['body'] ?? null) === [
&& !str_contains($encodedRestore, 'X-Amz-Signature'),
'Prepared restore evidence retained an expired capability or secret.');
$publicNetwork = [
'attachment_key' => str_repeat('3', 32),
'network' => 'bridge:br0',
'addresses' => [
[
'address_family' => 4,
'address_cidr' => '203.0.113.29/24',
'gateway' => '203.0.113.1',
'pool_key' => str_repeat('4', 32),
'dns_servers' => ['9.9.9.9'],
],
[
'address_family' => 6,
'address_cidr' => '2001:db8:100::29/64',
'gateway' => '2001:db8:100::1',
'pool_key' => str_repeat('5', 32),
'dns_servers' => ['2620:fe::fe'],
],
],
];
$vpcPort = [
'vpc_key' => str_repeat('6', 32),
'address_cidr' => '10.0.0.29/24',
'mac_address' => '02:00:00:00:00:29',
];
$migrationPayload = [
$identityKey => array_replace(
$identity,
['kind' => 'instance_migration_transfer']
),
'owner_id' => 42,
'can_manage' => true,
'reservation_id' => 92,
'maintenance_migration_id' => 93,
'body' => [
'vcpu' => 8,
'memory_mib' => 16384,
'disk_gib' => 160,
'bandwidth_mbps' => 1000,
'public_network' => $publicNetwork,
'vpc_port' => $vpcPort,
'public_ip_cidr' => '203.0.113.29/24',
'gateway' => '203.0.113.1',
'source_url' => $largeUrls[0],
'root_password' => 'must-not-survive',
],
];
$migrationCompact = $compact->invoke(
null,
'instance_migration_transfer',
$migrationPayload
);
$encodedMigration = json_encode(
$migrationCompact,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
);
$assert(($migrationCompact['body'] ?? null) === [
'vcpu' => 8,
'memory_mib' => 16384,
'disk_gib' => 160,
'bandwidth_mbps' => 1000,
'public_network' => $publicNetwork,
'vpc_port' => $vpcPort,
]
&& !str_contains($encodedMigration, 'public_ip_cidr')
&& !str_contains($encodedMigration, 'source_url')
&& !str_contains($encodedMigration, 'root_password')
&& !str_contains($encodedMigration, 'X-Amz-Signature'),
'Prepared migration evidence lost canonical dual-stack state or retained'
. ' a retired scalar field, capability, or secret.');
echo "Portable-backup prepared recovery envelope contract passed.\n";

@ -100,7 +100,8 @@ $deletedInstance = $method(
$assert(str_contains($gate, 'assertWriterReady')
&& str_contains($gate, 'assertPortableRestoreReady')
&& str_contains($gate, 'assertMigrationReady')
&& str_contains($gate, 'assertLegacyMigrationWriterRetired')
&& !str_contains($gate, 'assertMigrationReady')
&& str_contains($gate, 'assertInstanceDeleteReady'),
'Legacy-writer gate does not cover every pre-ledger writer.');
$enqueueStart = strpos($jobs, 'public static function enqueue(');
@ -128,7 +129,9 @@ $assert($before($worker,
&& $before($worker,
"(string) \$job->kind === 'backup_restore'",
"'phase' => 'dispatching'")
&& $before($worker, "'instance_migration_'", "'phase' => 'dispatching'"),
&& $before($worker,
'CloudOperationRecoveryIdentity::expectedFromPayload(',
"'phase' => 'dispatching'"),
'Worker defense runs after an old operation may be dispatched.');
$restoreDispatchGate = strpos(
$worker,
@ -165,27 +168,27 @@ $assert(!str_contains($backupRestore,
&& !str_contains($backupRestore, 'new CloudBackupRestore()')
&& !str_contains($backupRestore, 'reserveBackupRestore('),
'Portable-restore request seam retained the retired writer or closed gate.');
$assert($before($migration,
'CloudPublicNetworkTransitionGate::assertMigrationReady()',
'new CloudBackupRestore()'),
'Migration gate runs after target rows may be created.');
$assert(!str_contains($migration,
'CloudPublicNetworkTransitionGate::')
&& str_contains($migration, 'reserveMaintenanceMigrationTarget('),
'Canonical dual-stack migration start is still behind a legacy gate.');
$assert(str_contains($placement,
'self::assertBackupRestoreTransitionReady($restore)')
&& str_contains($placementGate,
'CloudPublicNetworkTransitionGate::assertMigrationReady()')
'assertLegacyMigrationWriterRetired()')
&& str_contains($placementGate,
'CloudPublicNetworkTransitionGate::assertPortableRestoreReady()'),
'Placement lacks a defense-in-depth gate for old restore writers.');
$assert($before($migrationEnsureCleanup,
'CloudPublicNetworkTransitionGate::assertMigrationReady()',
'getConnection()->transaction')
&& $before($migrationRecover,
'CloudPublicNetworkTransitionGate::assertMigrationReady()',
'getConnection()->transaction')
&& $before($migrationCleanup,
'CloudPublicNetworkTransitionGate::assertMigrationReady()',
'getConnection()->transaction'),
'A migration recovery entry can create retry intent before its gate.');
$assert(!str_contains($migrationEnsureCleanup,
'CloudPublicNetworkTransitionGate::')
&& !str_contains($migrationRecover,
'CloudPublicNetworkTransitionGate::')
&& !str_contains($migrationCleanup,
'CloudPublicNetworkTransitionGate::')
&& str_contains($migrationEnsureCleanup, 'getConnection()->transaction')
&& str_contains($migrationRecover, 'getConnection()->transaction')
&& str_contains($migrationCleanup, 'getConnection()->transaction'),
'Canonical migration recovery is still gated or lost its transaction.');
$assert($before($networkFinalizer,
'CloudPublicNetworkTransitionGate::assertWriterReady()',
'lockForUpdate()'),

@ -167,7 +167,7 @@ $assert(str_contains($debtShape,
&& str_contains($debtShape,
"state = 'cleanup_running' AND active_debt IS NOT NULL AND active_debt = 1 AND cleanup_operation_id IS NOT NULL AND cleanup_job_id IS NOT NULL AND resolved_at IS NULL")
&& str_contains($debtShape,
"state = 'attention' AND active_debt IS NOT NULL AND active_debt = 1 AND resolved_at IS NULL")
"state = 'attention' AND active_debt IS NOT NULL AND active_debt = 1 AND cleanup_operation_id IS NOT NULL AND cleanup_job_id IS NOT NULL AND resolved_at IS NULL")
&& str_contains($debtShape,
"state = 'released' AND active_debt IS NULL AND cleanup_operation_id IS NOT NULL AND cleanup_job_id IS NOT NULL AND resolved_at IS NOT NULL")
&& str_contains($debtShape,

Loading…
Cancel
Save