'执行中', 'succeeded' => '已完成', 'failed' => '失败', ]; public static function page(array $actor, array $input = []): array { self::authorize($actor); // Keep the administrator inventory convergent even if the worker // daemon is absent. This is a local deadline write only: no Agent // request and no mutation replay can occur here. CloudWorkerService::expireDueJobs(100); $filters = self::filters($input); $query = self::query(); self::applyFilters($query, $filters); $summaryRow = (clone $query)->selectRaw( "COUNT(*) AS total, " . "COALESCE(SUM(CASE WHEN cloud_jobs.phase <> 'terminal' THEN 1 ELSE 0 END), 0) AS active, " . "COALESCE(SUM(CASE WHEN cloud_jobs.phase = 'terminal' AND cloud_jobs.outcome = 'succeeded' THEN 1 ELSE 0 END), 0) AS succeeded, " . "COALESCE(SUM(CASE WHEN cloud_jobs.phase = 'terminal' AND cloud_jobs.outcome = 'failed' THEN 1 ELSE 0 END), 0) AS failed, " . "COALESCE(SUM(CASE WHEN cloud_jobs.phase = 'terminal' AND cloud_jobs.outcome = 'failed' AND cloud_jobs.effect_resolution = 'unknown' AND cloud_jobs.kind <> 'host_storage_configure' THEN 1 ELSE 0 END), 0) AS unresolved_effect" )->first(); $summary = []; foreach (['total', 'active', 'succeeded', 'failed', 'unresolved_effect'] as $key) { $summary[$key] = max(0, (int) ($summaryRow?->$key ?? 0)); } $pages = max(1, (int) ceil($summary['total'] / $filters['per_page'])); $filters['page'] = min($filters['page'], $pages); $records = self::select($query)->orderByDesc('cloud_jobs.id') ->offset(($filters['page'] - 1) * $filters['per_page']) ->limit($filters['per_page'])->get(); $items = []; $canManage = self::canManage($actor); foreach ($records as $job) { $items[] = self::row($job, $canManage); } $hosts = []; foreach (CloudHost::orderBy('name')->orderBy('id') ->get(['id', 'name', 'region']) as $host) { $hosts[] = [ 'id' => (string) $host->id, 'name' => (string) $host->name, 'region' => (string) $host->region, ]; } $from = $summary['total'] === 0 ? 0 : ($filters['page'] - 1) * $filters['per_page'] + 1; return [ 'items' => $items, 'pagination' => [ 'page' => $filters['page'], 'per_page' => $filters['per_page'], 'total' => $summary['total'], 'total_pages' => $pages, 'from' => $from, 'to' => $from === 0 ? 0 : $from + count($items) - 1, ], 'summary' => $summary, 'filters' => $filters, 'hosts' => $hosts, 'kinds' => CloudOperationCatalog::kindOptions(), 'generated_at' => time(), ]; } public static function detail(array $actor, string $id): array { self::authorize($actor); $jobId = self::identifier($id); CloudWorkerService::expireDueTaskForAdmin($jobId); $job = self::select(self::query()->where( 'cloud_jobs.id', $jobId ))->first(); if ($job === null) { throw new CloudError('任务不存在', 404); } $storageConfiguration = (string) $job->kind === 'host_storage_configure'; $effectNote = $storageConfiguration ? '存储配置失败不会保留跨任务资源栅栏;旧 operation ID 仍永久终止且绝不重放,管理员可按已有固定池的同一路径用新 operation ID 显式提交独立任务。' : '副作用可能已发生时,资源安全栅栏保持生效;只有超级管理员完成新鲜只读检查并记录审计结论后,才会显式解除面板与 Agent 栅栏。'; $ledgerNote = $storageConfiguration ? '新的存储配置任务只会核验或补全路径一致的固定池;不会更换已有池路径,也不会迁移或删除数据。' : '其他类型若还没有专用业务账本终结器,系统会拒绝假解锁;任务已终态失败,资源栅栏保持安全锁定。'; return [ 'job' => self::row($job, self::canManage($actor)), 'generated_at' => time(), 'notes' => [ '任务状态来自数据库,不会因打开页面而联系 Agent。', '任务最多派发一次;失败后不会自动核对、重新排队或重放宿主机操作。', '宿主机只读检查不改变任务终态,也不执行清理或续作。', $effectNote, '开通任务只有在宿主机明确确认虚拟机和管理资源均不存在时,才能按未应用原子退款并释放库存、公网 IP 与资源预留;只读检查不能把开通任务确认成已应用。', '支付创建结果不明时,签名回调可自动确认已应用;人工结论只收敛本地支付账本,绝不重新向渠道下单。', $ledgerNote, '正常关机明确返回 force_required 时,强制删除会创建具有新操作标识的独立任务。', ], ]; } /** Resolve only the resource-effect lock after a fresh read-only inspection. */ public static function resolveEffect( array $actor, string $id, array $input, array $inspection, array $fenceResolution ): array { self::authorize($actor); CloudAccess::manage($actor); if (!(bool) ($actor['is_super_admin'] ?? false)) { throw new CloudError('只有超级管理员可以确认任务影响', 403); } $resolution = $input['resolution'] ?? null; $reason = is_string($input['reason'] ?? null) ? trim($input['reason']) : ''; $checkedAt = $inspection['checked_at'] ?? null; $operationId = $inspection['operation_id'] ?? null; $fenceCheckedAt = $fenceResolution['inspection_checked_at'] ?? null; $fenceResolvedAt = $fenceResolution['resolved_at'] ?? null; $fenceResolvedBy = $fenceResolution['resolved_by'] ?? null; $now = time(); if (!in_array($resolution, ['applied', 'not_applied'], true) || mb_strlen($reason) < 20 || mb_strlen($reason) > 500 || !is_int($checkedAt) || $checkedAt < $now - 120 || $checkedAt > $now + 5 || !is_string($operationId) || preg_match('/^[a-f0-9]{32}$/D', $operationId) !== 1 || ($fenceResolution['operation_id'] ?? null) !== $operationId || ($fenceResolution['resolution'] ?? null) !== $resolution || !is_string($fenceResolution['resolution_id'] ?? null) || preg_match('/^[a-f0-9]{32}$/D', $fenceResolution['resolution_id']) !== 1 || !is_int($fenceCheckedAt) || $fenceCheckedAt < 1 || $fenceCheckedAt > $now + 5 || !is_int($fenceResolvedAt) || $fenceResolvedAt < $fenceCheckedAt || $fenceResolvedAt > $now + 5 || ((!is_int($fenceResolvedBy) || $fenceResolvedBy < 1) && (!is_string($fenceResolvedBy) || preg_match('/^[1-9][0-9]{0,18}$/D', $fenceResolvedBy) !== 1)) || !is_string($fenceResolution['reason_sha256'] ?? null) || preg_match('/^[a-f0-9]{64}$/D', $fenceResolution['reason_sha256']) !== 1 || !hash_equals(hash('sha256', $reason), $fenceResolution['reason_sha256'])) { throw new CloudError('影响结论、审计说明或只读检查无效', 400); } $jobId = self::identifier($id); $target = CloudJob::where('id', $jobId) ->where('operation_id', $operationId)->first(); if ($target === null) { throw new CloudError('任务不处于可确认的影响未知状态', 409); } if ((string) $target->kind !== 'create') { throw new CloudError( (string) $target->kind === 'payment_create' ? '支付任务必须通过本地支付账本核验流程确认' : '该任务类型尚无可原子收敛业务账本的解除流程', 409 ); } CloudCreateFailureFinalizer::assertResolutionSupported( $target, (string) $resolution, $inspection ); CloudCreateFailureFinalizer::resolveNotApplied( $jobId, (string) $operationId, (int) ($actor['user_id'] ?? 0), $reason, $inspection, $now ); error_log(sprintf( 'cloud admin resolved job effect job_id=%d resolution=%s actor_id=%d reason_sha256=%s inspection_checked_at=%d fence_resolution_id=%s', $jobId, $resolution, (int) ($actor['user_id'] ?? 0), hash('sha256', $reason), $checkedAt, (string) ($fenceResolution['resolution_id'] ?? '') )); return self::detail($actor, (string) $jobId) + ['inspection' => $inspection]; } public static function filters(array $input): array { foreach ($input as $key => $value) { if (!in_array($key, ['status', 'kind', 'host_id', 'q', 'page', 'per_page'], true) || (!is_string($value) && !is_int($value))) { throw new CloudError('筛选参数无效', 400); } } $status = (string) ($input['status'] ?? 'attention'); $kind = (string) ($input['kind'] ?? ''); if (!in_array($status, array_merge(['all', 'attention'], array_keys(self::STATUSES)), true) || ($kind !== '' && !array_key_exists($kind, CloudOperationCatalog::kinds()))) { throw new CloudError('任务状态或类型无效', 400); } $q = trim((string) ($input['q'] ?? '')); if (mb_strlen($q, 'UTF-8') > 80 || preg_match('/[\x00-\x1f\x7f]/u', $q) !== 0) { throw new CloudError('搜索关键词最多 80 个字符,且不能包含控制字符', 400); } $host = (string) ($input['host_id'] ?? ''); $page = self::identifier((string) ($input['page'] ?? '1')); $perPage = self::identifier((string) ($input['per_page'] ?? '20')); if (!in_array($perPage, [20, 50, 100], true)) { throw new CloudError('每页条数只能为 20、50 或 100', 400); } return [ 'status' => $status, 'kind' => $kind, 'host_id' => $host === '' ? null : (string) self::identifier($host), 'q' => $q, 'page' => $page, 'per_page' => $perPage, ]; } private static function authorize(array $actor): void { if (!($actor['is_admin'] ?? false)) { throw new CloudError('需要管理员权限', 403); } } private static function canManage(array $actor): bool { return ($actor['is_admin'] ?? false) === true && ($actor['is_super_admin'] ?? false) === true && ($actor['can_manage'] ?? false) === true; } private static function identifier(string $value): int { if (preg_match('/^[1-9][0-9]{0,17}$/D', $value) !== 1) { throw new CloudError('编号或页码无效', 400); } return (int) $value; } private static function query() { return CloudJob::query() ->leftJoin('cloud_hosts as operation_host', 'operation_host.id', '=', 'cloud_jobs.host_id') ->leftJoin('user as operation_actor', 'operation_actor.id', '=', 'cloud_jobs.user_id') ->leftJoin('cloud_instances as operation_instance', static function ($join): void { $join->on('operation_instance.id', '=', 'cloud_jobs.instance_id') ->on('operation_instance.host_id', '=', 'cloud_jobs.host_id'); }) ->leftJoin('cloud_orders as operation_order', static function ($join): void { $join->on('operation_order.id', '=', 'cloud_jobs.order_id') ->on('operation_order.host_id', '=', 'cloud_jobs.host_id') ->whereRaw('(cloud_jobs.instance_id IS NULL OR ' . '(operation_instance.id IS NOT NULL ' . 'AND operation_order.user_id = operation_instance.user_id ' . 'AND (operation_order.instance_id IS NULL ' . 'OR operation_order.instance_id = operation_instance.id)))'); }) ->leftJoin('cloud_instances as fallback_instance', static function ($join): void { $join->on('fallback_instance.id', '=', 'operation_order.instance_id') ->on('fallback_instance.user_id', '=', 'operation_order.user_id') ->on('fallback_instance.host_id', '=', 'cloud_jobs.host_id') ->whereNull('cloud_jobs.instance_id'); }) ->leftJoin('user as operation_owner', static function ($join): void { $join->whereRaw('operation_owner.id = ' . 'COALESCE(operation_instance.user_id, ' . 'fallback_instance.user_id, operation_order.user_id)'); }); } private static function select($query) { $columns = []; foreach ([ 'id', 'operation_id', 'user_id', 'host_id', 'kind', 'execution_mode', 'invoice_id', 'phase', 'outcome', 'status', 'attempts', 'dispatch_attempts', 'error_code', 'dispatched_at', 'dispatch_deadline_at', 'receipt_deadline_at', 'terminal_at', 'effect_may_have_applied', 'safe_to_resubmit', 'effect_resolution', 'effect_resolved_at', 'effect_resolved_by', 'finalization_incident', 'finalization_error_code', 'lease_until', 'available_at', 'created_at', 'updated_at', ] as $column) { $columns[] = 'cloud_jobs.' . $column; } return $query->select(array_merge($columns, [ 'operation_host.name as host_name', 'operation_host.region as host_region', 'operation_actor.user_name as actor_name', 'operation_actor.email as actor_email', 'operation_owner.user_name as owner_name', 'operation_owner.email as owner_email', 'operation_order.id as linked_order_id', ]))->selectRaw( 'COALESCE(operation_instance.user_id, fallback_instance.user_id, ' . 'operation_order.user_id) AS owner_id, ' . 'COALESCE(operation_instance.id, fallback_instance.id) ' . 'AS linked_instance_id, ' . 'COALESCE(operation_instance.name, fallback_instance.name) ' . 'AS instance_name, ' . 'COALESCE(operation_instance.uuid, fallback_instance.uuid) ' . 'AS instance_uuid, ' . 'COALESCE(operation_instance.status, fallback_instance.status) ' . 'AS instance_status, ' . "CASE WHEN JSON_VALID(cloud_jobs.result_json) THEN " . "JSON_EXTRACT(cloud_jobs.result_json, '$.cause_code') " . 'ELSE NULL END AS agent_cause_code_json' ); } private static function applyFilters($query, array $filters): void { if ($filters['status'] === 'attention') { $query->where('cloud_jobs.phase', 'terminal') ->where('cloud_jobs.outcome', 'failed'); } elseif ($filters['status'] === 'active') { $query->where('cloud_jobs.phase', '<>', 'terminal'); } elseif ($filters['status'] !== 'all') { $query->where('cloud_jobs.phase', 'terminal') ->where('cloud_jobs.outcome', $filters['status']); } if ($filters['kind'] !== '') { $query->where('cloud_jobs.kind', $filters['kind']); } if ($filters['host_id'] !== null) { $query->where('cloud_jobs.host_id', $filters['host_id']); } if ($filters['q'] !== '') { $like = '%' . str_replace( ['!', '%', '_'], ['!!', '!%', '!_'], $filters['q'] ) . '%'; $query->where(static function ($search) use ($filters, $like): void { $search->whereRaw( "cloud_jobs.operation_id LIKE ? ESCAPE '!'", [$like] ); foreach (['operation_instance', 'fallback_instance'] as $table) { foreach (['uuid', 'name'] as $column) { $search->orWhereRaw( $table . '.' . $column . " LIKE ? ESCAPE '!'", [$like] ); } } if (preg_match('/^[1-9][0-9]{0,17}$/D', $filters['q']) === 1) { $search->orWhere('cloud_jobs.id', (int) $filters['q']); } }); } } private static function row($job, bool $canManage = false): array { $completed = (string) $job->phase === 'terminal'; $status = $completed && in_array((string) $job->outcome, ['succeeded', 'failed'], true) ? (string) $job->outcome : 'active'; $agentCauseCode = $job->agent_cause_code_json; if (is_string($agentCauseCode) && str_starts_with($agentCauseCode, '"')) { $agentCauseCode = json_decode($agentCauseCode, true); } $agentCauseCode = CloudOperationErrorCatalog::agentCauseCode( $agentCauseCode ); $uuid = (string) ($job->instance_uuid ?? ''); $validUuid = preg_match( '/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iD', $uuid ) === 1; $action = CloudJobService::action($job); $labels = CloudOperationCatalog::labels((string) $job->kind, $action); [$canInspect, $inspectReason] = self::inspectable($job, $canManage); [$canResolve, $resolveReason] = self::effectResolvable( $job, $canManage ); [$canForceDelete, $forceDeleteReason] = self::forceDeleteable( $job, $canManage ); return [ 'id' => (string) $job->id, 'operation_id' => preg_match('/^[a-f0-9]{32}$/D', (string) $job->operation_id) === 1 ? (string) $job->operation_id : null, 'kind' => (string) $job->kind, 'execution_mode' => (string) $job->execution_mode, 'invoice_id' => $job->invoice_id === null ? null : (string) $job->invoice_id, 'action' => $action, 'kind_label' => $labels['kind_label'], 'action_label' => $labels['action_label'], 'completed' => $completed, 'status' => $status, 'can_inspect' => $canInspect, 'inspect_reason' => $inspectReason, 'can_resolve_effect' => $canResolve, 'resolve_effect_reason' => $resolveReason, 'can_force_delete' => $canForceDelete, 'force_delete_reason' => $forceDeleteReason, 'dispatch_attempts' => max(0, (int) $job->dispatch_attempts), 'effect_may_have_applied' => $job->effect_may_have_applied === null ? null : (bool) $job->effect_may_have_applied, 'safe_to_resubmit' => $job->safe_to_resubmit === null ? null : (bool) $job->safe_to_resubmit, 'effect_resolution' => (string) $job->effect_resolution, 'effect_resolved_at' => self::timestamp($job->effect_resolved_at), 'effect_resolved_by' => $job->effect_resolved_by === null ? null : (string) $job->effect_resolved_by, 'finalization_incident' => (bool) $job->finalization_incident, 'finalization_error_code' => (bool) $job->finalization_incident ? (string) $job->finalization_error_code : null, 'error_code' => CloudOperationErrorCatalog::publicCode( $job->error_code ), 'agent_cause_code' => $agentCauseCode, 'agent_cause_label' => CloudOperationErrorCatalog::agentCauseLabel($agentCauseCode), 'error' => $completed && $status === 'failed' ? CloudOperationErrorCatalog::adminSummary( (string) $job->kind, $status, $job->error_code, $job->linked_order_id !== null, $action ) : null, 'host_id' => (string) $job->host_id, 'host_name' => (string) ($job->host_name ?? ''), 'region' => (string) ($job->host_region ?? ''), 'actor_id' => (string) $job->user_id, 'actor_name' => AdminDataMasker::account($job->actor_name ?? ''), 'actor_email' => AdminDataMasker::email($job->actor_email ?? ''), 'owner_id' => $job->owner_id === null ? null : (string) $job->owner_id, 'owner_name' => $job->owner_id === null ? null : AdminDataMasker::account($job->owner_name ?? ''), 'owner_email' => $job->owner_id === null ? null : AdminDataMasker::email($job->owner_email ?? ''), 'instance_id' => $job->linked_instance_id === null ? null : (string) $job->linked_instance_id, 'instance_name' => $job->instance_name, 'instance_uuid' => $job->instance_uuid, 'instance_status' => $job->instance_status, 'order_id' => $job->linked_order_id === null ? null : (string) $job->linked_order_id, 'created_at' => max(0, (int) $job->created_at), 'updated_at' => max(0, (int) $job->updated_at), 'dispatched_at' => self::timestamp($job->dispatched_at), 'dispatch_deadline_at' => self::timestamp($job->dispatch_deadline_at), 'receipt_deadline_at' => self::timestamp($job->receipt_deadline_at), 'terminal_at' => self::timestamp($job->terminal_at), 'links' => [ 'instance' => $validUuid && $job->instance_status !== 'deleted' ? '/admin/cloud/instances?q=' . rawurlencode($uuid) : null, 'billing' => $job->linked_order_id === null ? null : '/admin/billing?view=orders&q=' . $job->linked_order_id, ], 'display' => [ 'kind' => $labels['kind_label'], 'action' => $labels['action_label'], 'status' => self::STATUSES[$status], 'effect' => (string) $job->effect_resolution === 'unknown' ? ((string) $job->kind === 'host_storage_configure' ? '部分固定存储池可能已应用;旧任务已终止且不阻断新的独立任务' : '副作用状态未知;任务已失败,资源已安全锁定') : '无任务级安全栅栏', ], ]; } /** @return array{0:bool,1:string} */ private static function inspectable($job, bool $canManage): array { if (!$canManage) { return [false, '只有超级管理员可以读取宿主机实时状态']; } if ((string) $job->kind === 'payment_create') { return [false, '支付任务不使用宿主机 Agent 检查']; } if ((int) $job->host_id < 1 || preg_match('/^[a-f0-9]{32}$/D', (string) $job->operation_id) !== 1) { return [false, '任务缺少可检查的 Agent 操作标识']; } if ($job->dispatched_at === null || (int) $job->dispatched_at < 1) { return [false, '任务没有跨越 Agent 派发边界']; } return [true, '只读检查不会改变任务或宿主机']; } /** @return array{0:bool,1:string} */ private static function effectResolvable($job, bool $canManage): array { if (!$canManage) { return [false, '只有超级管理员可以记录影响结论']; } if ((string) $job->phase !== 'terminal' || (string) $job->outcome !== 'failed' || (string) $job->effect_resolution !== 'unknown' || !(bool) $job->effect_may_have_applied) { return [false, '任务不处于副作用未知的终态失败']; } if ((string) $job->kind === 'create') { return [true, '仅可在宿主机确认虚拟机及管理资源均不存在后选择未应用并退款;不能用只读检查确认已应用']; } if ((string) $job->kind === 'payment_create') { return [true, '需要先在外部支付平台核实原订单;本操作不会重新下单']; } if ((string) $job->kind === 'host_storage_configure') { return [false, '存储配置终态失败不保留跨任务资源栅栏;请按已有固定池的同一路径,或只修正尚未定义的角色后提交新任务']; } return [false, '该任务类型尚无可原子收敛业务账本的解除流程;任务已失败终止,资源保持安全锁定']; } /** @return array{0:bool,1:string} */ private static function forceDeleteable($job, bool $canManage): array { if (!$canManage) { return [false, '只有超级管理员可以确认强制删除']; } if (!in_array((string) $job->kind, ['delete', 'expiry_delete', 'service_suspend'], true)) { return [false, '当前任务不是可升级的删除任务']; } if ((string) $job->phase !== 'terminal' || (string) $job->outcome !== 'failed' || (string) $job->error_code !== 'force_required') { return [false, '原删除任务没有明确返回 force_required']; } if ($job->dispatched_at === null || (int) $job->dispatched_at < 1) { return [false, '原删除任务没有跨越 Agent 派发边界']; } return [true, '将创建新的任务并再次确认数据丢失风险']; } private static function timestamp($value): ?int { return $value !== null && (int) $value > 0 ? (int) $value : null; } }