feat: expose Go Agent operation status through job API

go-agent
admin 1 month ago
parent 703529eef4
commit 4055f91a4d

@ -12,6 +12,11 @@ use App\Services\Auth;
use App\Services\AdminCsrf;
use App\Services\Config;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudAgentHostClientResolverFactory;
use App\Services\Cloud\CloudAgentObservationService;
use App\Services\Cloud\CloudAgentOperationException;
use App\Services\Cloud\CloudAgentOperationRepository;
use App\Services\Cloud\CloudAgentOperationStatusService;
use App\Services\Cloud\CloudDeploymentPageService;
use App\Services\Cloud\CloudEngineClient;
use App\Services\Cloud\CloudError;
@ -57,6 +62,19 @@ final class CloudApiController
return $response->withJson($value, $status)->withHeader('Cache-Control', 'no-store');
}
/**
* Build the request-local Agent observation seam. The factory reads only
* the fresh Agent registry and root-only key directory; no legacy engine
* client is constructed on this page-facing path.
*/
private function agentObservationService(): CloudAgentObservationService
{
return new CloudAgentObservationService(
CloudAgentHostClientResolverFactory::fromConfig(),
new CloudAgentOperationRepository(),
);
}
private function userIsoImportAllowed(array $actor, bool $throw = false): bool
{
$user = User::where('id', $actor['user_id'])->first();
@ -388,7 +406,15 @@ final class CloudApiController
public function job($request, $response, $args)
{
$actor = $this->actor($request);
$query = CloudJob::where('id', $args['id']);
$id = (string) ($args['id'] ?? '');
// Fresh Go Agent operations use UUID identities. Keep the historical
// numeric CloudJob path unchanged while allowing the browser to poll
// an Agent-backed operation through the same endpoint shape.
if (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $id) === 1) {
return $this->json($response,
CloudAgentOperationStatusService::forActor($id, $actor));
}
$query = CloudJob::where('id', $id);
if (!$actor['is_admin']) {
$query->where('user_id', $actor['user_id']);
}
@ -881,7 +907,8 @@ final class CloudApiController
$live = [];
// Detail pages use the runtime cache by default, so opening a VM does
// not wait for a potentially slow/offline host. Explicit live=1
// refreshes use a short deadline and write a valid observation through.
// refreshes use the typed Go Agent observation operation and write a
// valid observation through the same revision fence.
if (($request->getQueryParams()['live'] ?? '') === '1') {
try {
$instance = CloudAccess::instance($args['id'], $actor);
@ -904,16 +931,21 @@ final class CloudApiController
// Live state remains useful during a rolling schema
// update, but an unclaimed response must not write back.
}
$candidate = (new CloudEngineClient(null, 5.0))->host(
$observed = $this->agentObservationService()->observe(
(int) $instance->host_id,
'GET',
'vms/' . rawurlencode((string) $snapshot['uuid']) . '/state',
$actor
(string) $snapshot['uuid'],
$actor,
);
$record = is_array($observed['record'] ?? null)
? $observed['record'] : [];
if (($record['status'] ?? null) !== 'succeeded') {
throw new CloudError('宿主机 Agent 观察结果待核对', 503);
}
$candidate = is_array($observed['observation'] ?? null)
? $observed['observation'] : [];
$observedState = CloudInstanceRuntimeService::normalizeState(
$candidate['state'] ?? null
);
$observedState = is_array($candidate)
? CloudInstanceRuntimeService::normalizeState(
$candidate['state'] ?? ($candidate['power_state'] ?? null)
) : 'unknown';
if (is_array($candidate)
&& is_string($candidate['uuid'] ?? null)
&& hash_equals(strtolower((string) $snapshot['uuid']),
@ -943,7 +975,7 @@ final class CloudApiController
}
$live = $candidate;
}
} catch (CloudError $error) {
} catch (CloudError|CloudAgentOperationException $error) {
// Preserve the identity-checked runtime snapshot when the
// optional live probe cannot reach the host.
}

@ -25,6 +25,7 @@ final class CloudApi
|| preg_match('#^/api/v1/admin/hosts/[0-9]+/scheduling$#D', $path) === 1
|| preg_match('#^/api/v1/ssh-keys(?:/|$)#D', $path) === 1
|| preg_match('#^/api/v1/(?:jobs|reinstall-jobs|rescue-jobs)/[0-9]+$#D', $path) === 1
|| preg_match('#^/api/v1/(?:jobs|reinstall-jobs|rescue-jobs)/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$#D', $path) === 1
|| preg_match('#^/api/v1/vms/[0-9]+/operations$#D', $path) === 1
|| preg_match('#^/api/v1/vms/[0-9]+/firewall$#D', $path) === 1
|| preg_match('#^/api/v1/vms/[0-9]+/snapshots(?:/[0-9a-f]{32}(?:/restore)?)?$#D', $path) === 1

@ -0,0 +1,133 @@
<?php
namespace App\Services\Cloud;
use App\Models\CloudAgentOperation;
use App\Models\CloudInstance;
/**
* Project a fresh Agent journal record into the existing job-status DTO.
*
* The browser can keep polling `/api/v1/jobs/{id}` while the panel changes
* the backing store from encrypted legacy jobs to the plaintext, typed Agent
* journal. Numeric legacy IDs remain handled by CloudJobService; UUID IDs
* are resolved here and are authorized against the instance UUID in the
* journal before any status is returned.
*/
final class CloudAgentOperationStatusService
{
/** @param array<string,mixed> $actor @return array<string,mixed> */
public static function forActor(string $operationId, array $actor): array
{
if (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $operationId) !== 1) {
throw new CloudError('任务编号无效', 400);
}
try {
$row = CloudAgentOperation::where('operation_id', $operationId)->first();
} catch (\Throwable) {
throw new CloudError('Agent 操作记录暂时不可用', 503);
}
if ($row === null || !is_string($row->instance_uuid ?? null)
|| preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $row->instance_uuid) !== 1) {
throw new CloudError('任务不存在', 404);
}
try {
// Keep the tombstone visible for the terminal delete operation.
// Authorization still uses the owner on the retained instance
// row; hiding `deleted` here would make a successful/uncertain
// delete job impossible to poll after the worker marks it done.
$instance = CloudInstance::where('uuid', $row->instance_uuid)->first();
} catch (\Throwable) {
throw new CloudError('任务所属实例暂时不可用', 503);
}
if ($instance === null || (!($actor['is_admin'] ?? false)
&& (int) $instance->user_id !== (int) ($actor['user_id'] ?? 0))) {
throw new CloudError('任务不存在', 404);
}
// Re-read through the repository so stored JSON/identity invariants
// are checked before they become a browser DTO. This also avoids
// exposing hidden lease/error-detail columns from the Eloquent row.
try {
$record = (new CloudAgentOperationRepository())->get($operationId);
} catch (CloudAgentOperationException $error) {
if ($error->errorCode === 'not_found') {
throw new CloudError('任务不存在', 404);
}
throw new CloudError('Agent 操作记录暂时不可用', 503);
}
$kind = (string) ($record['kind'] ?? '');
$panelKind = self::panelKind($kind);
$status = CloudOperationErrorCatalog::userStatus($record['status'] ?? null);
if ($status === null) {
// The repository validates this invariant. Keep the adapter
// fail-closed if a future repository implementation returns an
// unrecognised state rather than copying it to the browser.
throw new CloudError('Agent 操作状态损坏', 503);
}
$desired = is_array($record['desired'] ?? null) ? $record['desired'] : [];
$agentAction = is_string($desired['action'] ?? null) ? $desired['action'] : null;
$panelAction = self::panelAction($agentAction);
$administrator = (bool) ($actor['is_admin'] ?? false);
$errorCode = CloudOperationErrorCatalog::publicCode($record['error_code'] ?? null);
$error = CloudOperationErrorCatalog::userMessage(
$panelKind, $status, $errorCode, false, $panelAction,
);
if ($administrator) {
$error = CloudOperationErrorCatalog::adminSummary(
$panelKind, $status, $record['error_code'] ?? null, false, $panelAction,
);
}
$rawResult = is_array($record['result'] ?? null) ? $record['result'] : null;
// Repository JSON validation protects the storage shape, but it is
// intentionally not a presentation allow-list. Apply the same
// result projection used by legacy job DTOs before exposing any
// Agent-produced fields to users or administrators.
$result = $rawResult === null ? null : CloudOperationErrorCatalog::result(
$rawResult,
$administrator,
$panelKind,
$status,
false,
$panelAction,
);
$phaseValue = is_array($result) ? ($result['phase'] ?? null) : null;
$phase = $administrator
? CloudOperationErrorCatalog::adminSummary(
$panelKind, $status, $phaseValue, false, $panelAction,
)
: CloudOperationErrorCatalog::userPhase($phaseValue, $status, $panelKind);
return [
'id' => $operationId,
'job_id' => $operationId,
'operation_id' => $operationId,
'instance_id' => (string) $instance->id,
'kind' => $panelKind,
'status' => $status,
'error' => $error,
'error_code' => $errorCode,
'attempts' => max(0, (int) ($record['attempt_count'] ?? 0)),
'created_at' => max(0, (int) ($record['created_at'] ?? 0)),
'updated_at' => max(0, (int) ($record['updated_at'] ?? 0)),
'action' => $panelAction,
'kind_label' => CloudOperationCatalog::kindLabel($panelKind, $panelAction),
'action_label' => CloudOperationCatalog::actionLabel($panelAction),
'phase' => $phase,
'result' => $result,
];
}
private static function panelKind(string $agentKind): string
{
return $agentKind === 'domain_power' ? 'action' : $agentKind;
}
private static function panelAction(?string $agentAction): ?string
{
if ($agentAction === 'destroy') {
return 'poweroff';
}
return $agentAction !== null && CloudOperationCatalog::isPowerAction($agentAction)
? $agentAction : null;
}
}

