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

191 lines
8.9 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudInstance;
use App\Models\CloudJob;
final class CloudJobService
{
private const POWER_ACTIONS = [
'start', 'shutdown', 'reboot', 'poweroff', 'reset',
];
public static function enqueue(CloudInstance $instance, array $actor, string $kind, string $method,
string $suffix, array $body = [], ?array $credential = null): CloudJob
{
CloudAccess::vmActor($instance, $actor);
return $instance->getConnection()->transaction(function () use ($instance, $actor, $kind, $method, $suffix, $body, $credential) {
if ($kind === 'reinstall') {
CloudTemplateDeletionService::assertAvailable(
CloudInput::template($body['template_id'] ?? '')
);
}
if ($kind === 'network_change') {
if (($body['confirm_restart'] ?? false) !== true) {
throw new CloudError('更换公网 IP 前必须确认虚拟机会短暂重启');
}
$body['public_ip_cidr'] = CloudInput::publicIpCidr(
$body['public_ip_cidr'] ?? null
);
}
$locked = CloudInstance::where('id', $instance->id)->lockForUpdate()->first();
if ($locked === null || (string) $locked->status === 'deleted') {
throw new CloudError('虚拟机不存在', 404);
}
if ((string) $locked->status !== 'active') {
throw new CloudError('实例正在执行到期销毁流程,不能提交其他操作', 409);
}
$policyService = ['suspending_expired', 'resume_pending', 'resuming',
'suspend_failed', 'resume_failed', 'expired_grace',
'purge_stopping', 'purge_stop_failed', '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);
}
if (CloudJob::where('instance_id', $locked->id)->whereIn('status', ['queued', 'running', 'uncertain'])->exists()) {
throw new CloudError('虚拟机已有任务,请等待完成', 409);
}
$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->status = 'queued';
$job->payload_cipher = CloudSecrets::encrypt(['method' => $method,
'resource' => 'vms/' . rawurlencode($locked->uuid) . $suffix, 'body' => $body,
'credential' => $credential, 'owner_id' => (int) $locked->user_id,
'can_manage' => (bool) ($actor['can_manage'] ?? false)]);
$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 = CloudJob::where('instance_id', $locked->id)
->whereIn('status', ['queued', 'running', 'uncertain'])
->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->status = 'queued';
$job->payload_cipher = CloudSecrets::encrypt([
'method' => 'DELETE',
'resource' => 'vms/' . rawurlencode($locked->uuid)
. '?delete_disks=true',
'body' => [],
'owner_id' => (int) $locked->user_id,
'system_cleanup' => true,
]);
$job->available_at = $job->created_at = $job->updated_at = time();
$job->save();
return $job;
}, 3);
}
public static function display(CloudJob $job): array
{
$result = $job->result_json === null ? null : json_decode($job->result_json, true);
$safeResult = is_array($result) ? CloudInput::safeResult($result) : null;
return ['id' => (string) $job->id, 'operation_id' => $job->operation_id, 'kind' => $job->kind,
'status' => $job->status, 'error' => $job->error_code,
'attempts' => max(0, (int) $job->attempts),
'created_at' => max(0, (int) $job->created_at),
'updated_at' => max(0, (int) $job->updated_at),
'action' => self::action($job),
'phase' => is_string($safeResult['phase'] ?? null)
? mb_substr($safeResult['phase'], 0, 120) : null,
'result' => $safeResult];
}
/**
* 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->payload_cipher) === '') {
return null;
}
try {
$payload = CloudSecrets::decrypt((string) $job->payload_cipher);
} catch (\Throwable $error) {
return null;
}
$body = $payload['body'] ?? null;
$action = is_array($body) ? (string) ($body['action'] ?? '') : '';
return in_array($action, self::POWER_ACTIONS, true) ? $action : null;
}
/**
* Read the user's instance operation history directly from cloud_jobs.
* Only power and reinstall 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'])
->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', 'kind', 'status', 'attempts', 'error_code', 'result_json',
'payload_cipher', '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,
]];
}
}