You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudAgentObservationServic...

349 lines
15 KiB
PHP

<?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 MAX_BATCH_TARGETS = 20;
private const MAX_BATCH_SECONDS = 20.0;
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,
?int $instanceId = null,
): array {
$uuid = self::uuid($uuid);
if ($instanceId !== null && $instanceId < 1) {
throw new CloudError('虚拟机编号无效', 422);
}
if ($operationId !== null && $operationId !== '') {
$operationId = CloudAgentOperationIdentity::validateUuid($operationId);
if ($idempotencyKey === null || $idempotencyKey === '') {
throw new CloudError(
'面板 Agent 观察重试必须同时提供 operation_id 和幂等键', 422);
}
$idempotencyKey = CloudAgentOperationIdentity::validateIdempotencyKey($idempotencyKey);
} else {
$idempotencyKey = $idempotencyKey === null || $idempotencyKey === ''
? CloudAgentOperationIdentity::idempotencyKey('observe')
: CloudAgentOperationIdentity::validateIdempotencyKey($idempotencyKey);
$operationId = CloudAgentOperationIdentity::uuidForIdempotencyKey($idempotencyKey);
}
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);
if ($handle->hostId !== $hostId) {
throw new CloudError('宿主机 Agent 身份不匹配', 503);
}
$reservation = $this->operations->reserve([
'operation_id' => $operationId,
'idempotency_key' => $idempotencyKey,
'agent_id' => $handle->agentId,
'host_id' => $hostId,
'instance_uuid' => $uuid,
'instance_id' => $instanceId,
'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)) {
$errorCode = is_string($response['error_code'] ?? null)
&& $response['error_code'] !== ''
? $response['error_code'] : 'agent_observation_rejected';
if (self::isDefinitiveReducedRejection($response)) {
$record = $this->operations->finalize(
$claim, 'failed', null, $errorCode, null,
);
} else {
$record = $this->operations->markUncertain(
$claim, 'agent_observation_transport_uncertain',
);
}
} 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) {
// CloudAgentClient uses 502 for transport or malformed-response
// ambiguity. Other statuses are local/configuration or explicit
// request rejection and can be finalized as failed without
// manufacturing a "待核对" host outcome.
if ($error->httpStatus !== 502) {
try {
$this->operations->finalize(
$claim, 'failed', null, 'agent_request_rejected', null,
);
} catch (CloudAgentOperationException) {
throw $error;
}
throw $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,id?:int}> $targets
* @param array<string,mixed> $actor
* @return array<string,array<string,mixed>>
*/
public function observeMany(array $targets, array $actor): array
{
$live = [];
$started = microtime(true);
$processed = 0;
foreach ($targets as $key => $target) {
if ($processed >= self::MAX_BATCH_TARGETS
|| microtime(true) - $started >= self::MAX_BATCH_SECONDS) {
break;
}
if (!is_string($key) || !is_array($target)
|| !is_int($target['host_id'] ?? null)
|| $target['host_id'] < 1
|| !is_string($target['uuid'] ?? null)) {
continue;
}
$instanceId = $target['id'] ?? null;
if ($instanceId !== null && (!is_int($instanceId) || $instanceId < 1)) {
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 {
$processed++;
$observed = $this->observe(
$target['host_id'], $uuid, $actor, null, null, $instanceId
);
$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 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
&& isset($response['_agent_http_status'])
&& is_int($response['_agent_http_status'])
&& $response['_agent_http_status'] >= 400
&& $response['_agent_http_status'] <= 599
&& is_string($response['status'] ?? null)
&& in_array($response['status'], [
'pending', 'running', 'succeeded', 'failed', 'uncertain',
], true)
&& !array_key_exists('result', $response)
&& !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);
}
/** @param array<string,mixed> $response */
private static function isDefinitiveReducedRejection(array $response): bool
{
return ($response['status'] ?? null) === 'failed'
&& in_array((int) ($response['_agent_http_status'] ?? 0),
[400, 401, 403, 404, 413, 422, 501], true);
}
}