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/CloudJobService.php

1304 lines
57 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudHostNetworkAttachment;
use App\Models\CloudInstance;
use App\Models\CloudJob;
use App\Models\CloudPublicIp;
use App\Models\CloudPublicIpPool;
use App\Models\CloudResourcePool;
use App\Models\CloudResourceReservation;
final class CloudJobService
{
private const RECEIPT_DEADLINE_SECONDS = 960;
private const STORAGE_DISPATCH_DEADLINE_SECONDS = 60;
private const STORAGE_RECEIPT_DEADLINE_SECONDS = 180;
private const IMPORT_RECEIPT_DEADLINE_SECONDS = 8100;
private const AGGREGATE_FINALIZATION_BUFFER_SECONDS = 300;
private const AGGREGATE_DEADLINE_SECONDS =
CloudJob::DISPATCH_DEADLINE_SECONDS
+ self::RECEIPT_DEADLINE_SECONDS
+ self::AGGREGATE_FINALIZATION_BUFFER_SECONDS;
private const IMPORT_AGGREGATE_DEADLINE_SECONDS =
CloudJob::DISPATCH_DEADLINE_SECONDS
+ self::IMPORT_RECEIPT_DEADLINE_SECONDS
+ self::AGGREGATE_FINALIZATION_BUFFER_SECONDS;
private const LONG_IMPORT_KINDS = [
'template_import_replica',
'rescue_template_import',
'user_iso_import_replica',
];
private const LONG_IMPORT_AGGREGATE_KINDS = [
'template_import',
'user_iso_import',
];
private const AGGREGATE_KINDS = [
'template_import',
'template_metadata_sync',
'template_delete',
'user_iso_import',
'user_iso_delete',
];
/** Absolute dispatch windows are selected once and are never extended. */
public static function dispatchDeadlineSeconds(string $kind): int
{
return $kind === 'host_storage_configure'
? self::STORAGE_DISPATCH_DEADLINE_SECONDS
: CloudJob::DISPATCH_DEADLINE_SECONDS;
}
public static function effectiveDispatchDeadline(CloudJob $job): int
{
$stored = (int) ($job->dispatch_deadline_at ?? 0);
if ($stored < 1 || (string) $job->kind !== 'host_storage_configure') {
return $stored;
}
$createdAt = (int) ($job->created_at ?? 0);
return $createdAt < 1 ? $stored : min(
$stored,
$createdAt + self::STORAGE_DISPATCH_DEADLINE_SECONDS
);
}
/** Absolute receipt windows are selected once and are never extended. */
public static function receiptDeadlineSeconds(string $kind): int
{
if (in_array($kind, self::LONG_IMPORT_KINDS, true)) {
return self::IMPORT_RECEIPT_DEADLINE_SECONDS;
}
return $kind === 'host_storage_configure'
? self::STORAGE_RECEIPT_DEADLINE_SECONDS
: self::RECEIPT_DEADLINE_SECONDS;
}
/**
* Apply the current bounded window to persisted work as well as new work.
* This lets a deployment shorten an old storage task's 960-second value
* without rewriting history or extending any previously stored deadline.
*/
public static function effectiveReceiptDeadline(CloudJob $job): int
{
$stored = (int) ($job->receipt_deadline_at ?? 0);
if ($stored < 1 || (string) $job->kind !== 'host_storage_configure') {
return $stored;
}
$dispatchedAt = (int) ($job->dispatched_at ?? 0);
return $dispatchedAt < 1 ? $stored : min(
$stored,
$dispatchedAt + self::STORAGE_RECEIPT_DEADLINE_SECONDS
);
}
public static function receiptDeadlineReached(CloudJob $job,
?int $now = null): bool
{
$deadline = self::effectiveReceiptDeadline($job);
return $deadline > 0 && $deadline <= ($now ?? time());
}
public static function activeDeadlineReached(CloudJob $job,
?int $now = null): bool
{
$now ??= time();
if ((string) $job->phase === 'accepted') {
$deadline = self::effectiveDispatchDeadline($job);
return $deadline > 0 && $deadline <= $now;
}
return in_array((string) $job->phase,
['dispatching', 'awaiting_receipt'], true)
&& self::receiptDeadlineReached($job, $now);
}
public static function aggregateDeadlineSeconds(string $kind): int
{
return in_array($kind, self::LONG_IMPORT_AGGREGATE_KINDS, true)
? self::IMPORT_AGGREGATE_DEADLINE_SECONDS
: self::AGGREGATE_DEADLINE_SECONDS;
}
/** Aggregate parents are local coordination rows and are never dispatched. */
public static function isAggregateKind(string $kind): bool
{
return in_array($kind, self::AGGREGATE_KINDS, true);
}
/**
* Operations that still own an instance resource. Active work blocks new
* mutations; a terminal unknown-effect failure remains fenced until a
* kind-specific, audited ledger finalizer has safely converged it.
*/
public static function blockingQueryForInstance(int $instanceId)
{
return CloudJob::where('instance_id', $instanceId)
->where(static function ($query): void {
$query->where('phase', '<>', 'terminal')
->orWhere(static function ($terminal): void {
$terminal->where('phase', 'terminal')
->where('outcome', 'failed')
->where(static function ($blocked): void {
$blocked->where('error_code', 'force_required')
->orWhere(static function ($unknown): void {
$unknown->where('effect_resolution', 'unknown')
->where(static function ($effect): void {
$effect->where('effect_may_have_applied', 1)
->orWhere('safe_to_resubmit', 0);
});
});
});
});
});
}
public static function blockingQueryForInvoice(int $invoiceId)
{
return CloudJob::where('invoice_id', $invoiceId)
->where('kind', 'payment_create')
->where(static function ($query): void {
$query->where('phase', '<>', 'terminal')
->orWhere(static function ($terminal): void {
$terminal->where('phase', 'terminal')
->where('outcome', 'failed')
->where('effect_resolution', 'unknown')
->where('safe_to_resubmit', 0);
});
});
}
/**
* Reserve the one public task that represents a multi-host mutation.
*
* Callers must invoke this while holding their catalog authority row (or
* before creating that row) inside the same database transaction. The
* aggregate is never claimed by a worker and can only be completed by the
* terminal transition of its persisted child jobs.
*
* @return array{0: CloudJob, 1: bool} job and whether it was newly created
*/
public static function reserveAggregate(
array $actor,
string $kind,
array $canonicalRequest
): array {
$userId = (int) ($actor['user_id'] ?? 0);
if ($userId < 1 || !self::isAggregateKind($kind)) {
throw new CloudError('任务请求无效', 400);
}
$fingerprint = hash('sha256', json_encode(
self::canonicalRequestValue([
'kind' => $kind,
'request' => $canonicalRequest,
]), JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
));
$requestKey = self::requestKey($actor);
if ($requestKey !== null) {
$prior = CloudJob::where('user_id', $userId)
->where('request_idempotency_key', $requestKey)
->lockForUpdate()->first();
if ($prior !== null) {
if (!hash_equals((string) $prior->request_fingerprint,
$fingerprint)) {
throw new CloudError(
'同一请求标识不能用于不同的任务', 409
);
}
return [$prior, false];
}
}
$job = new CloudJob();
$job->operation_id = bin2hex(random_bytes(16));
$job->request_idempotency_key = $requestKey
?? (string) $job->operation_id;
$job->request_fingerprint = $fingerprint;
$job->user_id = $userId;
$job->host_id = null;
$job->kind = $kind;
$job->execution_mode = 'aggregate';
$job->sealed_payload = CloudSecrets::encrypt([
'aggregate' => true,
], 'job-payload');
$now = time();
$job->receipt_deadline_at = $now
+ self::aggregateDeadlineSeconds($kind);
$job->available_at = $job->created_at = $job->updated_at = $now;
$job->save();
return [$job, true];
}
/**
* Reserve one public, host-targeted mutation with a plaintext canonical
* fingerprint. Replaying the same HTTP idempotency key returns the first
* CloudJob; it never creates another Agent operation.
*
* @return array{0: CloudJob, 1: bool}
*/
public static function reserveStandaloneAgentMutation(
array $actor,
int $hostId,
string $kind,
string $method,
string $target,
array $body,
array $metadata,
array $canonicalRequest,
?string $operationId = null
): array {
$userId = (int) ($actor['user_id'] ?? 0);
$method = strtoupper($method);
if ($userId < 1 || $hostId < 1
|| !array_key_exists($kind, CloudOperationCatalog::kinds())
|| !in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE'], true)
|| !str_starts_with($target, '/v1/')) {
throw new CloudError('Agent 任务请求无效', 400);
}
$fingerprint = hash('sha256', json_encode(
self::canonicalRequestValue([
'host_id' => $hostId,
'kind' => $kind,
'method' => $method,
'target' => $target,
'request' => $canonicalRequest,
]), JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
));
$requestKey = self::requestKey($actor);
if ($requestKey !== null) {
$prior = CloudJob::where('user_id', $userId)
->where('request_idempotency_key', $requestKey)
->lockForUpdate()->first();
if ($prior !== null) {
if (!hash_equals((string) $prior->request_fingerprint,
$fingerprint)) {
throw new CloudError(
'同一请求标识不能用于不同的任务', 409
);
}
return [$prior, false];
}
}
$operationId ??= bin2hex(random_bytes(16));
if (preg_match('/^[a-f0-9]{32}$/D', $operationId) !== 1) {
throw new CloudError('Agent 任务操作标识无效', 400);
}
$body['operation_id'] = $operationId;
$job = new CloudJob();
$job->operation_id = $operationId;
$job->request_idempotency_key = $requestKey ?? $operationId;
$job->request_fingerprint = $fingerprint;
$job->user_id = $userId;
$job->host_id = $hostId;
$job->kind = $kind;
$job->execution_mode = 'agent';
$job->sealed_payload = CloudSecrets::encrypt(array_merge($metadata, [
'method' => $method,
'request_target' => $target,
'body' => $body,
'owner_id' => (int) ($metadata['owner_id'] ?? $userId),
'can_manage' => (bool) ($metadata['can_manage'] ?? false),
]), 'job-payload');
$now = time();
$job->dispatch_deadline_at = $now
+ self::dispatchDeadlineSeconds($kind);
$job->available_at = $job->created_at = $job->updated_at = $now;
$job->save();
return [$job, true];
}
/** Persist one exact Agent mutation. It can be claimed only once. */
public static function reserveAgentMutation(
array $actor,
int $hostId,
string $kind,
string $method,
string $target,
array $body,
array $metadata = [],
?int $parentJobId = null,
?string $operationId = null
): CloudJob {
$userId = (int) ($actor['user_id'] ?? 0);
$method = strtoupper($method);
if ($userId < 1 || $hostId < 1
|| !array_key_exists($kind, CloudOperationCatalog::kinds())
|| !in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE'], true)
|| !str_starts_with($target, '/v1/')) {
throw new CloudError('Agent 任务请求无效', 400);
}
$operationId ??= bin2hex(random_bytes(16));
if (preg_match('/^[a-f0-9]{32}$/D', $operationId) !== 1) {
throw new CloudError('Agent 任务操作标识无效', 400);
}
$body['operation_id'] = $operationId;
$fingerprint = hash('sha256', json_encode(
self::canonicalRequestValue([
'host_id' => $hostId,
'kind' => $kind,
'method' => $method,
'target' => $target,
'body' => $body,
'metadata' => $metadata,
]), JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
));
$job = new CloudJob();
$job->operation_id = $operationId;
$job->request_idempotency_key = $operationId;
$job->request_fingerprint = $fingerprint;
$job->parent_job_id = $parentJobId;
$job->user_id = $userId;
$job->host_id = $hostId;
$job->kind = $kind;
$job->execution_mode = 'agent';
$job->sealed_payload = CloudSecrets::encrypt(array_merge($metadata, [
'method' => $method,
'request_target' => $target,
'body' => $body,
'owner_id' => (int) ($metadata['owner_id'] ?? $userId),
'can_manage' => (bool) ($metadata['can_manage'] ?? false),
]), 'job-payload');
$now = time();
$job->dispatch_deadline_at = $now
+ self::dispatchDeadlineSeconds($kind);
$job->available_at = $job->created_at = $job->updated_at = $now;
$job->save();
return $job;
}
/** Strict HTTP acknowledgement used by every asynchronous mutation. */
public static function acknowledgement(CloudJob $job): array
{
return [
'task_id' => (string) $job->id,
'status_url' => '/api/v1/tasks/' . (int) $job->id,
];
}
/**
* Record a proven no-op as a successful public task without ever making it
* claimable by a worker. The row is first persisted with the normal task
* invariants, then terminalized in the caller's database transaction.
*/
public static function completeWithoutDispatchLocked(
CloudJob $job,
array $result
): void {
if (!$job->exists
|| (string) $job->phase !== 'accepted'
|| (int) $job->dispatch_attempts !== 0
|| (int) $job->attempts !== 0
|| $job->dispatch_started_at !== null
|| $job->dispatched_at !== null
|| $job->agent_accepted_at !== null
|| $job->receipt_deadline_at !== null) {
throw new \LogicException(
'Only a fresh, undispatched task can complete as a no-op'
);
}
self::completeAggregateLocked(
$job,
'succeeded',
false,
false,
'',
$result
);
}
/** Complete an aggregate without dispatching another Agent mutation. */
public static function completeAggregateLocked(
CloudJob $job,
string $outcome,
bool $effectMayHaveApplied,
bool $safeToResubmit,
string $errorCode = '',
?array $result = null
): void {
if ((string) $job->phase === 'terminal') {
return;
}
if (!in_array($outcome, ['succeeded', 'failed'], true)) {
throw new \InvalidArgumentException('Invalid aggregate outcome');
}
if ($outcome !== 'failed') {
$effectMayHaveApplied = false;
$safeToResubmit = false;
$errorCode = '';
} elseif ($effectMayHaveApplied) {
$safeToResubmit = false;
}
$now = time();
$job->phase = 'terminal';
$job->outcome = $outcome;
$job->status = $outcome;
$job->terminal_at = $now;
$job->effect_may_have_applied = $effectMayHaveApplied ? 1 : 0;
$job->safe_to_resubmit = $safeToResubmit ? 1 : 0;
$job->effect_resolution = $outcome === 'succeeded' ? 'applied'
: ($effectMayHaveApplied ? 'unknown' : 'not_applied');
$job->error_code = $errorCode === '' ? null
: substr($errorCode, 0, 128);
$job->result_json = $result === null ? null : json_encode(
$result,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
);
$job->sealed_payload = CloudSecrets::encrypt([], 'job-payload');
$job->lease_token = null;
$job->lease_until = 0;
$job->available_at = 0;
$job->updated_at = $now;
$job->save();
}
public static function enqueue(CloudInstance $instance, array $actor, string $kind, string $method,
string $suffix, array $body = [], ?array $credential = null): CloudJob
{
CloudAccess::vmActor($instance, $actor);
$requestKey = self::requestKey($actor);
return $instance->getConnection()->transaction(function () use ($instance, $actor, $kind, $method, $suffix, $body, $credential, $requestKey) {
$templateMetadata = null;
$settingsFields = [];
if ($kind === 'reinstall') {
$body['template_id'] = CloudInput::template(
$body['template_id'] ?? ''
);
// Defense in depth for internal callers: this UI confirmation
// is not part of the strict Agent ReinstallRequest schema.
unset($body['confirmation_name']);
}
if ($kind === 'network_change') {
CloudInput::only($body,
['public_ip_cidr', 'public_pool_key', 'confirm_restart']);
if (($body['confirm_restart'] ?? false) !== true) {
throw new CloudError('更换公网 IP 前必须确认虚拟机会短暂重启');
}
$body['public_ip_cidr'] = CloudInput::publicIpCidr(
$body['public_ip_cidr'] ?? null
);
$body['public_pool_key'] = CloudInput::publicPoolKey(
$body['public_pool_key'] ?? null
);
}
if ($kind === 'instance_settings') {
CloudInput::only($body, ['hostname', 'root_password', 'ssh_public_key', 'confirm_restart']);
if (($body['confirm_restart'] ?? false) !== true) {
throw new CloudError('修改实例设置前必须确认虚拟机会短暂重启');
}
$changed = false;
if (array_key_exists('hostname', $body)) {
$body['hostname'] = CloudInput::hostname($body['hostname']);
$settingsFields[] = 'hostname';
$changed = true;
}
if (array_key_exists('root_password', $body)) {
if (!is_string($body['root_password']) || $body['root_password'] === '') {
throw new CloudError('实例密码不能为空');
}
$body['root_password'] = CloudInput::password($body['root_password']);
$settingsFields[] = 'password';
$changed = true;
}
if (array_key_exists('ssh_public_key', $body)) {
$parsed = CloudSSHKeys::parse((string) $body['ssh_public_key']);
$body['ssh_public_key'] = $parsed['public_key'];
$settingsFields[] = 'ssh_key';
$changed = true;
}
if (!$changed) {
throw new CloudError('请至少填写一项需要修改的实例设置');
}
}
$requestFingerprint = hash('sha256', json_encode(
self::canonicalRequestValue([
'instance_id' => (int) $instance->id,
'kind' => $kind,
'method' => strtoupper($method),
'suffix' => $suffix,
'body' => $body,
]), JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES));
$locked = CloudInstance::where('id', $instance->id)->lockForUpdate()->first();
if ($locked === null || (string) $locked->status === 'deleted') {
throw new CloudError('虚拟机不存在', 404);
}
if ($requestKey !== null) {
$prior = CloudJob::where('user_id', (int) $actor['user_id'])
->where('request_idempotency_key', $requestKey)
->lockForUpdate()->first();
if ($prior !== null) {
if (!hash_equals((string) $prior->request_fingerprint,
$requestFingerprint)) {
throw new CloudError(
'同一请求标识不能用于不同的虚拟机操作', 409
);
}
return $prior;
}
}
if ((string) $locked->status !== 'active') {
throw new CloudError('实例正在执行到期销毁流程,不能提交其他操作', 409);
}
if ($kind === 'reinstall') {
CloudTemplateCatalogService::assertProvisionable(
(string) $body['template_id']
);
CloudSnapshotService::assertReinstallAllowedLocked($locked);
$body = CloudTemplateCatalogService::applyProvisioningSnapshot(
$body,
false
);
$templateMetadata =
CloudTemplateCatalogService::templateMetadataSnapshot(
$body
);
}
$policyService = ['suspending_expired', 'resume_pending', 'resuming',
'suspend_failed', 'resume_failed', 'expired_grace',
'purge_stopping', 'purge_stop_failed', 'purge_force_required',
'purge_deleting',
'purge_failed'];
$policyNetwork = ['blocking', 'blocking_expired', 'blocked_expired',
'restore_pending', 'restoring', 'block_failed', 'restore_failed'];
$superAdmin = ($actor['is_super_admin'] ?? false)
&& ($actor['can_manage'] ?? false);
if ($kind !== 'delete' && !$superAdmin
&& (in_array((string) $locked->service_status, $policyService, true)
|| in_array((string) $locked->network_status, $policyNetwork, true)
|| ((string) $locked->service_status !== 'exempt'
&& ($locked->expires_at === null || (int) $locked->expires_at <= time())))) {
throw new CloudError('实例正在执行到期或流量策略,请稍后重试', 409);
}
$activeJobs = self::blockingQueryForInstance((int) $locked->id);
if ($activeJobs->exists()) {
throw new CloudError('虚拟机已有任务,请等待完成', 409);
}
$networkLedger = null;
if ($kind === 'network_change') {
$host = CloudHost::where('id', (int) $locked->host_id)
->lockForUpdate()->first();
// The host row is the sentinel for all of these references.
// Read their identifiers first, then lock attachment/pools,
// reservation and IP rows in the scheduler's fixed order.
$reservationRef = $locked->reservation_id === null ? null
: CloudResourceReservation::where('id', (int) $locked->reservation_id)
->first();
if ($host === null || $reservationRef === null
|| !CloudNetworkSelector::isValid($host->default_network)
|| (int) $reservationRef->host_id !== (int) $host->id
|| (int) ($reservationRef->network_attachment_id ?? 0) < 1
|| (int) ($reservationRef->public_ip_pool_id ?? 0) < 1) {
throw new CloudError('虚拟机缺少有效的公网 IP 资源预留', 409);
}
$parts = explode('/', (string) $body['public_ip_cidr'], 2);
$targetPoolRef = CloudPublicIpPool::where('host_id', (int) $host->id)
->where('pool_key', (string) $body['public_pool_key'])->first();
if ($targetPoolRef === null) {
throw new CloudError('所选公网地址池已不可用,请刷新后重试', 409);
}
$targetRef = CloudPublicIp::where('host_id', (int) $host->id)
->where('public_ip_pool_id', (int) $targetPoolRef->id)
->where('address', $parts[0])
->where('prefix_length', (int) $parts[1])->first();
if ($targetRef === null) {
throw new CloudError('所选公网 IP 不在指定地址池的可用账本中', 409);
}
$networkAttachmentId = (int) $reservationRef->network_attachment_id;
$sourcePoolId = (int) $reservationRef->public_ip_pool_id;
$targetPoolId = (int) $targetPoolRef->id;
$attachment = CloudHostNetworkAttachment::where(
'id', $networkAttachmentId
)->lockForUpdate()->first();
$poolIds = array_values(array_unique([$sourcePoolId, $targetPoolId]));
sort($poolIds, SORT_NUMERIC);
$pools = CloudPublicIpPool::whereIn('id', $poolIds)->orderBy('id')
->lockForUpdate()->get()->keyBy('id');
$sourcePool = $pools->get($sourcePoolId);
$targetPool = $pools->get($targetPoolId);
$reservation = CloudResourceReservation::where(
'id', (int) $reservationRef->id
)->lockForUpdate()->first();
$reservationPool = $reservation === null ? null
: CloudResourcePool::find((int) $reservation->resource_pool_id);
if ($reservation === null) {
throw new CloudError('虚拟机缺少有效的公网 IP 资源预留', 409);
}
$ipIds = array_values(array_unique([
(int) $reservation->public_ip_id, (int) $targetRef->id,
]));
sort($ipIds, SORT_NUMERIC);
$ips = CloudPublicIp::whereIn('id', $ipIds)->orderBy('id')
->lockForUpdate()->get()->keyBy('id');
$source = $ips->get((int) $reservation->public_ip_id);
$target = $ips->get((int) $targetRef->id);
if ($attachment === null || $sourcePool === null
|| $targetPool === null || $source === null || $target === null
|| $reservationPool === null
|| (int) $attachment->host_id !== (int) $host->id
|| (int) $reservation->resource_pool_id
!== (int) ($locked->resource_pool_id ?? 0)
|| (int) $attachment->line_id
!== (int) $reservationPool->line_id
|| (string) $attachment->state !== 'active'
|| (string) $attachment->sync_state !== 'applied'
|| (int) $attachment->observed_revision
< (int) $attachment->desired_revision
|| (string) $attachment->network_selector
!== (string) $host->default_network
|| (int) $sourcePool->host_id !== (int) $host->id
|| (int) $targetPool->host_id !== (int) $host->id
|| (string) $sourcePool->state !== 'active'
|| (string) $sourcePool->sync_state !== 'applied'
|| (int) $sourcePool->observed_revision
< (int) $sourcePool->desired_revision
|| preg_match('/^[a-f0-9]{32}$/D',
(string) $sourcePool->pool_key) !== 1
|| (int) $sourcePool->network_attachment_id
!== $networkAttachmentId
|| (int) $targetPool->network_attachment_id
!== $networkAttachmentId
|| (string) $targetPool->pool_key
!== (string) $body['public_pool_key']
|| (string) $targetPool->state !== 'active'
|| (string) $targetPool->sync_state !== 'applied'
|| (int) $targetPool->observed_revision
< (int) $targetPool->desired_revision
|| (int) $reservation->host_id !== (int) $host->id
|| (int) ($reservation->instance_id ?? 0) !== (int) $locked->id
|| (string) $reservation->state !== 'committed'
|| (int) ($reservation->network_attachment_id ?? 0)
!== $networkAttachmentId
|| (int) ($reservation->public_ip_pool_id ?? 0) !== $sourcePoolId
|| (int) $source->host_id !== (int) $host->id
|| (int) ($source->public_ip_pool_id ?? 0) !== $sourcePoolId
|| (int) ($target->public_ip_pool_id ?? 0) !== $targetPoolId
|| (int) $target->prefix_length
!== (int) $targetPool->guest_prefix_length
|| !self::publicIpBelongsToPool($source, $sourcePool)
|| !self::publicIpBelongsToPool($target, $targetPool)
|| !self::instancePublicIpMatches($locked, $source)
|| (string) $source->state !== 'assigned'
|| (int) ($source->reservation_id ?? 0) !== (int) $reservation->id
|| (int) ($source->instance_id ?? 0) !== (int) $locked->id
|| !hash_equals((string) $reservation->operation_id,
(string) ($source->operation_id ?? ''))) {
throw new CloudError('虚拟机当前公网 IP 账本关联不一致', 409);
}
if ((int) $target->id === (int) $source->id
|| (string) $target->state !== 'available'
|| $target->reservation_id !== null
|| $target->instance_id !== null
|| $target->operation_id !== null) {
throw new CloudError('所选公网 IP 已不可分配,请刷新后重试', 409);
}
$body['network'] = (string) $attachment->network_selector;
$body['public_pool_cidr'] = (string) $targetPool->cidr;
$body['gateway'] = (string) $targetPool->gateway;
$body['dns_servers'] = self::poolDnsServers($targetPool);
$networkLedger = [
'source' => $source,
'target' => $target,
'network_attachment_id' => $networkAttachmentId,
'source_public_ip_pool_id' => $sourcePoolId,
'target_public_ip_pool_id' => $targetPoolId,
];
}
$job = new CloudJob();
$job->operation_id = bin2hex(random_bytes(16));
$job->instance_id = $locked->id;
$job->user_id = $actor['user_id'];
$job->host_id = $locked->host_id;
$job->kind = $kind;
$job->execution_mode = 'agent';
$job->status = 'queued';
if ($requestKey !== null) {
$job->request_idempotency_key = $requestKey;
}
$job->request_fingerprint = $requestFingerprint;
$jobPayload = ['method' => $method,
'request_target' => '/v1/vms/' . rawurlencode($locked->uuid) . $suffix,
'body' => $body,
'credential' => $credential, 'owner_id' => (int) $locked->user_id,
'can_manage' => (bool) ($actor['can_manage'] ?? false)];
if ($settingsFields !== []) {
// This allow-listed metadata remains outside the strict Agent
// body and survives terminal secret redaction. Never persist a
// hostname, password or public-key value as presentation data.
$jobPayload['settings_fields'] = $settingsFields;
}
if ($templateMetadata !== null) {
// Encrypted panel metadata is deliberately outside body:
// body is the exact strict Go ReinstallRequest DTO.
$jobPayload['template_metadata'] = $templateMetadata;
}
if ($networkLedger !== null) {
$source = $networkLedger['source'];
$target = $networkLedger['target'];
$jobPayload['source_public_ip_id'] = (int) $source->id;
$jobPayload['target_public_ip_id'] = (int) $target->id;
$jobPayload['network_attachment_id'] =
$networkLedger['network_attachment_id'];
$jobPayload['source_public_ip_pool_id'] =
$networkLedger['source_public_ip_pool_id'];
$jobPayload['target_public_ip_pool_id'] =
$networkLedger['target_public_ip_pool_id'];
// reservation_id is deliberately left NULL until the swap
// succeeds because cloud_public_ips enforces one current IP
// per reservation.
$target->state = 'changing';
$target->instance_id = (int) $locked->id;
$target->operation_id = $job->operation_id;
$target->updated_at = time();
$target->save();
}
$job->sealed_payload = CloudSecrets::encrypt(
$jobPayload, 'job-payload'
);
$job->available_at = $job->created_at = $job->updated_at = time();
$job->save();
return $job;
}, 3);
}
/**
* Queue the irreversible second phase of expiry cleanup.
*
* Only the lifecycle state machine may reach this method. Unlike the
* four target-state policy jobs, expiry deletion is intentionally never
* replayed after dispatch because an interrupted volume deletion may be
* only partly complete.
*/
public static function enqueueExpiryDelete(CloudInstance $instance): CloudJob
{
return $instance->getConnection()->transaction(function () use ($instance) {
$locked = CloudInstance::where('id', $instance->id)->lockForUpdate()->first();
if ($locked === null || (string) $locked->status === 'deleted') {
throw new CloudError('虚拟机不存在', 404);
}
if ((string) $locked->status !== 'deleting'
|| (string) $locked->service_status !== 'purge_deleting') {
throw new CloudError('实例尚未完成销毁前停机,不能删除磁盘', 409);
}
$existing = self::blockingQueryForInstance((int) $locked->id)
->orderByDesc('id')->first();
if ($existing !== null) {
if ((string) $existing->kind === 'expiry_delete') {
return $existing;
}
throw new CloudError('虚拟机已有任务,请等待完成', 409);
}
$job = new CloudJob();
$job->operation_id = bin2hex(random_bytes(16));
$job->instance_id = $locked->id;
$job->user_id = $locked->user_id;
$job->host_id = $locked->host_id;
$job->kind = 'expiry_delete';
$job->execution_mode = 'agent';
$job->status = 'queued';
$job->sealed_payload = CloudSecrets::encrypt([
'method' => 'DELETE',
'request_target' => '/v1/vms/' . rawurlencode($locked->uuid),
'body' => ['remove_managed_disks' => true],
'owner_id' => (int) $locked->user_id,
'system_cleanup' => true,
], 'job-payload');
$job->available_at = $job->created_at = $job->updated_at = time();
$job->save();
return $job;
}, 3);
}
/**
* Queue the separately audited force phase of a delete operation.
*
* The original graceful operation remains the authorization anchor. It is
* never replayed or changed into a force request; the Agent validates that
* exact prior operation before accepting this new operation ID.
*/
public static function enqueueForceDelete(
CloudJob $prior,
array $actor
): CloudJob {
CloudAccess::manage($actor);
$priorId = filter_var($prior->id, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]);
$instanceId = filter_var($prior->instance_id, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]);
if ($priorId === false || $instanceId === false) {
throw new CloudError('当前任务没有关联实例', 409);
}
return $prior->getConnection()->transaction(function () use (
$priorId, $instanceId, $actor
) {
// Keep the global instance-mutation lock order: instance first,
// then jobs. The prior row is fully revalidated after both locks.
$instance = CloudInstance::where('id', (int) $instanceId)
->lockForUpdate()->first();
$lockedPrior = CloudJob::where('id', (int) $priorId)
->lockForUpdate()->first();
if ($lockedPrior === null) {
throw new CloudError('任务不存在', 404);
}
if (!in_array((string) $lockedPrior->kind,
['delete', 'expiry_delete', 'service_suspend'], true)
|| (string) $lockedPrior->phase !== 'terminal'
|| (string) $lockedPrior->outcome !== 'failed'
|| (string) $lockedPrior->error_code !== 'force_required'
|| $lockedPrior->dispatched_at === null
|| preg_match('/^[a-f0-9]{32}$/D',
(string) $lockedPrior->operation_id) !== 1
|| (int) $lockedPrior->instance_id !== (int) $instanceId) {
throw new CloudError('当前任务没有经过确认的强制删除前置状态', 409);
}
if ($instance === null || (string) $instance->status === 'deleted'
|| (int) $instance->host_id !== (int) $lockedPrior->host_id
|| preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iD',
(string) $instance->uuid) !== 1) {
throw new CloudError('关联实例已不存在或与原删除任务不一致', 409);
}
$priorPayload = CloudSecrets::decrypt(
(string) $lockedPrior->sealed_payload,
'job-payload'
);
$target = '/v1/vms/' . rawurlencode((string) $instance->uuid);
$gracefulDelete = ($priorPayload['method'] ?? null) === 'DELETE'
&& ($priorPayload['request_target'] ?? null) === $target
&& ($priorPayload['body'] ?? null)
=== ['remove_managed_disks' => true];
$expiryGracefulStop = (string) $lockedPrior->kind
=== 'service_suspend'
&& ($priorPayload['method'] ?? null) === 'POST'
&& ($priorPayload['request_target'] ?? null)
=== $target . '/service/suspend'
&& ($priorPayload['body'] ?? null) === ['reason' => 'purge']
&& ($priorPayload['system_policy'] ?? false) === true
&& (string) $instance->status === 'deleting'
&& (string) $instance->service_status
=== 'purge_force_required';
if (!$gracefulDelete && !$expiryGracefulStop) {
throw new CloudError('原删除任务不允许强制删除面板管理磁盘', 409);
}
$otherBlocker = self::blockingQueryForInstance((int) $instance->id)
->where('id', '<>', (int) $lockedPrior->id)
->lockForUpdate()->first();
if ($otherBlocker !== null) {
throw new CloudError('虚拟机还有其他未完成任务,不能发起强制删除', 409);
}
do {
$operationId = bin2hex(random_bytes(16));
} while (hash_equals((string) $lockedPrior->operation_id, $operationId));
$job = new CloudJob();
$job->operation_id = $operationId;
$job->instance_id = $instance->id;
$job->user_id = (int) ($actor['user_id'] ?? 0);
$job->host_id = $instance->host_id;
$job->kind = 'delete_force';
$job->execution_mode = 'agent';
$job->status = 'queued';
$job->sealed_payload = CloudSecrets::encrypt([
'method' => 'POST',
'request_target' => '/v1/vms/'
. rawurlencode((string) $instance->uuid) . '/force-delete',
'body' => [
'operation_id' => $operationId,
'prior_operation_id' => (string) $lockedPrior->operation_id,
'ack_data_loss' => true,
'remove_managed_disks' => true,
],
'owner_id' => (int) $instance->user_id,
'can_manage' => true,
'prior_job_id' => (int) $lockedPrior->id,
'prior_operation_id' => (string) $lockedPrior->operation_id,
], 'job-payload');
$now = time();
$job->available_at = $job->created_at = $job->updated_at = $now;
$job->save();
error_log(sprintf(
'cloud admin queued force delete prior_job_id=%d force_job_id=%d prior_operation_id=%s force_operation_id=%s actor_id=%d',
(int) $lockedPrior->id, (int) $job->id,
(string) $lockedPrior->operation_id, $operationId,
(int) ($actor['user_id'] ?? 0)
));
return $job;
}, 3);
}
public static function display(CloudJob $job, bool $administrator = false): array
{
$completed = (string) $job->phase === 'terminal'
&& in_array((string) $job->outcome,
['succeeded', 'failed'], true);
$action = self::action($job);
$labels = CloudOperationCatalog::labels((string) $job->kind, $action,
self::settingsFields($job));
$base = [
'id' => (string) $job->id,
'operation_id' => (string) $job->operation_id,
'kind' => (string) $job->kind,
'completed' => $completed,
'created_at' => max(0, (int) $job->created_at),
'updated_at' => max(0, (int) $job->updated_at),
'status_url' => '/api/v1/tasks/' . (int) $job->id,
'action' => $action,
'kind_label' => $labels['kind_label'],
'action_label' => $labels['action_label'],
];
if (!$completed) {
return $base;
}
$result = $job->result_json === null ? null : json_decode($job->result_json, true);
$status = (string) $job->outcome;
$safeResult = (string) $job->kind === 'payment_create'
&& $status === 'succeeded' && is_array($result)
? self::displayPaymentResult($job, $result)
: self::displayResult(is_array($result) ? $result : null,
$administrator, (string) $job->kind, $status,
$job->order_id !== null, $action);
$error = $administrator
? CloudOperationErrorCatalog::adminSummary((string) $job->kind,
$status, $job->error_code, $job->order_id !== null, $action)
: CloudOperationErrorCatalog::userMessage((string) $job->kind,
$status, $job->error_code, $job->order_id !== null, $action);
$phase = $safeResult['phase'] ?? null;
$phase = $administrator
? CloudOperationErrorCatalog::adminSummary((string) $job->kind,
$status, $phase, $job->order_id !== null, $action)
: CloudOperationErrorCatalog::userPhase($phase, $status, (string) $job->kind);
return array_merge($base, [
'status' => $status, 'error' => $error,
'error_code' => CloudOperationErrorCatalog::publicCode($job->error_code),
'phase' => is_string($phase) ? mb_substr($phase, 0, 120) : null,
'result' => $safeResult,
'effect_may_have_applied' => $job->effect_may_have_applied === null
? null : (bool) $job->effect_may_have_applied,
'safe_to_resubmit' => $job->safe_to_resubmit === null
? null : (bool) $job->safe_to_resubmit,
'unread' => $job->read_at === null,
'terminal_at' => max(0, (int) $job->terminal_at),
]);
}
public static function tasks(array $actor, string $state,
?int $cursor = null, int $limit = 20): array
{
if (!in_array($state, ['active', 'completed'], true)) {
throw new CloudError('任务状态筛选无效', 400);
}
// The task center is also the owner-scoped daemon-loss fail-safe. It
// persists only already-due local outcomes and never contacts Agents.
CloudWorkerService::expireDueTasksForOwner(
(int) ($actor['user_id'] ?? 0), null, 100
);
$limit = max(1, min(50, $limit));
$owner = static function ($query) use ($actor): void {
$query->where('user_id', (int) ($actor['user_id'] ?? 0));
};
// Per-host child jobs are implementation details of one public batch.
// Only their parent appears in the task center.
$base = CloudJob::query()->whereNull('parent_job_id');
$owner($base);
$activeCount = (clone $base)->where('phase', '<>', 'terminal')->count();
$unreadCount = (clone $base)->where('phase', 'terminal')
->whereNull('read_at')->count();
$query = clone $base;
$query->where('phase', $state === 'active' ? '<>' : '=', 'terminal');
if ($cursor !== null) {
$query->where('id', '<', $cursor);
}
$rows = $query->orderByDesc('id')->limit($limit + 1)->get();
$hasMore = $rows->count() > $limit;
if ($hasMore) {
$rows = $rows->take($limit);
}
$items = $rows->map(static fn (CloudJob $job): array =>
self::display($job, (bool) ($actor['is_admin'] ?? false)))->all();
$last = $rows->last();
return [
'items' => $items,
'pagination' => [
'next_cursor' => $hasMore && $last !== null
? (string) $last->id : null,
'has_more' => $hasMore,
],
'active_count' => (int) $activeCount,
'unread_count' => (int) $unreadCount,
];
}
public static function markRead(CloudJob $job): void
{
if ((string) $job->phase !== 'terminal' || $job->read_at !== null) {
return;
}
CloudJob::where('id', (int) $job->id)->where('phase', 'terminal')
->whereNull('read_at')->update(['read_at' => time()]);
}
public static function unreadCount(array $actor): int
{
$query = CloudJob::where('phase', 'terminal')->whereNull('read_at')
->where('user_id', (int) ($actor['user_id'] ?? 0))
->whereNull('parent_job_id');
return (int) $query->count();
}
private static function requestKey(array $actor): ?string
{
$key = $actor['request_idempotency_key'] ?? null;
if ($key === null || $key === '') {
return null;
}
if (!is_string($key)
|| preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $key) !== 1) {
throw new CloudError('请求幂等标识无效', 400);
}
return $key;
}
private static function canonicalRequestValue($value)
{
if (!is_array($value)) {
return $value;
}
if (!array_is_list($value)) {
ksort($value, SORT_STRING);
}
foreach ($value as $key => $item) {
$value[$key] = self::canonicalRequestValue($item);
}
return $value;
}
/**
* Keep only the catalogued result DTO. Historical result JSON is not a
* trusted presentation format and must not bypass the error boundary.
*/
private static function displayResult(?array $result, bool $administrator,
?string $kind, ?string $status, bool $hasOrder, ?string $action): ?array
{
if ($result === null) {
return null;
}
return CloudOperationErrorCatalog::result($result, $administrator, $kind,
$status, $hasOrder, $action);
}
/** Resolve a trusted payment DTO from its owner-scoped durable record. */
private static function displayPaymentResult(CloudJob $job,
array $result): ?array
{
$id = $result['payment_id'] ?? null;
if (!is_string($id)
|| preg_match('/^[1-9][0-9]{0,18}$/D', $id) !== 1
|| $job->invoice_id === null) {
return null;
}
$payment = \App\Models\CloudInvoicePayment::where('id', (int) $id)
->where('invoice_id', (int) $job->invoice_id)
->where('user_id', (int) $job->user_id)->first();
if ($payment === null) {
return null;
}
try {
return ['payment' => CloudInvoicePaymentService::display($payment)];
} catch (\Throwable $error) {
return null;
}
}
/**
* Return the non-sensitive power action from the encrypted task payload.
*
* The durable job payload is encrypted at rest and is never returned to
* the browser. Terminal jobs retain only CloudInput::safeResult($payload),
* so this lookup continues to work for historical rows while removing
* credentials and all other payload fields from the public response.
*/
public static function action(CloudJob $job): ?string
{
if ((string) $job->kind !== 'action' || trim((string) $job->sealed_payload) === '') {
return null;
}
try {
$payload = CloudSecrets::decrypt(
(string) $job->sealed_payload,
'job-payload'
);
} catch (\Throwable $error) {
return null;
}
$body = $payload['body'] ?? null;
$action = is_array($body) && is_string($body['action'] ?? null)
? $body['action'] : '';
return CloudOperationCatalog::isPowerAction($action) ? $action : null;
}
/** Return the same safe labels used by every administrator DTO. */
public static function labels(CloudJob $job): array
{
return CloudOperationCatalog::labels((string) $job->kind,
self::action($job), self::settingsFields($job));
}
/**
* Read only safe setting-category codes from an encrypted job payload.
*
* New jobs persist the codes outside the strict Agent body so terminal
* redaction retains them. Jobs already active during deployment can still
* be described from body key presence; completed legacy password/key jobs
* have intentionally lost those keys and safely fall back to the generic
* instance-settings label.
*/
private static function settingsFields(CloudJob $job): array
{
if ((string) $job->kind !== 'instance_settings'
|| trim((string) $job->sealed_payload) === '') {
return [];
}
try {
$payload = CloudSecrets::decrypt(
(string) $job->sealed_payload,
'job-payload'
);
} catch (\Throwable $error) {
return [];
}
if (array_key_exists('settings_fields', $payload)) {
$fields = $payload['settings_fields'];
return is_array($fields) && array_is_list($fields)
? $fields : [];
}
$body = $payload['body'] ?? null;
if (!is_array($body) || array_is_list($body)) {
return [];
}
$fields = [];
foreach ([
'hostname' => 'hostname',
'root_password' => 'password',
'ssh_public_key' => 'ssh_key',
] as $bodyField => $detailCode) {
if (array_key_exists($bodyField, $body)) {
$fields[] = $detailCode;
}
}
return $fields;
}
/**
* Read the user's instance operation history directly from cloud_jobs.
* Power, reinstall and snapshot jobs are part of this user-facing audit view.
*/
public static function operationLogs(CloudInstance $instance, int $page = 1, int $perPage = 10): array
{
$perPage = max(1, min(50, $perPage));
$query = CloudJob::where('instance_id', $instance->id)
->whereIn('kind', ['action', 'reinstall', 'snapshot_create',
'snapshot_restore', 'snapshot_delete', 'firewall_apply'])
->orderByDesc('id');
$total = max(0, (int) (clone $query)->count('id'));
$pages = max(1, (int) ceil($total / $perPage));
$page = max(1, min($pages, $page));
$jobs = $query->offset(($page - 1) * $perPage)->limit($perPage)
->get(['id', 'operation_id', 'kind', 'order_id', 'status',
'phase', 'outcome', 'attempts', 'error_code', 'result_json',
'effect_may_have_applied', 'safe_to_resubmit', 'terminal_at',
'read_at', 'sealed_payload', 'created_at', 'updated_at']);
$items = [];
foreach ($jobs as $job) {
$entry = self::display($job);
unset($entry['operation_id'], $entry['result']);
$items[] = $entry;
}
$from = $total === 0 ? 0 : ($page - 1) * $perPage + 1;
return ['items' => $items, 'pagination' => [
'page' => $page, 'per_page' => $perPage, 'total' => $total,
'total_pages' => $pages, 'from' => $from,
'to' => $from === 0 ? 0 : $from + count($items) - 1,
]];
}
private static function publicIpBelongsToPool(CloudPublicIp $ip,
CloudPublicIpPool $pool): bool
{
$parts = explode('/', (string) $pool->cidr, 2);
if (count($parts) !== 2 || !ctype_digit($parts[1])) {
return false;
}
$prefix = (int) $parts[1];
if ($prefix < 24 || $prefix > 30
|| (int) $ip->prefix_length !== (int) $pool->guest_prefix_length) {
return false;
}
$address = self::ipv4Number((string) $ip->address);
$network = self::ipv4Number($parts[0]);
if ($address === null || $network === null) {
return false;
}
$block = 2 ** (32 - $prefix);
$base = (int) (floor($network / $block) * $block);
return $address > $base && $address < $base + $block - 1;
}
private static function instancePublicIpMatches(CloudInstance $instance,
CloudPublicIp $ip): bool
{
$spec = json_decode((string) $instance->spec_json, true);
$recorded = is_array($spec) && !array_is_list($spec)
? ($spec['public_ip_cidr'] ?? null) : null;
return is_string($recorded) && hash_equals(
(string) $ip->address . '/' . (int) $ip->prefix_length,
trim($recorded)
);
}
private static function ipv4Number(string $value): ?int
{
if (filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
return null;
}
$packed = inet_pton($value);
if ($packed === false || strlen($packed) !== 4) {
return null;
}
$parts = unpack('Nnumber', $packed);
return is_array($parts) && isset($parts['number'])
? (int) sprintf('%u', $parts['number']) : null;
}
private static function poolDnsServers(CloudPublicIpPool $pool): array
{
try {
$values = json_decode(
(string) $pool->dns_servers_json,
true,
16,
JSON_THROW_ON_ERROR
);
} catch (\Throwable $error) {
throw new CloudError('公网地址池 DNS 配置损坏', 409);
}
if (!is_array($values) || !array_is_list($values)
|| $values === [] || count($values) > 4
|| count(array_filter($values, static fn ($value): bool =>
is_string($value) && filter_var(
$value,
FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4
) !== false
)) !== count($values)) {
throw new CloudError('公网地址池 DNS 配置损坏', 409);
}
return array_values($values);
}
}