diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index d68ff92a..06437fb2 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -1,5 +1,40 @@ # 本版验证记录 +## 2026-10-14:VPC 自动加入/退出及默认组内 ACL + +- 新版页面确认短暂中断后提交 `auto_power: true`。VPC 操作独立保存电源进度: + 正常关机回执、确认停止、既有严格配置/清理证明、恢复原运行状态。 + 原本停止或已经在关机的实例不会被自动启动;120 秒关机等待超时暂停, + 不自动强制断电,不把 QGA 私网核验加入普通电源任务完成条件。 +- `cloud_vpc_operations.power_workflow_json` 和带索引的 `power_instance_id` + 是可空增量字段。按实例索引定位待核对任务,避免加锁查询扫描全部操作;不改变 VPC + immutable payload/digest。旧任务、缺省 `auto_power` 的 API 请求保持原行为; + 未升级字段时普通电源任务仍可入队,新自动流程拒绝接纳。 +- 子电源操作先保存固定 ID 再派发,恢复时查询原回执。后续手动电源意图取消 + 自动开机,也禁止旧流程补发尚未执行的关机。最后成员的 NIC/IP 已清理、 + 但电源恢复未结束时,禁止该实例被另一 VPC 工作流接纳。 +- 新 VPC 在同一创建事务中保存自身 `/24` 的两条全协议 allow ACL,分别为 + ingress 32760、egress 32761。现有规则不回填,创建请求重放不恢复用户删除的 + 默认规则。空 VPC 仅完成地址/规则预留,不伪造宿主已安装 ACL 的证据。 +- Python 3.12:`test_vpc.py`、`test_vpc_dataplane.py` **137 passed**;保留 + 19 条既有 ElementTree truth-value 弃用警告。额外将 PHP 实际生成的默认 ACL + DTO 交给 Python 解析和 coordinator,验证摘要一致、空 VPC 预留,以及同宿主/ + 跨宿主 nft 输出仍先执行身份、防伪与跨 VPC 隔离检查。 +- PHP 8.5 WASM/SQLite:自动电源完整 worker 流程、普通电源回执、创建策略、 + 根 VPC 删除、tombstone 收敛、失败重试、实例任务准入、页面契约、控制面契约、 + 快照、未派发创建失败共 **11 项脚本通过**。自动流程测试复用成员/私网 IP + 复用测试;覆盖开机回执丢失、旧版本任务、超时手动 force-off、初始 shutdown、 + 持久进度损坏、跨 VPC 竞争和旧数据库结构。准入测试对 MariaDB NOWAIT 错误 + 作注入验证;SQLite 不能证明真实 MariaDB 并发行为。 +- Node 页面行为和成员选择 **2 项脚本通过**,包含确认取消不发送请求、显式 + auto_power、当前操作进度、最后成员退出后的重试入口和错误提示。 +- 扩展财务工作流在旧创建核对断言处失败;防火墙工作流因既有 + `GuzzleHttp\\Handler\\HandlerStack` 导入失败。两项均在修改前 `387237a` 的 + 独立源码快照、相同运行时复现,未为本次功能放宽断言。 +- 未操作生产、未做真实 MariaDB/libvirt/QGA/转发验收。部署需通过 + `php xcat cloudInit` 应用增量字段,再加载新版 PHP/worker;在线更新器已有 + 该步骤。使用和验收边界见 [VPC 自动成员流程](VPC_AUTOMATIC_MEMBERSHIP.md)。 + ## 2026-10-13:按镜像配置首次启动脚本 - 管理员镜像目录新增启动脚本对话框和独立接口;超级管理员可写、普通管理员 diff --git a/docs/VPC_AUTOMATIC_MEMBERSHIP.md b/docs/VPC_AUTOMATIC_MEMBERSHIP.md new file mode 100644 index 00000000..057a7ecd --- /dev/null +++ b/docs/VPC_AUTOMATIC_MEMBERSHIP.md @@ -0,0 +1,55 @@ +# VPC 成员自动加入、退出与默认 ACL + +## 操作边界 + +新版用户页面在加入或退出实例时明确确认短暂中断,并提交 `auto_power: true`。 +PHP 的 VPC 工作流负责保存进度,Python 引擎仍负责 libvirt 调用。旧请求未携带 +该字段时保留原流程,历史任务不会因升级自动获得关机权限。 + +自动流程仅针对本次加入或退出的实例:读取原电源状态,请求正常关机,等待 +确认停止,应用 VPC 配置并核对宿主回执,最后恢复原来运行的实例。原来已经 +停止的实例继续保持停止。不会为了更新 ACL、例行健康核对或其他成员的状态 +而自动重启整个 VPC。 + +正常关机请求被接受并不代表来宾已经停止。依照 +[libvirt shutdown 契约](https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainShutdown), +工作流将命令回执和实际电源状态分开处理;正常关机等待超时后暂停,绝不自动 +强制断电。管理员或用户可以自行处理电源状态,再核对原 VPC 操作。 + +后续手动电源意图取消旧流程的自动恢复开机权。子电源操作使用固定 operation ID, +先持久化再发送;通信中断后核对原 ID,不以新 ID 重复提交。真正不确定的远端 +写操作继续沿用引擎已有保护。 + +宿主 XML、seed 和私网清理回执确认后即可进入恢复开机步骤。开机后的 QGA、 +来宾地址和路由核对继续走既有观测流程,不把来宾尚未就绪变成普通电源任务的锁。 +退出时只有原有严格删除证据成立,才释放成员和私网 IP;不能仅凭关机回执释放。 + +## 默认私网互通 + +每个新 VPC 在分配 `/24` 的同一事务中创建两条可编辑 ACL: + +| 方向 | 优先级 | 源 CIDR | 目标 CIDR | 协议与端口 | +| --- | --- | --- | --- | --- | +| ingress | 32760 | 本 VPC 的 /24 | 本 VPC 的 /24 | all / 全部 | +| egress | 32761 | 本 VPC 的 /24 | 本 VPC 的 /24 | all / 全部 | + +规则仅允许当前 VPC 内通信,不包含其他 VPC 或公网。较低数字的规则可用于 +明确限制。既有 VPC、用户修改的规则和已删除的规则不补写;重复创建请求不会 +恢复默认规则。VM 内部防火墙仍独立生效。 + +空 VPC 可以保存默认 ACL 并等待成员;没有宿主回读时不会把 ACL 标记为已经 +安装成功。第一台实例加入后,默认规则随该版本配置一起应用并核对。 + +## 部署与验收 + +部署前先应用 `web/sql/cloud.sql` 中的增量结构,再启动新版 PHP worker。 +自动流程使用 `cloud_vpc_operations.power_workflow_json` 保存持久进度,使用带索引的 +`power_instance_id` 定位实例任务,避免锁定查询扫描无关实例的历史操作;不能通过 +删除字段或操作行解决未知执行结果。 +索引和短事务用于缩小数据库锁的范围;具体部署仍需检查执行计划与并发行为, +参见 [InnoDB 锁定读取与扫描范围](https://dev.mysql.com/doc/refman/8.0/en/innodb-locks-set.html)。 + +本地回归和模拟引擎验证不能代替真实宿主验收。部署后应分别验收运行和停止 +实例的加入、退出,同宿主和跨宿主的 `/24` 双向通信,正常关机超时后的手动 +强制断电,以及 worker 重启后继续核对原操作。还需确认公网配置保持不变、 +退出成员不能再访问原私网、旧 VPC 的自定义 ACL 保持原样。 diff --git a/web/app/Models/CloudVpcOperation.php b/web/app/Models/CloudVpcOperation.php index 90637d65..005daa91 100644 --- a/web/app/Models/CloudVpcOperation.php +++ b/web/app/Models/CloudVpcOperation.php @@ -19,5 +19,6 @@ final class CloudVpcOperation extends Model 'finished_at' => 'int', 'lease_until' => 'int', 'attempts' => 'int', + 'power_instance_id' => 'int', ]; } diff --git a/web/app/Services/Cloud/CloudJobService.php b/web/app/Services/Cloud/CloudJobService.php index 6115f51e..05bee8d4 100644 --- a/web/app/Services/Cloud/CloudJobService.php +++ b/web/app/Services/Cloud/CloudJobService.php @@ -61,6 +61,10 @@ final class CloudJobService throw new CloudError('请至少填写一项需要修改的实例设置'); } } + // Match the VPC root -> instance lock order before admitting a + // competing power intent. The workflow never owns a lasting VM + // task lock while it waits for the guest to stop. + CloudVpcPowerWorkflow::lockForInstance($instance); $locked = CloudInstance::where('id', $instance->id)->lockForUpdate()->first(); if ($locked === null || (string) $locked->status === 'deleted') { throw new CloudError('虚拟机不存在', 404); @@ -234,6 +238,11 @@ final class CloudJobService 'target_public_ip_pool_id' => $targetPoolId, ]; } + CloudVpcPowerWorkflow::manualIntentLocked( + $locked, $kind, + $kind === 'action' && is_string($body['action'] ?? null) + ? $body['action'] : null + ); $job = new CloudJob(); $job->operation_id = bin2hex(random_bytes(16)); $job->instance_id = $locked->id; diff --git a/web/app/Services/Cloud/CloudVpcDefaultAcl.php b/web/app/Services/Cloud/CloudVpcDefaultAcl.php new file mode 100644 index 00000000..3bfb0628 --- /dev/null +++ b/web/app/Services/Cloud/CloudVpcDefaultAcl.php @@ -0,0 +1,59 @@ + 32760, 'egress' => 32761]; + + /** + * An empty VPC may reserve the exact initial policy without a host. This + * does not attest that an ACL has been installed: its rows remain pending + * until an exact host receipt. Older empty-policy reservations still pass. + */ + public static function matchesEmptyReservation(CloudVpc $vpc): bool + { + $rules = CloudVpcAclRule::where('vpc_id', $vpc->id) + ->whereNotIn('state', ['deleting', 'deleted'])->get(); + if ($rules->isEmpty()) { + return true; + } + $cidr = (string) $vpc->cidr; + if ($rules->count() !== 2 || !str_ends_with($cidr, '/24')) { + return false; + } + $address = substr($cidr, 0, -3); + $network = ip2long($address); + if ($network === false || ($network & 255) !== 0) { + return false; + } + $seen = []; + foreach ($rules as $rule) { + $direction = (string) $rule->direction; + if (isset($seen[$direction]) + || (self::PRIORITIES[$direction] ?? 0) !== (int) $rule->priority + || preg_match('/^[0-9a-f]{32}$/D', (string) $rule->rule_key) !== 1 + || (string) $rule->action !== 'allow' + || (string) $rule->protocol !== 'all' + || $rule->port_from !== null || $rule->port_to !== null + || (int) $rule->desired_revision !== (int) $vpc->desired_revision + || !hash_equals((string) $vpc->desired_digest, (string) $rule->desired_digest)) { + return false; + } + foreach (['source', 'destination'] as $side) { + if ((string) $rule->{$side . '_cidr'} !== $cidr + || (int) $rule->{$side . '_int'} !== $network + || (int) $rule->{$side . '_broadcast_int'} !== ($network + 255) + || (int) $rule->{$side . '_prefix_length'} !== 24) { + return false; + } + } + $seen[$direction] = true; + } + return true; + } +} diff --git a/web/app/Services/Cloud/CloudVpcPowerWorkflow.php b/web/app/Services/Cloud/CloudVpcPowerWorkflow.php new file mode 100644 index 00000000..1fbf60dc --- /dev/null +++ b/web/app/Services/Cloud/CloudVpcPowerWorkflow.php @@ -0,0 +1,507 @@ +power_instance_id = (int) $instance->id; + $operation->power_workflow_json = json_encode([ + 'version' => 1, 'instance_id' => (int) $instance->id, + 'host_id' => (int) $instance->host_id, 'uuid' => (string) $instance->uuid, + 'member_key' => (string) $member->member_key, + 'phase' => 'preflight', 'original_running' => null, + 'resume_cancelled' => false, 'config_confirmed' => false, + 'baseline_job_id' => (int) CloudJob::where('instance_id', $instance->id)->max('id'), + 'shutdown_id' => substr(hash('sha256', $operation->operation_id . ':vpc:shutdown'), 0, 32), + 'start_id' => substr(hash('sha256', $operation->operation_id . ':vpc:start'), 0, 32), + 'error_code' => null, + ], JSON_THROW_ON_ERROR); + $operation->save(); + } + + public static function state(CloudVpcOperation $operation): ?array + { + if ($operation->power_workflow_json === null) { + return null; + } + $state = json_decode((string) $operation->power_workflow_json, true); + if (!is_array($state) || ($state['version'] ?? null) !== 1 + || !is_int($state['instance_id'] ?? null) + || $state['instance_id'] < 1 + || (int) $operation->power_instance_id !== $state['instance_id'] + || !in_array((string) $operation->kind, ['member_attach', 'member_detach'], true) + || !is_int($state['host_id'] ?? null) || $state['host_id'] < 1 + || !is_string($state['uuid'] ?? null) + || preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/D', $state['uuid']) !== 1 + || !is_string($state['member_key'] ?? null) + || preg_match('/^[a-f0-9]{32}$/D', $state['member_key']) !== 1 + || !is_int($state['baseline_job_id'] ?? null) || $state['baseline_job_id'] < 0 + || !is_bool($state['resume_cancelled'] ?? null) + || !is_bool($state['config_confirmed'] ?? null) + || !array_key_exists('original_running', $state) + || ($state['original_running'] !== null && !is_bool($state['original_running'])) + || ($state['shutdown_id'] ?? null) !== substr(hash('sha256', $operation->operation_id . ':vpc:shutdown'), 0, 32) + || ($state['start_id'] ?? null) !== substr(hash('sha256', $operation->operation_id . ':vpc:start'), 0, 32) + || (isset($state['shutdown_deadline']) && (!is_int($state['shutdown_deadline']) || $state['shutdown_deadline'] < 1)) + || (isset($state['start_deadline']) && (!is_int($state['start_deadline']) || $state['start_deadline'] < 1)) + || (($state['phase'] ?? null) === 'paused' && !in_array($state['paused_from'] ?? null, + ['preflight', 'shutting_down', 'waiting_stopped', 'applying', 'configured', 'starting'], true)) + || !in_array($state['phase'] ?? null, ['preflight', 'shutting_down', + 'waiting_stopped', 'applying', 'configured', 'starting', 'paused', 'completed'], true)) { + throw new CloudError('VPC 自动电源任务记录无效', 503, 'vpc_power_record_invalid'); + } + return $state; + } + + public static function publicState(CloudVpcOperation $operation): ?array + { + $state = self::state($operation); + return $state === null ? null : array_intersect_key($state, array_flip([ + 'instance_id', 'phase', 'original_running', 'resume_cancelled', 'error_code', + ])); + } + + public static function unfinished(CloudVpcOperation $operation): bool + { + $state = self::state($operation); + return $state !== null && $state['phase'] !== 'completed'; + } + + private static function requireSchema(): void + { + $schema = (new CloudVpcOperation())->getConnection()->getSchemaBuilder(); + if (!$schema->hasColumn('cloud_vpc_operations', 'power_workflow_json') + || !$schema->hasColumn('cloud_vpc_operations', 'power_instance_id') + || !$schema->hasIndex('cloud_vpc_operations', ['power_instance_id'])) { + throw new CloudError('VPC 数据库需要升级,请先执行数据库更新', 503, + 'vpc_power_schema_required'); + } + } + + private static function instanceOperations(int $instanceId) + { + self::requireSchema(); + // The indexed instance predicate bounds InnoDB's locking read to this + // VM. JSON is verified only after loading; filtering JSON would scan + // and potentially lock unrelated operations under REPEATABLE READ. + return CloudVpcOperation::select('cloud_vpc_operations.*') + ->join('cloud_vpcs as workflow_root', static function ($join): void { + $join->on('workflow_root.id', '=', 'cloud_vpc_operations.vpc_id') + ->on('workflow_root.last_operation_id', '=', 'cloud_vpc_operations.operation_id'); + }) + ->where('cloud_vpc_operations.power_instance_id', $instanceId) + ->whereNotNull('power_workflow_json'); + } + + /** Call before locking the instance row in every manual job transaction. */ + public static function lockForInstance(CloudInstance $instance): void + { + if (!$instance->getConnection()->getSchemaBuilder()->hasColumn('cloud_vpc_operations', 'power_workflow_json')) { + return; // Existing non-VPC installations have no workflow to fence. + } + $ids = self::instanceOperations((int) $instance->id)->orderBy('vpc_id') + ->pluck('vpc_id')->all(); + if ($ids !== []) { + CloudVpc::whereIn('id', $ids)->orderBy('id')->lockForUpdate()->get(); + } + self::$lockedRootIds[(int) $instance->id] = array_map('intval', $ids); + } + + /** Root and instance locks have already been taken by lockForInstance. */ + public static function manualIntentLocked(CloudInstance $instance, + string $kind, ?string $action): void + { + if (!$instance->getConnection()->getSchemaBuilder()->hasColumn('cloud_vpc_operations', 'power_workflow_json')) { + return; + } + $candidates = self::currentInstanceOperations($instance); + foreach ($candidates as $candidate) { + if (!in_array((int) $candidate->vpc_id, self::$lockedRootIds[(int) $instance->id] ?? [], true)) { + throw new CloudError('实例刚开始 VPC 配置,请刷新后重试', 409, + 'vpc_power_workflow_busy'); + } + } + // A new attachment must acquire this same instance lock; after the + // comparison no new current workflow can appear before commit. + foreach ($candidates as $operation) { + $state = self::state($operation); + if ($state === null || $state['phase'] === 'completed') { + continue; + } + if ($kind !== 'action' || !CloudOperationCatalog::isPowerAction((string) $action) + || (in_array($state['phase'], ['shutting_down', 'applying', 'starting'], true) + && (int) $operation->lease_until > time())) { + throw new CloudError('VPC 正在配置该实例,请等待当前步骤完成', 409, + 'vpc_power_workflow_busy'); + } + // No later worker may undo this newer human intent by starting + // the guest. Keep the workflow retryable after a manual force-off. + $state['resume_cancelled'] = true; + if ($state['phase'] === 'preflight') { + $state['phase'] = 'paused'; + $state['paused_from'] = 'preflight'; + $state['error_code'] = 'vpc_power_manual_override'; + $operation->status = 'paused'; + } + self::saveState($operation, $state); + } + } + + /** A current read that cannot deadlock with root -> operation -> instance. */ + private static function currentInstanceOperations(CloudInstance $instance) + { + $lock = match ($instance->getConnection()->getDriverName()) { + 'mysql', 'mariadb' => 'FOR UPDATE NOWAIT', + 'sqlite' => true, + default => throw new CloudError('无法核对 VPC 自动电源任务', 503, 'vpc_power_state_unavailable'), + }; + try { + return self::instanceOperations((int) $instance->id)->lock($lock)->get(); + } catch (QueryException $error) { + $driverCode = (int) ($error->errorInfo[1] ?? 0); + if (in_array($driverCode, [1205, 1213, 3572], true)) { + throw new CloudError('VPC 正在处理实例,请稍后重试', 409, 'vpc_power_workflow_busy'); + } + throw new CloudError('VPC 自动电源任务暂不可核对', 503, 'vpc_power_state_unavailable'); + } + } + + /** Also covers a detached member whose NIC/IP ledger is already removed. */ + public static function assertAttachAllowedLocked(CloudInstance $instance): void + { + if (!$instance->getConnection()->getSchemaBuilder()->hasColumn('cloud_vpc_operations', 'power_workflow_json')) { + return; + } + foreach (self::currentInstanceOperations($instance) as $operation) { + if (self::unfinished($operation)) { + throw new CloudError('该实例仍有 VPC 自动配置任务,请先核对完成', 409, + 'vpc_power_workflow_busy'); + } + } + } + + public static function assertMutationAllowed(CloudVpc $vpc): void + { + if (!$vpc->last_operation_id) { + return; + } + $operation = CloudVpcOperation::where('operation_id', $vpc->last_operation_id)->first(); + if ($operation !== null && self::unfinished($operation)) { + throw new CloudError('请先完成或核对当前 VPC 实例自动配置任务', 409, + 'vpc_power_workflow_busy'); + } + } + + /** Release the PHP worker lease between polls; never wait inside a VM lock. */ + private static function release(CloudVpcOperation $operation, array $state): void + { + $done = $state['phase'] === 'completed'; + $operation->status = $done ? 'succeeded' + : ($state['phase'] === 'paused' ? 'paused' : 'waiting_observed'); + $operation->error_code = $state['error_code'] ?? null; + $operation->finished_at = $done ? time() : null; + $operation->lease_token = null; + $operation->lease_until = 0; + self::saveState($operation, $state); + } + + private static function saveState(CloudVpcOperation $operation, array $state): void + { + $operation->power_workflow_json = json_encode($state, JSON_THROW_ON_ERROR); + $operation->updated_at = time(); + $operation->save(); + } + + /** The root prevents supersession; the instance serializes manual intent. */ + private static function locked(CloudVpcOperation $claimed, string $lease, callable $callback) + { + return $claimed->getConnection()->transaction(static function () use ($claimed, $lease, $callback) { + $root = CloudVpc::where('id', $claimed->vpc_id)->lockForUpdate()->first(); + $operation = CloudVpcOperation::where('id', $claimed->id)->lockForUpdate()->first(); + if ($root === null || $operation === null + || (string) $root->last_operation_id !== (string) $claimed->operation_id + || (int) $root->desired_revision !== (int) $claimed->desired_revision + || (string) $operation->lease_token !== $lease) { + throw new CloudError('VPC 自动配置任务已变化,请重新核对', 409, 'vpc_power_stale'); + } + $state = self::state($operation); + if ($state === null) { + return true; + } + $instance = CloudInstance::where('id', $state['instance_id'])->lockForUpdate()->first(); + if ($instance === null || (string) $instance->uuid !== $state['uuid'] + || (int) $instance->host_id !== $state['host_id']) { + throw new CloudError('VPC 实例身份已变化', 409, 'vpc_power_target_changed'); + } + if (CloudJob::where('instance_id', $instance->id) + ->where('id', '>', $state['baseline_job_id'])->exists()) { + $state['resume_cancelled'] = true; + } + return $callback($root, $operation, $instance, $state); + }); // Never replay an HTTP side effect by retrying a DB transaction. + } + + private static function powerState(CloudEngineClient $client, array $actor, array $state): string + { + $result = $client->host($state['host_id'], 'GET', 'vms/' . $state['uuid'] . '/state', $actor); + if (($result['uuid'] ?? null) !== $state['uuid'] + || !in_array($result['state'] ?? null, ['running', 'shutoff', 'shutdown'], true)) { + throw new CloudError('无法安全核对实例电源状态', 409, 'vpc_power_state_unavailable'); + } + return $result['state']; + } + + private static function pause(CloudVpc $root, CloudVpcOperation $operation, array $state, + string $code): void + { + $state['paused_from'] = $state['phase']; + $state['phase'] = 'paused'; + $state['error_code'] = $code; + self::release($operation, $state); + $root->state = 'degraded'; + $root->sync_state = 'waiting'; + $root->last_error_code = $code; + $root->save(); + } + + /** Return true only when a stopped guest may enter the existing apply lane. */ + public static function beforeApply(CloudVpcOperation $operation, string $lease, + array $actor, bool $explicitRetry, ?CloudEngineClient $client = null): bool + { + if (!self::unfinished($operation)) { + return true; + } + $client ??= new CloudEngineClient(); + $phase = self::locked($operation, $lease, static function ($root, $row, $instance, $state) + use ($client, $actor, $explicitRetry): string { + if ($state['phase'] === 'paused') { + if (!$explicitRetry) { + self::release($row, $state); + return 'paused'; + } + $state['phase'] = $state['paused_from'] ?? 'waiting_stopped'; + $state['error_code'] = null; + $state['shutdown_deadline'] = time() + self::SHUTDOWN_SECONDS; + if ($state['phase'] === 'starting') { + $state['start_deadline'] = time() + self::SHUTDOWN_SECONDS; + } + } + if ((string) $instance->status !== 'active' || !$instance->serviceAvailable() + || CloudJob::where('instance_id', $instance->id) + ->whereIn('status', ['queued', 'running', 'uncertain'])->exists()) { + self::pause($root, $row, $state, 'vpc_power_instance_busy'); + return 'paused'; + } + if ($state['phase'] === 'preflight') { + $power = self::powerState($client, $actor, $state); + $state['original_running'] = $power === 'running'; + $state['phase'] = $power === 'shutoff' ? 'applying' + : ($power === 'shutdown' || $state['resume_cancelled'] === true + ? 'waiting_stopped' : 'shutting_down'); + $state['shutdown_deadline'] = time() + self::SHUTDOWN_SECONDS; + } + if ($state['phase'] === 'waiting_stopped') { + if (self::powerState($client, $actor, $state) === 'shutoff') { + $state['phase'] = 'applying'; + } elseif (time() >= (int) $state['shutdown_deadline']) { + self::pause($root, $row, $state, 'vpc_power_shutdown_timeout'); + return 'paused'; + } else { + self::release($row, $state); + return 'waiting_stopped'; + } + } + if ($state['phase'] === 'applying' + && self::powerState($client, $actor, $state) !== 'shutoff') { + self::pause($root, $row, $state, 'vpc_power_manual_override'); + return 'paused'; + } + self::saveState($row, $state); + return $state['phase']; + }); + if ($phase === 'shutting_down') { + self::command($operation, $lease, $actor, 'shutdown', $client); + return false; + } + if (in_array($phase, ['configured', 'starting'], true)) { + self::afterApply($operation, $lease, $actor, $client); + return false; + } + return $phase === 'applying' || $phase === 'completed'; + } + + /** Called under recordObserved's root/operation locks after strict proof. */ + public static function configurationObserved(CloudVpcOperation $operation, bool $confirmed): bool + { + $state = self::state($operation); + if ($state === null || $state['phase'] === 'completed') { + return false; + } + if ($confirmed && $state['phase'] === 'applying') { + $state['config_confirmed'] = true; + $state['phase'] = 'configured'; + } + self::saveState($operation, $state); + return true; + } + + /** Preflight failures have no remote mutation uncertainty of their own. */ + public static function handleFailure(CloudVpcOperation $operation, string $lease, + CloudError $error): bool + { + if (!self::unfinished($operation)) { + return false; + } + self::locked($operation, $lease, static function ($root, $row, $instance, $state) + use ($error): void { + self::pause($root, $row, $state, + in_array($state['phase'], ['preflight', 'waiting_stopped'], true) + ? 'vpc_power_state_unavailable' + : (in_array($error->errorCode, ['vpc_power_state_unavailable', 'vpc_power_instance_busy'], true) + ? $error->errorCode : 'vpc_power_result_uncertain')); + }); + return true; + } + + public static function afterApply(CloudVpcOperation $operation, string $lease, + array $actor, ?CloudEngineClient $client = null): void + { + if (!self::unfinished($operation)) { + return; + } + $client ??= new CloudEngineClient(); + $start = self::locked($operation, $lease, static function ($root, $row, $instance, $state): bool { + if (!($state['config_confirmed'] ?? false)) { + self::pause($root, $row, $state, 'vpc_power_configuration_unconfirmed'); + return false; + } + if ($state['original_running'] !== true || $state['resume_cancelled'] === true + || (string) $instance->status !== 'active' || !$instance->serviceAvailable() + || in_array((string) $instance->network_status, + ['blocking', 'blocking_expired', 'blocked_expired', 'restore_pending', 'restoring'], true)) { + $state['phase'] = 'completed'; + self::release($row, $state); + return false; + } + if ($state['phase'] !== 'starting') { + $state['start_deadline'] = time() + self::SHUTDOWN_SECONDS; + $state['phase'] = 'starting'; + } + self::saveState($row, $state); + return true; + }); + if ($start) { + self::command($operation, $lease, $actor, 'start', $client); + } + } + + /** The fixed child ID and committed phase precede every network dispatch. */ + private static function command(CloudVpcOperation $operation, string $lease, + array $actor, string $action, CloudEngineClient $client): void + { + self::locked($operation, $lease, static function ($root, $row, $instance, $state) + use ($actor, $action, $client): void { + $id = $state[$action === 'start' ? 'start_id' : 'shutdown_id']; + $commandActor = array_replace($actor, ['operation_id' => $id]); + try { + try { + $result = $client->request('GET', '/internal/v1/operations/' . $id, + $commandActor, null, $id); + } catch (CloudError $error) { + if ($error->httpStatus !== 404) { + throw $error; + } + if ($action === 'start' && $state['resume_cancelled'] === true) { + $state['phase'] = 'completed'; + self::release($row, $state); + return; + } + if ($action === 'shutdown' && $state['resume_cancelled'] === true) { + // The old worker may have died after persisting intent + // but before sending it. A newer manual start wins. + $state['phase'] = self::powerState($client, $actor, $state) === 'shutoff' + ? 'applying' : 'waiting_stopped'; + self::release($row, $state); + return; + } + if ((string) $instance->status !== 'active' || !$instance->serviceAvailable() + || CloudJob::where('instance_id', $instance->id) + ->whereIn('status', ['queued', 'running', 'uncertain'])->exists()) { + self::pause($root, $row, $state, 'vpc_power_instance_busy'); + return; + } + $result = $client->host($state['host_id'], 'POST', + 'vms/' . $state['uuid'] . '/actions', $commandActor, + ['action' => $action], $id); + } + $receipt = $result['result'] ?? null; + if (($result['operation_id'] ?? null) === $id + && in_array($result['status'] ?? null, ['queued', 'running', 'pending'], true)) { + if (time() >= (int) ($state[$action === 'start' ? 'start_deadline' : 'shutdown_deadline'] ?? 0)) { + self::pause($root, $row, $state, 'vpc_power_result_uncertain'); + } else { + self::release($row, $state); + } + return; + } + if (($result['operation_id'] ?? null) === $id + && ($result['status'] ?? null) === 'failed' + && (($result['execution_outcome'] ?? null) === 'not_dispatched' + || ($result['mutation_started'] ?? null) === false)) { + if ($action === 'shutdown' + && self::powerState($client, $actor, $state) === 'shutoff') { + $state['phase'] = 'applying'; + $state['error_code'] = null; + self::release($row, $state); + return; + } + if ($action === 'start' && $state['resume_cancelled'] === true) { + $state['phase'] = 'completed'; + $state['error_code'] = null; + self::release($row, $state); + return; + } + self::pause($root, $row, $state, 'vpc_power_command_rejected'); + return; + } + if (($result['operation_id'] ?? null) !== $id + || ($result['status'] ?? null) !== 'succeeded' + || !is_array($receipt) || ($receipt['command_accepted'] ?? null) !== true + || ($receipt['uuid'] ?? null) !== $state['uuid'] + || ($receipt['action'] ?? null) !== $action) { + self::pause($root, $row, $state, 'vpc_power_result_uncertain'); + return; + } + $state[$action . '_accepted'] = true; + $state['phase'] = $action === 'start' ? 'completed' : 'waiting_stopped'; + $state['error_code'] = null; + self::release($row, $state); + } catch (CloudError $error) { + self::pause($root, $row, $state, 'vpc_power_result_uncertain'); + } + }); + } +} diff --git a/web/app/Services/Cloud/CloudVpcService.php b/web/app/Services/Cloud/CloudVpcService.php index 9428d53b..1ffc902e 100644 --- a/web/app/Services/Cloud/CloudVpcService.php +++ b/web/app/Services/Cloud/CloudVpcService.php @@ -255,6 +255,37 @@ final class CloudVpcService $row->updated_at = $now; $row->save(); + // Seed editable member-to-member defaults only for a new + // VPC. Create replay returns above, so it never restores a + // rule that the owner later removed or changed. Both ends + // stay within this VPC's allocated /24; host/public/foreign + // VPC isolation remains enforced by the engine. + foreach (CloudVpcDefaultAcl::PRIORITIES as $direction => $priority) { + $rule = new CloudVpcAclRule(); + $rule->rule_key = self::randomKey(); + $rule->vpc_id = $vpc->id; + $rule->priority = $priority; + $rule->direction = $direction; + $rule->action = 'allow'; + $rule->protocol = 'all'; + foreach (['source', 'destination'] as $side) { + $rule->{$side . '_cidr'} = $subnetValue['cidr']; + $rule->{$side . '_int'} = $subnetValue['network']; + $rule->{$side . '_broadcast_int'} = $subnetValue['broadcast']; + $rule->{$side . '_prefix_length'} = $subnetValue['prefix']; + } + $rule->port_from = null; + $rule->port_to = null; + $rule->state = 'applying'; + $rule->desired_revision = 0; + $rule->observed_revision = 0; + $rule->desired_digest = null; + $rule->observed_digest = null; + $rule->last_error_code = null; + $rule->created_at = $rule->updated_at = $now; + $rule->save(); + } + $result = self::touchDesiredLocked($vpc, 'vpc_create', $requestKey, $requestHash); return self::documentView($result['vpc'], $actor); }, 3); @@ -344,13 +375,17 @@ final class CloudVpcService // already committed operation during a rolling UI/API deployment. // They can never create a new member under the automatic policy. CloudInput::only($input, [ - 'instance_id', 'request_key', 'subnet_key', 'private_ip', + 'instance_id', 'request_key', 'subnet_key', 'private_ip', 'auto_power', ]); + $autoPower = CloudVpcPowerWorkflow::requested($input); $key = self::requestKey($input['request_key'] ?? null); $instanceId = self::positiveInt($input['instance_id'] ?? null, 1, 1000000000, '虚拟机无效'); $hasLegacySubnet = array_key_exists('subnet_key', $input); $hasLegacyIp = array_key_exists('private_ip', $input); + if ($hasLegacySubnet && $autoPower) { + throw new CloudError('自动电源流程不接受旧子网参数,请刷新页面', 422); + } if ($hasLegacyIp && !$hasLegacySubnet) { throw new CloudError('私网 IP 只能由平台自动分配,请刷新页面后重试', 422); } @@ -388,11 +423,11 @@ final class CloudVpcService // was lost must still resolve the original operation even if the VM's // runtime state or host-region mapping has changed in the meantime. $prepared = $vpc->getConnection()->transaction(function () use ( - $vpc, $actor, $key, $instanceId, $legacyRequestHash + $vpc, $actor, $key, $instanceId, $legacyRequestHash, $autoPower ): array { $locked = self::lockOwned($vpc->vpc_key, $actor); if (self::hasMemberAttachOperation( - $locked, $key, $instanceId, $legacyRequestHash + $locked, $key, $instanceId, $legacyRequestHash, $autoPower )) { return [ 'request_hash' => null, @@ -413,7 +448,7 @@ final class CloudVpcService 'subnet_key' => (string) $subnet->subnet_key, 'instance_id' => $instanceId, 'private_ip' => null, - ]); + ] + ($autoPower ? ['auto_power' => true] : [])); return [ 'request_hash' => $requestHash, 'subnet_key' => (string) $subnet->subnet_key, @@ -438,11 +473,11 @@ final class CloudVpcService } return $vpc->getConnection()->transaction(function () use ( $vpc, $actor, $key, $requestHash, $instanceId, $automaticSubnetKey, - $legacyRequestHash + $legacyRequestHash, $autoPower ): array { $vpc = self::lockOwned($vpc->vpc_key, $actor); if (self::hasMemberAttachOperation( - $vpc, $key, $instanceId, $legacyRequestHash + $vpc, $key, $instanceId, $legacyRequestHash, $autoPower )) { return self::documentView($vpc, $actor); } @@ -504,6 +539,7 @@ final class CloudVpcService : '首版每台虚拟机只能加入一个 VPC'; throw new CloudError($message, 409); } + CloudVpcPowerWorkflow::assertAttachAllowedLocked($instance); // A lease without its member is not reusable capacity. It can // represent a partially migrated/corrupt ledger or an unproven // host-side address, so do not let the global member unique key be @@ -596,6 +632,9 @@ final class CloudVpcService $member->private_ip_id = $privateIp->id; $member->save(); $result = self::touchDesiredLocked($vpc, 'member_attach', $key, $requestHash); + if ($autoPower) { + CloudVpcPowerWorkflow::initialize($result['operation'], $instance, $member); + } return self::documentView($result['vpc'], $actor); }, 3); } @@ -603,13 +642,15 @@ final class CloudVpcService public static function detachMember(string $vpcKey, string $memberKey, array $actor, array $input): array { - CloudInput::only($input, ['request_key']); + CloudInput::only($input, ['request_key', 'auto_power']); + $autoPower = CloudVpcPowerWorkflow::requested($input); $key = self::requestKey($input['request_key'] ?? null); self::assertKey($memberKey, '成员'); - $requestHash = self::requestHash('member_detach', ['member_key' => $memberKey]); + $requestHash = self::requestHash('member_detach', ['member_key' => $memberKey] + + ($autoPower ? ['auto_power' => true] : [])); $vpc = self::lockOwned($vpcKey, $actor); return $vpc->getConnection()->transaction(function () use ( - $vpc, $memberKey, $actor, $key, $requestHash + $vpc, $memberKey, $actor, $key, $requestHash, $autoPower ): array { $vpc = self::lockOwned($vpc->vpc_key, $actor); if (self::hasOperation($vpc, $key, 'member_detach', $requestHash)) { @@ -642,6 +683,9 @@ final class CloudVpcService $privateIp->updated_at = time(); $privateIp->save(); $result = self::touchDesiredLocked($vpc, 'member_detach', $key, $requestHash); + if ($autoPower) { + CloudVpcPowerWorkflow::initialize($result['operation'], $instance, $member); + } return self::documentView($result['vpc'], $actor); }, 3); } @@ -925,7 +969,7 @@ final class CloudVpcService // Keep the original immutable operation and target; // the worker does not automatically select failed rows. $query->orWhere(function ($failed) use ($locked): void { - $failed->where('status', 'failed') + $failed->whereIn('status', ['failed', 'paused']) ->where('operation_id', (string) $locked->last_operation_id) ->where('desired_revision', @@ -1048,6 +1092,11 @@ final class CloudVpcService [$operation, $payload, $runtimeProofRefresh, $previousOutcomePending] = $claim; $leaseToken = (string) $operation->lease_token; try { + if (!CloudVpcPowerWorkflow::beforeApply( + $operation, $leaseToken, $actor, $allowFailedRetry + )) { + return self::show($vpcKey, $actor); + } if ((string) $operation->kind === 'vpc_delete') { $result = (new CloudEngineClient( null, self::ENGINE_TIMEOUT_SECONDS @@ -1132,8 +1181,12 @@ final class CloudVpcService self::recordObserved($vpcKey, (int) ($payload['desired_revision'] ?? 0), (string) ($payload['desired_digest'] ?? ''), $observed, (string) $operation->operation_id, $leaseToken); + CloudVpcPowerWorkflow::afterApply($operation, $leaseToken, $actor); return self::show($vpcKey, $actor); } catch (CloudError $error) { + if (CloudVpcPowerWorkflow::handleFailure($operation, $leaseToken, $error)) { + return self::show($vpcKey, $actor); + } // A rejection of this retry cannot prove that an earlier remote // attempt did nothing. Only exact readback may close that result. $status = $previousOutcomePending || $error->httpStatus >= 500 @@ -2053,7 +2106,8 @@ final class CloudVpcService && ($desired['hosts'] ?? null) === [] && ($desired['members'] ?? null) === [] && ($desired['routes'] ?? null) === [] - && ($desired['acls'] ?? null) === [] + && is_array($desired['acls'] ?? null) + && CloudVpcDefaultAcl::matchesEmptyReservation($vpc) && is_array($desired['subnets'] ?? null) && count($desired['subnets']) === 1 && $emptyAutomaticSubnetValid @@ -2066,8 +2120,6 @@ final class CloudVpcService && !CloudVpcPrivateIp::where('vpc_id', $vpc->id) ->whereNotIn('state', ['deleting', 'deleted'])->exists() && !CloudVpcRoute::where('vpc_id', $vpc->id) - ->whereNotIn('state', ['deleting', 'deleted'])->exists() - && !CloudVpcAclRule::where('vpc_id', $vpc->id) ->whereNotIn('state', ['deleting', 'deleted'])->exists(); $emptyControlPlaneComplete = $noDataPlaneTerminalProof && (string) $operation->kind === 'vpc_create' @@ -2342,8 +2394,14 @@ final class CloudVpcService $operation->updated_at = time(); $operation->finished_at = ($operationSucceeded || $dataPlaneDeferred || $terminalFailure) ? time() : null; - $operation->lease_token = null; - $operation->lease_until = 0; + $powerPending = CloudVpcPowerWorkflow::configurationObserved($operation, $operationSucceeded); + if ($powerPending && $leaseToken !== null) { + $operation->status = 'running'; + $operation->finished_at = null; + } else { + $operation->lease_token = null; + $operation->lease_until = 0; + } $operation->save(); $vpc->observed_revision = $operationSucceeded ? $revision : (int) $vpc->observed_revision; $vpc->observed_digest = $operationSucceeded ? $digest : $vpc->observed_digest; @@ -4429,6 +4487,7 @@ final class CloudVpcService } return ['vpc' => $vpc, 'operation' => $existing, 'unchanged' => true]; } + CloudVpcPowerWorkflow::assertMutationAllowed($vpc); self::assertMemberTasksIdleLocked($vpc); $revision = (int) $vpc->desired_revision + 1; $vpc->desired_revision = $revision; @@ -4618,7 +4677,8 @@ final class CloudVpcService CloudVpc $vpc, string $requestKey, int $instanceId, - ?string $legacyRequestHash = null + ?string $legacyRequestHash = null, + bool $autoPower = false ): bool { $operation = CloudVpcOperation::where('vpc_id', $vpc->id) ->where('idempotency_key', $requestKey) @@ -4666,12 +4726,12 @@ final class CloudVpcService 'subnet_key' => (string) $member['subnet_id'], 'instance_id' => $instanceId, 'private_ip' => null, - ]); + ] + ($autoPower ? ['auto_power' => true] : [])); $explicitHash = self::requestHash('member_attach', [ 'subnet_key' => (string) $member['subnet_id'], 'instance_id' => $instanceId, 'private_ip' => $match[1], - ]); + ] + ($autoPower ? ['auto_power' => true] : [])); if (hash_equals((string) $operation->request_hash, $automaticHash) || hash_equals((string) $operation->request_hash, $explicitHash)) { return true; @@ -4985,8 +5045,7 @@ final class CloudVpcService ->whereNotIn('state', ['deleting', 'deleted'])->exists() && !CloudVpcRoute::where('vpc_id', $vpc->id) ->whereNotIn('state', ['deleting', 'deleted'])->exists() - && !CloudVpcAclRule::where('vpc_id', $vpc->id) - ->whereNotIn('state', ['deleting', 'deleted'])->exists(); + && CloudVpcDefaultAcl::matchesEmptyReservation($vpc); // A successful exact operation is already the signed proof // for its revision. Rehashing the current document would // reject a valid last-member detach because the released @@ -5001,7 +5060,7 @@ final class CloudVpcService && ($emptyDesired['hosts'] ?? null) === [] && ($emptyDesired['members'] ?? null) === [] && ($emptyDesired['routes'] ?? null) === [] - && ($emptyDesired['acls'] ?? null) === [] + && is_array($emptyDesired['acls'] ?? null) && is_array($emptyDesired['subnets'] ?? null) && count($emptyDesired['subnets']) === 1 && self::digestMatches( @@ -5093,6 +5152,7 @@ final class CloudVpcService return ['operation_id' => (string) $row->operation_id, 'kind' => (string) $row->kind, 'desired_revision' => (int) $row->desired_revision, 'status' => (string) $row->status, 'evidence_version' => (int) ($row->evidence_version ?? 0), + 'power_workflow' => CloudVpcPowerWorkflow::publicState($row), 'error_code' => self::safeErrorCode((string) ($row->error_code ?? '')), 'created_at' => (int) $row->created_at, 'updated_at' => (int) $row->updated_at, 'finished_at' => $row->finished_at === null ? null : (int) $row->finished_at]; diff --git a/web/public/cloud/vpc.css b/web/public/cloud/vpc.css index 037463df..b28fa098 100644 --- a/web/public/cloud/vpc.css +++ b/web/public/cloud/vpc.css @@ -2,6 +2,12 @@ .vpc-tombstone-row{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:11px 12px;border:1px dashed #e6c9a8;border-radius:8px;background:#fffaf2;color:#8a6a3b}.vpc-tombstone-row strong{overflow-wrap:anywhere;font-size:11px}.vpc-tombstone-row small{color:#a17e4d;font-size:9px;line-height:1.4;text-align:right} body.vpc-modal-open{overflow:hidden} +.vpc-power-workflow { border-color: #cfe6e6; background: #f4fbfa; } +.vpc-power-workflow.paused { border-color: #f0d8aa; background: #fff8eb; } +.vpc-power-phase { display: block; color: #285563; font-size: 14px; line-height: 1.6; } +.vpc-power-workflow.paused .vpc-power-phase { color: #916323; } +.vpc-state-pill.paused { background: #fff5e3; color: #a26d1e; } +.vpc-power-guidance { margin: 10px 0 0; color: #617d8b; font-size: 12px; line-height: 1.8; overflow-wrap: anywhere; } .vpc-create-availability{max-width:210px;color:#9a6a22;font-size:10px;line-height:1.45;text-align:right} .vpc-create-backdrop{z-index:80} .vpc-create-backdrop[hidden]{display:none} diff --git a/web/public/cloud/vpc.js b/web/public/cloud/vpc.js index 6f969a78..4d1e5f35 100644 --- a/web/public/cloud/vpc.js +++ b/web/public/cloud/vpc.js @@ -14,7 +14,7 @@ const STATUS_LABELS = Object.freeze({ applying: '应用中', waiting: '等待宿主机回读', uncertain: '结果待核对', degraded: '部分失败', active: '已生效', suspended: '网络已暂停', deleting: '清理中', succeeded: '已完成', failed: '失败', queued: '排队中', - running: '执行中', unknown: '状态未知', + running: '执行中', paused: '已暂停', unknown: '状态未知', }); const EMPTY_MEMBER_GATE_CODES = Object.freeze(new Set([ @@ -199,6 +199,13 @@ function errorLabel(code) { vpc_private_guest_route_mismatch: '实例内的私网路由与当前 VPC 配置不一致,请检查私网路由后重新核对。', vpc_private_guest_link_mismatch: '实例内的私网网卡尚未正常连通,请检查网卡状态后重新核对。', vpc_instance_operation_pending: '成员实例还有未完成或结果待核对的任务,请先在实例详情中核对任务,再修改 VPC。', + vpc_power_shutdown_timeout: '正常关机等待超时,自动流程已暂停,平台未强制断电。可在实例详情检查电源,必要时手动强制断电,再点击“核对 / 重试”继续。', + vpc_power_result_uncertain: '电源请求的执行结果未确认,请先在实例详情核对原操作;不要重复提交加入或退出。', + vpc_power_state_unavailable: '当前实例电源状态不支持自动处理。请在实例详情核对状态,处理后再点击“核对 / 重试”。', + vpc_power_instance_busy: '实例还有其他任务或服务暂不可用,自动流程已暂停。请先在实例详情处理,再点击“核对 / 重试”。', + vpc_power_manual_override: '检测到新的手动电源操作,自动流程已暂停。确认实例状态后可点击“核对 / 重试”;本次流程不再自动恢复开机。', + vpc_power_command_rejected: '电源命令已确认未执行,自动流程已暂停。请在实例详情手动完成所需的关机或开机,再点击“核对 / 重试”;该按钮不会重新发送已失败的电源命令,手动操作后也不会再自动恢复开机。', + vpc_power_configuration_unconfirmed: '私网配置尚未完整确认,自动流程已暂停。请联系管理员核对宿主机;如需先恢复业务,可在实例详情处理电源。修复后再点击“核对 / 重试”,不要重复加入或退出。', }[String(code || '')] || ''; } @@ -206,6 +213,62 @@ function operationLabel(kind) { return OPERATION_LABELS[String(kind || '')] || safeText(kind, '未知操作'); } +function powerWorkflow(doc = state.selected) { + const operationId = String(doc?.vpc?.last_operation_id || ''); + if (!operationId) return null; + const operation = doc?.operations?.find(row => row.operation_id === operationId + && ['member_attach', 'member_detach'].includes(row.kind)); + const value = operation?.power_workflow; + if (!value || typeof value !== 'object' || Array.isArray(value)) return null; + const removing = operation.kind === 'member_detach'; + const phases = { + preflight: ['准备自动处理', '正在核对实例电源状态和本次私网操作。'], + shutting_down: ['正在请求正常关机', '只发送正常关机请求,不会自动强制断电。'], + waiting_stopped: ['等待实例完全关机', '关机请求已提交;确认实例停止后才会修改私网配置。'], + applying: [removing ? '正在移除私网配置' : '正在写入私网配置', + '正在应用并核对实例私网网卡和网络配置。'], + configured: ['私网配置已确认', '正在处理本次操作后的电源状态。'], + starting: ['正在恢复开机', '私网配置已确认,正在恢复原本运行的实例。'], + paused: ['自动流程已暂停', '请核对实例和最近操作,处理后点击“核对 / 重试”继续。'], + completed: ['自动流程已完成', removing + ? '退出和电源处理已完成;私网地址以清理回读结果为准。' + : '加入和电源处理已完成;来宾网络可用性将单独核验。'], + }; + const phase = String(value.phase || ''); + if (!Object.prototype.hasOwnProperty.call(phases, phase)) return null; + const instanceId = Number(value.instance_id); + return { + phase, title: phases[phase][0], description: phases[phase][1], + operationLabel: operationLabel(operation.kind), + instanceId: Number.isSafeInteger(instanceId) && instanceId > 0 ? instanceId : null, + originalRunning: typeof value.original_running === 'boolean' ? value.original_running : null, + resumeCancelled: value.resume_cancelled === true, + error: errorLabel(value.error_code), + }; +} + +function renderPowerWorkflow(doc) { + const workflow = powerWorkflow(doc); + if (!workflow) return null; + const title = `${workflow.operationLabel}进度${workflow.instanceId + ? ` · ${instanceName(workflow.instanceId)}` : ''}`; + const card = section(title, workflow.description, `vpc-power-workflow ${workflow.phase}`); + card.append(element('strong', 'vpc-power-phase', workflow.title)); + if (workflow.error) card.append(element('p', 'vpc-power-guidance', workflow.error)); + if (workflow.resumeCancelled) { + card.append(element('p', 'vpc-power-guidance', + '已检测到新的手动电源操作,本次流程不再自动恢复开机;后续电源状态由你控制。')); + } else if (workflow.originalRunning === false) { + card.append(element('p', 'vpc-power-guidance', '实例原本已关机,本次操作会保持关机。')); + } + return card; +} + +function hasPendingPowerWorkflow(doc = state.selected) { + const workflow = powerWorkflow(doc); + return Boolean(workflow && workflow.phase !== 'completed'); +} + function regionName(regionId) { const row = state.regions.find(item => Number(item.id) === Number(regionId)); return row ? safeText(row.name, `地区 ${regionId}`) : `地区 ${regionId || '未知'}`; @@ -261,10 +324,12 @@ function normalizeDocument(value) { function needsPolling() { const fastStatuses = new Set(['applying', 'waiting', 'uncertain', 'degraded', 'deleting']); + const workflow = powerWorkflow(); return Boolean(state.vpcs.some(vpc => fastStatuses.has(rootStatus( state.selected?.vpc?.vpc_key === vpc.vpc_key ? state.selected.vpc : vpc ))) - || (state.selected && fastStatuses.has(rootStatus(state.selected.vpc)))); + || (state.selected && fastStatuses.has(rootStatus(state.selected.vpc))) + || (workflow && !['paused', 'completed'].includes(workflow.phase))); } function markDetailDirty() { @@ -433,7 +498,8 @@ function renderList() { const reconcile = byId('vpc-list-reconcile'); const selectedStatus = rootStatus(selectedDocumentCurrent() ? state.selected.vpc : null); const canReconcile = selectedDocumentCurrent() - && (!['active', 'awaiting_members'].includes(selectedStatus) || hasMemberCleanup()); + && (!['active', 'awaiting_members'].includes(selectedStatus) || hasMemberCleanup() + || hasPendingPowerWorkflow()); reconcile.hidden = !canReconcile; reconcile.disabled = !canReconcile || state.busy; renderSummary(); @@ -542,7 +608,8 @@ function renderDetail() { addMember.disabled = state.busy; actions.append(addMember); } - if (!['active', 'awaiting_members'].includes(status) || hasMemberCleanup(doc)) { + if (!['active', 'awaiting_members'].includes(status) || hasMemberCleanup(doc) + || hasPendingPowerWorkflow(doc)) { reconcile = button('核对 / 重试', 'button button-primary small'); reconcile.dataset.vpcAction = 'reconcile'; reconcile.disabled = state.busy; @@ -560,6 +627,8 @@ function renderDetail() { overview.append(overviewHeading, facts); container.append(overview); + const workflow = renderPowerWorkflow(doc); + if (workflow) container.append(workflow); if (status === 'awaiting_members') container.append(renderSetupGuide()); container.append(renderMembers(doc)); const policyAvailable = hasPolicyMember(doc); @@ -661,7 +730,7 @@ function refreshMemberChoices() { } function renderMembers(doc) { - const card = section('成员与私网 IP', '平台自动分配私网 IP。首次加入请先完全关机,提交后点“核对 / 重试”写入配置,再启动实例等待来宾网络核验。', 'vpc-members'); + const card = section('成员与私网 IP', '加入或退出时,平台会自动正常关机、修改私网配置,再恢复原本运行的实例;原本已关机的实例保持关机。运行中的实例会短暂中断服务,关机超时不会自动强制断电。', 'vpc-members'); const form = element('form', 'vpc-inline-form vpc-member-form'); form.dataset.vpcForm = 'member'; const instance = input('选择实例', '', 'select'); instance.control.name = 'instance_id'; instance.control.required = true; instance.control.id = 'vpc-member-instance'; @@ -781,7 +850,7 @@ function aclRow(value = {}) { } function renderAcl(doc) { - const card = section('VPC ACL', '默认策略由数据面保持拒绝;这里只提交结构化规则,不会修改实例公网防火墙。保存会替换整套 ACL。', 'vpc-acl'); + const card = section('VPC ACL', '新建 VPC 自动添加本 VPC /24 网段入站、出站允许规则,让组内实例互通;不匹配规则的通信仍默认拒绝。规则可编辑或删除,保存会替换整套 ACL,不会修改实例公网防火墙。', 'vpc-acl'); const list = element('div', 'vpc-editor-list'); list.id = 'vpc-acl-editor'; const tombstones = doc.acl_rules.filter(row => ['deleting', 'deleted'].includes(childStatus(row.state))); const editable = doc.acl_rules.filter(row => !['deleting', 'deleted'].includes(childStatus(row.state))); @@ -1111,9 +1180,10 @@ async function submitMember(form) { refreshMemberChoices(); return; } - const body = { instance_id: instanceId, request_key: requestKey('member-add') }; + if (!confirm(`确认将“${instanceName(instanceId)}”加入 VPC?运行中的实例将自动正常关机,写入私网配置后恢复开机,期间服务会中断;原本已关机的实例保持关机。关机超时会暂停,平台不会自动强制断电。`)) return; + const body = { instance_id: instanceId, auto_power: true, request_key: requestKey('member-add') }; await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/members`, 'POST', body, - '实例已加入 VPC 目标。请完全关机后点“核对 / 重试”写入配置,再启动实例等待来宾网络核验。'); + '已提交加入 VPC,平台将自动处理关机、私网配置和开机恢复。可在下方查看进度;私网可用性将单独核验。'); } function readRoutes() { @@ -1172,7 +1242,8 @@ async function reconcile() { if (!state.busy) setError('VPC 详情尚未读取完成,请等待刷新后再核对。'); return; } - if (rootStatus(state.selected?.vpc) === 'awaiting_members' && !hasMemberCleanup()) { + if (rootStatus(state.selected?.vpc) === 'awaiting_members' && !hasMemberCleanup() + && !hasPendingPowerWorkflow()) { setNotice('VPC 正在等待实例;添加同地区实例后会自动生成新的配置版本。', 'warning'); return; } @@ -1183,9 +1254,9 @@ async function reconcile() { async function removeMember(key) { if (!state.selectedKey || state.busy || !allowSelectedMutation() || !confirmDetailMutation() - || !confirm('确认让这个实例退出 VPC?若已有私网配置,请先完全关机再核对清理;从未实际加入的实例会自动核对。清理确认前,私网 IP 不会重新分配。')) return; + || !confirm('确认让这个实例退出 VPC?运行中的实例将自动正常关机,移除私网配置后恢复开机,期间服务会中断;原本已关机的实例保持关机。关机超时会暂停,不会自动强制断电。清理确认前,私网 IP 不会重新分配。')) return; await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/members/${encodeURIComponent(key)}`, - 'DELETE', { request_key: requestKey('member-remove') }, '成员退出目标已提交,等待私网网卡移除回读。'); + 'DELETE', { auto_power: true, request_key: requestKey('member-remove') }, '已提交退出 VPC,平台将自动处理关机、私网清理和开机恢复;清理确认前私网 IP 会继续保留。'); } async function deleteVpc() { diff --git a/web/resources/views/venix/cloud/pages/vpcs.tpl b/web/resources/views/venix/cloud/pages/vpcs.tpl index 9a5c24d4..5aacb9cb 100644 --- a/web/resources/views/venix/cloud/pages/vpcs.tpl +++ b/web/resources/views/venix/cloud/pages/vpcs.tpl @@ -43,7 +43,7 @@
填写名称并选择地区,平台会自动绑定 Fabric、分配独立 /24 网段并建立唯一子网。
填写名称并选择地区,平台会自动绑定 Fabric、分配独立 /24 网段并建立唯一子网。新 VPC 默认允许本 /24 网段入站和出站通信,组内实例无需逐台配置 ACL。