feat: add typed PHP Go Agent VM gateway
parent
954096def7
commit
0dcc4f42a2
@ -0,0 +1,284 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/**
|
||||
* Typed panel-to-Agent boundary for VM operations.
|
||||
*
|
||||
* This class is intentionally not a compatibility adapter for the Python
|
||||
* engine. It resolves one enrolled Go Agent, reserves a fresh panel CAS
|
||||
* record, submits one typed operation, and projects the Agent envelope into
|
||||
* the panel journal. A panel kind without an exact Agent implementation is
|
||||
* rejected before a row is dispatched; it must never be reported as success.
|
||||
*/
|
||||
final class CloudAgentVmGateway
|
||||
{
|
||||
private const LEASE_SECONDS = 120;
|
||||
|
||||
/**
|
||||
* Every persisted panel kind is listed here, including unsupported ones.
|
||||
* A null value is deliberate: it makes a missing implementation visible
|
||||
* at the PHP boundary rather than silently routing to a legacy transport.
|
||||
*
|
||||
* @var array<string,string|null>
|
||||
*/
|
||||
private const PANEL_TO_AGENT_KIND = [
|
||||
'create' => null,
|
||||
'action' => 'domain_power',
|
||||
'reinstall' => null,
|
||||
'rescue' => null,
|
||||
'delete' => null,
|
||||
'network_change' => null,
|
||||
'instance_settings' => null,
|
||||
'snapshot_create' => null,
|
||||
'snapshot_restore' => null,
|
||||
'snapshot_delete' => null,
|
||||
'firewall_apply' => null,
|
||||
'service_suspend' => null,
|
||||
'service_resume' => null,
|
||||
'network_suspend' => null,
|
||||
'network_resume' => null,
|
||||
'expiry_delete' => null,
|
||||
];
|
||||
|
||||
/** @var \Closure():string */
|
||||
private \Closure $leaseOwnerFactory;
|
||||
|
||||
/**
|
||||
* @param callable|null $leaseOwnerFactory Returns a process-local lease
|
||||
* owner. It is injected in contract tests and must not be queued or
|
||||
* persisted as an authentication credential.
|
||||
*/
|
||||
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 operation lease is outside the supported range');
|
||||
}
|
||||
$this->leaseOwnerFactory = \Closure::fromCallable(
|
||||
$leaseOwnerFactory ?? static function (): string {
|
||||
return 'php-agent-gateway-' . bin2hex(random_bytes(8));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** @return array<string,string|null> */
|
||||
public static function panelAgentKindMap(): array
|
||||
{
|
||||
return self::PANEL_TO_AGENT_KIND;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the exact Agent kind for a panel kind, or fail closed when the
|
||||
* Agent does not implement the panel operation yet.
|
||||
*/
|
||||
public static function agentKindForPanelKind(string $panelKind): string
|
||||
{
|
||||
if (!array_key_exists($panelKind, self::PANEL_TO_AGENT_KIND)) {
|
||||
throw new CloudError('面板操作类型无效', 422);
|
||||
}
|
||||
$agentKind = self::PANEL_TO_AGENT_KIND[$panelKind];
|
||||
if ($agentKind === null) {
|
||||
throw new CloudError('该虚拟机操作尚未由 Go Agent 实现', 501);
|
||||
}
|
||||
return $agentKind;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reserve and dispatch one typed VM operation.
|
||||
*
|
||||
* The request hash is computed over the exact `/v1/operations` JSON body
|
||||
* generated by CloudAgentClient. The repository stores a redacted desired
|
||||
* projection; raw Agent responses never enter the panel database.
|
||||
*
|
||||
* @param array<string,mixed> $payload
|
||||
* @param array<string,mixed> $actor
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function dispatch(
|
||||
int $hostId,
|
||||
string $panelKind,
|
||||
string $operationId,
|
||||
string $idempotencyKey,
|
||||
string $target,
|
||||
array $payload,
|
||||
array $actor,
|
||||
?string $instanceUuid = null,
|
||||
): array {
|
||||
$agentKind = self::agentKindForPanelKind($panelKind);
|
||||
self::assertOperationIdentity($operationId, $idempotencyKey, $target, $instanceUuid);
|
||||
$payload = self::validatePayload($agentKind, $target, $payload);
|
||||
$requestHash = self::requestHash($operationId, $idempotencyKey, $agentKind, $target, $payload);
|
||||
|
||||
// Resolve before reserving so an operation cannot be written against
|
||||
// a host whose current enrollment or key material is unusable.
|
||||
$handle = $this->resolver->resolve($hostId);
|
||||
$reservation = $this->operations->reserve([
|
||||
'operation_id' => $operationId,
|
||||
'idempotency_key' => $idempotencyKey,
|
||||
'agent_id' => $handle->agentId,
|
||||
'instance_uuid' => $instanceUuid,
|
||||
'kind' => $agentKind,
|
||||
'target' => $target,
|
||||
'request_hash' => $requestHash,
|
||||
'desired' => self::journalDesired($agentKind, $payload),
|
||||
]);
|
||||
if (($reservation['replay'] ?? false) === true) {
|
||||
return [
|
||||
'record' => $reservation['record'],
|
||||
'replayed' => true,
|
||||
'panel_kind' => $panelKind,
|
||||
'agent_kind' => $agentKind,
|
||||
];
|
||||
}
|
||||
|
||||
$leaseOwner = ($this->leaseOwnerFactory)();
|
||||
if (!is_string($leaseOwner) || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D', $leaseOwner) !== 1) {
|
||||
throw new CloudError('面板 Agent 操作租约身份无效', 503);
|
||||
}
|
||||
$claimResult = $this->operations->claim(
|
||||
$operationId,
|
||||
$leaseOwner,
|
||||
$this->leaseSeconds,
|
||||
);
|
||||
$claim = $claimResult['claim'] ?? null;
|
||||
if (!$claim instanceof CloudAgentOperationClaim) {
|
||||
throw new CloudError('面板 Agent 操作未能取得租约', 503);
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $handle->operation(
|
||||
$operationId,
|
||||
$idempotencyKey,
|
||||
$agentKind,
|
||||
$target,
|
||||
$payload,
|
||||
$actor,
|
||||
);
|
||||
$envelope = CloudAgentOperationEnvelope::fromResponse(
|
||||
$response,
|
||||
$operationId,
|
||||
$idempotencyKey,
|
||||
$requestHash,
|
||||
$agentKind,
|
||||
$target,
|
||||
);
|
||||
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_operation_incomplete',
|
||||
$envelope->commitBoundary,
|
||||
);
|
||||
}
|
||||
} catch (CloudAgentOperationException $error) {
|
||||
// A database CAS failure must not be converted into a transport
|
||||
// result. The caller must surface it and reconcile by operation ID.
|
||||
throw $error;
|
||||
} catch (CloudError $error) {
|
||||
// A timeout, reset, or incomplete envelope does not prove whether
|
||||
// the host acted. Keep the row uncertain and never replay blindly.
|
||||
try {
|
||||
$record = $this->operations->markUncertain($claim, 'agent_transport_uncertain');
|
||||
} catch (CloudAgentOperationException) {
|
||||
throw $error;
|
||||
}
|
||||
throw new CloudError('宿主机 Agent 响应不确定,请按操作编号核对结果', $error->httpStatus);
|
||||
} catch (\Throwable $error) {
|
||||
try {
|
||||
$record = $this->operations->markUncertain($claim, 'agent_response_invalid');
|
||||
} catch (CloudAgentOperationException) {
|
||||
throw new CloudError('宿主机 Agent 响应无效,请按操作编号核对结果', 502);
|
||||
}
|
||||
throw new CloudError('宿主机 Agent 响应无效,请按操作编号核对结果', 502);
|
||||
}
|
||||
|
||||
return [
|
||||
'record' => $record,
|
||||
'replayed' => false,
|
||||
'panel_kind' => $panelKind,
|
||||
'agent_kind' => $agentKind,
|
||||
];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload @return array<string,mixed> */
|
||||
private static function validatePayload(string $agentKind, string $target, array $payload): array
|
||||
{
|
||||
if ($agentKind !== 'domain_power') {
|
||||
throw new CloudError('宿主机 Agent 操作映射无效', 501);
|
||||
}
|
||||
$keys = array_keys($payload);
|
||||
sort($keys, SORT_STRING);
|
||||
if ($keys !== ['action', 'uuid']
|
||||
|| !is_string($payload['uuid'] ?? null)
|
||||
|| $payload['uuid'] !== $target
|
||||
|| preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $target) !== 1
|
||||
|| !is_string($payload['action'] ?? null)
|
||||
|| !CloudOperationCatalog::isPowerAction($payload['action'])) {
|
||||
throw new CloudError('电源操作参数无效', 422);
|
||||
}
|
||||
return ['uuid' => $target, 'action' => $payload['action']];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload */
|
||||
private static function requestHash(
|
||||
string $operationId,
|
||||
string $idempotencyKey,
|
||||
string $kind,
|
||||
string $target,
|
||||
array $payload,
|
||||
): string {
|
||||
$body = json_encode([
|
||||
'operation_id' => $operationId,
|
||||
'idempotency_key' => $idempotencyKey,
|
||||
'kind' => $kind,
|
||||
'target' => $target,
|
||||
'payload' => $payload === [] ? (object) [] : $payload,
|
||||
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
return hash('sha256', $body);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload @return array<string,mixed> */
|
||||
private static function journalDesired(string $kind, array $payload): array
|
||||
{
|
||||
if ($kind === 'domain_power') {
|
||||
return ['uuid' => $payload['uuid'], 'action' => $payload['action']];
|
||||
}
|
||||
throw new CloudError('宿主机 Agent 操作 journal 映射无效', 501);
|
||||
}
|
||||
|
||||
private static function assertOperationIdentity(
|
||||
string $operationId,
|
||||
string $idempotencyKey,
|
||||
string $target,
|
||||
?string $instanceUuid,
|
||||
): 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
|
||||
|| $target !== trim($target)
|
||||
|| strlen($target) > 128
|
||||
|| preg_match('/[\x00-\x1F\x7F]/', $target) === 1
|
||||
|| ($instanceUuid !== null
|
||||
&& preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $instanceUuid) !== 1)) {
|
||||
throw new CloudError('面板 Agent 操作身份无效', 422);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
// This contract test is intentionally dependency-free. The development shell
|
||||
// may not have PHP/Composer, so it checks the source-level boundary that must
|
||||
// hold before the gateway is wired into controllers.
|
||||
$root = dirname(__DIR__);
|
||||
$gateway = file_get_contents($root . '/app/Services/Cloud/CloudAgentVmGateway.php');
|
||||
$catalog = file_get_contents($root . '/app/Services/Cloud/CloudOperationCatalog.php');
|
||||
if (!is_string($gateway) || !is_string($catalog)) {
|
||||
throw new RuntimeException('Cloud Agent gateway contract sources are missing.');
|
||||
}
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
foreach ([
|
||||
'create', 'action', 'reinstall', 'rescue', 'delete', 'network_change',
|
||||
'instance_settings', 'snapshot_create', 'snapshot_restore', 'snapshot_delete',
|
||||
'firewall_apply', 'service_suspend', 'service_resume', 'network_suspend',
|
||||
'network_resume', 'expiry_delete',
|
||||
] as $kind) {
|
||||
$assert(str_contains($gateway, "'{$kind}' =>"),
|
||||
'Gateway map does not explicitly cover panel kind: ' . $kind);
|
||||
$assert(str_contains($catalog, "'{$kind}' =>"),
|
||||
'CloudOperationCatalog no longer contains panel kind: ' . $kind);
|
||||
}
|
||||
|
||||
$assert(str_contains($gateway, "'action' => 'domain_power'"),
|
||||
'The supported power-action mapping is missing.');
|
||||
$assert(str_contains($gateway, "'create' => null")
|
||||
&& str_contains($gateway, "'snapshot_create' => null")
|
||||
&& str_contains($gateway, "'delete' => null"),
|
||||
'Unsupported VM operations must fail closed instead of being aliased.');
|
||||
foreach ([
|
||||
'CloudEngineClient', 'CloudJobService', 'CloudWorkerService',
|
||||
'ssh', 'SSH', 'shell_exec', 'exec(', 'curl_exec',
|
||||
] as $forbidden) {
|
||||
$assert(!str_contains($gateway, $forbidden),
|
||||
'Gateway contains a forbidden legacy transport reference: ' . $forbidden);
|
||||
}
|
||||
foreach ([
|
||||
'CloudAgentHostClientResolver', 'CloudAgentOperationRepository',
|
||||
'CloudAgentOperationEnvelope', 'requestHash(', 'idempotency_key',
|
||||
'operation_id', 'markUncertain', 'CloudError',
|
||||
] as $required) {
|
||||
$assert(str_contains($gateway, $required),
|
||||
'Gateway is missing required typed operation boundary: ' . $required);
|
||||
}
|
||||
|
||||
fwrite(STDOUT, "Cloud Agent VM gateway contract passed.\n");
|
||||
Loading…
Reference in New Issue