@ -19,6 +19,8 @@ $app->group('/api/v1', function () {
$this->post('/invoices/{id:[0-9]+}/payments', 'App\Controllers\CloudApiController:createInvoicePayment');
foreach (['jobs', 'reinstall-jobs', 'rescue-jobs'] as $name) {
$this->get('/' . $name . '/{id:[0-9]+}', 'App\Controllers\CloudApiController:job');
$this->get('/' . $name . '/{id:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}}',
'App\Controllers\CloudApiController:job');
}
$this->get('/resources', 'App\Controllers\CloudApiController:resources');
$this->map(['GET', 'POST'], '/user-isos', 'App\Controllers\CloudApiController:userIsos');

@ -0,0 +1,59 @@
<?php
// Dependency-free contract for the UUID Agent-operation polling bridge. The
// panel shell may not have PHP/Composer in the development environment, so
// keep this test at source level and leave the full HTTP/model test to panel
// CI.
$root = dirname(__DIR__);
$read = static function (string $path) use ($root): string {
$value = file_get_contents($root . '/' . $path);
if (!is_string($value)) {
throw new RuntimeException('Missing Cloud Agent status contract source: ' . $path);
}
return $value;
};
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$service = $read('app/Services/Cloud/CloudAgentOperationStatusService.php');
$controller = $read('app/Controllers/CloudApiController.php');
$routes = $read('config/routes_cloud.php');
$middleware = $read('app/Middleware/CloudApi.php');
$uuid = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
$jobRoute = "{id:{$uuid}}";
$jobPath = '(?:jobs|reinstall-jobs|rescue-jobs)/' . $uuid;
$assert(str_contains($routes, $jobRoute)
&& str_contains($routes, "'/' . $name . '/{id:[0-9]+}'"),
'Agent UUID job routes were added without retaining numeric legacy routes.');
$assert(str_contains($middleware, $jobPath)
&& str_contains($middleware, '(?:jobs|reinstall-jobs|rescue-jobs)/[0-9]+'),
'Cloud API middleware does not classify both Agent UUID and numeric jobs as database-only.');
$jobOffset = strpos($controller, 'public function job(');
$agentOffset = strpos($controller, 'CloudAgentOperationStatusService::forActor', $jobOffset === false ? 0 : $jobOffset);
$legacyOffset = strpos($controller, 'CloudJob::where', $jobOffset === false ? 0 : $jobOffset);
$assert($jobOffset !== false && $agentOffset !== false && $legacyOffset !== false
&& $agentOffset < $legacyOffset,
'The job controller must dispatch UUIDs to the Agent projection before the numeric CloudJob query.');
$assert(str_contains($service, 'CloudAgentOperationRepository')
&& str_contains($service, 'CloudInstance::where(\'uuid\', $row->instance_uuid)')
&& str_contains($service, 'CloudOperationErrorCatalog::result(')
&& str_contains($service, "'result' => $result"),
'Agent status projection lost repository validation, owner lookup, or result redaction.');
$assert(str_contains($service, "'job_id' => $operationId")
&& str_contains($service, "'operation_id' => $operationId")
&& str_contains($service, "'instance_id' => (string) $instance->id"),
'Agent status DTO no longer preserves the browser job identity fields.');
foreach (['CloudEngineClient', 'CloudJobService', 'CloudWorkerService', 'ssh', 'SSH', 'shell_exec', 'curl_exec'] as $forbidden) {
$assert(!str_contains($service, $forbidden),
'Agent status projection crossed a legacy transport boundary: ' . $forbidden);
}
fwrite(STDOUT, "Cloud Agent operation status contract passed.\n");
Loading…
Cancel
Save