feat: cut VM reads over typed Go Agent observations
parent
bb153a51b0
commit
fafe32a037
@ -0,0 +1,291 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/**
|
||||
* Read one explicitly authorised VM through the Go Agent.
|
||||
*
|
||||
* This is the first page-facing cutover seam: the caller keeps the existing
|
||||
* actor/instance lookup and response DTO, while host state is obtained from a
|
||||
* typed `domain_observe` operation. It never enumerates a host and it never
|
||||
* falls back to the Python engine or SSH. A transport interruption is kept
|
||||
* as an uncertain operation in the fresh panel journal and must be
|
||||
* reconciled by operation ID rather than replayed.
|
||||
*/
|
||||
final class CloudAgentObservationService
|
||||
{
|
||||
private const LEASE_SECONDS = 60;
|
||||
|
||||
/** @var \Closure():string */
|
||||
private \Closure $leaseOwnerFactory;
|
||||
|
||||
public function __construct(
|
||||
private readonly CloudAgentHostClientResolver $resolver,
|
||||
private readonly CloudAgentOperationRepository $operations,
|
||||
?callable $leaseOwnerFactory = null,
|
||||
private readonly int $leaseSeconds = self::LEASE_SECONDS,
|
||||
) {
|
||||
if ($leaseSeconds < 1 || $leaseSeconds > 900) {
|
||||
throw new \InvalidArgumentException('Agent observation lease is outside the supported range');
|
||||
}
|
||||
$this->leaseOwnerFactory = \Closure::fromCallable(
|
||||
$leaseOwnerFactory ?? static fn (): string => 'php-agent-observe-' . bin2hex(random_bytes(8)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $actor
|
||||
* @return array{record:array<string,mixed>,observation:array<string,mixed>|null,replayed:bool}
|
||||
*/
|
||||
public function observe(
|
||||
int $hostId,
|
||||
string $uuid,
|
||||
array $actor,
|
||||
?string $operationId = null,
|
||||
?string $idempotencyKey = null,
|
||||
): array {
|
||||
$uuid = self::uuid($uuid);
|
||||
$operationId ??= self::newUuid();
|
||||
$idempotencyKey ??= 'observe-' . bin2hex(random_bytes(16));
|
||||
self::assertOperationIdentity($operationId, $idempotencyKey);
|
||||
$payload = ['uuid' => $uuid];
|
||||
$requestHash = self::requestHash($operationId, $idempotencyKey, $uuid, $payload);
|
||||
|
||||
// A degraded registration is sufficient for a read-only observation;
|
||||
// the resolver still requires a pinned endpoint, certificate and key.
|
||||
$handle = $this->resolver->resolveReadOnly($hostId);
|
||||
$reservation = $this->operations->reserve([
|
||||
'operation_id' => $operationId,
|
||||
'idempotency_key' => $idempotencyKey,
|
||||
'agent_id' => $handle->agentId,
|
||||
'instance_uuid' => $uuid,
|
||||
'kind' => 'domain_observe',
|
||||
'target' => $uuid,
|
||||
'request_hash' => $requestHash,
|
||||
'desired' => ['uuid' => $uuid],
|
||||
]);
|
||||
if (($reservation['replay'] ?? false) === true) {
|
||||
$record = $reservation['record'];
|
||||
return [
|
||||
'record' => $record,
|
||||
'observation' => is_array($record['result'] ?? null) ? $record['result'] : null,
|
||||
'replayed' => true,
|
||||
];
|
||||
}
|
||||
|
||||
$owner = ($this->leaseOwnerFactory)();
|
||||
if (!is_string($owner)
|
||||
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D', $owner) !== 1) {
|
||||
throw new CloudError('面板 Agent 观察租约身份无效', 503);
|
||||
}
|
||||
$claimResult = $this->operations->claim(
|
||||
$operationId,
|
||||
$owner,
|
||||
$this->leaseSeconds,
|
||||
);
|
||||
$claim = $claimResult['claim'] ?? null;
|
||||
if (!$claim instanceof CloudAgentOperationClaim) {
|
||||
throw new CloudError('面板 Agent 观察未能取得租约', 503);
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $handle->operation(
|
||||
$operationId,
|
||||
$idempotencyKey,
|
||||
'domain_observe',
|
||||
$uuid,
|
||||
$payload,
|
||||
$actor,
|
||||
);
|
||||
// CloudAgentClient returns a reduced envelope for a definitive
|
||||
// HTTP rejection. Preserve that deterministic failure in the
|
||||
// panel journal; only transport/unknown outcomes are uncertain.
|
||||
if (self::isReducedFailure($response, $operationId)) {
|
||||
$status = $response['status'];
|
||||
$errorCode = is_string($response['error_code'] ?? null)
|
||||
&& $response['error_code'] !== ''
|
||||
? $response['error_code'] : 'agent_observation_rejected';
|
||||
if ($status === 'failed') {
|
||||
$record = $this->operations->finalize(
|
||||
$claim, 'failed', null, $errorCode, null,
|
||||
);
|
||||
} else {
|
||||
$record = $this->operations->markUncertain($claim, $errorCode);
|
||||
}
|
||||
} else {
|
||||
$envelope = CloudAgentOperationEnvelope::fromResponse(
|
||||
$response,
|
||||
$operationId,
|
||||
$idempotencyKey,
|
||||
$requestHash,
|
||||
'domain_observe',
|
||||
$uuid,
|
||||
);
|
||||
if ($envelope->status === 'succeeded') {
|
||||
$record = $this->operations->finalize(
|
||||
$claim,
|
||||
'succeeded',
|
||||
$envelope->result,
|
||||
'',
|
||||
$envelope->commitBoundary,
|
||||
);
|
||||
} elseif ($envelope->status === 'failed') {
|
||||
$record = $this->operations->finalize(
|
||||
$claim,
|
||||
'failed',
|
||||
$envelope->result,
|
||||
$envelope->errorCode,
|
||||
$envelope->commitBoundary,
|
||||
);
|
||||
} else {
|
||||
$record = $this->operations->markUncertain(
|
||||
$claim,
|
||||
$envelope->errorCode !== '' ? $envelope->errorCode : 'agent_observation_incomplete',
|
||||
$envelope->commitBoundary,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (CloudAgentOperationException $error) {
|
||||
throw $error;
|
||||
} catch (CloudError $error) {
|
||||
try {
|
||||
$this->operations->markUncertain($claim, 'agent_observation_transport_uncertain');
|
||||
} catch (CloudAgentOperationException) {
|
||||
throw $error;
|
||||
}
|
||||
throw new CloudError('宿主机 Agent 观察结果待核对,请按操作编号重试查询', 503);
|
||||
} catch (\Throwable) {
|
||||
try {
|
||||
$this->operations->markUncertain($claim, 'agent_observation_response_invalid');
|
||||
} catch (CloudAgentOperationException) {
|
||||
throw new CloudError('宿主机 Agent 观察结果待核对,请按操作编号重试查询', 503);
|
||||
}
|
||||
throw new CloudError('宿主机 Agent 观察结果待核对,请按操作编号重试查询', 503);
|
||||
}
|
||||
|
||||
return [
|
||||
'record' => $record,
|
||||
'observation' => is_array($record['result'] ?? null) ? $record['result'] : null,
|
||||
'replayed' => false,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Observe an already actor-scoped set of VMs through typed Agent calls.
|
||||
*
|
||||
* The v1 Agent intentionally exposes one explicit UUID per
|
||||
* `domain_observe`; there is no host inventory or batch endpoint. This
|
||||
* adapter keeps the old list DTO while validating every returned UUID and
|
||||
* bounded power state. A failed or uncertain item is omitted so the
|
||||
* caller can retain its database/runtime snapshot instead of fabricating
|
||||
* a successful state. Keys are caller-provided host/UUID identities and
|
||||
* are never taken from Agent response data.
|
||||
*
|
||||
* @param array<string,array{host_id:int,uuid:string}> $targets
|
||||
* @param array<string,mixed> $actor
|
||||
* @return array<string,array<string,mixed>>
|
||||
*/
|
||||
public function observeMany(array $targets, array $actor): array
|
||||
{
|
||||
$live = [];
|
||||
foreach ($targets as $key => $target) {
|
||||
if (!is_string($key) || !is_array($target)
|
||||
|| !is_int($target['host_id'] ?? null)
|
||||
|| $target['host_id'] < 1
|
||||
|| !is_string($target['uuid'] ?? null)) {
|
||||
continue;
|
||||
}
|
||||
$uuid = strtolower(trim($target['uuid']));
|
||||
if (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $uuid) !== 1) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$observed = $this->observe($target['host_id'], $uuid, $actor);
|
||||
$record = is_array($observed['record'] ?? null)
|
||||
? $observed['record'] : [];
|
||||
if (($record['status'] ?? null) !== 'succeeded') {
|
||||
continue;
|
||||
}
|
||||
$candidate = is_array($observed['observation'] ?? null)
|
||||
? $observed['observation'] : [];
|
||||
$candidateUuid = is_string($candidate['uuid'] ?? null)
|
||||
? strtolower(trim($candidate['uuid'])) : '';
|
||||
if ($candidateUuid === '' || !hash_equals($uuid, $candidateUuid)) {
|
||||
continue;
|
||||
}
|
||||
$state = CloudInstanceMetadata::state($candidate['state'] ?? null);
|
||||
if ($state === 'unknown') {
|
||||
continue;
|
||||
}
|
||||
$candidate['uuid'] = $candidateUuid;
|
||||
$candidate['state'] = $state;
|
||||
$live[$key] = $candidate;
|
||||
} catch (CloudError|CloudAgentOperationException) {
|
||||
// A list refresh is best-effort per VM. The operation row is
|
||||
// retained (including uncertain transport outcomes); the
|
||||
// caller returns the previous cache for this item.
|
||||
} catch (\Throwable) {
|
||||
// Do not allow one malformed target/Agent response to turn a
|
||||
// bounded list endpoint into a tenant-visible 500.
|
||||
}
|
||||
}
|
||||
return $live;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload */
|
||||
public static function requestHash(
|
||||
string $operationId,
|
||||
string $idempotencyKey,
|
||||
string $uuid,
|
||||
array $payload,
|
||||
): string {
|
||||
$body = json_encode([
|
||||
'operation_id' => $operationId,
|
||||
'idempotency_key' => $idempotencyKey,
|
||||
'kind' => 'domain_observe',
|
||||
'target' => $uuid,
|
||||
'payload' => $payload === [] ? (object) [] : $payload,
|
||||
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
return hash('sha256', $body);
|
||||
}
|
||||
|
||||
private static function uuid(string $uuid): string
|
||||
{
|
||||
$uuid = strtolower(trim($uuid));
|
||||
if (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $uuid) !== 1) {
|
||||
throw new CloudError('虚拟机标识无效', 422);
|
||||
}
|
||||
return $uuid;
|
||||
}
|
||||
|
||||
private static function newUuid(): string
|
||||
{
|
||||
$bytes = random_bytes(16);
|
||||
$bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40);
|
||||
$bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80);
|
||||
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
|
||||
}
|
||||
|
||||
private static function assertOperationIdentity(string $operationId, string $idempotencyKey): void
|
||||
{
|
||||
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
|
||||
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_-]{7,63}$/D', $idempotencyKey) !== 1) {
|
||||
throw new CloudError('面板 Agent 观察操作身份无效', 422);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $response */
|
||||
private static function isReducedFailure(array $response, string $operationId): bool
|
||||
{
|
||||
return ($response['operation_id'] ?? null) === $operationId
|
||||
&& is_string($response['status'] ?? null)
|
||||
&& in_array($response['status'], [
|
||||
'pending', 'running', 'succeeded', 'failed', 'uncertain',
|
||||
], true)
|
||||
&& !array_key_exists('idempotency_key', $response)
|
||||
&& !array_key_exists('request_hash', $response)
|
||||
&& !array_key_exists('kind', $response)
|
||||
&& !array_key_exists('target', $response)
|
||||
&& !array_key_exists('commit_boundary', $response);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
// Source contract for the first page-facing read cutover. The repository's
|
||||
// full integration test requires Laravel/Guzzle and is run in the panel CI;
|
||||
// this dependency-free check guards the transport and legacy boundaries in
|
||||
// the lightweight audit environment.
|
||||
$root = dirname(__DIR__);
|
||||
$service = file_get_contents($root . '/app/Services/Cloud/CloudAgentObservationService.php');
|
||||
$client = file_get_contents($root . '/app/Services/Cloud/CloudAgentClient.php');
|
||||
$handle = file_get_contents($root . '/app/Services/Cloud/CloudAgentHandle.php');
|
||||
$repository = file_get_contents($root . '/app/Services/Cloud/CloudAgentOperationRepository.php');
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$assert(is_string($service)
|
||||
&& str_contains($service, "'domain_observe'")
|
||||
&& str_contains($service, 'resolveReadOnly')
|
||||
&& str_contains($service, 'markUncertain')
|
||||
&& str_contains($service, 'CloudAgentOperationEnvelope::fromResponse')
|
||||
&& str_contains($service, 'public function observeMany(')
|
||||
&& str_contains($service, 'CloudInstanceMetadata::state')
|
||||
&& str_contains($service, 'isReducedFailure')
|
||||
&& !str_contains($service, 'CloudEngineClient')
|
||||
&& !str_contains($service, 'ssh'),
|
||||
'Observation service crossed the legacy Python/SSH boundary or lost its journal gate.');
|
||||
$assert(is_string($client) && str_contains($client, "'domain_observe'"),
|
||||
'Agent transport does not allow the domain observation kind.');
|
||||
$assert(is_string($handle)
|
||||
&& str_contains($handle, "['domain_read', 'domain_observe']"),
|
||||
'Read-only Agent handles do not allow the observation kind.');
|
||||
$assert(is_string($repository) && str_contains($repository, "'domain_observe'"),
|
||||
'Panel operation repository does not recognize observation records.');
|
||||
|
||||
fwrite(STDOUT, "Cloud Agent observation service contract passed.\n");
|
||||
Loading…
Reference in New Issue