'succeeded', 'failed' => 'failed', 'uncertain' => 'inconclusive', ]; private const SUMMARY_LABELS = [ 'operation_succeeded' => '只读证据与宿主机成功结果一致', 'operation_failed' => '只读证据与宿主机失败结果一致', 'evidence_incomplete' => '只读证据不足;原任务终态保持不变', 'abortable_job_active' => '检测到活动作业;本接口不会中止或续作', 'cleanup_required' => '检测到残留;本接口不会自动清理', ]; private const INSPECTION_ERROR_LABELS = [ 'creation_absent' => '宿主机未发现虚拟机或面板管理资源', 'expected_state_resource_absent' => '目标虚拟机不存在', 'settings_not_committed' => '实例设置没有提交', 'network_not_committed' => '网络变更没有提交', 'network_state_not_applied' => '虚拟机网卡未达到请求状态', 'service_state_not_applied' => '虚拟机服务未达到请求状态', 'firewall_not_committed' => '防火墙策略没有提交', 'rescue_not_committed' => '救援系统没有启用', 'rescue_force_start_incomplete' => '救援系统已准备但未成功启动', 'rescue_exit_incomplete' => '救援系统仍处于准备或运行状态', 'reinstall_not_committed' => '系统盘没有切换', 'snapshot_not_created' => '快照没有创建', 'snapshot_not_deleted' => '快照仍然存在', 'snapshot_not_restored' => '系统盘没有切换到快照', 'storage_configuration_mismatch' => '固定存储池与面板配置不一致', 'storage_configuration_incomplete' => '存储池配置尚未完成', 'import_not_completed' => '目录资源导入未完成', 'delete_not_completed' => '目录资源仍然存在', 'force_required' => '正常关机等待结束后虚拟机仍在运行', 'force_delete_unconfirmed_active' => '强制删除没有确认完成且虚拟机仍在运行', ]; public static function inspect(array $actor, string $id): array { [$job, $client] = self::context($actor, $id, 30.0); try { $value = $client->request( 'GET', self::agentPath($job, '/inspect'), $actor ); } catch (CloudAgentError $error) { throw new CloudAgentError( '宿主机只读检查暂不可用', $error->retryable ? 503 : 502, 'operation_inspection_unavailable', false, $error->agentHttpStatus ); } return self::inspection($value, (string) $job->operation_id); } /** * Resolve only the Agent's durable resource fence. * * This is journal metadata, not a libvirt mutation. We first read any * previously committed resolution so a PHP crash after the Agent commit * can be completed without replaying the POST. A new POST is attempted * at most once; a lost response is followed by one read-only verification. */ public static function resolveFence( array $actor, string $id, string $resolution, string $reason, array $inspection ): array { if (!($actor['is_admin'] ?? false) || !($actor['is_super_admin'] ?? false) || !($actor['can_manage'] ?? false)) { throw new CloudError('只有超级管理员可以确认任务影响', 403); } CloudAccess::manage($actor); if (!in_array($resolution, ['applied', 'not_applied'], true) || mb_strlen($reason) < 20 || mb_strlen($reason) > 500) { throw new CloudError('影响结论或审计说明无效', 400); } [$job, $client] = self::context($actor, $id, 30.0); $checkedAt = $inspection['checked_at'] ?? null; if (($inspection['operation_id'] ?? null) !== (string) $job->operation_id || !is_int($checkedAt) || $checkedAt < time() - 120 || $checkedAt > time() + 5) { throw new CloudError('宿主机只读检查已经失效', 409); } $current = CloudJob::where('id', (int) $job->id) ->where('operation_id', (string) $job->operation_id) ->where('phase', 'terminal')->where('outcome', 'failed') ->where('effect_resolution', 'unknown') ->where('effect_may_have_applied', 1)->first(); if ($current === null) { throw new CloudError('任务不处于可确认的影响未知状态', 409); } if ((string) $current->kind !== 'create') { // Never clear the Agent fence first and discover afterwards that // PHP cannot atomically converge the corresponding business // ledger (network IPs, snapshots, firewall, catalog, lifecycle, // credentials, and so on). Each such kind needs its own finalizer // before it can be enabled here. throw new CloudError( '该任务类型尚无可原子收敛业务账本的解除流程', 409 ); } // A create needs kind-specific financial/placement settlement. Reject // unsupported "applied" conclusions and incomplete absence evidence // before reading or writing Agent fence metadata. CloudCreateFailureFinalizer::assertResolutionSupported( $current, $resolution, $inspection ); $reasonDigest = hash('sha256', $reason); $agentActor = $actor; $agentActor['operation_id'] = (string) $job->operation_id; $path = self::agentPath($job, '/fence-resolution'); // Recover an Agent commit left behind by a prior PHP failure without // issuing another write request. try { $existing = self::fenceResolution( $client->request('GET', $path, $agentActor), (string) $job->operation_id ); if (!hash_equals($resolution, $existing['resolution']) || !hash_equals($reasonDigest, $existing['reason_sha256'])) { throw new CloudError( '宿主机栅栏已有不同的审计结论,不能覆盖', 409 ); } return $existing; } catch (CloudAgentError $error) { if ($error->agentHttpStatus !== 404) { throw new CloudAgentError( '无法确认宿主机资源栅栏状态', 503, 'fence_resolution_read_failed', false, $error->agentHttpStatus ); } } $request = [ 'resolution_id' => bin2hex(random_bytes(16)), 'resolution' => $resolution, 'inspection_checked_at' => $checkedAt, 'reason_sha256' => $reasonDigest, ]; try { return self::matchingFenceResolution( $client->request('POST', self::agentPath( $job, '/resolve-fence' ), $agentActor, $request), (string) $job->operation_id, $request ); } catch (\Throwable $writeError) { // Never retry the metadata POST. A single GET can prove that the // first write committed before its response was lost. try { return self::matchingFenceResolution( $client->request('GET', $path, $agentActor), (string) $job->operation_id, $request ); } catch (\Throwable $readError) { if ($writeError instanceof CloudError) { throw $writeError; } throw new CloudError('宿主机资源栅栏未确认解除', 503); } } } /** Queue a new force phase; the failed graceful task remains immutable. */ public static function forceDelete( array $actor, string $id, array $input ): array { CloudInput::only($input, ['ack_data_loss']); if (($input['ack_data_loss'] ?? null) !== true) { throw new CloudError('必须明确确认强制断电可能造成未刷盘数据丢失', 409); } if (!($actor['is_admin'] ?? false) || !($actor['is_super_admin'] ?? false) || !($actor['can_manage'] ?? false)) { throw new CloudError('只有超级管理员可以确认强制删除', 403); } CloudAccess::manage($actor); if (preg_match('/^[1-9][0-9]{0,17}$/D', $id) !== 1) { throw new CloudError('编号无效', 400); } $prior = CloudJob::where('id', (int) $id)->first(); if ($prior === null) { throw new CloudError('任务不存在', 404); } $job = CloudJobService::enqueueForceDelete($prior, $actor); return [ 'task_id' => (string) $job->id, 'status_url' => '/api/v1/tasks/' . (int) $job->id, ]; } /** @return array{0:CloudJob,1:CloudAgentClient} */ private static function context( array $actor, string $id, float $timeoutSeconds ): array { if (!($actor['is_admin'] ?? false)) { throw new CloudError('需要管理员权限', 403); } CloudAccess::manage($actor); if (preg_match('/^[1-9][0-9]{0,17}$/D', $id) !== 1) { throw new CloudError('编号无效', 400); } $job = CloudJob::query()->select([ 'id', 'operation_id', 'host_id', 'dispatched_at', ])->where('id', (int) $id)->first(); if ($job === null) { throw new CloudError('任务不存在', 404); } if (preg_match('/^[a-f0-9]{32}$/D', (string) $job->operation_id) !== 1 || (int) $job->host_id < 1) { throw new CloudError('任务缺少可检查的 Agent 操作标识', 409); } if ($job->dispatched_at === null || (int) $job->dispatched_at < 1) { throw new CloudError('任务没有跨越 Agent 派发边界', 409); } return [$job, CloudAgentSettingsService::clientForConfiguration( (int) $job->host_id, $timeoutSeconds )]; } private static function agentPath(CloudJob $job, string $suffix): string { return '/v1/operations/' . rawurlencode((string) $job->operation_id) . $suffix; } /** Convert the fixed Agent inspection schema without exposing action tokens. */ private static function inspection(array $value, string $operationId): array { $status = $value['operation_status'] ?? null; $outcome = $value['outcome'] ?? null; $summaryCode = $value['summary_code'] ?? null; $checkedAt = $value['checked_at'] ?? null; if (($value['operation_id'] ?? null) !== $operationId || !is_string($status) || !in_array($status, self::OPERATION_STATUSES, true) || !is_string($outcome) || !array_key_exists($outcome, self::OUTCOMES) || !is_string($summaryCode) || !array_key_exists($summaryCode, self::SUMMARY_LABELS) || !is_int($checkedAt) || $checkedAt < 1) { throw new CloudAgentError( '宿主机 Agent 只读检查响应格式无效', 502, 'agent_invalid_inspection', false, 200 ); } $candidateErrorCode = $value['error_code'] ?? null; $errorCode = is_string($candidateErrorCode) && array_key_exists($candidateErrorCode, self::INSPECTION_ERROR_LABELS) ? $candidateErrorCode : null; $dto = [ 'operation_id' => $operationId, 'journal_status' => $status, 'checked_at' => $checkedAt, 'outcome' => self::OUTCOMES[$outcome], 'summary_code' => $summaryCode, 'summary' => self::SUMMARY_LABELS[$summaryCode], ]; if ($errorCode !== null) { $dto['error_code'] = $errorCode; $dto['error'] = self::INSPECTION_ERROR_LABELS[$errorCode]; } return $dto; } private static function matchingFenceResolution( array $value, string $operationId, array $expected ): array { $resolution = self::fenceResolution($value, $operationId); foreach (['resolution_id', 'resolution', 'reason_sha256'] as $key) { if (!hash_equals((string) $expected[$key], (string) $resolution[$key])) { throw new CloudAgentError( '宿主机资源栅栏回执与请求不匹配', 502, 'agent_invalid_fence_resolution', false, 200 ); } } if ((int) $resolution['inspection_checked_at'] !== (int) $expected['inspection_checked_at']) { throw new CloudAgentError( '宿主机资源栅栏回执与检查时间不匹配', 502, 'agent_invalid_fence_resolution', false, 200 ); } return $resolution; } /** Validate the bounded Agent audit DTO before it influences panel state. */ private static function fenceResolution( array $value, string $operationId ): array { $allowed = ['operation_id', 'resolution_id', 'resolution', 'inspection_checked_at', 'reason_sha256', 'resolved_at', 'resolved_by', 'replayed']; if (array_is_list($value) || array_diff(array_keys($value), $allowed) !== [] || ($value['operation_id'] ?? null) !== $operationId || !is_string($value['resolution_id'] ?? null) || preg_match('/^[a-f0-9]{32}$/D', $value['resolution_id']) !== 1 || !in_array($value['resolution'] ?? null, ['applied', 'not_applied'], true) || !is_int($value['inspection_checked_at'] ?? null) || (int) $value['inspection_checked_at'] < 1 || !is_string($value['reason_sha256'] ?? null) || preg_match('/^[a-f0-9]{64}$/D', $value['reason_sha256']) !== 1 || !is_int($value['resolved_at'] ?? null) || (int) $value['resolved_at'] < 1 || (!is_int($value['resolved_by'] ?? null) && (!is_string($value['resolved_by'] ?? null) || preg_match('/^[1-9][0-9]{0,18}$/D', $value['resolved_by']) !== 1)) || (int) $value['resolved_by'] < 1 || (array_key_exists('replayed', $value) && !is_bool($value['replayed']))) { throw new CloudAgentError( '宿主机 Agent 栅栏回执格式无效', 502, 'agent_invalid_fence_resolution', false, 200 ); } return [ 'operation_id' => $operationId, 'resolution_id' => $value['resolution_id'], 'resolution' => $value['resolution'], 'inspection_checked_at' => $value['inspection_checked_at'], 'reason_sha256' => $value['reason_sha256'], 'resolved_at' => $value['resolved_at'], 'resolved_by' => (string) $value['resolved_by'], ]; } }