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/CloudAgentCreatePlanService...

453 lines
18 KiB
PHP

<?php
namespace App\Services\Cloud;
/**
* Typed, read-only create-plan boundary for the Go Agent.
*
* A plan validates the immutable EFI/q35/no-Secure-Boot policy, seed identity,
* first-boot script and image digest, then asks the Agent for a fresh host
* capability observation. It never publishes a seed, allocates storage,
* defines a domain, powers a guest, or changes networking. Callers must not
* interpret a successful plan as a created VM.
*/
final class CloudAgentCreatePlanService
{
private const KIND = 'domain_create_plan';
private const LEASE_SECONDS = 120;
/** @var \Closure():string */
private \Closure $leaseOwnerFactory;
/**
* Production assembly helper. It reads only the fresh Agent registry,
* root-only key files and explicit address allowlist; no legacy transport
* configuration is consulted.
*/
public static function fromConfig(
?callable $leaseOwnerFactory = null,
int $leaseSeconds = self::LEASE_SECONDS,
): self {
return new self(
CloudAgentHostClientResolverFactory::fromConfig(),
new CloudAgentOperationRepository(),
$leaseOwnerFactory,
$leaseSeconds,
);
}
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 create-plan lease is outside the supported range');
}
$this->leaseOwnerFactory = \Closure::fromCallable(
$leaseOwnerFactory ?? static fn (): string => 'php-agent-create-plan-' . bin2hex(random_bytes(8)),
);
}
/**
* Validate and dispatch one read-only create plan.
*
* The returned record is a redacted panel journal projection. A
* `succeeded` record means only that the plan and host capability policy
* were confirmed; it is never a create acknowledgement.
*
* @param array<string,mixed> $request
* @param array<string,mixed> $actor
* @return array{record:array<string,mixed>,replayed:bool,agent_kind:string,operation_id:string,idempotency_key:string}
*/
public function plan(
int $hostId,
array $request,
array $actor,
?string $operationId = null,
?string $idempotencyKey = null,
): array {
$request = self::validateRequest($request);
$domainUuid = $request['domain']['uuid'];
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('create-plan')
: CloudAgentOperationIdentity::validateIdempotencyKey($idempotencyKey);
$operationId = CloudAgentOperationIdentity::uuidForIdempotencyKey($idempotencyKey);
}
$requestHash = self::requestHash(
$operationId,
$idempotencyKey,
$domainUuid,
$request,
);
// Planning is a protected Agent operation. Resolve an active handle;
// a degraded read-only handle is intentionally not allowed to report
// a create plan because its capability snapshot may be stale.
$handle = $this->resolver->resolve($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' => $domainUuid,
'instance_id' => null,
'kind' => self::KIND,
'target' => $domainUuid,
'request_hash' => $requestHash,
'desired' => self::journalDesired($request),
]);
if (($reservation['replay'] ?? false) === true) {
return [
'record' => $reservation['record'],
'replayed' => true,
'agent_kind' => self::KIND,
'operation_id' => $operationId,
'idempotency_key' => $idempotencyKey,
];
}
$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,
self::KIND,
$domainUuid,
$request,
$actor,
);
if (self::isReducedFailure($response, $operationId)) {
$errorCode = is_string($response['error_code'] ?? null)
&& $response['error_code'] !== ''
? $response['error_code'] : 'agent_create_plan_rejected';
if (self::isDefinitiveReducedRejection($response)) {
$record = $this->operations->finalize(
$claim, 'failed', null, $errorCode, null,
);
} else {
// A 5xx or non-terminal reduced response does not prove
// whether the Agent completed its capability observation.
$record = $this->operations->markUncertain(
$claim, 'agent_create_plan_transport_uncertain',
);
}
} else {
$envelope = CloudAgentOperationEnvelope::fromResponse(
$response,
$operationId,
$idempotencyKey,
$requestHash,
self::KIND,
$domainUuid,
);
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_create_plan_incomplete',
$envelope->commitBoundary,
);
}
}
} catch (CloudAgentOperationException $error) {
// A panel journal CAS/lease failure is not a host result. The
// caller must surface the operation ID and reconcile explicitly.
throw $error;
} catch (CloudError $error) {
// CloudAgentClient normalizes only transport/malformed-response
// ambiguity to 502. Deterministic local/configuration or explicit
// Agent rejection must be terminal failure, not "待核对".
if ($error->httpStatus !== 502) {
try {
$this->operations->finalize(
$claim, 'failed', null, 'agent_request_rejected', null,
);
} catch (CloudAgentOperationException) {
throw $error;
}
throw $error;
}
try {
$record = $this->operations->markUncertain(
$claim, 'agent_create_plan_transport_uncertain'
);
} catch (CloudAgentOperationException) {
throw $error;
}
throw new CloudAgentDispatchUncertain(
$operationId,
$record,
$error->httpStatus,
);
} catch (\Throwable) {
try {
$record = $this->operations->markUncertain(
$claim, 'agent_create_plan_response_invalid'
);
} catch (CloudAgentOperationException) {
throw new CloudError('宿主机 Agent 创建计划响应无效,请按操作编号核对结果', 502);
}
throw new CloudAgentDispatchUncertain($operationId, $record, 502);
}
return [
'record' => $record,
'replayed' => false,
'agent_kind' => self::KIND,
'operation_id' => $operationId,
'idempotency_key' => $idempotencyKey,
];
}
/**
* Validate and canonicalize the strict plan request without contacting a
* host. Agent-side validation remains authoritative; this boundary only
* prevents arbitrary fields/content from entering the signed request.
*
* @param array<string,mixed> $request
* @return array<string,mixed>
*/
public static function validateRequest(array $request): array
{
self::keys($request, ['domain', 'seed'], ['image']);
$domain = $request['domain'] ?? null;
$seed = $request['seed'] ?? null;
if (!is_array($domain) || array_is_list($domain)
|| !is_array($seed) || array_is_list($seed)) {
throw new CloudError('创建计划请求结构无效', 422);
}
self::keys($domain,
['uuid', 'firmware', 'architecture', 'machine', 'os_type', 'loader']);
$loader = $domain['loader'] ?? null;
if (!is_array($loader) || array_is_list($loader)) {
throw new CloudError('创建计划 loader 参数无效', 422);
}
self::keys($loader, ['type', 'readonly', 'secure_boot']);
$uuid = self::uuid($domain['uuid'] ?? null, '虚拟机');
if (($domain['firmware'] ?? null) !== 'efi'
|| ($domain['architecture'] ?? null) !== 'x86_64'
|| ($domain['machine'] ?? null) !== 'q35'
|| ($domain['os_type'] ?? null) !== 'hvm'
|| ($loader['type'] ?? null) !== 'pflash'
|| ($loader['readonly'] ?? null) !== true
|| ($loader['secure_boot'] ?? null) !== false) {
throw new CloudError('创建计划必须使用 EFI/q35 且关闭安全启动', 422);
}
$domain['uuid'] = $uuid;
$domain['loader'] = [
'type' => 'pflash',
'readonly' => true,
'secure_boot' => false,
];
self::keys($seed,
['artifact_id', 'instance_id', 'hostname'],
['network_config', 'startup_script']);
$artifact = self::uuid($seed['artifact_id'] ?? null, 'seed artifact');
$instanceId = self::scalar($seed['instance_id'] ?? null, '实例标识', 255);
$hostname = self::scalar($seed['hostname'] ?? null, '主机名', 255);
$network = $seed['network_config'] ?? '';
$script = $seed['startup_script'] ?? '';
if (!is_string($network) || !is_string($script)) {
throw new CloudError('创建计划 seed 参数无效', 422);
}
self::utf8Text($network, '网络配置', 1024 * 1024, true);
self::utf8Text($script, '启动脚本', 32 * 1024, true);
if ($network !== '') {
try {
$decoded = json_decode($network, true, 32, JSON_THROW_ON_ERROR);
} catch (\Throwable) {
throw new CloudError('网络配置必须是 JSON 对象', 422);
}
if (!is_array($decoded) || array_is_list($decoded)) {
throw new CloudError('网络配置必须是 JSON 对象', 422);
}
}
$seed['artifact_id'] = $artifact;
$seed['instance_id'] = $instanceId;
$seed['hostname'] = $hostname;
$seed['network_config'] = $network;
$seed['startup_script'] = str_replace("\r\n", "\n", $script);
$normalized = [
'domain' => $domain,
'seed' => $seed,
];
if (array_key_exists('image', $request)) {
$image = $request['image'];
if (!is_array($image) || array_is_list($image)) {
throw new CloudError('镜像标识无效', 422);
}
self::keys($image, ['id', 'sha256']);
$imageId = self::scalar($image['id'] ?? null, '镜像标识', 128);
$digest = $image['sha256'] ?? null;
if (!is_string($digest) || preg_match('/^[a-f0-9]{64}$/D', $digest) !== 1) {
throw new CloudError('镜像摘要无效', 422);
}
if (preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/D', $imageId) !== 1) {
throw new CloudError('镜像标识无效', 422);
}
$normalized['image'] = ['id' => $imageId, 'sha256' => $digest];
}
return $normalized;
}
/** @param array<string,mixed> $request */
private static function journalDesired(array $request): array
{
$seed = $request['seed'];
$script = (string) $seed['startup_script'];
$network = (string) $seed['network_config'];
$desired = [
'domain' => $request['domain'],
'seed_artifact_id' => $seed['artifact_id'],
'instance_id' => $seed['instance_id'],
'hostname' => $seed['hostname'],
// These are hashes of panel input, not claims about the Agent's
// canonical rendered seed. The Agent's own journal remains the
// authoritative reconciliation identity.
'network_input_sha256' => hash('sha256', $network),
'first_boot_present' => $script !== '',
'first_boot_digest' => hash('sha256', $script),
];
if (array_key_exists('image', $request)) {
$desired['image'] = $request['image'];
}
return $desired;
}
/** @param array<string,mixed> $payload */
public static function requestHash(
string $operationId,
string $idempotencyKey,
string $target,
array $payload,
): string {
$body = json_encode([
'operation_id' => $operationId,
'idempotency_key' => $idempotencyKey,
'kind' => self::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> $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('idempotency_key', $response)
&& !array_key_exists('result', $response)
&& !array_key_exists('commit_boundary', $response)
&& !array_key_exists('request_hash', $response)
&& !array_key_exists('kind', $response)
&& !array_key_exists('target', $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);
}
/** @param array<string,mixed> $value @param list<string> $required @param list<string> $optional */
private static function keys(array $value, array $required, array $optional = []): void
{
$allowed = array_fill_keys(array_merge($required, $optional), true);
foreach ($required as $key) {
if (!array_key_exists($key, $value)) {
throw new CloudError('创建计划请求缺少必要字段', 422);
}
}
foreach (array_keys($value) as $key) {
if (!is_string($key) || !isset($allowed[$key])) {
throw new CloudError('创建计划请求包含未允许字段', 422);
}
}
}
private static function uuid(mixed $value, string $label): string
{
if (!is_string($value)) {
throw new CloudError($label . '标识无效', 422);
}
$value = strtolower(trim($value));
if (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $value) !== 1) {
throw new CloudError($label . '标识无效', 422);
}
return $value;
}
private static function scalar(mixed $value, string $label, int $maxBytes): string
{
if (!is_string($value) || $value === '' || $value !== trim($value)
|| strlen($value) > $maxBytes
|| preg_match('/[\x00-\x1F\x7F]/', $value) === 1
|| preg_match('//u', $value) !== 1) {
throw new CloudError($label . '无效', 422);
}
return $value;
}
private static function utf8Text(string $value, string $label, int $maxBytes, bool $allowEmpty): void
{
if ((!$allowEmpty && $value === '') || strlen($value) > $maxBytes
|| preg_match('//u', $value) !== 1 || str_contains($value, "\0")) {
throw new CloudError($label . '无效', 422);
}
}
}