|
|
<?php
|
|
|
|
|
|
namespace App\Services\Cloud;
|
|
|
|
|
|
/**
|
|
|
* The single trust boundary for operation failure text.
|
|
|
*
|
|
|
* Agent responses are authenticated, but their human-readable fields are
|
|
|
* still host-controlled data. They must never be copied into a tenant
|
|
|
* response verbatim. This catalog keeps the tenant message intentionally
|
|
|
* small while retaining a bounded, unconditionally redacted summary for
|
|
|
* administrator diagnostics.
|
|
|
*/
|
|
|
final class CloudOperationErrorCatalog
|
|
|
{
|
|
|
/**
|
|
|
* Exact Agent messages reviewed as safe for a tenant to see. Keep this
|
|
|
* list deliberately small: adding a message is a review of the complete
|
|
|
* Agent call path, not a convenience for a new error string.
|
|
|
*/
|
|
|
private const USER_SAFE_DETAILS = [
|
|
|
'虚拟机参数校验失败',
|
|
|
'虚拟机不存在',
|
|
|
'虚拟机已经在运行',
|
|
|
'虚拟机未运行',
|
|
|
'虚拟机强制停机失败',
|
|
|
'虚拟机停机状态未确认',
|
|
|
'虚拟机服务恢复后启动失败',
|
|
|
'虚拟机持久网络状态未确认',
|
|
|
'虚拟机实时网络状态未确认',
|
|
|
'虚拟机操作已完成,但数据库状态保存失败;请管理员检查救援记录',
|
|
|
'任务执行器已不存在,不会自动重放;请核查虚拟机实际状态',
|
|
|
'重装系统失败,请查看面板日志',
|
|
|
'重装失败,已恢复原虚拟机定义及旧系统盘',
|
|
|
'网络修改失败,已恢复原配置',
|
|
|
'实例设置失败,已恢复原配置',
|
|
|
'实例设置修改失败,已恢复原配置',
|
|
|
'虚拟机名称已存在',
|
|
|
'虚拟机 UUID 已存在',
|
|
|
'虚拟机配置已变化,请重新提交救援操作',
|
|
|
'虚拟机配置已变化,网络修改已停止',
|
|
|
'虚拟机配置已变化,重装已停止',
|
|
|
'正常关机超时,重装已停止;旧系统盘未改变',
|
|
|
'正常关机超时,网络未修改',
|
|
|
'确认名称与虚拟机名称不一致',
|
|
|
'虚拟机操作缺少持久幂等编号',
|
|
|
'实例服务已到期或正在执行策略,不能执行该操作',
|
|
|
'在线快照要求虚拟机处于运行状态',
|
|
|
'文件系统一致快照未能安全完成或降级',
|
|
|
'在线快照创建失败',
|
|
|
'快照恢复失败,原系统盘保持不变',
|
|
|
'快照删除失败',
|
|
|
'防火墙能力不可用',
|
|
|
'防火墙规则无效',
|
|
|
'防火墙应用失败',
|
|
|
'防火墙策略漂移',
|
|
|
];
|
|
|
|
|
|
private const MAX_ADMIN_LENGTH = 300;
|
|
|
|
|
|
/**
|
|
|
* A deliberately small set of progress labels that are safe to show to
|
|
|
* an instance owner. New Agent phases fall back to a status label
|
|
|
* instead of becoming an accidental error-message channel.
|
|
|
*/
|
|
|
private const USER_SAFE_PHASES = [
|
|
|
'等待任务开始', '正在处理', '正在执行', '正在检查虚拟机',
|
|
|
'等待重装任务开始', '重装完成', '重装失败',
|
|
|
'正在预挂载救援 ISO 并等待正常关机', '正在强制断电并从救援 ISO 冷启动',
|
|
|
'正在强制停止救援系统并恢复原系统启动配置', '救援 ISO 已预挂载,等待手动强制断电后开机',
|
|
|
'救援系统已启动', '已退出救援模式,原系统已启动', '救援操作失败',
|
|
|
'网络修改完成', '网络修改失败', '任务已中断',
|
|
|
'正在创建在线快照', '在线快照创建完成', '在线快照创建失败',
|
|
|
'正在恢复快照', '快照恢复完成', '快照恢复失败',
|
|
|
'正在删除快照', '快照删除完成', '快照删除失败',
|
|
|
'正在应用防火墙', '防火墙已生效', '防火墙应用失败',
|
|
|
'等待管理员确认是否强制删除', '已授权独立强制删除任务',
|
|
|
'独立强制删除任务已完成',
|
|
|
// User ISO jobs use the same Agent progress store but have their own
|
|
|
// reviewed phrases. Keep these here so the ISO endpoint does not
|
|
|
// become a second arbitrary phase-text channel.
|
|
|
'等待下载', '正在安全下载 ISO', '正在保存到面板 ISO 目录',
|
|
|
'ISO 已保存,可用于所有宿主机', '导入失败',
|
|
|
];
|
|
|
|
|
|
private const USER_SAFE_STATUSES = [
|
|
|
'active', 'succeeded', 'failed',
|
|
|
];
|
|
|
|
|
|
/**
|
|
|
* Stable values persisted in cloud_jobs.error_code for unreviewed Agent
|
|
|
* failures. Keep values independent of HTTP text or host names.
|
|
|
*/
|
|
|
private const WORKER_CODES = [
|
|
|
'uncertain' => 'operation_failed_effect_unknown',
|
|
|
'provision_failed' => 'provision_failed_refunded',
|
|
|
'failed' => 'operation_failed',
|
|
|
];
|
|
|
|
|
|
private const CODE_LABELS = [
|
|
|
'operation_failed_effect_unknown' => '操作已失败并结束;宿主机影响无法确认,系统不会自动重试,相关资源已安全锁定',
|
|
|
'reinstall_cleanup_pending' => '重装任务已失败并结束;新系统可能已提交,但旧系统盘清理未确认,相关资源已安全锁定',
|
|
|
'provision_failed_refunded' => '开通失败,订单已退款',
|
|
|
'operation_failed' => '虚拟机操作失败;任务已结束且不会自动重试',
|
|
|
'snapshot_guest_agent_unavailable' => '宿主机 Agent 未能把不可用的 QEMU Guest Agent 安全降级;请联系管理员更新 Agent 后重试',
|
|
|
'snapshot_filesystem_freeze_failed' => 'QEMU Guest Agent 已连接,但文件系统冻结失败;本次未创建快照,请联系管理员检查 Guest Agent 和文件系统状态',
|
|
|
'firewall_capability_missing' => '宿主机缺少防火墙能力,请联系管理员处理',
|
|
|
'firewall_rule_invalid' => '防火墙规则未通过 Agent 校验,请刷新后重新提交',
|
|
|
'firewall_apply_failed' => '防火墙应用失败;上一版已生效策略保持不变',
|
|
|
'firewall_result_uncertain' => '防火墙任务已失败并结束;生效结果无法确认,系统不会自动重试',
|
|
|
'firewall_drift_detected' => '检测到防火墙策略漂移,请联系管理员核对',
|
|
|
'firewall_cleanup_pending' => '实例删除任务已失败并结束;防火墙清理状态未确认',
|
|
|
'firewall_apply_superseded' => '防火墙请求已被更新的策略替代',
|
|
|
'vpc_host_apply_failed' => 'VPC 宿主机路由同步失败;端口和地址保持锁定,可核对后重试',
|
|
|
'vpc_host_remove_failed' => 'VPC 宿主机路由清理失败;私网地址保持锁定,可核对后重试',
|
|
|
'vpc_port_attach_failed' => 'VPC 私网连接失败;宿主机路由保持不变,可核对后重试',
|
|
|
'vpc_port_detach_failed' => 'VPC 私网断开失败;当前端口账本保持锁定,可核对后重试',
|
|
|
'vpc_result_uncertain' => 'VPC 操作结果暂时无法确认;系统不会重复执行,资源保持锁定并等待核对',
|
|
|
'vpc_batch_attach_failed' => '部分实例未能加入 VPC;已成功实例保持生效,失败实例可在状态核对后重试',
|
|
|
'vpc_batch_detach_failed' => '所选实例均未能移出 VPC;现有私网连接保持不变',
|
|
|
'vpc_batch_detach_partial' => '部分实例已移出 VPC;其余实例保持连接,可在状态核对后重试',
|
|
|
'force_required' => '虚拟机未在正常关机等待期内停止;必须由超级管理员明确确认数据丢失风险后发起独立强制删除任务',
|
|
|
'force_delete_queued' => '已创建独立强制删除任务,原正常关机任务不再自动重试',
|
|
|
'force_delete_completed' => '原正常关机任务未完成,后续独立强制删除任务已完成',
|
|
|
'force_delete_unconfirmed_active' => '强制删除任务已失败并结束,宿主机仍发现虚拟机运行;资源保持安全锁定',
|
|
|
'graceful_shutdown_request_failed' => '正常关机任务已失败并结束,未授予强制删除资格',
|
|
|
'graceful_shutdown_unconfirmed' => '正常关机任务已失败并结束,结果无法确认且未授予强制删除资格',
|
|
|
];
|
|
|
|
|
|
/** Administrator-only labels for selected durable Agent root causes. */
|
|
|
private const AGENT_CAUSE_LABELS = [
|
|
|
'external_snapshot_cleanup_required' => '检测到原生外部快照或回滚元数据;请先在宿主机安全完成外部快照清理,再立即核对',
|
|
|
'native_snapshot_delete_in_progress' => '原生快照删除尚未完成;请先在宿主机继续完成该删除,再立即核对',
|
|
|
'managed_disk_shared' => '目标受管磁盘仍被另一台虚拟机的当前配置、快照或保存状态引用;请先解除引用,再立即核对',
|
|
|
'managed_filter_shared' => '目标网络过滤器仍被另一台虚拟机或过滤器引用;请先解除引用,再立即核对',
|
|
|
'graceful_shutdown_ambiguous' => '正常关机请求结果无法确认;该任务不会授权强制删除,请立即核对后重新发起正常关机操作',
|
|
|
'resource_operation_blocked' => '本次请求因当时存在的资源栅栏未执行;固定存储配置请先更新并重启 Agent 后创建新任务,其他资源仍需核对旧任务',
|
|
|
'storage_path_root_unavailable' => 'Agent 无法访问 storage_path_roots 允许根目录;请检查目录存在性、权限和服务沙箱',
|
|
|
'storage_directory_invalid' => '存储目录不存在、不是目录或路径中包含符号链接;请修正宿主机目录',
|
|
|
'storage_path_not_allowed' => '存储目录不在 Agent storage_path_roots 允许范围内;请核对 Agent 配置',
|
|
|
'storage_pool_path_conflict' => '固定存储池已存在,但类型或目标路径与请求不一致;为保护现有磁盘,Agent 不会改绑',
|
|
|
'storage_pool_definition_invalid' => '固定存储池定义无效或无法生成;请检查 libvirt 存储池定义',
|
|
|
'storage_pool_configuration_failed' => '固定存储池未达到持久、活动且自动启动状态;请检查 libvirt 存储池状态',
|
|
|
'storage_configuration_busy' => '另一存储配置 helper 尚未退出;本次任务已立即失败且不会重试,请在 helper 退出后创建新任务',
|
|
|
'storage_configuration_lock_unavailable' => 'Agent 无法使用存储配置进程锁;请检查 journal_path 所在目录的权限和文件系统锁支持',
|
|
|
'libvirt_unavailable' => 'Agent 无法连接 libvirt;请检查 libvirt 服务和 Agent 权限',
|
|
|
'backup_disk_transition_active' => '实例仍有旧系统盘等待清理,当前不能创建备份;若重装或快照恢复已完成,请核对宿主机持久配置',
|
|
|
];
|
|
|
|
|
|
/**
|
|
|
* These fields are transport diagnostics rather than operation state.
|
|
|
* Keep the list token based: Agent versions use bounded snake_case,
|
|
|
* camelCase, dotted and hyphenated names for the same values.
|
|
|
*/
|
|
|
private const DIAGNOSTIC_TOKENS = [
|
|
|
'error', 'errors', 'detail', 'details', 'message', 'messages',
|
|
|
'exception', 'exceptions', 'trace', 'traces', 'traceback', 'tracebacks',
|
|
|
'stderr', 'stdout', 'diagnostic', 'diagnostics', 'reason', 'reasons',
|
|
|
'path', 'paths', 'command', 'commands', 'cmd', 'debug', 'debug_info',
|
|
|
'stack', 'stacktrace', 'url', 'uri', 'warning', 'warnings',
|
|
|
'diagnosis', 'diagnoses', 'error_code', 'status_code', 'http_status',
|
|
|
'agent_status', 'agent_http_status', 'safe_to_refund',
|
|
|
];
|
|
|
|
|
|
/**
|
|
|
* Result fields that have a stable, user-facing meaning. Unknown Agent
|
|
|
* fields are intentionally dropped, even when they are scalar: a future
|
|
|
* libvirt response must not become a new disclosure channel by merely
|
|
|
* adding a key to its JSON envelope.
|
|
|
*/
|
|
|
private const SAFE_RESULT_KEYS = [
|
|
|
'phase', 'status', 'state', 'uuid', 'name', 'hostname', 'task_id',
|
|
|
'public_ip', 'public_ip_cidr', 'network_changed', 'network_enabled',
|
|
|
'network_suspended', 'skipped',
|
|
|
'settings_changed', 'resources_resized',
|
|
|
'originally_running', 'power_state_restored',
|
|
|
'snapshot_key', 'consistency', 'size_bytes',
|
|
|
'backup_key', 'sha256', 'virtual_size_bytes', 'public_pool_key',
|
|
|
'revision', 'policy_digest',
|
|
|
'port_key', 'vpc_key', 'private_ip', 'mac', 'mac_address',
|
|
|
'bridge', 'host_revision', 'host_digest', 'desired_revision',
|
|
|
'desired_digest', 'vpc_port', 'attached', 'removed',
|
|
|
'created', 'restored', 'deleted',
|
|
|
'service_was_running', 'service_was_running_hint', 'vm',
|
|
|
'reinstall_committed', 'cleanup_pending',
|
|
|
'source_stopped', 'source_was_running',
|
|
|
'source_autostart_disabled',
|
|
|
'forced', 'managed_artifacts_absent',
|
|
|
'vcpu', 'cpu_cores', 'memory_mib', 'ram_mib', 'disk_gib',
|
|
|
'applied_vcpu', 'applied_memory_mib', 'applied_disk_gib',
|
|
|
'applied_bandwidth_mbps',
|
|
|
'os_source', 'os_name', 'install_iso', 'login_name',
|
|
|
'autostart', 'managed',
|
|
|
'active', 'staged', 'pending_manual_restart',
|
|
|
];
|
|
|
|
|
|
/** Keys that are safe only after the administrator summary redactor. */
|
|
|
private const ADMIN_RESULT_DIAGNOSTICS = ['error', 'detail', 'message'];
|
|
|
|
|
|
/** Keys that should never survive in a persisted or presented result. */
|
|
|
private const FORBIDDEN_RESULT_KEYS = [
|
|
|
'console_port', 'credential_generation', 'rescue_mode', 'rescue_staged',
|
|
|
'rescue_volume_name', 'volume_name', 'snapshot_volume_name',
|
|
|
'auth_mode', 'password_available',
|
|
|
'generated_password', 'safe_to_refund',
|
|
|
];
|
|
|
|
|
|
/** Keys that are diagnostic transport data, never tenant result data. */
|
|
|
public static function isDiagnosticKey(string $key): bool
|
|
|
{
|
|
|
$key = self::normalizeKey($key);
|
|
|
if ($key === '') {
|
|
|
return false;
|
|
|
}
|
|
|
foreach (explode('_', $key) as $token) {
|
|
|
if (in_array($token, self::DIAGNOSTIC_TOKENS, true)) {
|
|
|
return true;
|
|
|
}
|
|
|
}
|
|
|
return in_array($key, self::DIAGNOSTIC_TOKENS, true);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Sanitize an Agent operation result at the presentation
|
|
|
* boundary. Ordinary users receive only the reviewed state fields;
|
|
|
* administrators may also receive a bounded/redacted diagnostic string.
|
|
|
*/
|
|
|
public static function result(array $value, bool $administrator = false,
|
|
|
?string $kind = null, ?string $status = null, bool $hasOrder = false,
|
|
|
?string $action = null): array
|
|
|
{
|
|
|
return self::sanitizeResult($value, $administrator, $kind, $status,
|
|
|
$hasOrder, $action, false);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Return the only error text that may be sent to an ordinary user.
|
|
|
*
|
|
|
* A successful or active job has no error. For failed jobs the base text
|
|
|
* is selected from the persisted kind and
|
|
|
* the optional reviewed detail is appended only when it is an exact
|
|
|
* allow-list match.
|
|
|
*/
|
|
|
public static function userMessage(?string $kind, ?string $status, $raw,
|
|
|
bool $hasOrder = false, ?string $action = null): ?string
|
|
|
{
|
|
|
$status = (string) $status;
|
|
|
if (in_array($status, ['succeeded', 'active'], true)) {
|
|
|
return null;
|
|
|
}
|
|
|
|
|
|
$code = self::publicCode($raw);
|
|
|
if ($code !== null) {
|
|
|
return self::CODE_LABELS[$code];
|
|
|
}
|
|
|
$base = self::baseMessage($kind, $status, $hasOrder, $action);
|
|
|
$detail = self::reviewedDetail($raw);
|
|
|
if ($detail === null || str_contains($base, $detail)) {
|
|
|
return $base;
|
|
|
}
|
|
|
return $base . ':' . $detail;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Return a bounded diagnostic summary for administrator-only views.
|
|
|
*
|
|
|
* This method intentionally does not consult AdminDataMasker::shouldMask:
|
|
|
* even a super administrator should not receive credentials or arbitrary
|
|
|
* host paths through an operation DTO. Exact reviewed messages are kept;
|
|
|
* unknown Agent text is redacted in-place and bounded.
|
|
|
*/
|
|
|
public static function adminSummary(?string $kind, ?string $status, $raw,
|
|
|
bool $hasOrder = false, ?string $action = null): ?string
|
|
|
{
|
|
|
if ($raw === null || !is_scalar($raw)) {
|
|
|
return null;
|
|
|
}
|
|
|
$value = trim((string) $raw);
|
|
|
if ($value === '') {
|
|
|
return null;
|
|
|
}
|
|
|
|
|
|
$reviewed = self::reviewedDetail($value);
|
|
|
if ($reviewed !== null) {
|
|
|
return $reviewed;
|
|
|
}
|
|
|
if (isset(self::CODE_LABELS[$value])) {
|
|
|
return self::CODE_LABELS[$value];
|
|
|
}
|
|
|
|
|
|
$value = self::redact($value);
|
|
|
if ($value === '') {
|
|
|
return self::baseMessage($kind, $status, $hasOrder, $action);
|
|
|
}
|
|
|
return mb_substr($value, 0, self::MAX_ADMIN_LENGTH, 'UTF-8');
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Convert an Agent operation envelope to a safe durable worker value.
|
|
|
* Only reviewed details or stable internal codes are returned; the
|
|
|
* operation envelope itself is never serialized into a tenant field.
|
|
|
*/
|
|
|
public static function workerSummary(?string $kind, ?string $status,
|
|
|
array $operation, bool $hasOrder = false, ?string $action = null): ?string
|
|
|
{
|
|
|
$status = (string) $status;
|
|
|
if (in_array($status, ['succeeded', 'running', 'queued'], true)) {
|
|
|
return null;
|
|
|
}
|
|
|
|
|
|
$agentCode = is_string($operation['error_code'] ?? null)
|
|
|
? strtolower(trim($operation['error_code'])) : '';
|
|
|
if ((string) $kind === 'snapshot_create'
|
|
|
&& in_array($agentCode,
|
|
|
['qga_unavailable', 'snapshot_qga_unavailable',
|
|
|
'snapshot_guest_agent_unavailable'], true)) {
|
|
|
return 'snapshot_guest_agent_unavailable';
|
|
|
}
|
|
|
if ((string) $kind === 'snapshot_create'
|
|
|
&& $agentCode === 'snapshot_filesystem_freeze_failed') {
|
|
|
return 'snapshot_filesystem_freeze_failed';
|
|
|
}
|
|
|
if ((string) $kind === 'reinstall'
|
|
|
&& in_array($agentCode, [
|
|
|
'reinstall_cleanup_pending', 'reinstall_result_uncertain',
|
|
|
], true)) {
|
|
|
return $agentCode === 'reinstall_cleanup_pending'
|
|
|
? $agentCode : 'operation_failed_effect_unknown';
|
|
|
}
|
|
|
if (in_array((string) $kind,
|
|
|
['delete', 'expiry_delete', 'service_suspend'], true)
|
|
|
&& in_array($agentCode, [
|
|
|
'force_required', 'graceful_shutdown_request_failed',
|
|
|
'graceful_shutdown_unconfirmed',
|
|
|
], true)) {
|
|
|
return $agentCode;
|
|
|
}
|
|
|
if ((string) $kind === 'delete_force'
|
|
|
&& $agentCode === 'force_delete_unconfirmed_active') {
|
|
|
return $agentCode;
|
|
|
}
|
|
|
if ((string) $kind === 'reinstall'
|
|
|
&& is_array($operation['result'] ?? null)) {
|
|
|
$result = $operation['result'];
|
|
|
if (($result['cleanup_pending'] ?? false) === true) {
|
|
|
return 'reinstall_cleanup_pending';
|
|
|
}
|
|
|
if (($result['reinstall_committed'] ?? false) === true) {
|
|
|
return 'operation_failed_effect_unknown';
|
|
|
}
|
|
|
}
|
|
|
if ((string) $kind === 'firewall_apply') {
|
|
|
if ($status === 'uncertain') {
|
|
|
return 'operation_failed_effect_unknown';
|
|
|
}
|
|
|
if (in_array($agentCode, [
|
|
|
'firewall_capability_missing', 'firewall_rule_invalid',
|
|
|
'firewall_apply_failed', 'firewall_drift_detected',
|
|
|
'firewall_apply_superseded',
|
|
|
], true)) {
|
|
|
return $agentCode;
|
|
|
}
|
|
|
return 'firewall_apply_failed';
|
|
|
}
|
|
|
if (in_array((string) $kind, [
|
|
|
'vpc_host_apply', 'vpc_host_remove',
|
|
|
'vpc_port_attach', 'vpc_port_detach',
|
|
|
], true)) {
|
|
|
if ($status === 'uncertain') {
|
|
|
return 'vpc_result_uncertain';
|
|
|
}
|
|
|
return [
|
|
|
'vpc_host_apply' => 'vpc_host_apply_failed',
|
|
|
'vpc_host_remove' => 'vpc_host_remove_failed',
|
|
|
'vpc_port_attach' => 'vpc_port_attach_failed',
|
|
|
'vpc_port_detach' => 'vpc_port_detach_failed',
|
|
|
][(string) $kind];
|
|
|
}
|
|
|
if ((string) $kind === 'create' && $hasOrder) {
|
|
|
// Only PHP's normalized safety decision reaches this point. A
|
|
|
// create failure is described as refunded solely when the worker
|
|
|
// proved both the VM and every managed artifact absent and then
|
|
|
// completed the refund transaction. Every other failure is a
|
|
|
// terminal, fenced unknown-effect result.
|
|
|
return ($operation['effect_may_have_applied'] ?? null) === false
|
|
|
&& ($operation['safe_to_resubmit'] ?? null) === true
|
|
|
? self::WORKER_CODES['provision_failed']
|
|
|
: self::WORKER_CODES['uncertain'];
|
|
|
}
|
|
|
|
|
|
// Persist only a reviewed detail or stable code. Never place an
|
|
|
// arbitrary Agent/admin summary in the durable error_code field.
|
|
|
foreach (['error', 'detail', 'message'] as $field) {
|
|
|
$reviewed = self::reviewedDetail($operation[$field] ?? null);
|
|
|
if ($reviewed !== null) {
|
|
|
return $reviewed;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
return self::workerCode($kind, $status, $hasOrder);
|
|
|
}
|
|
|
|
|
|
/** Stable code allow-list for browser branching; raw Agent codes stay private. */
|
|
|
public static function publicCode($value): ?string
|
|
|
{
|
|
|
if (!is_string($value)) {
|
|
|
return null;
|
|
|
}
|
|
|
$value = strtolower(trim($value));
|
|
|
return array_key_exists($value, self::CODE_LABELS) ? $value : null;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Validate the Agent's durable root-cause identifier.
|
|
|
*
|
|
|
* This code is administrator-only diagnostic metadata, not a tenant
|
|
|
* message. Accept the canonical lower-case snake_case wire format only
|
|
|
* so result_json cannot become a store for free-form host data.
|
|
|
*/
|
|
|
public static function agentCauseCode($value): ?string
|
|
|
{
|
|
|
if (!is_string($value) || strlen($value) > 64
|
|
|
|| preg_match('/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/D', $value) !== 1) {
|
|
|
return null;
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
/** Return only a reviewed administrator action for a stable cause code. */
|
|
|
public static function agentCauseLabel($value): ?string
|
|
|
{
|
|
|
$code = self::agentCauseCode($value);
|
|
|
return $code === null ? null : (self::AGENT_CAUSE_LABELS[$code] ?? null);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Sanitize an operation result before it is persisted in result_json.
|
|
|
* Error-like fields are represented by the durable error_code instead.
|
|
|
* The one exception is the Agent's strictly validated cause_code, which
|
|
|
* is retained for the dedicated administrator operations DTO and removed
|
|
|
* again at every ordinary presentation boundary.
|
|
|
*/
|
|
|
public static function workerResult(array $value): array
|
|
|
{
|
|
|
// Persistence is stricter than the administrator presentation view:
|
|
|
// error/detail/message remain in error_code and never get a second
|
|
|
// durable copy in result_json.
|
|
|
return self::sanitizeResult($value, false, null, null, false, null, true);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Return a status-only phase for a tenant. The Agent may add arbitrary
|
|
|
* progress text over time; exposing that text would recreate the same
|
|
|
* host/libvirt disclosure problem as a raw error field.
|
|
|
*/
|
|
|
public static function userPhase($value, ?string $status, ?string $kind = null): ?string
|
|
|
{
|
|
|
if (is_string($value)) {
|
|
|
$phase = self::normalize($value);
|
|
|
if (in_array($phase, self::USER_SAFE_PHASES, true)) {
|
|
|
return $phase;
|
|
|
}
|
|
|
}
|
|
|
return match ((string) $status) {
|
|
|
'active' => '正在处理',
|
|
|
'succeeded' => '已完成',
|
|
|
'failed' => '处理失败',
|
|
|
default => null,
|
|
|
};
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Normalize a status emitted by a user-scoped Agent job.
|
|
|
*
|
|
|
* Unknown values are rejected instead of being copied to the browser;
|
|
|
* callers can then omit the record or show their own fixed fallback.
|
|
|
*/
|
|
|
public static function userStatus($value): ?string
|
|
|
{
|
|
|
if (!is_string($value)) {
|
|
|
return null;
|
|
|
}
|
|
|
$status = strtolower(trim($value));
|
|
|
return in_array($status, self::USER_SAFE_STATUSES, true) ? $status : null;
|
|
|
}
|
|
|
|
|
|
/** Return a detail only when it exactly matches a reviewed message. */
|
|
|
public static function reviewedDetail($value): ?string
|
|
|
{
|
|
|
if (!is_string($value)) {
|
|
|
return null;
|
|
|
}
|
|
|
$value = self::normalize($value);
|
|
|
if (isset(self::CODE_LABELS[$value])) {
|
|
|
return null;
|
|
|
}
|
|
|
return in_array($value, self::USER_SAFE_DETAILS, true) ? $value : null;
|
|
|
}
|
|
|
|
|
|
private static function workerCode(?string $kind, string $status, bool $hasOrder): string
|
|
|
{
|
|
|
if ($status === 'uncertain') {
|
|
|
return self::WORKER_CODES['uncertain'];
|
|
|
}
|
|
|
if ((string) $kind === 'create' && $hasOrder) {
|
|
|
return self::WORKER_CODES['failed'];
|
|
|
}
|
|
|
return self::WORKER_CODES['failed'];
|
|
|
}
|
|
|
|
|
|
private static function baseMessage(?string $kind, string $status,
|
|
|
bool $hasOrder, ?string $action): string
|
|
|
{
|
|
|
if ($status === 'uncertain') {
|
|
|
return self::CODE_LABELS['operation_failed_effect_unknown'];
|
|
|
}
|
|
|
if ((string) $kind === 'create' && $hasOrder) {
|
|
|
return '开通失败;任务已结束且不会自动重试';
|
|
|
}
|
|
|
return match ((string) $kind) {
|
|
|
'action' => self::actionMessage($action),
|
|
|
'reinstall' => '重装系统失败;任务已结束且不会自动重试',
|
|
|
'rescue' => '救援操作失败;任务已结束且不会自动重试',
|
|
|
'delete', 'expiry_delete', 'delete_force'
|
|
|
=> '删除实例失败;任务已结束且不会自动重试',
|
|
|
'network_change' => '更换公网 IP 失败;任务已结束且不会自动重试',
|
|
|
'public_ip_pool_replacement_batch'
|
|
|
=> '批量迁移公网地址池未全部完成;请核对父任务及子任务,系统不会自动重放',
|
|
|
'instance_upgrade' => '实例升级失败;任务已结束且不会自动重试',
|
|
|
'instance_settings' => '实例设置失败;任务已结束且不会自动重试',
|
|
|
'snapshot_create' => '创建快照失败;任务已结束且不会自动重试',
|
|
|
'snapshot_restore' => '恢复快照失败;任务已结束且不会自动重试',
|
|
|
'snapshot_delete' => '删除快照失败;任务已结束且不会自动重试',
|
|
|
'backup_create' => '创建云备份失败;任务已结束且不会自动重试',
|
|
|
'backup_workspace_cleanup' => '清理备份工作区失败;远端备份不受影响,可重新核对后创建新的清理任务',
|
|
|
'backup_restore' => '从备份创建实例失败;任务已结束且不会自动重试',
|
|
|
'backup_recover' => '从云备份恢复实例失败;任务已结束且不会自动重试',
|
|
|
'instance_migration_prepare' => '维护迁移源准备失败;请按迁移恢复出口处理',
|
|
|
'instance_migration_transfer' => '维护迁移传输失败;请按迁移恢复出口处理',
|
|
|
'instance_migration_target_clean' => '维护迁移目标残留清理失败;原迁移仍保持锁定并继续核对',
|
|
|
'instance_migration_cleanup' => '维护迁移源清理失败;目标实例不受影响',
|
|
|
'instance_migration_rollback' => '维护迁移源恢复失败;请按迁移恢复出口处理',
|
|
|
'instance_migration_activate' => '维护迁移目标状态恢复失败;请按迁移恢复出口处理',
|
|
|
'firewall_apply' => '防火墙应用失败;任务已结束且不会自动重试',
|
|
|
'vpc_host_apply' => 'VPC 宿主机路由同步失败;请核对任务后重试',
|
|
|
'vpc_host_remove' => 'VPC 宿主机路由清理失败;请核对任务后重试',
|
|
|
'vpc_port_attach' => '连接 VPC 私网失败;请核对任务后重试',
|
|
|
'vpc_port_detach' => '断开 VPC 私网失败;请核对任务后重试',
|
|
|
'service_suspend', 'network_suspend', 'network_resume'
|
|
|
=> '实例策略执行失败;本次任务不会自动重试',
|
|
|
default => '虚拟机操作失败;任务已结束且不会自动重试',
|
|
|
};
|
|
|
}
|
|
|
|
|
|
private static function actionMessage(?string $action): string
|
|
|
{
|
|
|
return match ((string) $action) {
|
|
|
'start' => '开机操作失败;任务已结束且不会自动重试',
|
|
|
'shutdown' => '关机操作失败;任务已结束且不会自动重试',
|
|
|
'reboot' => '重启操作失败;任务已结束且不会自动重试',
|
|
|
'poweroff' => '强制断电操作失败;任务已结束且不会自动重试',
|
|
|
'reset' => '强制重置操作失败;任务已结束且不会自动重试',
|
|
|
default => '电源操作失败;任务已结束且不会自动重试',
|
|
|
};
|
|
|
}
|
|
|
|
|
|
private static function normalize(string $value): string
|
|
|
{
|
|
|
$value = trim($value);
|
|
|
if ($value === '' || preg_match('//u', $value) !== 1) {
|
|
|
return '';
|
|
|
}
|
|
|
$value = preg_replace('/[\x00-\x1F\x7F]+/u', ' ', $value) ?? '';
|
|
|
return trim(preg_replace('/\s+/u', ' ', $value) ?? '');
|
|
|
}
|
|
|
|
|
|
/** Normalize transport field spelling before applying the deny-list. */
|
|
|
private static function normalizeKey(string $key): string
|
|
|
{
|
|
|
$key = trim($key);
|
|
|
if ($key === '') {
|
|
|
return '';
|
|
|
}
|
|
|
$key = preg_replace('/([a-z0-9])([A-Z])/', '$1_$2', $key) ?? '';
|
|
|
$key = preg_replace('/[^A-Za-z0-9]+/', '_', $key) ?? '';
|
|
|
return strtolower(trim($key, '_'));
|
|
|
}
|
|
|
|
|
|
private static function sanitizeResult(array $value, bool $administrator,
|
|
|
?string $kind, ?string $status, bool $hasOrder, ?string $action,
|
|
|
bool $persist, bool $nested = false): array
|
|
|
{
|
|
|
$value = CloudInput::safeResult($value);
|
|
|
if (array_is_list($value)) {
|
|
|
return [];
|
|
|
}
|
|
|
if (!$nested && $kind === 'vpc_membership_batch') {
|
|
|
return self::vpcMembershipBatchResult($value);
|
|
|
}
|
|
|
$result = [];
|
|
|
foreach ($value as $key => $item) {
|
|
|
$name = self::normalizeKey((string) $key);
|
|
|
if ($name === '' || in_array($name, self::FORBIDDEN_RESULT_KEYS, true)) {
|
|
|
continue;
|
|
|
}
|
|
|
if ($name === 'cause_code') {
|
|
|
$causeCode = !$nested && $persist
|
|
|
? self::agentCauseCode($item) : null;
|
|
|
if ($causeCode !== null) {
|
|
|
$result[$name] = $causeCode;
|
|
|
}
|
|
|
continue;
|
|
|
}
|
|
|
if (self::isDiagnosticKey($name)) {
|
|
|
if ($persist || !$administrator) {
|
|
|
continue;
|
|
|
}
|
|
|
$summary = self::adminSummary($kind, $status, $item,
|
|
|
$hasOrder, $action);
|
|
|
if ($summary !== null) {
|
|
|
// Preserve the historical key for the three common
|
|
|
// fields; normalize every camelCase/dotted variant to a
|
|
|
// single generic administrator diagnostic slot.
|
|
|
$diagnosticKey = in_array($name, self::ADMIN_RESULT_DIAGNOSTICS, true)
|
|
|
? $name : 'diagnostic';
|
|
|
if (!isset($result[$diagnosticKey])) {
|
|
|
$result[$diagnosticKey] = $summary;
|
|
|
}
|
|
|
}
|
|
|
continue;
|
|
|
}
|
|
|
if (!in_array($name, self::SAFE_RESULT_KEYS, true)) {
|
|
|
continue;
|
|
|
}
|
|
|
if ($name === 'phase') {
|
|
|
$phase = $administrator && !$persist
|
|
|
? self::adminSummary($kind, $status, $item, $hasOrder, $action)
|
|
|
: self::userPhase($item, $status, $kind);
|
|
|
if ($phase !== null) {
|
|
|
$result[$name] = mb_substr($phase, 0, self::MAX_ADMIN_LENGTH, 'UTF-8');
|
|
|
}
|
|
|
continue;
|
|
|
}
|
|
|
if ($name === 'vm') {
|
|
|
if (is_array($item) && !array_is_list($item)) {
|
|
|
$result[$name] = self::sanitizeResult($item, $administrator,
|
|
|
$kind, $status, $hasOrder, $action, $persist, true);
|
|
|
}
|
|
|
continue;
|
|
|
}
|
|
|
$safe = self::safeResultScalar($name, $item);
|
|
|
if ($safe !== null) {
|
|
|
$result[$name] = $safe;
|
|
|
}
|
|
|
}
|
|
|
return $result;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* Return the complete public result of one durable VPC membership batch.
|
|
|
*
|
|
|
* The batch key is deliberately excluded: the task id is the public
|
|
|
* identity, while this DTO only reports the bounded operation outcome.
|
|
|
*/
|
|
|
private static function vpcMembershipBatchResult(array $value): array
|
|
|
{
|
|
|
$action = $value['action'] ?? null;
|
|
|
$total = $value['total'] ?? null;
|
|
|
$succeeded = $value['succeeded'] ?? null;
|
|
|
$failed = $value['failed'] ?? null;
|
|
|
if (!in_array($action, ['attach', 'detach'], true)
|
|
|
|| !is_int($total) || $total < 1
|
|
|
|| !is_int($succeeded) || $succeeded < 0
|
|
|
|| !is_int($failed) || $failed < 0
|
|
|
|| $succeeded > $total || $failed > $total
|
|
|
|| $succeeded + $failed !== $total) {
|
|
|
return [];
|
|
|
}
|
|
|
return [
|
|
|
'action' => $action,
|
|
|
'total' => $total,
|
|
|
'succeeded' => $succeeded,
|
|
|
'failed' => $failed,
|
|
|
];
|
|
|
}
|
|
|
|
|
|
private static function safeResultScalar(string $key, $value)
|
|
|
{
|
|
|
if (is_bool($value)) {
|
|
|
return in_array($key, ['network_changed', 'network_enabled',
|
|
|
'network_suspended', 'settings_changed',
|
|
|
'resources_resized', 'originally_running',
|
|
|
'power_state_restored', 'skipped',
|
|
|
'service_was_running', 'service_was_running_hint',
|
|
|
'autostart', 'managed', 'created', 'restored', 'deleted',
|
|
|
'reinstall_committed', 'cleanup_pending', 'forced',
|
|
|
'cleaned', 'workspace_absent', 'metadata_absent',
|
|
|
'source_stopped', 'source_was_running',
|
|
|
'source_autostart_disabled',
|
|
|
'managed_artifacts_absent', 'active', 'staged',
|
|
|
'pending_manual_restart'], true)
|
|
|
? $value : null;
|
|
|
}
|
|
|
if (is_int($value) || is_float($value)) {
|
|
|
if (!is_finite((float) $value)) {
|
|
|
return null;
|
|
|
}
|
|
|
$maximums = [
|
|
|
'vcpu' => 512, 'cpu_cores' => 512,
|
|
|
'applied_vcpu' => 512,
|
|
|
'memory_mib' => 262144, 'ram_mib' => 262144,
|
|
|
'applied_memory_mib' => 16777216,
|
|
|
'disk_gib' => 1048576, 'applied_disk_gib' => 4096,
|
|
|
'applied_bandwidth_mbps' => 100000,
|
|
|
'size_bytes' => PHP_INT_MAX,
|
|
|
'revision' => PHP_INT_MAX,
|
|
|
];
|
|
|
$minimums = [
|
|
|
'vcpu' => 1, 'cpu_cores' => 1, 'applied_vcpu' => 1,
|
|
|
'memory_mib' => 1, 'ram_mib' => 1,
|
|
|
'applied_memory_mib' => 128,
|
|
|
'disk_gib' => 1, 'applied_disk_gib' => 1,
|
|
|
'applied_bandwidth_mbps' => 1,
|
|
|
'size_bytes' => 0,
|
|
|
'revision' => 1,
|
|
|
];
|
|
|
if (!array_key_exists($key, $maximums)
|
|
|
|| $value < $minimums[$key] || $value > $maximums[$key]
|
|
|
|| floor((float) $value) !== (float) $value) {
|
|
|
return null;
|
|
|
}
|
|
|
return (int) $value;
|
|
|
}
|
|
|
if (!is_string($value)) {
|
|
|
return null;
|
|
|
}
|
|
|
$value = self::normalize($value);
|
|
|
if ($value === '' || mb_strlen($value) > 255) {
|
|
|
return null;
|
|
|
}
|
|
|
if (in_array($key, ['vcpu', 'cpu_cores', 'memory_mib', 'ram_mib',
|
|
|
'disk_gib', 'applied_vcpu', 'applied_memory_mib',
|
|
|
'applied_disk_gib', 'applied_bandwidth_mbps',
|
|
|
'size_bytes', 'revision'], true)) {
|
|
|
if (preg_match('/^[0-9]+$/D', $value) !== 1) {
|
|
|
return null;
|
|
|
}
|
|
|
$maximums = [
|
|
|
'vcpu' => 512, 'cpu_cores' => 512,
|
|
|
'applied_vcpu' => 512,
|
|
|
'memory_mib' => 262144, 'ram_mib' => 262144,
|
|
|
'applied_memory_mib' => 16777216,
|
|
|
'disk_gib' => 1048576, 'applied_disk_gib' => 4096,
|
|
|
'applied_bandwidth_mbps' => 100000,
|
|
|
'size_bytes' => PHP_INT_MAX,
|
|
|
'revision' => PHP_INT_MAX,
|
|
|
];
|
|
|
$number = (int) $value;
|
|
|
$minimum = $key === 'size_bytes' ? 0 : 1;
|
|
|
return $number >= $minimum && $number <= $maximums[$key]
|
|
|
? $number : null;
|
|
|
}
|
|
|
if (in_array($key, ['network_changed', 'network_enabled',
|
|
|
'network_suspended', 'settings_changed',
|
|
|
'resources_resized', 'originally_running',
|
|
|
'power_state_restored', 'skipped',
|
|
|
'service_was_running', 'service_was_running_hint',
|
|
|
'source_stopped', 'source_was_running',
|
|
|
'source_autostart_disabled',
|
|
|
'autostart', 'managed', 'created', 'restored', 'deleted',
|
|
|
'forced', 'managed_artifacts_absent', 'active', 'staged',
|
|
|
'cleaned', 'workspace_absent', 'metadata_absent',
|
|
|
'pending_manual_restart'], true)) {
|
|
|
return null;
|
|
|
}
|
|
|
if (in_array($key, ['snapshot_key', 'backup_key'], true)
|
|
|
&& preg_match('/^[a-f0-9]{32}$/D', $value) !== 1) {
|
|
|
return null;
|
|
|
}
|
|
|
if ($key === 'policy_digest'
|
|
|
&& preg_match('/^[a-f0-9]{64}$/D', $value) !== 1) {
|
|
|
return null;
|
|
|
}
|
|
|
if ($key === 'consistency'
|
|
|
&& !in_array($value, ['filesystem', 'crash'], true)) {
|
|
|
return null;
|
|
|
}
|
|
|
if (in_array($key, ['public_ip', 'public_ip_cidr'], true)) {
|
|
|
if (($key === 'public_ip_cidr' && !str_contains($value, '/'))
|
|
|
|| ($key === 'public_ip' && str_contains($value, '/'))) {
|
|
|
return null;
|
|
|
}
|
|
|
$address = explode('/', $value, 2)[0];
|
|
|
if (filter_var($address, FILTER_VALIDATE_IP) === false) {
|
|
|
return null;
|
|
|
}
|
|
|
if (str_contains($value, '/')) {
|
|
|
$parts = explode('/', $value, 2);
|
|
|
$maximum = filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)
|
|
|
!== false ? 32 : 128;
|
|
|
if (preg_match('/^[0-9]{1,3}$/D', $parts[1]) !== 1
|
|
|
|| (int) $parts[1] > $maximum) {
|
|
|
return null;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
if ($key === 'state') {
|
|
|
$state = CloudInstanceMetadata::state($value);
|
|
|
return $state === 'unknown' && $value !== 'unknown' ? null : $state;
|
|
|
}
|
|
|
if ($key === 'status' && !in_array($value, [
|
|
|
'active', 'succeeded', 'failed',
|
|
|
], true)) {
|
|
|
return null;
|
|
|
}
|
|
|
if ($key === 'uuid' && preg_match(
|
|
|
'/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iD',
|
|
|
$value
|
|
|
) !== 1) {
|
|
|
return null;
|
|
|
}
|
|
|
if ($key === 'task_id' && preg_match('/^[A-Za-z0-9_-]{8,128}$/D', $value) !== 1) {
|
|
|
return null;
|
|
|
}
|
|
|
if ($key === 'hostname') {
|
|
|
if (strlen($value) > 253 || str_ends_with($value, '.')
|
|
|
|| preg_match('/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/D', $value) !== 1) {
|
|
|
return null;
|
|
|
}
|
|
|
}
|
|
|
if ($key === 'os_source' && !in_array($value, ['cloud_template', 'iso', 'unknown'], true)) {
|
|
|
return null;
|
|
|
}
|
|
|
if ($key === 'login_name' && preg_match('/^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/D', $value) !== 1) {
|
|
|
return null;
|
|
|
}
|
|
|
if (in_array($key, ['name', 'os_name', 'install_iso'], true)
|
|
|
&& (str_contains($value, '/') || str_contains($value, '\\')
|
|
|
|| str_contains($value, ':'))) {
|
|
|
return null;
|
|
|
}
|
|
|
return $value;
|
|
|
}
|
|
|
|
|
|
private static function redact(string $value): string
|
|
|
{
|
|
|
$value = self::normalize($value);
|
|
|
if ($value === '') {
|
|
|
return '';
|
|
|
}
|
|
|
$value = preg_replace(
|
|
|
'/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----.*?(?:-----END (?:[A-Z]+ )?PRIVATE KEY-----|$)/is',
|
|
|
'[私密内容已隐藏]', $value
|
|
|
) ?? '';
|
|
|
$value = preg_replace('/\bBearer\s+\S+/i', 'Bearer [凭据已隐藏]', $value) ?? '';
|
|
|
$value = preg_replace(
|
|
|
'/((?:password|passwd|password_hash|api[_ -]?key|api[_ -]?token|access[_ -]?token|refresh[_ -]?token|token|secret|client_secret|authorization|credential|private[_ -]?key)\s*[:=]\s*)(?:"[^"]*"|\'[^\']*\'|[^\s,;]+)/i',
|
|
|
'$1[凭据已隐藏]', $value
|
|
|
) ?? '';
|
|
|
$value = preg_replace('#https?://[^\s]+#i', '[地址已隐藏]', $value) ?? '';
|
|
|
$value = preg_replace(
|
|
|
'#(?:[A-Za-z]:[\\\\/]|/|\\\\)[^\s,;)]*#',
|
|
|
'[路径已隐藏]', $value
|
|
|
) ?? '';
|
|
|
$value = preg_replace('/\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}(?::[0-9]{1,5})?\b/', '[地址已隐藏]', $value) ?? '';
|
|
|
$value = preg_replace('/\b(?:[0-9A-F]{1,4}:){2,}[0-9A-F:.]*\b/i', '[地址已隐藏]', $value) ?? '';
|
|
|
$value = preg_replace('/\s{2,}/u', ' ', trim($value)) ?? '';
|
|
|
return trim($value);
|
|
|
}
|
|
|
}
|