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.
2434 lines
102 KiB
PHP
2434 lines
102 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Cloud;
|
|
|
|
use App\Models\CloudDeploymentSnapshot;
|
|
use App\Models\CloudInstance;
|
|
use App\Models\CloudInstanceBackup;
|
|
use App\Models\CloudInstanceMigration;
|
|
use App\Models\CloudInstanceMigrationSourceDebt;
|
|
use App\Models\CloudInstanceFirewallVersion;
|
|
use App\Models\CloudInstanceSnapshot;
|
|
use App\Models\CloudPeerMigrationArtifact;
|
|
use App\Models\CloudBackupRestore;
|
|
use App\Models\CloudBackupRestoreAttempt;
|
|
use App\Models\CloudBackupRecovery;
|
|
use App\Models\CloudHostStorageConfiguration;
|
|
use App\Models\CloudJob;
|
|
use App\Models\CloudOrder;
|
|
use App\Models\CloudPublicNetworkTransition;
|
|
use App\Models\CloudResourceReservation;
|
|
use App\Models\CloudRescueTemplate;
|
|
use App\Models\CloudRescueTemplateReplica;
|
|
use App\Models\CloudTemplate;
|
|
use App\Models\CloudTemplateReplica;
|
|
use App\Models\CloudUserIso;
|
|
use App\Models\CloudUserIsoReplica;
|
|
|
|
/** Rebuilds the immutable Agent Journal identity from PHP-owned durable state. */
|
|
final class CloudOperationRecoveryIdentity
|
|
{
|
|
private const VERSION = 1;
|
|
private const KEY = '_operation_identity';
|
|
private const UUID_PATTERN =
|
|
'/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/D';
|
|
private const CATALOG_ID_PATTERN = '/^[a-f0-9]{32}$/D';
|
|
private const TEMPLATE_ID_PATTERN =
|
|
'/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D';
|
|
|
|
/**
|
|
* Every PHP job kind that crosses an Agent mutation endpoint must carry an
|
|
* immutable Journal identity. This is intentionally broader than
|
|
* CloudOperationRecoveryPolicy: create and host storage keep their existing
|
|
* financial/operator recovery rules, but their responses are no less
|
|
* security-sensitive than automatically recoverable VM/catalog jobs.
|
|
*/
|
|
public static function supports(string $kind): bool
|
|
{
|
|
return CloudOperationRecoveryPolicy::identityScope($kind) !== null;
|
|
}
|
|
|
|
/**
|
|
* @return array{action:string,resource_id:string,request_fingerprint:string}
|
|
*/
|
|
public static function expected(
|
|
CloudJob $job,
|
|
bool $forAppliedEffect = false
|
|
): array {
|
|
try {
|
|
$payload = CloudSecrets::decrypt(
|
|
(string) $job->sealed_payload,
|
|
'job-payload'
|
|
);
|
|
} catch (\Throwable $error) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'任务恢复请求无法解密',
|
|
409
|
|
);
|
|
}
|
|
if (!is_array($payload) || array_is_list($payload)) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'任务恢复请求结构无效',
|
|
409
|
|
);
|
|
}
|
|
|
|
$stored = self::stored($payload);
|
|
$portableRestoreAttempt = CloudPortableRestoreFinalizer::owns($job);
|
|
if ($portableRestoreAttempt) {
|
|
$attempt = CloudBackupRestoreAttempt::where(
|
|
'job_id', (int) $job->id
|
|
)->first();
|
|
if (!$attempt instanceof CloudBackupRestoreAttempt
|
|
|| !hash_equals(
|
|
(string) $attempt->operation_id,
|
|
(string) $job->operation_id
|
|
)
|
|
|| $stored === null
|
|
|| (int) $job->dispatch_attempts !== 1) {
|
|
throw new CloudRecoveryOperationIdentityConflict(
|
|
'恢复任务缺少唯一派发的持久化操作身份',
|
|
409
|
|
);
|
|
}
|
|
if (in_array((string) $attempt->state, [
|
|
'queued', 'awaiting_receipt', 'effect_unknown',
|
|
'finalization_pending',
|
|
], true)
|
|
&& in_array((string) $job->phase,
|
|
['dispatching', 'awaiting_receipt', 'terminal'], true)) {
|
|
$envelope = CloudPortableRestoreJobEnvelope::
|
|
fromJobForRecovery($job, $payload);
|
|
if (!hash_equals($envelope->action(), $stored['action'])
|
|
|| !hash_equals(
|
|
$envelope->resourceId(),
|
|
$stored['resource_id']
|
|
)) {
|
|
throw new CloudRecoveryOperationIdentityConflict(
|
|
'恢复任务持久化操作身份与尝试账本不匹配',
|
|
409
|
|
);
|
|
}
|
|
return $stored;
|
|
}
|
|
if (in_array((string) $attempt->state,
|
|
['succeeded', 'failed'], true)
|
|
&& (string) $job->phase === 'terminal'
|
|
&& in_array((string) $job->effect_resolution,
|
|
['applied', 'not_applied'], true)) {
|
|
return $stored;
|
|
}
|
|
throw new CloudRecoveryOperationIdentityConflict(
|
|
'恢复任务与尝试生命周期不一致',
|
|
409
|
|
);
|
|
}
|
|
if ($stored !== null && self::isPreparedEscrow($job, $payload, $stored)) {
|
|
// prepareRecoveredEffect() may legitimately mutate or remove the
|
|
// catalog/instance row used for the original strict validation.
|
|
// Its encrypted prepare envelope therefore carries the immutable
|
|
// identity which was validated before that ledger mutation.
|
|
return $stored;
|
|
}
|
|
if ($stored !== null
|
|
&& (string) $job->phase === 'terminal'
|
|
&& in_array((string) $job->effect_resolution,
|
|
['applied', 'not_applied'], true)) {
|
|
// A resolved task intentionally keeps only this non-secret
|
|
// binding. Any surviving safeResult body is redacted audit data,
|
|
// not the original wire payload and must not be re-fingerprinted.
|
|
return $stored;
|
|
}
|
|
$hasRequest = is_string($payload['method'] ?? null)
|
|
&& is_string($payload['request_target'] ?? null)
|
|
&& is_array($payload['body'] ?? null);
|
|
if (!$hasRequest) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'任务缺少可重建的 Agent 请求',
|
|
409
|
|
);
|
|
}
|
|
|
|
$identity = self::expectedFromPayload(
|
|
$job,
|
|
$payload,
|
|
$forAppliedEffect
|
|
);
|
|
if ($stored !== null && !self::same($identity, $stored)) {
|
|
throw new CloudRecoveryOperationIdentityConflict(
|
|
'任务持久化操作身份与原请求不匹配',
|
|
409
|
|
);
|
|
}
|
|
return $identity;
|
|
}
|
|
|
|
/**
|
|
* @return array{action:string,resource_id:string,request_fingerprint:string}
|
|
*/
|
|
public static function expectedFromPayload(
|
|
CloudJob $job,
|
|
array $payload,
|
|
bool $forAppliedEffect = false
|
|
): array {
|
|
if (!self::supports((string) $job->kind)
|
|
|| (string) $job->execution_mode !== 'agent'
|
|
|| preg_match('/^[a-f0-9]{32}$/D',
|
|
(string) $job->operation_id) !== 1
|
|
|| (int) $job->host_id < 1
|
|
|| array_is_list($payload)) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'任务不具备可恢复的 Agent 身份',
|
|
409
|
|
);
|
|
}
|
|
$method = strtoupper((string) ($payload['method'] ?? ''));
|
|
$target = $payload['request_target'] ?? null;
|
|
$body = $payload['body'] ?? null;
|
|
if (!in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE'], true)
|
|
|| !is_string($target) || !str_starts_with($target, '/v1/')
|
|
|| !is_array($body)
|
|
|| ($body !== [] && array_is_list($body))) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'任务中的 Agent 线上请求无效',
|
|
409
|
|
);
|
|
}
|
|
self::assertBodyOperation($job, $body);
|
|
|
|
$kind = (string) $job->kind;
|
|
$scope = CloudOperationRecoveryPolicy::identityScope($kind);
|
|
if ($scope === 'create') {
|
|
[$action, $resourceId] = self::createIdentity(
|
|
$job,
|
|
$payload,
|
|
$method,
|
|
$target,
|
|
$body,
|
|
$forAppliedEffect
|
|
);
|
|
} elseif ($scope === 'storage') {
|
|
[$action, $resourceId] = self::storageIdentity(
|
|
$job,
|
|
$payload,
|
|
$method,
|
|
$target,
|
|
$body
|
|
);
|
|
} elseif ($scope === 'instance') {
|
|
[$action, $resourceId] = self::instanceIdentity(
|
|
$job,
|
|
$payload,
|
|
$method,
|
|
$target,
|
|
$body,
|
|
$forAppliedEffect
|
|
);
|
|
} else {
|
|
[$action, $resourceId] = self::catalogIdentity(
|
|
$job,
|
|
$payload,
|
|
$method,
|
|
$target,
|
|
$body
|
|
);
|
|
}
|
|
if (!CloudOperationRecoveryPolicy::allowsAction($kind, $action)) {
|
|
throw new CloudRecoveryOperationIdentityConflict(
|
|
'任务种类与 Agent 操作契约不匹配',
|
|
409
|
|
);
|
|
}
|
|
$wire = self::wireBody($kind, $body);
|
|
$encoded = json_encode(
|
|
$wire === [] ? (object) [] : $wire,
|
|
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
|
|
| JSON_UNESCAPED_UNICODE
|
|
);
|
|
return [
|
|
'action' => $action,
|
|
'resource_id' => $resourceId,
|
|
'request_fingerprint' => hash(
|
|
'sha256',
|
|
$method . "\n" . $target . "\n" . $encoded
|
|
),
|
|
];
|
|
}
|
|
|
|
/** Exact body translation used by both dispatch and identity recovery. */
|
|
public static function wireBody(string $kind, array $body): array
|
|
{
|
|
if ($kind === 'action' && ($body['action'] ?? null) === 'poweroff') {
|
|
$body['action'] = 'destroy';
|
|
}
|
|
return $body;
|
|
}
|
|
|
|
/** @param array{action:string,resource_id:string,request_fingerprint:string} $identity */
|
|
public static function persisted(array $identity): array
|
|
{
|
|
self::assertIdentityShape($identity);
|
|
return [
|
|
'version' => self::VERSION,
|
|
'action' => $identity['action'],
|
|
'resource_id' => $identity['resource_id'],
|
|
'request_fingerprint' => $identity['request_fingerprint'],
|
|
];
|
|
}
|
|
|
|
public static function payloadKey(): string
|
|
{
|
|
return self::KEY;
|
|
}
|
|
|
|
public static function same(array $expected, array $actual): bool
|
|
{
|
|
foreach (['action', 'resource_id', 'request_fingerprint'] as $key) {
|
|
if (!is_string($expected[$key] ?? null)
|
|
|| !is_string($actual[$key] ?? null)
|
|
|| !hash_equals($expected[$key], $actual[$key])) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public static function assertMatches(array $expected, array $actual): void
|
|
{
|
|
if (!self::same($expected, $actual)) {
|
|
throw new CloudRecoveryOperationIdentityConflict(
|
|
'Agent 操作身份与当前任务不匹配',
|
|
409
|
|
);
|
|
}
|
|
}
|
|
|
|
private static function instanceIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body,
|
|
bool $forAppliedEffect
|
|
): array {
|
|
$kind = (string) $job->kind;
|
|
if ($kind === 'backup_workspace_cleanup') {
|
|
return self::backupWorkspaceCleanupAction(
|
|
$job, $payload, $method, $target, $body
|
|
);
|
|
}
|
|
if (in_array($kind,
|
|
['instance_migration_prepare', 'instance_migration_transfer',
|
|
'instance_migration_target_clean',
|
|
'instance_migration_cleanup', 'instance_migration_rollback',
|
|
'instance_migration_activate'], true)
|
|
&& isset($payload['maintenance_migration_id'])) {
|
|
return self::maintenanceMigrationIdentity(
|
|
$job,
|
|
$payload,
|
|
$method,
|
|
$target,
|
|
$body
|
|
);
|
|
}
|
|
if (in_array($kind, [
|
|
'vpc_host_apply', 'vpc_host_remove',
|
|
'vpc_port_attach', 'vpc_port_detach',
|
|
], true)) {
|
|
return self::vpcIdentity(
|
|
$job, $payload, $method, $target, $body
|
|
);
|
|
}
|
|
$instanceId = filter_var($job->instance_id, FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]);
|
|
$instance = $instanceId === false ? null
|
|
: CloudInstance::find((int) $instanceId);
|
|
if ($instance === null
|
|
|| (int) $instance->host_id !== (int) $job->host_id
|
|
|| preg_match(self::UUID_PATTERN,
|
|
strtolower((string) $instance->uuid)) !== 1
|
|
|| (int) ($payload['owner_id'] ?? 0)
|
|
!== (int) $instance->user_id
|
|
|| ((int) $job->user_id !== (int) $instance->user_id
|
|
&& ($payload['can_manage'] ?? false) !== true)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'任务与实例所属人、宿主机或 UUID 账本不匹配',
|
|
409
|
|
);
|
|
}
|
|
if ((string) $instance->status === 'deleted'
|
|
&& !in_array($kind,
|
|
['delete', 'delete_force', 'expiry_delete'], true)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'实例状态与原操作请求矛盾',
|
|
409
|
|
);
|
|
}
|
|
$uuid = strtolower((string) $instance->uuid);
|
|
$base = '/v1/vms/' . rawurlencode($uuid);
|
|
$action = match ($kind) {
|
|
'action' => self::powerAction($method, $target, $base, $body),
|
|
'reinstall' => self::reinstallAction(
|
|
$job, $payload, $method, $target, $base, $body,
|
|
$forAppliedEffect
|
|
),
|
|
'rescue' => self::rescueAction($method, $target, $base, $body),
|
|
'delete', 'expiry_delete' => self::deleteAction(
|
|
$method, $target, $base, $body
|
|
),
|
|
'delete_force' => self::forceDeleteAction(
|
|
$job, $payload, $method, $target, $base, $body
|
|
),
|
|
'network_change' => self::networkChangeAction(
|
|
$job, $payload, $method, $target, $base, $body
|
|
),
|
|
'instance_upgrade' => self::resizeResourcesAction(
|
|
$method, $target, $base, $body
|
|
),
|
|
'instance_settings' => self::settingsAction(
|
|
$method, $target, $base, $body
|
|
),
|
|
'snapshot_create', 'snapshot_restore', 'snapshot_delete' =>
|
|
self::snapshotAction(
|
|
$job, $payload, $instance, $method, $target, $base, $body
|
|
),
|
|
'backup_create' => self::backupCreateAction(
|
|
$job, $payload, $instance, $method, $target, $base, $body
|
|
),
|
|
'backup_recover' => self::backupRecoverAction(
|
|
$job, $payload, $instance, $method, $target, $base, $body
|
|
),
|
|
'firewall_apply' => self::firewallAction(
|
|
$job, $payload, $instance, $method, $target, $base, $body
|
|
),
|
|
'service_suspend' => self::policyAction(
|
|
$method, $target, $base . '/service/suspend', $body,
|
|
['operation_id', 'reason'],
|
|
($body['reason'] ?? null) === 'purge',
|
|
'service-suspend'
|
|
),
|
|
'network_suspend' => self::policyAction(
|
|
$method, $target, $base . '/network/suspend', $body,
|
|
['operation_id', 'reason'],
|
|
is_string($body['reason'] ?? null)
|
|
&& in_array($body['reason'], ['traffic', 'expired'], true),
|
|
'network-suspend'
|
|
),
|
|
'network_resume' => self::policyAction(
|
|
$method, $target, $base . '/network/resume', $body,
|
|
['operation_id'],
|
|
true,
|
|
'network-resume'
|
|
),
|
|
default => throw new CloudRecoveryPayloadUnavailable(
|
|
'实例任务类型没有恢复身份映射', 409
|
|
),
|
|
};
|
|
return [$action, $uuid];
|
|
}
|
|
|
|
private static function vpcIdentity(CloudJob $job, array $payload,
|
|
string $method, string $target, array $body): array
|
|
{
|
|
// This validator reconstructs the complete immutable request from the
|
|
// VPC, port, host-state and instance ledgers. It also checks method,
|
|
// target and body, so recovery cannot inspect a different host-global
|
|
// projection under a valid operation ID.
|
|
CloudVpcPortService::assertJobRunnable($job, $payload);
|
|
$kind = (string) $job->kind;
|
|
$vpcKey = $body['vpc_key']
|
|
?? ($body['network']['vpc_key'] ?? null);
|
|
if (!is_string($vpcKey)
|
|
|| preg_match(self::CATALOG_ID_PATTERN, $vpcKey) !== 1) {
|
|
self::invalidPayload('VPC 恢复任务标识无效');
|
|
}
|
|
if ($kind === 'vpc_host_apply') {
|
|
return ['apply-vpc-network:' . $vpcKey, 'vpc:' . $vpcKey];
|
|
}
|
|
if ($kind === 'vpc_host_remove') {
|
|
return ['remove-vpc-network:' . $vpcKey, 'vpc:' . $vpcKey];
|
|
}
|
|
$instance = $job->instance_id === null ? null
|
|
: CloudInstance::find((int) $job->instance_id);
|
|
if ($instance === null || preg_match(self::UUID_PATTERN,
|
|
strtolower((string) $instance->uuid)) !== 1) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'VPC 网卡任务缺少有效实例身份', 409
|
|
);
|
|
}
|
|
return [$kind === 'vpc_port_attach'
|
|
? 'apply-vpc-port' : 'remove-vpc-port',
|
|
strtolower((string) $instance->uuid)];
|
|
}
|
|
|
|
private static function maintenanceMigrationIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body
|
|
): array {
|
|
$migrationId = filter_var(
|
|
$payload['maintenance_migration_id'] ?? null,
|
|
FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]
|
|
);
|
|
$migration = $migrationId === false ? null
|
|
: CloudInstanceMigration::find((int) $migrationId);
|
|
$instance = $migration === null ? null
|
|
: CloudInstance::find((int) $migration->instance_id);
|
|
if ($migration === null || $instance === null
|
|
|| (int) $job->instance_id !== (int) $instance->id
|
|
|| (int) ($payload['owner_id'] ?? 0) !== (int) $instance->user_id
|
|
|| ((int) $job->user_id !== (int) $instance->user_id
|
|
&& ($payload['can_manage'] ?? false) !== true)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移任务与实例所属人账本不匹配',
|
|
409
|
|
);
|
|
}
|
|
if ((string) $job->kind === 'instance_migration_prepare') {
|
|
if ((int) $migration->source_prepare_job_id !== (int) $job->id
|
|
|| (int) $migration->source_host_id !== (int) $job->host_id
|
|
|| preg_match(self::UUID_PATTERN,
|
|
strtolower((string) $migration->source_uuid)) !== 1) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'PeerMigration 源准备身份不一致', 409
|
|
);
|
|
}
|
|
$uuid = strtolower((string) $migration->source_uuid);
|
|
self::expectRequest($method, $target, 'POST',
|
|
'/v1/vms/' . rawurlencode($uuid)
|
|
. '/peer-migration/prepare');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'migration_id', 'ticket', 'expires_at',
|
|
'artifacts',
|
|
]);
|
|
self::assertPeerPrepareBody($migration, $body);
|
|
return ['prepare-peer-migration:'
|
|
. (string) $migration->migration_key, $uuid];
|
|
}
|
|
if ((string) $job->kind === 'instance_migration_transfer') {
|
|
if ((int) $migration->target_receive_job_id !== (int) $job->id
|
|
|| (int) $migration->target_host_id !== (int) $job->host_id
|
|
|| preg_match(self::UUID_PATTERN,
|
|
strtolower((string) $migration->target_uuid)) !== 1) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'PeerMigration 目标接收身份不一致',
|
|
409
|
|
);
|
|
}
|
|
$uuid = strtolower((string) $migration->target_uuid);
|
|
self::expectRequest($method, $target, 'POST',
|
|
'/v1/vms/' . rawurlencode($uuid)
|
|
. '/peer-migration/receive');
|
|
self::assertPeerTransferBody(
|
|
$job, $migration, $instance, $payload, $body
|
|
);
|
|
return ['receive-peer-migration:'
|
|
. (string) $migration->migration_key, $uuid];
|
|
}
|
|
if ((string) $job->kind === 'instance_migration_target_clean') {
|
|
$prior = $job->parent_job_id === null ? null : CloudJob::find(
|
|
(int) $job->parent_job_id
|
|
);
|
|
if ($prior === null
|
|
|| (int) $migration->target_receive_job_id
|
|
!== (int) $prior->id
|
|
|| (string) $prior->kind
|
|
!== 'instance_migration_transfer'
|
|
|| (int) $migration->target_host_id !== (int) $job->host_id
|
|
|| preg_match(self::UUID_PATTERN,
|
|
strtolower((string) $migration->target_uuid)) !== 1) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'PeerMigration 目标残留清理身份不一致', 409
|
|
);
|
|
}
|
|
$uuid = strtolower((string) $migration->target_uuid);
|
|
self::expectRequest($method, $target, 'POST',
|
|
'/v1/vms/' . rawurlencode($uuid)
|
|
. '/peer-migration/cleanup-target');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'migration_id', 'prior_operation_id',
|
|
'cleanup_plan_id',
|
|
]);
|
|
if (($body['migration_id'] ?? null)
|
|
!== (string) $migration->migration_key
|
|
|| !hash_equals((string) $prior->operation_id,
|
|
(string) ($body['prior_operation_id'] ?? ''))
|
|
|| !is_string($body['cleanup_plan_id'] ?? null)
|
|
|| preg_match('/^[a-f0-9]{64}$/D',
|
|
(string) $body['cleanup_plan_id']) !== 1
|
|
|| !hash_equals((string) ($payload['cleanup_plan_id'] ?? ''),
|
|
(string) $body['cleanup_plan_id'])
|
|
|| (int) ($payload['prior_job_id'] ?? 0)
|
|
!== (int) $prior->id) {
|
|
self::invalidPayload(
|
|
'PeerMigration 目标残留清理确认无效'
|
|
);
|
|
}
|
|
return ['cleanup-peer-migration-target:'
|
|
. (string) $migration->migration_key, $uuid];
|
|
}
|
|
if ((string) $job->kind === 'instance_migration_activate') {
|
|
if ((int) $migration->activate_job_id !== (int) $job->id
|
|
|| (int) $migration->target_host_id !== (int) $job->host_id
|
|
|| preg_match(self::UUID_PATTERN,
|
|
strtolower((string) $migration->target_uuid)) !== 1) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移目标激活身份不一致',
|
|
409
|
|
);
|
|
}
|
|
$uuid = strtolower((string) $migration->target_uuid);
|
|
$base = '/v1/vms/' . rawurlencode($uuid);
|
|
self::expectRequest(
|
|
$method,
|
|
$target,
|
|
'POST',
|
|
$base . '/peer-migration/activate'
|
|
);
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'migration_id', 'target_was_running',
|
|
'target_autostart_enabled',
|
|
]);
|
|
if (($body['migration_id'] ?? null)
|
|
!== (string) $migration->migration_key
|
|
|| !is_bool($body['target_was_running'] ?? null)
|
|
|| !is_bool($body['target_autostart_enabled'] ?? null)
|
|
|| $body['target_was_running']
|
|
!== (bool) $migration->source_was_running
|
|
|| $body['target_autostart_enabled']
|
|
!== (bool) $migration->source_autostart_enabled) {
|
|
self::invalidPayload('维护迁移目标激活确认无效');
|
|
}
|
|
return ['activate-peer-migration:'
|
|
. (string) $migration->migration_key, $uuid];
|
|
}
|
|
if ((string) $job->kind === 'instance_migration_rollback') {
|
|
if ((int) $migration->rollback_job_id !== (int) $job->id
|
|
|| (int) $migration->source_host_id !== (int) $job->host_id
|
|
|| preg_match(self::UUID_PATTERN,
|
|
strtolower((string) $migration->source_uuid)) !== 1) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移源实例回滚身份不一致',
|
|
409
|
|
);
|
|
}
|
|
$uuid = strtolower((string) $migration->source_uuid);
|
|
$base = '/v1/vms/' . rawurlencode($uuid);
|
|
self::expectRequest(
|
|
$method,
|
|
$target,
|
|
'POST',
|
|
$base . '/peer-migration/rollback'
|
|
);
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'migration_id', 'source_was_running',
|
|
'source_autostart_enabled',
|
|
]);
|
|
if (($body['migration_id'] ?? null)
|
|
!== (string) $migration->migration_key
|
|
|| !is_bool($body['source_was_running'] ?? null)
|
|
|| !is_bool($body['source_autostart_enabled'] ?? null)
|
|
|| $body['source_was_running']
|
|
!== (bool) $migration->source_was_running
|
|
|| $body['source_autostart_enabled']
|
|
!== (bool) $migration->source_autostart_enabled) {
|
|
self::invalidPayload('维护迁移源实例回滚确认无效');
|
|
}
|
|
return ['rollback-peer-migration:'
|
|
. (string) $migration->migration_key, $uuid];
|
|
}
|
|
if ((int) $migration->cleanup_job_id !== (int) $job->id
|
|
|| (int) $migration->source_host_id !== (int) $job->host_id
|
|
|| preg_match(self::UUID_PATTERN,
|
|
strtolower((string) $migration->source_uuid)) !== 1) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移源副本清理身份不一致',
|
|
409
|
|
);
|
|
}
|
|
$sourceDebt = CloudInstanceMigrationSourceDebt::where(
|
|
'migration_id', (int) $migration->id
|
|
)->first();
|
|
if ($sourceDebt === null
|
|
|| !in_array((string) $sourceDebt->state,
|
|
['cleanup_running', 'attention', 'released'], true)
|
|
|| (int) $sourceDebt->cleanup_job_id !== (int) $job->id
|
|
|| !hash_equals(
|
|
(string) $sourceDebt->cleanup_operation_id,
|
|
(string) $job->operation_id
|
|
)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移源清理任务与资源债务不一致',
|
|
409
|
|
);
|
|
}
|
|
$uuid = strtolower((string) $migration->source_uuid);
|
|
$base = '/v1/vms/' . rawurlencode($uuid);
|
|
self::expectRequest($method, $target, 'POST',
|
|
$base . '/peer-migration/cleanup');
|
|
self::assertAllowedBody($body,
|
|
['operation_id', 'migration_id', 'remove_managed_disks']);
|
|
if (($body['migration_id'] ?? null)
|
|
!== (string) $migration->migration_key
|
|
|| ($body['remove_managed_disks'] ?? null) !== true) {
|
|
self::invalidPayload('维护迁移源副本清理确认无效');
|
|
}
|
|
return ['delete-vm', $uuid];
|
|
}
|
|
|
|
private static function assertPeerPrepareBody(
|
|
CloudInstanceMigration $migration,
|
|
array $body
|
|
): void {
|
|
$ticket = $body['ticket'] ?? null;
|
|
$expiresAt = filter_var($body['expires_at'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
|
$artifacts = $body['artifacts'] ?? null;
|
|
$rows = CloudPeerMigrationArtifact::where(
|
|
'migration_id', (int) $migration->id
|
|
)->orderBy('id')->get();
|
|
if (($body['migration_id'] ?? null)
|
|
!== (string) $migration->migration_key
|
|
|| !is_string($ticket)
|
|
|| preg_match('/^[a-f0-9]{64}$/D', $ticket) !== 1
|
|
|| $expiresAt === false
|
|
|| $expiresAt <= (int) $migration->created_at
|
|
|| $expiresAt > (int) $migration->created_at + 604800
|
|
|| !is_array($artifacts) || !array_is_list($artifacts)
|
|
|| count($artifacts) !== count($rows)) {
|
|
self::invalidPayload('PeerMigration 源准备请求无效');
|
|
}
|
|
foreach ($rows as $index => $row) {
|
|
$item = $artifacts[$index] ?? null;
|
|
$allowed = (string) $row->role === 'snapshot'
|
|
? ['id', 'role', 'snapshot_key'] : ['id', 'role'];
|
|
if (!is_array($item) || array_is_list($item)
|
|
|| array_diff(array_keys($item), $allowed) !== []
|
|
|| array_diff($allowed, array_keys($item)) !== []
|
|
|| !hash_equals((string) $row->artifact_id,
|
|
(string) ($item['id'] ?? ''))
|
|
|| !hash_equals((string) $row->role,
|
|
(string) ($item['role'] ?? ''))
|
|
|| ((string) $row->role === 'snapshot'
|
|
&& !hash_equals((string) $row->snapshot_key,
|
|
(string) ($item['snapshot_key'] ?? '')))) {
|
|
self::invalidPayload('PeerMigration 源工件目录无效');
|
|
}
|
|
}
|
|
}
|
|
|
|
private static function assertPeerTransferBody(
|
|
CloudJob $job,
|
|
CloudInstanceMigration $migration,
|
|
CloudInstance $instance,
|
|
array $payload,
|
|
array $body
|
|
): void {
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'migration_id', 'ticket', 'source_endpoints',
|
|
'source_identity_sha256', 'source_uuid', 'manifest_digest',
|
|
'network_suspended',
|
|
'debian_12_network_fix', 'uuid', 'source', 'name', 'description',
|
|
'vcpu', 'memory_mib', 'disk_gib', 'bandwidth_mbps',
|
|
'public_network', 'vpc_port',
|
|
'template_id', 'template_revision', 'template_generation_token',
|
|
'startup_script', 'hostname', 'guest_ssh_public_key',
|
|
'root_password',
|
|
'platform_network_policy_snapshot',
|
|
]);
|
|
$restore = CloudBackupRestore::find((int) $migration->restore_id);
|
|
$reservation = CloudResourceReservation::find(
|
|
(int) $migration->target_reservation_id
|
|
);
|
|
$prepare = CloudJob::find((int) $migration->source_prepare_job_id);
|
|
try {
|
|
$preparePayload = $prepare === null ? null : CloudSecrets::decrypt(
|
|
(string) $prepare->sealed_payload, 'job-payload'
|
|
);
|
|
} catch (\Throwable $error) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'PeerMigration 源传输票据无法读取', 409
|
|
);
|
|
}
|
|
$prepareBody = is_array($preparePayload)
|
|
? ($preparePayload['body'] ?? null) : null;
|
|
$spec = json_decode((string) $instance->spec_json, true);
|
|
$rootDisk = filter_var($body['disk_gib'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
|
$reservationId = filter_var($payload['reservation_id'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
|
$expectedDisk = $rootDisk === false ? 0 : (int) $rootDisk
|
|
+ CloudPeerMigrationArtifactService::artifactDiskGib($migration);
|
|
$expectedPolicy = is_array($spec) && !array_is_list($spec)
|
|
? ($spec['platform_network_policy_snapshot'] ?? []) : [];
|
|
if (!is_array($expectedPolicy) || array_is_list($expectedPolicy)) {
|
|
$expectedPolicy = [];
|
|
}
|
|
$sourceEndpoints = $body['source_endpoints'] ?? null;
|
|
$encodedEndpoints = is_array($sourceEndpoints)
|
|
&& array_is_list($sourceEndpoints)
|
|
? json_encode($sourceEndpoints, JSON_UNESCAPED_SLASHES) : false;
|
|
$migrationTarget = $payload['migration_target'] ?? null;
|
|
$targetKeys = [
|
|
'contract', 'backup_restore_id', 'reservation_id', 'host_id',
|
|
'resource_pool_id', 'operation_id', 'target_uuid',
|
|
'target_agent_revision', 'target_agent_contract_sha256',
|
|
'target_identity_json', 'target_identity_sha256',
|
|
'target_claim_set_sha256', 'target_public_network_json',
|
|
'target_public_network_sha256', 'vpc_port',
|
|
];
|
|
if (!self::hasExactKeys($migrationTarget, $targetKeys)) {
|
|
self::invalidPayload('PeerMigration 目标冻结信封无效');
|
|
}
|
|
$targetAgentRevision = filter_var(
|
|
$migrationTarget['target_agent_revision'] ?? null,
|
|
FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]
|
|
);
|
|
$reservationState = (string) ($reservation->state ?? '');
|
|
try {
|
|
$claimSet = $reservation === null ? null
|
|
: CloudPublicNetworkAllocationService::currentClaimSet(
|
|
(int) $reservation->id,
|
|
$reservationState,
|
|
$reservationState === 'committed'
|
|
? (int) $reservation->instance_id : null
|
|
);
|
|
$frozenNetwork = $claimSet === null ? null
|
|
: CloudFrozenPublicNetworkIdentity::fromStored(
|
|
(int) $reservation->id,
|
|
(int) $reservation->host_id,
|
|
strtolower((string) $migration->target_uuid),
|
|
$claimSet->networkAttachmentId(),
|
|
(string) ($migrationTarget[
|
|
'target_identity_json'
|
|
] ?? ''),
|
|
(string) ($migrationTarget[
|
|
'target_identity_sha256'
|
|
] ?? ''),
|
|
(string) ($migrationTarget[
|
|
'target_public_network_json'
|
|
] ?? ''),
|
|
(string) ($migrationTarget[
|
|
'target_public_network_sha256'
|
|
] ?? ''),
|
|
(string) ($migrationTarget[
|
|
'target_claim_set_sha256'
|
|
] ?? ''),
|
|
$claimSet
|
|
);
|
|
$requestedNetwork = CloudPublicNetworkSnapshot::fromArray(
|
|
$body['public_network'] ?? null
|
|
);
|
|
} catch (\Throwable) {
|
|
self::invalidPayload('PeerMigration 目标双栈冻结身份无效');
|
|
}
|
|
$frozenVpcPort = $migrationTarget['vpc_port'] ?? null;
|
|
$requestedVpcPort = $body['vpc_port'] ?? null;
|
|
$supportedAgentContract =
|
|
CloudPortableRestoreCompatibility::supported()->sha256();
|
|
if ($restore === null || $reservation === null
|
|
|| !is_array($prepareBody) || array_is_list($prepareBody)
|
|
|| !is_array($spec) || array_is_list($spec)
|
|
|| !in_array($reservationState,
|
|
['held', 'uncertain', 'committed'], true)
|
|
|| !$frozenNetwork instanceof CloudFrozenPublicNetworkIdentity
|
|
|| !$requestedNetwork instanceof CloudPublicNetworkSnapshot
|
|
|| $targetAgentRevision === false
|
|
|| (int) $job->backup_restore_id !== (int) $restore->id
|
|
|| (int) $restore->target_host_id !== (int) $job->host_id
|
|
|| (int) $restore->reservation_id !== (int) $reservation->id
|
|
|| (int) $migration->target_reservation_id
|
|
!== (int) $reservation->id
|
|
|| !hash_equals((string) $restore->operation_id,
|
|
(string) $job->operation_id)
|
|
|| $restore->backup_id !== null
|
|
|| (int) $reservationId !== (int) $reservation->id
|
|
|| (int) $reservation->backup_restore_id !== (int) $restore->id
|
|
|| (int) $reservation->host_id !== (int) $job->host_id
|
|
|| (int) $reservation->resource_pool_id
|
|
!== (int) $instance->resource_pool_id
|
|
|| !hash_equals(
|
|
(string) $reservation->operation_id,
|
|
(string) $job->operation_id
|
|
)
|
|
|| $reservation->network_attachment_id !== null
|
|
|| $reservation->public_ip_pool_id !== null
|
|
|| $reservation->public_ip_id !== null
|
|
|| (int) $reservation->disk_gib !== $expectedDisk
|
|
|| ($migrationTarget['contract'] ?? null) !== 1
|
|
|| (int) ($migrationTarget['backup_restore_id'] ?? 0)
|
|
!== (int) $restore->id
|
|
|| (int) ($migrationTarget['reservation_id'] ?? 0)
|
|
!== (int) $reservation->id
|
|
|| (int) ($migrationTarget['host_id'] ?? 0)
|
|
!== (int) $job->host_id
|
|
|| (int) ($migrationTarget['resource_pool_id'] ?? 0)
|
|
!== (int) $reservation->resource_pool_id
|
|
|| !hash_equals(
|
|
(string) $job->operation_id,
|
|
(string) ($migrationTarget['operation_id'] ?? '')
|
|
)
|
|
|| !hash_equals(
|
|
strtolower((string) $migration->target_uuid),
|
|
strtolower((string) ($migrationTarget['target_uuid'] ?? ''))
|
|
)
|
|
|| !hash_equals(
|
|
$supportedAgentContract,
|
|
(string) ($migrationTarget[
|
|
'target_agent_contract_sha256'
|
|
] ?? '')
|
|
)
|
|
|| !hash_equals(
|
|
$frozenNetwork->publicNetworkSha256(),
|
|
$requestedNetwork->fingerprint()
|
|
)
|
|
|| $frozenNetwork->publicNetwork()->toArray()
|
|
!== $requestedNetwork->toArray()
|
|
|| $frozenVpcPort !== $requestedVpcPort
|
|
|| ($body['migration_id'] ?? null)
|
|
!== (string) $migration->migration_key
|
|
|| !is_string($body['ticket'] ?? null)
|
|
|| !hash_equals((string) ($prepareBody['ticket'] ?? ''),
|
|
(string) $body['ticket'])
|
|
|| !is_string($encodedEndpoints)
|
|
|| !hash_equals((string) $migration->source_endpoint,
|
|
$encodedEndpoints)
|
|
|| !hash_equals((string) $migration->peer_trust_id,
|
|
(string) ($body['source_identity_sha256'] ?? ''))
|
|
|| !hash_equals(strtolower((string) $migration->source_uuid),
|
|
strtolower((string) ($body['source_uuid'] ?? '')))
|
|
|| !hash_equals((string) $migration->manifest_digest,
|
|
(string) ($body['manifest_digest'] ?? ''))
|
|
|| strtolower((string) ($body['uuid'] ?? ''))
|
|
!== strtolower((string) $migration->target_uuid)
|
|
|| ($body['source'] ?? null) !== ''
|
|
|| ($body['template_id'] ?? null) !== ''
|
|
|| (int) ($body['template_revision'] ?? -1) !== 0
|
|
|| ($body['template_generation_token'] ?? null) !== ''
|
|
|| ($body['startup_script'] ?? null) !== ''
|
|
|| ($body['hostname'] ?? null) !== ''
|
|
|| ($body['guest_ssh_public_key'] ?? null) !== ''
|
|
|| ($body['root_password'] ?? null) !== ''
|
|
|| ($body['description'] ?? null) !== ''
|
|
|| !hash_equals((string) $instance->name,
|
|
(string) ($body['name'] ?? ''))
|
|
|| (int) ($body['vcpu'] ?? 0) !== (int) $reservation->cpu_cores
|
|
|| (int) ($body['memory_mib'] ?? 0)
|
|
!== (int) $reservation->memory_mib
|
|
|| $rootDisk === false
|
|
|| (int) $rootDisk !== (int) ($spec['disk_gib'] ?? 0)
|
|
|| (int) ($body['bandwidth_mbps'] ?? 0)
|
|
!== (int) ($spec['bandwidth_mbps'] ?? 0)
|
|
|| ($body['network_suspended'] ?? null)
|
|
!== ((string) $migration->source_network_status !== 'active')
|
|
|| ($body['debian_12_network_fix'] ?? null)
|
|
!== (($spec['debian_12_network_fix'] ?? null) === true)
|
|
|| ($body['platform_network_policy_snapshot'] ?? null)
|
|
!== $expectedPolicy) {
|
|
self::invalidPayload('PeerMigration 目标接收请求无效');
|
|
}
|
|
}
|
|
|
|
private static function createIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body,
|
|
bool $forAppliedEffect
|
|
): array {
|
|
if ((string) $job->kind === 'backup_restore') {
|
|
if (!isset($payload['attempt_key'])) {
|
|
self::invalidPayload('恢复任务缺少尝试权威');
|
|
}
|
|
return self::portableRestoreAttemptIdentity(
|
|
$job,
|
|
$payload,
|
|
$method,
|
|
$target,
|
|
$body
|
|
);
|
|
}
|
|
$backupProvision = array_key_exists('backup_metadata', $payload)
|
|
|| $job->backup_id !== null;
|
|
if ($backupProvision) {
|
|
$order = $job->order_id === null ? null
|
|
: CloudOrder::find((int) $job->order_id);
|
|
$orderSpec = $order === null ? null
|
|
: json_decode((string) $order->spec_json, true);
|
|
if ($order === null || !is_array($orderSpec)
|
|
|| array_is_list($orderSpec)
|
|
|| ($orderSpec['source'] ?? null)
|
|
!== 'deployment_snapshot'
|
|
|| $order->deployment_snapshot_id === null) {
|
|
self::invalidPayload(
|
|
'从云快照创建实例缺少可信订单快照'
|
|
);
|
|
}
|
|
return self::backupProvisionIdentity(
|
|
$job,
|
|
$payload,
|
|
$method,
|
|
$target,
|
|
$body,
|
|
$order,
|
|
$orderSpec
|
|
);
|
|
}
|
|
self::expectRequest($method, $target, 'POST', '/v1/vms');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'uuid', 'source', 'name', 'description', 'vcpu',
|
|
'memory_mib', 'disk_gib', 'bandwidth_mbps', 'public_network',
|
|
'template_id', 'template_revision', 'template_generation_token',
|
|
'startup_script', 'hostname', 'guest_ssh_public_key',
|
|
'root_password',
|
|
'platform_network_policy_snapshot',
|
|
]);
|
|
$order = $job->order_id === null ? null
|
|
: CloudOrder::find((int) $job->order_id);
|
|
$orderSpec = $order === null ? null
|
|
: json_decode((string) $order->spec_json, true);
|
|
$reservation = $order === null || $order->reservation_id === null
|
|
? null : CloudResourceReservation::find(
|
|
(int) $order->reservation_id
|
|
);
|
|
try {
|
|
$frozenPublicNetwork = CloudPublicNetworkSnapshot::fromArray(
|
|
is_array($orderSpec)
|
|
? ($orderSpec['public_network'] ?? null) : null
|
|
);
|
|
$requestedPublicNetwork = CloudPublicNetworkSnapshot::fromArray(
|
|
$body['public_network'] ?? null
|
|
);
|
|
} catch (\InvalidArgumentException) {
|
|
self::invalidPayload('创建实例的双栈公网快照无效');
|
|
}
|
|
$resourceId = self::operationUuid((string) $job->operation_id);
|
|
$requestedUuid = $body['uuid'] ?? null;
|
|
$integers = ['vcpu', 'memory_mib', 'disk_gib', 'bandwidth_mbps',
|
|
'template_revision'];
|
|
$validIntegers = true;
|
|
foreach ($integers as $field) {
|
|
if (filter_var(
|
|
$body[$field] ?? null,
|
|
FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]
|
|
) === false) {
|
|
$validIntegers = false;
|
|
break;
|
|
}
|
|
}
|
|
if (($body['source'] ?? null) !== 'cloud'
|
|
|| !is_string($body['name'] ?? null)
|
|
|| preg_match('/^[A-Za-z0-9_.-]{1,80}$/D', $body['name']) !== 1
|
|
|| !$validIntegers
|
|
|| !is_string($body['template_id'] ?? null)
|
|
|| preg_match(self::TEMPLATE_ID_PATTERN,
|
|
$body['template_id']) !== 1
|
|
|| !is_string($body['template_generation_token'] ?? null)
|
|
|| preg_match(self::CATALOG_ID_PATTERN,
|
|
$body['template_generation_token']) !== 1
|
|
|| !is_array($body['platform_network_policy_snapshot'] ?? null)
|
|
|| array_is_list($body['platform_network_policy_snapshot'])
|
|
|| ($requestedUuid !== null
|
|
&& (!is_string($requestedUuid)
|
|
|| !hash_equals($resourceId,
|
|
strtolower($requestedUuid))))
|
|
|| (int) $job->user_id < 1
|
|
|| $order === null || !is_array($orderSpec)
|
|
|| array_is_list($orderSpec)
|
|
|| ($orderSpec['source'] ?? null) !== 'cloud'
|
|
|| (int) $order->user_id !== (int) $job->user_id
|
|
|| (int) ($order->host_id ?? 0) !== (int) $job->host_id
|
|
|| $reservation === null
|
|
|| (int) $reservation->id !== (int) $order->reservation_id
|
|
|| (int) ($reservation->order_id ?? 0) !== (int) $order->id
|
|
|| (int) ($reservation->user_id ?? 0) !== (int) $order->user_id
|
|
|| (int) ($reservation->host_id ?? 0) !== (int) $job->host_id
|
|
|| (int) ($reservation->offer_id ?? 0) !== (int) $order->offer_id
|
|
|| (int) ($reservation->resource_pool_id ?? 0)
|
|
!== (int) $order->resource_pool_id
|
|
|| (int) ($reservation->backup_restore_id ?? 0) !== 0
|
|
|| !hash_equals(
|
|
(string) $job->operation_id,
|
|
(string) ($reservation->operation_id ?? '')
|
|
)
|
|
|| !in_array((string) $reservation->state,
|
|
['held', 'uncertain', 'committed'], true)
|
|
|| !hash_equals(
|
|
$frozenPublicNetwork->fingerprint(),
|
|
$requestedPublicNetwork->fingerprint()
|
|
)
|
|
|| array_key_exists('owner_id', $payload)) {
|
|
self::invalidPayload('创建实例请求与任务账本不匹配');
|
|
}
|
|
$metadata = $payload['template_metadata'] ?? null;
|
|
if (!is_array($metadata) || array_is_list($metadata)
|
|
|| ($metadata['template_id'] ?? null)
|
|
!== $body['template_id']
|
|
|| ($metadata['os_source'] ?? null) !== 'cloud_template'
|
|
|| !is_string($metadata['os_name'] ?? null)
|
|
|| trim($metadata['os_name']) === ''
|
|
|| ($metadata['login_name'] ?? null) !== 'root'
|
|
|| !is_bool($metadata['debian_12_network_fix'] ?? null)) {
|
|
self::invalidPayload('创建实例任务缺少可信模板快照');
|
|
}
|
|
if ($forAppliedEffect) {
|
|
self::assertCreateAppliedEscrow($payload, $body);
|
|
}
|
|
return ['create-vm', $resourceId];
|
|
}
|
|
|
|
/**
|
|
* Validate the create-like restore directly against its attempt ledger.
|
|
* No CloudInstance row exists until a successful Agent receipt has been
|
|
* finalized, so the frozen attempt UUID is the resource authority here.
|
|
*
|
|
* @return array{0:string,1:string}
|
|
*/
|
|
private static function portableRestoreAttemptIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body
|
|
): array {
|
|
$sourceUrl = $body['source_url'] ?? null;
|
|
if ($method !== 'POST'
|
|
|| !is_string($sourceUrl)
|
|
|| $sourceUrl === '') {
|
|
self::invalidPayload('恢复任务缺少临时对象下载能力');
|
|
}
|
|
$stable = $payload;
|
|
unset($stable['body']['source_url']);
|
|
$envelope = CloudPortableRestoreJobEnvelope::fromJobForDispatch(
|
|
$job,
|
|
$stable
|
|
);
|
|
$wire = $envelope->wirePayload($sourceUrl);
|
|
if ($wire !== $payload
|
|
|| !hash_equals(
|
|
'/v1/vms/' . rawurlencode($envelope->resourceId())
|
|
. '/restore-backup',
|
|
$target
|
|
)) {
|
|
self::invalidPayload('恢复任务线缆请求与冻结信封不匹配');
|
|
}
|
|
return [$envelope->action(), $envelope->resourceId()];
|
|
}
|
|
|
|
private static function backupProvisionIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body,
|
|
CloudOrder $order,
|
|
array $orderSpec
|
|
): array {
|
|
$resourceId = self::operationUuid((string) $job->operation_id);
|
|
self::expectRequest(
|
|
$method,
|
|
$target,
|
|
'POST',
|
|
'/v1/vms/' . rawurlencode($resourceId) . '/restore-backup'
|
|
);
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'uuid', 'source', 'name', 'description', 'vcpu',
|
|
'memory_mib', 'disk_gib', 'bandwidth_mbps', 'public_network',
|
|
'template_id', 'template_revision', 'template_generation_token',
|
|
'startup_script', 'hostname', 'guest_ssh_public_key',
|
|
'root_password',
|
|
'platform_network_policy_snapshot', 'debian_12_network_fix',
|
|
'backup_key', 'source_url', 'source_size_bytes', 'source_sha256',
|
|
]);
|
|
$snapshot = $order->deployment_snapshot_id === null ? null
|
|
: CloudDeploymentSnapshot::find(
|
|
(int) $order->deployment_snapshot_id
|
|
);
|
|
$backup = $job->backup_id === null ? null
|
|
: CloudInstanceBackup::find((int) $job->backup_id);
|
|
$sourceCompatibility = $backup === null ? null
|
|
: $backup->sourcePortableRestoreCompatibility();
|
|
$reservation = $order->reservation_id === null ? null
|
|
: CloudResourceReservation::find((int) $order->reservation_id);
|
|
$backupMetadata = $payload['backup_metadata'] ?? null;
|
|
$orderTargetAgentRevision = filter_var(
|
|
$orderSpec['target_agent_revision'] ?? null,
|
|
FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]
|
|
);
|
|
$payloadTargetAgentRevision = filter_var(
|
|
is_array($backupMetadata)
|
|
? ($backupMetadata['target_agent_revision'] ?? null)
|
|
: null,
|
|
FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]
|
|
);
|
|
$orderTargetAgentContract =
|
|
$orderSpec['target_agent_contract_sha256'] ?? null;
|
|
$payloadTargetAgentContract = is_array($backupMetadata)
|
|
? ($backupMetadata['target_agent_contract_sha256'] ?? null)
|
|
: null;
|
|
try {
|
|
$frozenPublicNetwork = CloudPublicNetworkSnapshot::fromArray(
|
|
$orderSpec['public_network'] ?? null
|
|
);
|
|
$requestedPublicNetwork = CloudPublicNetworkSnapshot::fromArray(
|
|
$body['public_network'] ?? null
|
|
);
|
|
} catch (\InvalidArgumentException) {
|
|
self::invalidPayload(
|
|
'从云快照创建实例的双栈公网快照无效'
|
|
);
|
|
}
|
|
$integers = ['vcpu', 'memory_mib', 'disk_gib', 'bandwidth_mbps'];
|
|
foreach ($integers as $field) {
|
|
if (filter_var(
|
|
$body[$field] ?? null,
|
|
FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]
|
|
) === false) {
|
|
self::invalidPayload('从云快照创建实例的资源规格无效');
|
|
}
|
|
}
|
|
if ($snapshot === null || $backup === null
|
|
|| $sourceCompatibility === null
|
|
|| $orderTargetAgentRevision === false
|
|
|| $payloadTargetAgentRevision === false
|
|
|| (int) $orderTargetAgentRevision
|
|
!== (int) $payloadTargetAgentRevision
|
|
|| !is_string($orderTargetAgentContract)
|
|
|| !is_string($payloadTargetAgentContract)
|
|
|| preg_match('/^[a-f0-9]{64}$/D',
|
|
$orderTargetAgentContract) !== 1
|
|
|| !hash_equals(
|
|
$orderTargetAgentContract,
|
|
$payloadTargetAgentContract
|
|
)
|
|
|| !hash_equals(
|
|
$sourceCompatibility->sha256(),
|
|
$orderTargetAgentContract
|
|
)
|
|
|| (int) $order->user_id !== (int) $job->user_id
|
|
|| (int) ($order->host_id ?? 0) !== (int) $job->host_id
|
|
|| (int) $snapshot->user_id !== (int) $job->user_id
|
|
|| (int) $backup->user_id !== (int) $job->user_id
|
|
|| (string) $snapshot->state !== 'ready'
|
|
|| (int) $snapshot->id
|
|
!== (int) ($orderSpec['deployment_snapshot_id'] ?? 0)
|
|
|| (int) $snapshot->backup_id !== (int) $backup->id
|
|
|| (int) $snapshot->source_instance_id
|
|
!== (int) $backup->source_instance_id
|
|
|| !hash_equals((string) $snapshot->snapshot_key,
|
|
(string) ($orderSpec['cloud_snapshot_key'] ?? ''))
|
|
|| (int) ($orderSpec['backing_backup_id'] ?? 0)
|
|
!== (int) $backup->id
|
|
|| !is_array($backupMetadata) || array_is_list($backupMetadata)
|
|
|| (int) ($backupMetadata['deployment_snapshot_id'] ?? 0)
|
|
!== (int) $snapshot->id
|
|
|| !hash_equals((string) $snapshot->snapshot_key,
|
|
(string) ($backupMetadata['cloud_snapshot_key'] ?? ''))
|
|
|| (int) ($backupMetadata['backing_backup_id'] ?? 0)
|
|
!== (int) $backup->id
|
|
|| (int) ($backupMetadata['backup_id'] ?? 0) !== (int) $backup->id
|
|
|| !hash_equals(
|
|
$sourceCompatibility->sha256(),
|
|
(string) ($orderSpec[
|
|
'source_portable_restore_contract_sha256'
|
|
] ?? '')
|
|
)
|
|
|| !hash_equals(
|
|
$sourceCompatibility->sha256(),
|
|
(string) ($backupMetadata[
|
|
'source_portable_restore_contract_sha256'
|
|
] ?? '')
|
|
)
|
|
|| !hash_equals((string) $backup->backup_key,
|
|
(string) ($orderSpec['backing_backup_key'] ?? ''))
|
|
|| !hash_equals((string) $backup->backup_key,
|
|
(string) ($backupMetadata['backing_backup_key'] ?? ''))
|
|
|| !hash_equals((string) $backup->backup_key,
|
|
(string) ($backupMetadata['backup_key'] ?? ''))
|
|
|| !hash_equals((string) $backup->backup_key,
|
|
(string) ($body['backup_key'] ?? ''))
|
|
|| (int) $backup->object_size_bytes
|
|
!== (int) ($orderSpec['backing_backup_size_bytes'] ?? 0)
|
|
|| (int) $backup->object_size_bytes
|
|
!== (int) ($body['source_size_bytes'] ?? 0)
|
|
|| (int) $backup->virtual_size_bytes
|
|
!== (int) ($orderSpec[
|
|
'backing_backup_virtual_size_bytes'
|
|
] ?? 0)
|
|
|| !hash_equals((string) $backup->sha256,
|
|
(string) ($orderSpec['backing_backup_sha256'] ?? ''))
|
|
|| !hash_equals((string) $backup->sha256,
|
|
(string) ($body['source_sha256'] ?? ''))
|
|
|| !hash_equals(self::backingBackupIdentity($backup),
|
|
(string) ($orderSpec['backing_backup_identity'] ?? ''))
|
|
|| (string) $backup->purpose !== 'portable'
|
|
|| (string) $backup->source !== 'automatic'
|
|
|| $backup->subscription_id === null
|
|
|| (string) $backup->state !== 'ready'
|
|
|| $reservation === null
|
|
|| (int) $reservation->id !== (int) $order->reservation_id
|
|
|| (int) ($reservation->order_id ?? 0) !== (int) $order->id
|
|
|| (int) $reservation->user_id !== (int) $order->user_id
|
|
|| (int) $reservation->host_id !== (int) $job->host_id
|
|
|| (int) ($reservation->offer_id ?? 0) !== (int) $order->offer_id
|
|
|| (int) $reservation->resource_pool_id
|
|
!== (int) $order->resource_pool_id
|
|
|| (int) ($reservation->backup_restore_id ?? 0) !== 0
|
|
|| !hash_equals(
|
|
(string) $job->operation_id,
|
|
(string) ($reservation->operation_id ?? '')
|
|
)
|
|
|| !in_array((string) $reservation->state,
|
|
['held', 'uncertain', 'committed'], true)
|
|
|| (int) $reservation->cpu_cores !== (int) $body['vcpu']
|
|
|| (int) $reservation->memory_mib !== (int) $body['memory_mib']
|
|
|| (int) $reservation->disk_gib !== (int) $body['disk_gib']
|
|
|| (int) ($orderSpec['vcpu'] ?? 0) !== (int) $body['vcpu']
|
|
|| (int) ($orderSpec['memory_mib'] ?? 0)
|
|
!== (int) $body['memory_mib']
|
|
|| (int) ($orderSpec['disk_gib'] ?? 0)
|
|
!== (int) $body['disk_gib']
|
|
|| (int) ($orderSpec['bandwidth_mbps'] ?? 0)
|
|
!== (int) $body['bandwidth_mbps']
|
|
|| ($orderSpec['name'] ?? null) !== $body['name']
|
|
|| !hash_equals(
|
|
$frozenPublicNetwork->fingerprint(),
|
|
$requestedPublicNetwork->fingerprint()
|
|
)
|
|
|| ($body['uuid'] ?? null) !== $resourceId
|
|
|| ($body['operation_id'] ?? null) !== (string) $job->operation_id
|
|
|| ($body['source'] ?? null) !== ''
|
|
|| ($body['template_id'] ?? null) !== ''
|
|
|| ($body['template_revision'] ?? null) !== 0
|
|
|| ($body['template_generation_token'] ?? null) !== ''
|
|
|| ($body['startup_script'] ?? null) !== ''
|
|
|| ($body['hostname'] ?? null) !== ''
|
|
|| ($body['guest_ssh_public_key'] ?? null) !== ''
|
|
|| ($body['root_password'] ?? null) !== ''
|
|
|| !is_string($body['name'] ?? null)
|
|
|| preg_match('/^[A-Za-z0-9_.-]{1,80}$/D', $body['name']) !== 1
|
|
|| !is_array($body['platform_network_policy_snapshot'] ?? null)
|
|
|| array_is_list($body['platform_network_policy_snapshot'])
|
|
|| ($orderSpec['platform_network_policy_snapshot'] ?? null)
|
|
!== $body['platform_network_policy_snapshot']
|
|
|| !is_bool($body['debian_12_network_fix'] ?? null)
|
|
|| ($orderSpec['debian_12_network_fix'] ?? null)
|
|
!== $body['debian_12_network_fix']
|
|
|| !is_string($body['source_url'] ?? null)
|
|
|| !str_starts_with($body['source_url'], 'https://')
|
|
|| preg_match('/^[a-f0-9]{64}$/D',
|
|
(string) ($body['source_sha256'] ?? '')) !== 1
|
|
|| (int) $job->user_id < 1
|
|
|| $job->order_id === null
|
|
|| array_key_exists('owner_id', $payload)) {
|
|
self::invalidPayload(
|
|
'从云快照创建实例的请求与订单、快照账本不匹配'
|
|
);
|
|
}
|
|
return ['restore-backup:' . (string) $backup->backup_key, $resourceId];
|
|
}
|
|
|
|
private static function backingBackupIdentity(
|
|
CloudInstanceBackup $backup
|
|
): string {
|
|
return CloudBackupStorageAuthority::backingBackupIdentity($backup);
|
|
}
|
|
|
|
private static function assertCreateAppliedEscrow(
|
|
array $payload,
|
|
array $body
|
|
): void {
|
|
$credential = $payload['credential'] ?? null;
|
|
$publicKey = $body['guest_ssh_public_key'] ?? null;
|
|
$hasKey = is_string($publicKey) && $publicKey !== '';
|
|
if (!is_array($credential) || array_is_list($credential)
|
|
|| array_diff(array_keys($credential), [
|
|
'password', 'login_name', 'auth_mode',
|
|
]) !== []
|
|
|| ($credential['login_name'] ?? null) !== 'root'
|
|
|| !is_string($credential['password'] ?? null)
|
|
|| !is_string($body['root_password'] ?? null)
|
|
|| !hash_equals(
|
|
(string) $body['root_password'],
|
|
(string) $credential['password']
|
|
)
|
|
|| ($credential['auth_mode'] ?? null)
|
|
!== ($hasKey ? 'password_and_key' : 'password')) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'创建成功恢复缺少完整且匹配的实例凭据',
|
|
409
|
|
);
|
|
}
|
|
}
|
|
|
|
private static function storageIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body
|
|
): array {
|
|
self::expectRequest(
|
|
$method,
|
|
$target,
|
|
'POST',
|
|
'/v1/storage/configuration'
|
|
);
|
|
$fields = [
|
|
'managed_directory', 'template_directory', 'seed_directory',
|
|
'user_iso_directory', 'rescue_directory',
|
|
];
|
|
self::assertAllowedBody($body, array_merge(
|
|
['operation_id'],
|
|
$fields
|
|
));
|
|
$revision = filter_var(
|
|
$payload['storage_revision'] ?? null,
|
|
FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]
|
|
);
|
|
$row = CloudHostStorageConfiguration::find((int) $job->host_id);
|
|
if (($payload['can_manage'] ?? null) !== true
|
|
|| $revision === false
|
|
|| $row === null
|
|
|| (int) $row->revision !== (int) $revision
|
|
|| (int) ($row->job_id ?? 0) !== (int) $job->id
|
|
|| !hash_equals((string) $job->operation_id,
|
|
(string) ($row->operation_id ?? ''))) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'宿主机存储任务与配置账本不匹配',
|
|
409
|
|
);
|
|
}
|
|
$paths = [];
|
|
foreach ($fields as $field) {
|
|
$value = $body[$field] ?? null;
|
|
if (!is_string($value)
|
|
|| preg_match(
|
|
'#^/(?:[A-Za-z0-9._-]+)(?:/[A-Za-z0-9._-]+)*$#D',
|
|
$value
|
|
) !== 1
|
|
|| !hash_equals((string) $row->{$field}, $value)) {
|
|
self::invalidPayload(
|
|
'宿主机存储请求与配置账本不匹配'
|
|
);
|
|
}
|
|
$paths[] = $value;
|
|
}
|
|
foreach ($paths as $leftIndex => $left) {
|
|
foreach (array_slice($paths, $leftIndex + 1) as $right) {
|
|
if ($left === $right
|
|
|| str_starts_with($left, $right . '/')
|
|
|| str_starts_with($right, $left . '/')) {
|
|
self::invalidPayload('宿主机存储目录存在重叠');
|
|
}
|
|
}
|
|
}
|
|
return ['configure-storage', 'host-storage'];
|
|
}
|
|
|
|
/** Exact Go agent/api.operationUUID derivation for body-omitted UUIDs. */
|
|
public static function operationUuid(string $operationId): string
|
|
{
|
|
$digest = hash(
|
|
'sha256',
|
|
'virt-cloud-operation:' . $operationId,
|
|
true
|
|
);
|
|
$digest[6] = chr((ord($digest[6]) & 0x0f) | 0x50);
|
|
$digest[8] = chr((ord($digest[8]) & 0x3f) | 0x80);
|
|
$hex = bin2hex(substr($digest, 0, 16));
|
|
return substr($hex, 0, 8) . '-'
|
|
. substr($hex, 8, 4) . '-'
|
|
. substr($hex, 12, 4) . '-'
|
|
. substr($hex, 16, 4) . '-'
|
|
. substr($hex, 20, 12);
|
|
}
|
|
|
|
private static function powerAction(
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
self::expectRequest($method, $target, 'POST', $base . '/actions');
|
|
self::assertAllowedBody($body, ['operation_id', 'action']);
|
|
$action = $body['action'] ?? null;
|
|
if (!is_string($action)
|
|
|| !in_array($action,
|
|
['start', 'shutdown', 'reboot', 'reset', 'poweroff'], true)) {
|
|
self::invalidPayload('电源操作请求无效');
|
|
}
|
|
return 'power-' . ($action === 'poweroff' ? 'destroy' : $action);
|
|
}
|
|
|
|
private static function resizeResourcesAction(
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
self::expectRequest($method, $target, 'POST', $base . '/resources');
|
|
$fields = [
|
|
'from_vcpu', 'from_memory_mib', 'from_disk_gib',
|
|
'from_bandwidth_mbps', 'target_vcpu', 'target_memory_mib',
|
|
'target_disk_gib', 'target_bandwidth_mbps',
|
|
];
|
|
self::assertAllowedBody($body, array_merge(
|
|
['operation_id', 'confirm_shutdown'],
|
|
$fields
|
|
));
|
|
$values = [];
|
|
foreach ($fields as $field) {
|
|
$value = filter_var(
|
|
$body[$field] ?? null,
|
|
FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]
|
|
);
|
|
if ($value === false) {
|
|
self::invalidPayload('实例升级请求中的资源规格无效');
|
|
}
|
|
$values[$field] = (int) $value;
|
|
}
|
|
$pairs = [
|
|
['from_vcpu', 'target_vcpu'],
|
|
['from_memory_mib', 'target_memory_mib'],
|
|
['from_disk_gib', 'target_disk_gib'],
|
|
['from_bandwidth_mbps', 'target_bandwidth_mbps'],
|
|
];
|
|
$increased = false;
|
|
foreach ($pairs as [$from, $to]) {
|
|
if ($values[$to] < $values[$from]) {
|
|
self::invalidPayload('实例升级请求不能缩减资源');
|
|
}
|
|
$increased = $increased || $values[$to] > $values[$from];
|
|
}
|
|
if (!$increased || ($body['confirm_shutdown'] ?? null) !== true) {
|
|
self::invalidPayload('实例升级请求缺少关机确认或资源未增加');
|
|
}
|
|
return 'resize-vm';
|
|
}
|
|
|
|
private static function reinstallAction(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body,
|
|
bool $forAppliedEffect
|
|
): string {
|
|
self::expectRequest($method, $target, 'POST', $base . '/reinstall');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'template_id', 'template_revision',
|
|
'template_generation_token', 'preserve_data', 'root_password',
|
|
'ssh_public_key',
|
|
]);
|
|
$templateId = $body['template_id'] ?? null;
|
|
if (!is_string($templateId)
|
|
|| preg_match(self::TEMPLATE_ID_PATTERN, $templateId) !== 1
|
|
|| filter_var($body['template_revision'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) === false
|
|
|| !is_string($body['template_generation_token'] ?? null)
|
|
|| preg_match('/^[a-f0-9]{32}$/D',
|
|
$body['template_generation_token']) !== 1) {
|
|
self::invalidPayload('重装请求中的模板快照无效');
|
|
}
|
|
if ($forAppliedEffect) {
|
|
self::assertReinstallAppliedEscrow($job, $payload, $body);
|
|
}
|
|
return 'reinstall-vm';
|
|
}
|
|
|
|
private static function assertReinstallAppliedEscrow(
|
|
CloudJob $job,
|
|
array $payload,
|
|
array $body
|
|
): void {
|
|
$credential = $payload['credential'] ?? null;
|
|
$metadata = $payload['template_metadata'] ?? null;
|
|
$hasKey = is_string($body['ssh_public_key'] ?? null)
|
|
&& $body['ssh_public_key'] !== '';
|
|
if (!is_array($credential) || array_is_list($credential)
|
|
|| array_diff(array_keys($credential), [
|
|
'password', 'login_name', 'auth_mode',
|
|
]) !== []
|
|
|| ($credential['login_name'] ?? null) !== 'root'
|
|
|| !is_string($credential['password'] ?? null)
|
|
|| ($credential['password'] ?? null)
|
|
!== ($body['root_password'] ?? null)
|
|
|| ($credential['auth_mode'] ?? null)
|
|
!== ($hasKey ? 'password_and_key' : 'password')
|
|
|| !is_array($metadata) || array_is_list($metadata)
|
|
|| array_diff(array_keys($metadata), [
|
|
'template_id', 'os_source', 'os_name', 'login_name',
|
|
'debian_12_network_fix',
|
|
]) !== []
|
|
|| ($metadata['template_id'] ?? null)
|
|
!== ($body['template_id'] ?? null)
|
|
|| ($metadata['os_source'] ?? null) !== 'cloud_template'
|
|
|| !is_string($metadata['os_name'] ?? null)
|
|
|| trim($metadata['os_name']) === ''
|
|
|| ($metadata['login_name'] ?? null) !== 'root'
|
|
|| !is_bool($metadata['debian_12_network_fix'] ?? null)) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'重装成功恢复缺少完整凭据或可信模板快照',
|
|
409
|
|
);
|
|
}
|
|
}
|
|
|
|
private static function rescueAction(
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
if ($method !== 'POST') {
|
|
self::invalidPayload('救援操作请求方法无效');
|
|
}
|
|
if ($target === $base . '/rescue/enter') {
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'template_id', 'revision',
|
|
'generation_token',
|
|
]);
|
|
if (!is_string($body['template_id'] ?? null)
|
|
|| preg_match(self::CATALOG_ID_PATTERN,
|
|
$body['template_id']) !== 1
|
|
|| !is_int($body['revision'] ?? null)
|
|
|| (int) $body['revision'] < 1
|
|
|| !is_string($body['generation_token'] ?? null)
|
|
|| preg_match('/^[a-f0-9]{32}$/D',
|
|
$body['generation_token']) !== 1) {
|
|
self::invalidPayload('救援镜像标识无效');
|
|
}
|
|
return 'enter-rescue';
|
|
}
|
|
if ($target === $base . '/rescue/force-start') {
|
|
self::assertAllowedBody($body, ['operation_id', 'ack_data_loss']);
|
|
if (($body['ack_data_loss'] ?? null) !== true) {
|
|
self::invalidPayload('救援强制启动确认无效');
|
|
}
|
|
return 'force-start-rescue';
|
|
}
|
|
if ($target === $base . '/rescue/exit') {
|
|
self::assertAllowedBody($body,
|
|
['operation_id', 'network_suspended', 'ack_data_loss']);
|
|
if (!is_bool($body['network_suspended'] ?? null)) {
|
|
self::invalidPayload('救援退出网络状态无效');
|
|
}
|
|
if (($body['ack_data_loss'] ?? null) !== true) {
|
|
self::invalidPayload('救援退出强制断电确认无效');
|
|
}
|
|
return 'exit-rescue:'
|
|
. ($body['network_suspended'] ? 'suspended' : 'connected');
|
|
}
|
|
self::invalidPayload('救援操作路径无效');
|
|
}
|
|
|
|
private static function deleteAction(
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
self::expectRequest($method, $target, 'DELETE', $base);
|
|
self::assertAllowedBody($body,
|
|
['operation_id', 'remove_managed_disks']);
|
|
if (($body['remove_managed_disks'] ?? null) !== true) {
|
|
self::invalidPayload('删除请求缺少托管磁盘清理确认');
|
|
}
|
|
return 'delete-vm';
|
|
}
|
|
|
|
private static function forceDeleteAction(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
self::expectRequest($method, $target, 'POST', $base . '/force-delete');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'prior_operation_id', 'ack_data_loss',
|
|
'remove_managed_disks',
|
|
]);
|
|
if (($body['operation_id'] ?? null) !== (string) $job->operation_id
|
|
|| !is_string($body['prior_operation_id'] ?? null)
|
|
|| preg_match('/^[a-f0-9]{32}$/D',
|
|
$body['prior_operation_id']) !== 1
|
|
|| ($payload['prior_operation_id'] ?? null)
|
|
!== $body['prior_operation_id']
|
|
|| ($body['ack_data_loss'] ?? null) !== true
|
|
|| ($body['remove_managed_disks'] ?? null) !== true) {
|
|
self::invalidPayload('强制删除请求关联无效');
|
|
}
|
|
return 'force-delete-vm';
|
|
}
|
|
|
|
private static function networkChangeAction(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
self::expectRequest($method, $target, 'POST', $base . '/network');
|
|
if ($job->public_network_transition_id === null) {
|
|
self::invalidPayload('公网网络变更缺少转换账本');
|
|
}
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'public_network', 'confirm_restart',
|
|
]);
|
|
$transitionId = filter_var(
|
|
$job->public_network_transition_id,
|
|
FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]
|
|
);
|
|
$transition = $transitionId === false ? null
|
|
: CloudPublicNetworkTransition::find((int) $transitionId);
|
|
try {
|
|
$requested = CloudPublicNetworkSnapshot::fromArray(
|
|
$body['public_network'] ?? null
|
|
);
|
|
$frozen = $transition instanceof CloudPublicNetworkTransition
|
|
? CloudPublicNetworkSnapshot::fromArray(json_decode(
|
|
(string) $transition->target_public_network_json,
|
|
true,
|
|
16,
|
|
JSON_THROW_ON_ERROR
|
|
)) : null;
|
|
} catch (\Throwable) {
|
|
$requested = $frozen = null;
|
|
}
|
|
if (($body['confirm_restart'] ?? null) !== true
|
|
|| !$transition instanceof CloudPublicNetworkTransition
|
|
|| !$requested instanceof CloudPublicNetworkSnapshot
|
|
|| !$frozen instanceof CloudPublicNetworkSnapshot
|
|
|| (int) $transition->id !== (int) ($payload[
|
|
'public_network_transition_id'
|
|
] ?? 0)
|
|
|| (int) $transition->instance_id !== (int) $job->instance_id
|
|
|| (int) $transition->host_id !== (int) $job->host_id
|
|
|| !hash_equals(
|
|
(string) $transition->operation_id,
|
|
(string) $job->operation_id
|
|
)
|
|
|| !hash_equals(
|
|
(string) $transition->target_public_network_sha256,
|
|
$frozen->fingerprint()
|
|
)
|
|
|| !hash_equals(
|
|
$frozen->fingerprint(),
|
|
$requested->fingerprint()
|
|
)
|
|
|| !hash_equals(
|
|
(string) $transition->source_claim_set_sha256,
|
|
(string) ($payload['source_claim_set_sha256'] ?? '')
|
|
)
|
|
|| !hash_equals(
|
|
(string) $transition->target_claim_set_sha256,
|
|
(string) ($payload['target_claim_set_sha256'] ?? '')
|
|
)) {
|
|
self::invalidPayload('公网 IP 变更请求无效');
|
|
}
|
|
return 'change-network';
|
|
}
|
|
|
|
private static function settingsAction(
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
if (!in_array($method, ['POST', 'PATCH'], true)
|
|
|| $target !== $base . '/settings') {
|
|
self::invalidPayload('实例设置请求路径无效');
|
|
}
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'hostname', 'root_password', 'ssh_public_key',
|
|
'confirm_restart',
|
|
]);
|
|
$changed = array_intersect(
|
|
array_keys($body),
|
|
['hostname', 'root_password', 'ssh_public_key']
|
|
);
|
|
if (($body['confirm_restart'] ?? null) !== true || $changed === []) {
|
|
self::invalidPayload('实例设置恢复字段无效');
|
|
}
|
|
return 'update-settings';
|
|
}
|
|
|
|
private static function snapshotAction(
|
|
CloudJob $job,
|
|
array $payload,
|
|
CloudInstance $instance,
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
$snapshotId = filter_var($job->snapshot_id, FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]);
|
|
$snapshot = $snapshotId === false ? null
|
|
: CloudInstanceSnapshot::find((int) $snapshotId);
|
|
$key = $payload['snapshot_key'] ?? null;
|
|
if ($snapshot === null
|
|
|| (int) $snapshot->instance_id !== (int) $instance->id
|
|
|| (int) $snapshot->host_id !== (int) $job->host_id
|
|
|| (int) $snapshot->user_id !== (int) $instance->user_id
|
|
|| !is_string($key)
|
|
|| preg_match(self::CATALOG_ID_PATTERN, $key) !== 1
|
|
|| !hash_equals((string) $snapshot->snapshot_key, $key)
|
|
|| !hash_equals((string) $snapshot->last_operation_id,
|
|
(string) $job->operation_id)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'快照任务与实例目录账本不匹配',
|
|
409
|
|
);
|
|
}
|
|
if ((string) $job->kind === 'snapshot_create') {
|
|
self::expectRequest($method, $target, 'POST', $base . '/snapshots');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'snapshot_id', 'snapshot_key', 'name',
|
|
'description', 'quiesce', 'consistency_mode',
|
|
]);
|
|
$consistency = $body['consistency_mode'] ?? null;
|
|
if (($body['snapshot_key'] ?? null) !== $key
|
|
|| !in_array($consistency, ['filesystem', 'crash'], true)) {
|
|
self::invalidPayload('创建快照请求无效');
|
|
}
|
|
return 'create-snapshot:' . $key . ':' . $consistency;
|
|
}
|
|
self::assertAllowedBody($body, ['operation_id']);
|
|
if ((string) $job->kind === 'snapshot_restore') {
|
|
self::expectRequest($method, $target, 'POST',
|
|
$base . '/snapshots/' . rawurlencode($key) . '/restore');
|
|
return 'restore-snapshot:' . $key;
|
|
}
|
|
self::expectRequest($method, $target, 'DELETE',
|
|
$base . '/snapshots/' . rawurlencode($key));
|
|
return 'delete-snapshot:' . $key;
|
|
}
|
|
|
|
private static function backupCreateAction(
|
|
CloudJob $job,
|
|
array $payload,
|
|
CloudInstance $instance,
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
self::expectRequest($method, $target, 'POST', $base . '/backups');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'backup_key', 'name', 'consistency_mode',
|
|
'object_upload',
|
|
]);
|
|
$backupId = filter_var($job->backup_id, FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]);
|
|
$backup = $backupId === false ? null
|
|
: CloudInstanceBackup::find((int) $backupId);
|
|
$key = $payload['backup_key'] ?? null;
|
|
$mode = $body['consistency_mode'] ?? null;
|
|
$upload = $body['object_upload'] ?? null;
|
|
if ($backup === null
|
|
|| (int) $backup->source_instance_id !== (int) $instance->id
|
|
|| (int) $backup->source_host_id !== (int) $job->host_id
|
|
|| (int) $backup->user_id !== (int) $instance->user_id
|
|
|| !is_string($key)
|
|
|| preg_match(self::CATALOG_ID_PATTERN, $key) !== 1
|
|
|| !hash_equals((string) $backup->backup_key, $key)
|
|
|| !hash_equals((string) $backup->last_operation_id,
|
|
(string) $job->operation_id)
|
|
|| ($body['backup_key'] ?? null) !== $key
|
|
|| !in_array($mode, ['filesystem', 'crash'], true)
|
|
|| !is_string($body['name'] ?? null)
|
|
|| !is_array($upload) || array_is_list($upload)
|
|
|| !is_array($upload['part_urls'] ?? null)
|
|
|| !array_is_list($upload['part_urls'])
|
|
|| $upload['part_urls'] === []
|
|
|| count($upload['part_urls']) > 512
|
|
|| filter_var($upload['part_size_bytes'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) === false
|
|
|| filter_var($upload['maximum_size_bytes'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) === false
|
|
|| !is_string($upload['complete_url'] ?? null)
|
|
|| !is_string($upload['abort_url'] ?? null)
|
|
|| !is_string($upload['verify_url'] ?? null)
|
|
|| !str_starts_with($upload['complete_url'], 'https://')
|
|
|| !str_starts_with($upload['abort_url'], 'https://')
|
|
|| !str_starts_with($upload['verify_url'], 'https://')) {
|
|
self::invalidPayload('创建可移植备份请求无效');
|
|
}
|
|
foreach ($upload['part_urls'] as $url) {
|
|
if (!is_string($url) || !str_starts_with($url, 'https://')) {
|
|
self::invalidPayload('创建可移植备份请求无效');
|
|
}
|
|
}
|
|
return 'create-backup:' . $key . ':' . $mode;
|
|
}
|
|
|
|
private static function backupWorkspaceCleanupAction(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body
|
|
): array {
|
|
self::expectRequest(
|
|
$method,
|
|
$target,
|
|
'POST',
|
|
'/v1/operations/' . rawurlencode((string) $job->operation_id)
|
|
. '/cleanup-backup-workspace'
|
|
);
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'prior_operation_id', 'cleanup_plan_id',
|
|
]);
|
|
$backupId = filter_var($job->backup_id, FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]);
|
|
$backup = $backupId === false ? null
|
|
: CloudInstanceBackup::find((int) $backupId);
|
|
$priorJobId = filter_var($payload['prior_job_id'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
|
$prior = $priorJobId === false ? null
|
|
: CloudJob::find((int) $priorJobId);
|
|
$key = $payload['backup_key'] ?? null;
|
|
$planId = $body['cleanup_plan_id'] ?? null;
|
|
if ($backup === null || $prior === null
|
|
|| (int) $backup->source_instance_id !== (int) $job->instance_id
|
|
|| (int) $backup->source_host_id !== (int) $job->host_id
|
|
|| (int) ($payload['owner_id'] ?? 0) !== (int) $backup->user_id
|
|
|| ((int) $job->user_id !== (int) $backup->user_id
|
|
&& ($payload['can_manage'] ?? false) !== true)
|
|
|| (int) $prior->backup_id !== (int) $backup->id
|
|
|| (int) $prior->instance_id
|
|
!== (int) $backup->source_instance_id
|
|
|| (int) $prior->host_id !== (int) $job->host_id
|
|
|| (string) $prior->kind !== 'backup_create'
|
|
|| (string) $prior->phase !== 'terminal'
|
|
|| (string) $prior->outcome !== 'succeeded'
|
|
|| !is_string($key)
|
|
|| preg_match(self::CATALOG_ID_PATTERN, $key) !== 1
|
|
|| !hash_equals((string) $backup->backup_key, $key)
|
|
|| !hash_equals((string) $backup->last_operation_id,
|
|
(string) $prior->operation_id)
|
|
|| !hash_equals((string) $prior->operation_id,
|
|
(string) ($payload['prior_operation_id'] ?? ''))
|
|
|| !hash_equals((string) $prior->operation_id,
|
|
(string) ($body['prior_operation_id'] ?? ''))
|
|
|| !is_string($planId)
|
|
|| ($planId !== ''
|
|
&& preg_match('/^[a-f0-9]{64}$/D', $planId) !== 1)
|
|
|| !hash_equals((string) ($payload['cleanup_plan_id'] ?? ''),
|
|
$planId)) {
|
|
self::invalidPayload('备份工作区清理请求无效');
|
|
}
|
|
$resource = strtolower((string) $backup->source_uuid);
|
|
if (preg_match(self::UUID_PATTERN, $resource) !== 1) {
|
|
self::invalidPayload('备份工作区清理资源身份无效');
|
|
}
|
|
return ['cleanup-backup-workspace:' . $key, $resource];
|
|
}
|
|
|
|
private static function backupRecoverAction(
|
|
CloudJob $job,
|
|
array $payload,
|
|
CloudInstance $instance,
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
self::expectRequest(
|
|
$method,
|
|
$target,
|
|
'POST',
|
|
$base . '/recover-backup'
|
|
);
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'backup_key', 'source_url',
|
|
'source_size_bytes', 'source_sha256',
|
|
]);
|
|
$recovery = $job->backup_recovery_id === null ? null
|
|
: CloudBackupRecovery::find((int) $job->backup_recovery_id);
|
|
$backup = $job->backup_id === null ? null
|
|
: CloudInstanceBackup::find((int) $job->backup_id);
|
|
$key = $body['backup_key'] ?? null;
|
|
if ($recovery === null || $backup === null
|
|
|| (int) $recovery->job_id !== (int) $job->id
|
|
|| (int) $recovery->backup_id !== (int) $backup->id
|
|
|| (int) $recovery->instance_id !== (int) $instance->id
|
|
|| !hash_equals((string) $recovery->operation_id,
|
|
(string) $job->operation_id)
|
|
|| !hash_equals((string) $recovery->recovery_key,
|
|
(string) ($payload['recovery_key'] ?? ''))
|
|
|| (int) $backup->user_id !== (int) $instance->user_id
|
|
|| (int) $backup->source_instance_id !== (int) $instance->id
|
|
|| (string) $backup->source_uuid
|
|
!== strtolower((string) $instance->uuid)
|
|
|| (string) $backup->purpose !== 'portable'
|
|
|| (string) $backup->source !== 'automatic'
|
|
|| (string) $backup->state !== 'ready'
|
|
|| !is_string($key)
|
|
|| preg_match(self::CATALOG_ID_PATTERN, $key) !== 1
|
|
|| !hash_equals((string) $backup->backup_key, $key)
|
|
|| !hash_equals((string) $backup->backup_key,
|
|
(string) ($payload['backup_key'] ?? ''))
|
|
|| (int) $backup->object_size_bytes
|
|
!== (int) ($body['source_size_bytes'] ?? 0)
|
|
|| !hash_equals((string) $backup->sha256,
|
|
(string) ($body['source_sha256'] ?? ''))
|
|
|| !is_string($body['source_url'] ?? null)
|
|
|| !str_starts_with($body['source_url'], 'https://')) {
|
|
self::invalidPayload(
|
|
'云备份恢复请求与实例、备份或恢复账本不匹配'
|
|
);
|
|
}
|
|
return 'recover-backup:' . $key . ':'
|
|
. (string) $body['source_sha256'];
|
|
}
|
|
|
|
private static function firewallAction(
|
|
CloudJob $job,
|
|
array $payload,
|
|
CloudInstance $instance,
|
|
string $method,
|
|
string $target,
|
|
string $base,
|
|
array $body
|
|
): string {
|
|
self::expectRequest($method, $target, 'PUT', $base . '/firewall');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'revision', 'default_in', 'default_out',
|
|
'policy_digest', 'rules',
|
|
]);
|
|
$versionId = filter_var($payload['firewall_version_id'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
|
$version = $versionId === false ? null
|
|
: CloudInstanceFirewallVersion::find((int) $versionId);
|
|
if ($version === null
|
|
|| (int) $version->instance_id !== (int) $instance->id
|
|
|| (int) $version->job_id !== (int) $job->id
|
|
|| !hash_equals((string) $version->operation_id,
|
|
(string) $job->operation_id)
|
|
|| (int) $version->revision !== (int) ($body['revision'] ?? 0)
|
|
|| (int) ($payload['firewall_revision'] ?? 0)
|
|
!== (int) $version->revision
|
|
|| !is_string($body['policy_digest'] ?? null)
|
|
|| preg_match('/^[a-f0-9]{64}$/D',
|
|
$body['policy_digest']) !== 1
|
|
|| ($payload['agent_firewall_policy_digest'] ?? null)
|
|
!== $body['policy_digest']
|
|
|| !is_array($body['rules'] ?? null)
|
|
|| !array_is_list($body['rules'])) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'防火墙任务与版本账本不匹配',
|
|
409
|
|
);
|
|
}
|
|
return 'apply-firewall';
|
|
}
|
|
|
|
private static function policyAction(
|
|
string $method,
|
|
string $target,
|
|
string $expectedTarget,
|
|
array $body,
|
|
array $allowed,
|
|
bool $valid,
|
|
string $action
|
|
): string {
|
|
self::expectRequest($method, $target, 'POST', $expectedTarget);
|
|
self::assertAllowedBody($body, $allowed);
|
|
if (!$valid) {
|
|
self::invalidPayload('系统策略请求无效');
|
|
}
|
|
return $action;
|
|
}
|
|
|
|
private static function catalogIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body
|
|
): array {
|
|
return match ((string) $job->kind) {
|
|
'template_import_replica', 'template_metadata_replica',
|
|
'template_delete_replica' => self::templateIdentity(
|
|
$job, $payload, $method, $target, $body
|
|
),
|
|
'rescue_catalog_validate_replica',
|
|
'rescue_catalog_import_replica',
|
|
'rescue_catalog_delete_replica' =>
|
|
self::rescueCatalogIdentity(
|
|
$job, $payload, $method, $target, $body
|
|
),
|
|
'user_iso_import_replica', 'user_iso_delete_replica' =>
|
|
self::userIsoIdentity(
|
|
$job, $payload, $method, $target, $body
|
|
),
|
|
default => throw new CloudRecoveryPayloadUnavailable(
|
|
'目录任务类型没有恢复身份映射', 409
|
|
),
|
|
};
|
|
}
|
|
|
|
private static function templateIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body
|
|
): array {
|
|
$id = $payload['template_id'] ?? null;
|
|
$template = is_string($id) ? CloudTemplate::find($id) : null;
|
|
$replica = is_string($id) ? CloudTemplateReplica::where(
|
|
'host_id', (int) $job->host_id
|
|
)->where('template_id', $id)->first() : null;
|
|
$parent = $job->parent_job_id === null ? null
|
|
: CloudJob::find((int) $job->parent_job_id);
|
|
$expectedParent = [
|
|
'template_import_replica' => 'template_import',
|
|
'template_metadata_replica' => 'template_metadata_sync',
|
|
'template_delete_replica' => 'template_delete',
|
|
][(string) $job->kind];
|
|
$standaloneImport = (string) $job->kind
|
|
=== 'template_import_replica'
|
|
&& $job->parent_job_id === null
|
|
&& ($payload['replica_sync'] ?? null) === true;
|
|
if (!is_string($id)
|
|
|| preg_match(self::TEMPLATE_ID_PATTERN, $id) !== 1
|
|
|| $template === null || $replica === null
|
|
|| (!$standaloneImport && ($parent === null
|
|
|| (string) $parent->kind !== $expectedParent))
|
|
|| (int) $template->active_job_id !== ($standaloneImport
|
|
? (int) $job->id : (int) $parent->id)
|
|
|| (int) $replica->job_id !== (int) $job->id
|
|
|| !hash_equals((string) $replica->operation_id,
|
|
(string) $job->operation_id)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'云镜像子任务与副本账本不匹配', 409
|
|
);
|
|
}
|
|
$resource = 'template:' . $id;
|
|
if ((string) $job->kind === 'template_import_replica') {
|
|
self::expectRequest($method, $target, 'POST', '/v1/templates');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'id', 'name', 'source_url', 'source_token',
|
|
'source_size_bytes', 'os_family', 'version', 'architecture',
|
|
'sha256', 'revision', 'generation_token',
|
|
]);
|
|
if (($body['id'] ?? null) !== $id
|
|
|| (int) ($body['revision'] ?? 0) !== (int) $replica->revision
|
|
|| ($body['generation_token'] ?? null)
|
|
!== (string) $replica->generation_token) {
|
|
self::invalidPayload('云镜像导入请求与副本不匹配');
|
|
}
|
|
return ['import-template', $resource];
|
|
}
|
|
if ((string) $job->kind === 'template_metadata_replica') {
|
|
self::expectRequest($method, $target, 'PATCH',
|
|
'/v1/templates/' . rawurlencode($id));
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'name', 'revision', 'generation_token',
|
|
]);
|
|
if ((int) ($body['revision'] ?? 0) !== (int) $template->revision
|
|
|| ($body['generation_token'] ?? null)
|
|
!== (string) $template->generation_token) {
|
|
self::invalidPayload('云镜像元数据请求与目录不匹配');
|
|
}
|
|
return ['update-template', $resource];
|
|
}
|
|
self::expectRequest($method, $target, 'DELETE',
|
|
'/v1/templates/' . rawurlencode($id));
|
|
self::assertAllowedBody($body, ['operation_id']);
|
|
return ['delete-template', $resource];
|
|
}
|
|
|
|
private static function rescueCatalogIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body
|
|
): array {
|
|
$id = $payload['rescue_template_id'] ?? null;
|
|
$template = is_string($id)
|
|
? CloudRescueTemplate::find($id) : null;
|
|
$replica = is_string($id)
|
|
? CloudRescueTemplateReplica::query()
|
|
->where('host_id', (int) $job->host_id)
|
|
->where('template_id', $id)->first()
|
|
: null;
|
|
if (!is_string($id)
|
|
|| preg_match(self::CATALOG_ID_PATTERN, $id) !== 1
|
|
|| $template === null || $replica === null
|
|
|| $job->parent_job_id !== null
|
|
|| (int) $replica->job_id !== (int) $job->id
|
|
|| !hash_equals(
|
|
(string) $replica->operation_id,
|
|
(string) $job->operation_id
|
|
)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'全局救援 ISO 任务与副本账本不匹配',
|
|
409
|
|
);
|
|
}
|
|
if ((string) $job->kind === 'rescue_catalog_validate_replica'
|
|
&& $template->active_job_id !== null
|
|
&& (int) $template->active_job_id !== (int) $job->id) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'全局救援 ISO 首台校验绑定不匹配',
|
|
409
|
|
);
|
|
}
|
|
if ((string) $job->kind === 'rescue_catalog_delete_replica') {
|
|
self::expectRequest(
|
|
$method,
|
|
$target,
|
|
'DELETE',
|
|
'/v1/rescue-templates/' . rawurlencode($id)
|
|
);
|
|
self::assertAllowedBody($body, ['operation_id']);
|
|
if ((string) $template->state !== 'retiring'
|
|
|| !in_array((string) $replica->state, [
|
|
'deleting', 'delete_failed', 'delete_unknown', 'deleted',
|
|
], true)
|
|
|| (int) ($payload['revision'] ?? 0)
|
|
!== (int) $template->revision
|
|
|| ($payload['generation_token'] ?? null)
|
|
!== (string) $template->generation_token
|
|
|| (int) $replica->revision !== (int) $template->revision
|
|
|| !hash_equals(
|
|
(string) $template->generation_token,
|
|
(string) $replica->generation_token
|
|
)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'全局救援 ISO 删除任务与退役账本不匹配',
|
|
409
|
|
);
|
|
}
|
|
return ['delete-rescue-template', 'rescue-template:' . $id];
|
|
}
|
|
self::expectRequest(
|
|
$method,
|
|
$target,
|
|
'POST',
|
|
'/v1/rescue-templates'
|
|
);
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'id', 'name', 'source_url', 'source_token',
|
|
'source_size_bytes', 'sha256', 'revision', 'generation_token',
|
|
]);
|
|
if (($body['id'] ?? null) !== $id
|
|
|| ($body['name'] ?? null) !== (string) $template->name
|
|
|| (int) ($body['source_size_bytes'] ?? 0)
|
|
!== (int) $template->size_bytes
|
|
|| ($body['sha256'] ?? null) !== (string) $template->sha256
|
|
|| (int) ($body['revision'] ?? 0)
|
|
!== (int) $template->revision
|
|
|| ($body['generation_token'] ?? null)
|
|
!== (string) $template->generation_token
|
|
|| (int) $replica->revision !== (int) $template->revision
|
|
|| !hash_equals(
|
|
(string) $template->generation_token,
|
|
(string) $replica->generation_token
|
|
)) {
|
|
self::invalidPayload('全局救援 ISO 请求与副本不匹配');
|
|
}
|
|
return ['import-rescue-template', 'rescue-template:' . $id];
|
|
}
|
|
|
|
private static function userIsoIdentity(
|
|
CloudJob $job,
|
|
array $payload,
|
|
string $method,
|
|
string $target,
|
|
array $body
|
|
): array {
|
|
$id = $payload['user_iso_id'] ?? null;
|
|
$owner = filter_var($payload['owner_id'] ?? null,
|
|
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
|
$iso = is_string($id) ? CloudUserIso::find($id) : null;
|
|
$replica = is_string($id) ? CloudUserIsoReplica::where(
|
|
'host_id', (int) $job->host_id
|
|
)->where('user_iso_id', $id)->first() : null;
|
|
$parent = $job->parent_job_id === null ? null
|
|
: CloudJob::find((int) $job->parent_job_id);
|
|
$expectedParent = [
|
|
'user_iso_import_replica' => 'user_iso_import',
|
|
'user_iso_delete_replica' => 'user_iso_delete',
|
|
][(string) $job->kind];
|
|
if (!is_string($id)
|
|
|| preg_match(self::CATALOG_ID_PATTERN, $id) !== 1
|
|
|| $owner === false || $iso === null || $replica === null
|
|
|| $parent === null
|
|
|| $parent->parent_job_id !== null
|
|
|| (string) $parent->execution_mode !== 'aggregate'
|
|
|| (string) $parent->kind !== $expectedParent
|
|
|| (int) $parent->user_id !== (int) $owner
|
|
|| (int) $job->user_id !== (int) $owner
|
|
|| (int) $iso->active_job_id !== (int) $parent->id
|
|
|| (int) $iso->user_id !== (int) $owner
|
|
|| (int) $replica->user_id !== (int) $owner
|
|
|| (int) $replica->job_id !== (int) $job->id
|
|
|| !hash_equals((string) $replica->operation_id,
|
|
(string) $job->operation_id)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'ISO 子任务与所属人或副本账本不匹配', 409
|
|
);
|
|
}
|
|
$resource = 'user-iso:' . (int) $owner . ':' . $id;
|
|
if ((string) $job->kind === 'user_iso_import_replica') {
|
|
self::expectRequest($method, $target, 'POST', '/v1/user-isos');
|
|
self::assertAllowedBody($body, [
|
|
'operation_id', 'id', 'owner_id', 'name', 'source_url',
|
|
'source_token', 'sha256',
|
|
]);
|
|
if (($body['id'] ?? null) !== $id
|
|
|| (int) ($body['owner_id'] ?? 0) !== (int) $owner
|
|
|| ($body['name'] ?? null) !== (string) $iso->name) {
|
|
self::invalidPayload('ISO 导入请求与目录不匹配');
|
|
}
|
|
return ['import-user-iso', $resource];
|
|
}
|
|
self::expectRequest($method, $target, 'DELETE',
|
|
'/v1/user-isos/' . rawurlencode($id)
|
|
. '?owner_id=' . (int) $owner);
|
|
self::assertAllowedBody($body, ['operation_id']);
|
|
return ['delete-user-iso', $resource];
|
|
}
|
|
|
|
private static function assertBodyOperation(CloudJob $job, array $body): void
|
|
{
|
|
if (array_key_exists('operation_id', $body)
|
|
&& (!is_string($body['operation_id'])
|
|
|| !hash_equals((string) $job->operation_id,
|
|
$body['operation_id']))) {
|
|
self::invalidPayload('Agent 请求中的操作标识不匹配');
|
|
}
|
|
}
|
|
|
|
private static function expectRequest(
|
|
string $method,
|
|
string $target,
|
|
string $expectedMethod,
|
|
string $expectedTarget
|
|
): void {
|
|
if ($method !== $expectedMethod || $target !== $expectedTarget) {
|
|
self::invalidPayload('Agent 请求方法或路径与任务不匹配');
|
|
}
|
|
}
|
|
|
|
private static function assertAllowedBody(array $body, array $allowed): void
|
|
{
|
|
if (($body !== [] && array_is_list($body))
|
|
|| array_diff(array_keys($body), $allowed) !== []) {
|
|
self::invalidPayload('Agent 请求字段超出固定协议');
|
|
}
|
|
}
|
|
|
|
private static function hasExactKeys(mixed $value, array $expected): bool
|
|
{
|
|
if (!is_array($value) || array_is_list($value)) {
|
|
return false;
|
|
}
|
|
$actual = array_keys($value);
|
|
sort($actual, SORT_STRING);
|
|
sort($expected, SORT_STRING);
|
|
return $actual === $expected;
|
|
}
|
|
|
|
private static function invalidPayload(string $message): never
|
|
{
|
|
throw new CloudRecoveryPayloadUnavailable($message, 409);
|
|
}
|
|
|
|
private static function stored(array $payload): ?array
|
|
{
|
|
if (!array_key_exists(self::KEY, $payload)) {
|
|
return null;
|
|
}
|
|
$stored = $payload[self::KEY];
|
|
if (!is_array($stored) || array_is_list($stored)
|
|
|| array_diff(array_keys($stored), [
|
|
'version', 'action', 'resource_id', 'request_fingerprint',
|
|
]) !== []
|
|
|| ($stored['version'] ?? null) !== self::VERSION) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'任务持久化操作身份无效', 409
|
|
);
|
|
}
|
|
$identity = [
|
|
'action' => $stored['action'] ?? null,
|
|
'resource_id' => $stored['resource_id'] ?? null,
|
|
'request_fingerprint' => $stored['request_fingerprint'] ?? null,
|
|
];
|
|
self::assertIdentityShape($identity);
|
|
return $identity;
|
|
}
|
|
|
|
private static function isPreparedEscrow(
|
|
CloudJob $job,
|
|
array $payload,
|
|
array $identity
|
|
): bool {
|
|
$recovery = $payload['_operation_recovery'] ?? null;
|
|
$operation = is_array($recovery)
|
|
? ($recovery['operation'] ?? null) : null;
|
|
$operationIdentity = is_array($operation) ? [
|
|
'action' => $operation['action'] ?? null,
|
|
'resource_id' => $operation['resource_id'] ?? null,
|
|
'request_fingerprint' => $operation['request_fingerprint']
|
|
?? $operation['fingerprint'] ?? null,
|
|
] : [];
|
|
return is_array($recovery) && !array_is_list($recovery)
|
|
&& ($recovery['version'] ?? null) === 1
|
|
&& ($recovery['kind'] ?? null) === (string) $job->kind
|
|
&& is_string($recovery['prepared_marker'] ?? null)
|
|
&& str_starts_with(
|
|
$recovery['prepared_marker'],
|
|
'prepared:'
|
|
)
|
|
&& is_array($operation) && !array_is_list($operation)
|
|
&& ($operation['operation_id'] ?? null)
|
|
=== (string) $job->operation_id
|
|
&& self::same($identity, $operationIdentity);
|
|
}
|
|
|
|
private static function assertIdentityShape(array $identity): void
|
|
{
|
|
if (!is_string($identity['action'] ?? null)
|
|
|| strlen($identity['action']) > 128
|
|
|| preg_match(
|
|
'/^[a-z][a-z0-9]*(?:[-:][a-z0-9]+)*$/D',
|
|
$identity['action']
|
|
) !== 1
|
|
|| !is_string($identity['resource_id'] ?? null)
|
|
|| strlen($identity['resource_id']) > 255
|
|
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/D',
|
|
$identity['resource_id']) !== 1
|
|
|| !is_string($identity['request_fingerprint'] ?? null)
|
|
|| preg_match('/^[a-f0-9]{64}$/D',
|
|
$identity['request_fingerprint']) !== 1) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'任务操作身份结构无效', 409
|
|
);
|
|
}
|
|
}
|
|
}
|