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

451 lines
19 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudDeploymentSnapshot;
use App\Models\CloudInstance;
use App\Models\CloudInstanceBackup;
use App\Models\CloudJob;
use App\Models\CloudOrder;
use App\Models\User;
/** Durable user deployment sources promoted from automatic cloud backups. */
final class CloudDeploymentSnapshotService
{
public const MAX_PER_USER = 2;
/** Promote one immutable automatic backup without copying its S3 object. */
public static function promote(int $backupId, array $input,
array $actor): CloudDeploymentSnapshot
{
CloudInput::only($input, ['name', 'idempotency_key']);
$userId = self::actorUserId($actor);
$idempotency = $input['idempotency_key'] ?? null;
if (!is_string($idempotency)
|| preg_match('/^[A-Za-z0-9_.-]{16,128}$/D',
$idempotency) !== 1) {
throw new CloudError('请提供 16 至 128 字符的请求幂等标识');
}
$requestedName = $input['name'] ?? null;
if ($requestedName !== null && $requestedName !== '') {
$requestedName = CloudInput::snapshotName($requestedName);
} else {
$requestedName = null;
}
$requestHash = hash('sha256', json_encode([
'backup_id' => $backupId,
'name' => $requestedName,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE
| JSON_UNESCAPED_SLASHES));
return (new User())->getConnection()->transaction(function () use (
$backupId, $userId, $idempotency, $requestedName, $requestHash
): CloudDeploymentSnapshot {
$user = User::where('id', $userId)->lockForUpdate()->first();
if ($user === null || (int) $user->enable !== 1) {
throw new CloudError('账户不可用', 403);
}
$existing = CloudDeploymentSnapshot::where('user_id', $userId)
->where('idempotency_key', $idempotency)
->lockForUpdate()->first();
if ($existing !== null) {
if (!hash_equals((string) $existing->request_hash,
$requestHash)) {
throw new CloudError(
'同一请求标识不能用于不同的云快照操作', 409
);
}
return $existing;
}
$backup = CloudInstanceBackup::where('id', $backupId)
->where('user_id', $userId)->lockForUpdate()->first();
self::assertBackingReady($backup, true,
'云备份当前不能保存为云快照');
$alreadyPromoted = CloudDeploymentSnapshot::where(
'backup_id', (int) $backup->id
)->where('state', '<>', 'deleted')->lockForUpdate()->first();
if ($alreadyPromoted !== null) {
throw new CloudError('该云备份已经保存为云快照', 409);
}
$active = CloudDeploymentSnapshot::where('user_id', $userId)
->where('state', '<>', 'deleted')->count();
if ($active >= self::MAX_PER_USER) {
throw new CloudError(
'每个账户最多保留 ' . self::MAX_PER_USER . ' 个云快照',
409
);
}
$now = time();
$snapshot = new CloudDeploymentSnapshot();
$snapshot->snapshot_key = bin2hex(random_bytes(16));
$snapshot->user_id = $userId;
$snapshot->backup_id = (int) $backup->id;
$snapshot->source_instance_id = (int) $backup->source_instance_id;
$snapshot->name = $requestedName
?? 'cloud-' . substr((string) $backup->backup_key, 0, 8);
$snapshot->state = 'ready';
$snapshot->idempotency_key = $idempotency;
$snapshot->request_hash = $requestHash;
$snapshot->error_code = '';
$snapshot->ready_at = $now;
$snapshot->deleted_at = null;
$snapshot->created_at = $snapshot->updated_at = $now;
$snapshot->save();
return $snapshot;
}, 3);
}
/** Paginated owner catalog; backing object locations and secrets stay hidden. */
public static function library(array $actor, array $input): array
{
CloudInput::only($input, ['page', 'per_page']);
$userId = self::actorUserId($actor);
$page = self::positiveInteger($input['page'] ?? 1, 1, 1000000);
$perPage = self::positiveInteger($input['per_page'] ?? 20, 1, 50);
if (!in_array($perPage, [20, 50], true)) {
throw new CloudError('云快照库每页条数仅支持 20 或 50');
}
$query = CloudDeploymentSnapshot::where('user_id', $userId)
->where('state', '<>', 'deleted');
$total = (int) (clone $query)->count('id');
$pages = max(1, (int) ceil($total / $perPage));
$page = min($page, $pages);
$rows = $query->orderByDesc('id')
->offset(($page - 1) * $perPage)->limit($perPage)->get();
$backups = [];
$instances = [];
if ($rows->isNotEmpty()) {
$backupIds = array_values(array_unique(array_map(
static fn (CloudDeploymentSnapshot $snapshot): int =>
(int) $snapshot->backup_id,
$rows->all()
)));
foreach (CloudInstanceBackup::whereIn('id', $backupIds)
->where('user_id', $userId)->get() as $backup) {
$backups[(int) $backup->id] = $backup;
}
$instanceIds = array_values(array_unique(array_map(
static fn (CloudDeploymentSnapshot $snapshot): int =>
(int) $snapshot->source_instance_id,
$rows->all()
)));
foreach (CloudInstance::whereIn('id', $instanceIds)
->where('user_id', $userId)
->get(['id', 'name', 'status']) as $instance) {
$instances[(int) $instance->id] = $instance;
}
}
$items = [];
foreach ($rows as $snapshot) {
$backup = $backups[(int) $snapshot->backup_id] ?? null;
if ($backup !== null
&& (int) $snapshot->source_instance_id
!== (int) $backup->source_instance_id) {
$backup = null;
}
$items[] = self::display(
$snapshot,
$backup,
$instances[(int) $snapshot->source_instance_id] ?? null
);
}
$from = $total === 0 ? 0 : (($page - 1) * $perPage) + 1;
return [
'items' => $items,
'limit' => self::MAX_PER_USER,
'pagination' => [
'page' => $page,
'per_page' => $perPage,
'total' => $total,
'total_pages' => $pages,
'from' => $from,
'to' => $from === 0 ? 0 : $from + count($items) - 1,
],
];
}
/** Lock and resolve one public snapshot key for order creation/payment. */
public static function resolveForOrder(string $snapshotKey, int $userId): array
{
self::assertSnapshotKey($snapshotKey);
if ($userId < 1) {
throw new CloudError('请先登录', 401);
}
$snapshot = CloudDeploymentSnapshot::where(
'snapshot_key', $snapshotKey
)->where('user_id', $userId)->lockForUpdate()->first();
if ($snapshot === null || (string) $snapshot->state !== 'ready') {
throw new CloudError('云快照不存在或当前不可用于部署', 404);
}
$backup = CloudInstanceBackup::where('id', (int) $snapshot->backup_id)
->where('user_id', $userId)->lockForUpdate()->first();
self::assertBackingReady($backup, false,
'云快照不存在或当前不可用于部署');
self::assertBinding($snapshot, $backup);
return ['snapshot' => $snapshot, 'backup' => $backup];
}
/** Safe read-only source projection for the deployment-page bootstrap. */
public static function deploymentSource(string $snapshotKey,
array $actor): array
{
self::assertSnapshotKey($snapshotKey);
$userId = self::actorUserId($actor);
$snapshot = CloudDeploymentSnapshot::where(
'snapshot_key', $snapshotKey
)->where('user_id', $userId)->first();
if ($snapshot === null || (string) $snapshot->state !== 'ready') {
throw new CloudError('云快照不存在或当前不可用于部署', 404);
}
$backup = CloudInstanceBackup::where('id', (int) $snapshot->backup_id)
->where('user_id', $userId)->first();
self::assertBackingReady($backup, false,
'云快照不存在或当前不可用于部署');
self::assertBinding($snapshot, $backup);
$instance = CloudInstance::where(
'id', (int) $snapshot->source_instance_id
)->where('user_id', $userId)->first();
return self::display($snapshot, $backup, $instance);
}
/** Delete or reconcile one owner snapshot and its dedicated backing object. */
public static function delete(string $snapshotKey, array $actor,
?CloudObjectStorageS3Client $client = null): array
{
self::assertSnapshotKey($snapshotKey);
$userId = self::actorUserId($actor);
$prepared = (new User())->getConnection()->transaction(function () use (
$snapshotKey, $userId
): array {
User::where('id', $userId)->lockForUpdate()->first();
$snapshot = CloudDeploymentSnapshot::where(
'snapshot_key', $snapshotKey
)->where('user_id', $userId)->lockForUpdate()->first();
if ($snapshot === null) {
throw new CloudError('云快照不存在或无权访问', 404);
}
if ((string) $snapshot->state === 'deleted') {
return ['snapshot' => $snapshot, 'backup' => null];
}
if (self::hasBlockingUse($snapshot)) {
throw new CloudError(
'云快照仍有关联的待支付账单或创建任务,不能删除', 409
);
}
if (!in_array((string) $snapshot->state,
['ready', 'deleting', 'delete_uncertain'], true)) {
throw new CloudError('当前云快照状态不允许删除', 409);
}
$backup = CloudInstanceBackup::where(
'id', (int) $snapshot->backup_id
)->where('user_id', $userId)->lockForUpdate()->first();
if ($backup === null) {
throw new CloudError('云快照的存储对象记录缺失', 409);
}
if ((string) $snapshot->state === 'ready') {
$snapshot->state = 'deleting';
$snapshot->error_code = '';
$snapshot->updated_at = time();
$snapshot->save();
}
return ['snapshot' => $snapshot, 'backup' => $backup];
}, 3);
if ($prepared['backup'] === null) {
return self::display($prepared['snapshot'], null, null);
}
$systemActor = [
'user_id' => $userId,
'is_admin' => true,
'is_super_admin' => true,
'can_manage' => true,
'session_id' => 'deployment-snapshot-delete',
];
try {
$result = CloudBackupService::delete(
$prepared['backup'], $systemActor, $client
);
} catch (\Throwable $error) {
$backingState = (string) (CloudInstanceBackup::where(
'id', (int) $prepared['backup']->id
)->value('state') ?? '');
$effectUnknown = in_array($backingState,
['deleting', 'delete_uncertain', 'delete_attention', 'deleted'], true);
CloudDeploymentSnapshot::where(
'id', (int) $prepared['snapshot']->id
)->where('state', 'deleting')->update([
'state' => $effectUnknown ? 'delete_uncertain' : 'ready',
'error_code' => $effectUnknown
? 'snapshot_delete_effect_unknown'
: 'snapshot_delete_failed',
'updated_at' => time(),
]);
throw $error;
}
$snapshot = (new User())->getConnection()->transaction(function () use (
$prepared, $result
): CloudDeploymentSnapshot {
$locked = CloudDeploymentSnapshot::where(
'id', (int) $prepared['snapshot']->id
)->lockForUpdate()->firstOrFail();
if (($result['deleted'] ?? false) === true) {
$locked->state = 'deleted';
$locked->deleted_at = time();
$locked->error_code = '';
} elseif (($result['requires_reconciliation'] ?? false) === true
|| ($result['requires_attention'] ?? false) === true) {
$locked->state = 'delete_uncertain';
$locked->error_code = ($result['requires_attention'] ?? false)
? 'object_delete_attention_required'
: 'object_delete_uncertain';
} else {
$locked->state = 'deleting';
}
$locked->updated_at = time();
$locked->save();
return $locked;
}, 3);
return self::display(
$snapshot,
CloudInstanceBackup::find((int) $snapshot->backup_id),
null
);
}
public static function display(CloudDeploymentSnapshot $snapshot,
?CloudInstanceBackup $backup = null,
?CloudInstance $instance = null): array
{
$state = in_array((string) $snapshot->state,
['ready', 'deleting', 'delete_uncertain', 'deleted'], true)
? (string) $snapshot->state : 'delete_uncertain';
$spec = $backup === null
? null : json_decode((string) $backup->spec_json, true);
$activeInvoiceCount = (int) CloudOrder::where(
'deployment_snapshot_id', (int) $snapshot->id
)->where('status', 'awaiting_payment')->count('id');
$blocked = self::hasBlockingUse($snapshot);
return [
'snapshot_key' => (string) $snapshot->snapshot_key,
'name' => (string) $snapshot->name,
'state' => $state,
'source_instance' => [
'id' => (string) $snapshot->source_instance_id,
'name' => $instance === null ? '' : (string) $instance->name,
'deleted' => $instance === null
|| (string) $instance->status === 'deleted',
],
'consistency' => $backup !== null
&& in_array((string) $backup->consistency,
['filesystem', 'crash'], true)
? (string) $backup->consistency : 'unknown',
'os_name' => is_array($spec)
&& is_string($spec['os_name'] ?? null)
? trim((string) $spec['os_name']) : '',
'object_size_bytes' => $backup === null
? 0 : max(0, (int) $backup->object_size_bytes),
'virtual_size_bytes' => $backup === null
? 0 : max(0, (int) $backup->virtual_size_bytes),
'created_at' => max(0, (int) $snapshot->created_at),
'ready_at' => max(0, (int) $snapshot->ready_at),
'can_create_instance' => $state === 'ready'
&& $backup !== null && (string) $backup->state === 'ready',
'can_delete' => in_array($state,
['ready', 'deleting', 'delete_uncertain'], true) && !$blocked,
'active_invoice_count' => $activeInvoiceCount,
'has_blocking_use' => $blocked,
'error' => $state === 'delete_uncertain'
? '删除结果尚未确认;系统会按稳定对象证据继续受控清理,达到上限后转管理员处理。'
: null,
];
}
private static function assertBackingReady(?CloudInstanceBackup $backup,
bool $requireRecoveryGrace, string $errorMessage): void
{
$spec = $backup === null
? null : json_decode((string) $backup->spec_json, true);
if ($backup === null
|| (string) $backup->purpose !== 'portable'
|| (string) $backup->source !== 'automatic'
|| $backup->subscription_id === null
|| (string) $backup->state !== 'ready'
|| ($requireRecoveryGrace
&& !CloudAutomaticBackupService::withinRecoveryGrace($backup))
|| (int) $backup->object_size_bytes < 1
|| (int) $backup->virtual_size_bytes < 1
|| preg_match('/^[a-f0-9]{32}$/D',
(string) $backup->backup_key) !== 1
|| preg_match('/^[a-f0-9]{64}$/D',
(string) $backup->sha256) !== 1
|| !is_array($spec) || array_is_list($spec)
|| ($spec['managed'] ?? null) !== true
|| ($spec['os_source'] ?? null) !== 'cloud_template'
|| !is_string($spec['os_name'] ?? null)
|| trim((string) $spec['os_name']) === ''
|| ($spec['login_name'] ?? null) !== 'root'
|| !is_bool($spec['debian_12_network_fix'] ?? null)) {
throw new CloudError($errorMessage, 409);
}
try {
CloudBackupStorageAuthority::readyEvidence($backup);
} catch (\InvalidArgumentException) {
throw new CloudError($errorMessage, 409);
}
}
private static function hasBlockingUse(
CloudDeploymentSnapshot $snapshot
): bool {
if (CloudOrder::where('deployment_snapshot_id', (int) $snapshot->id)
->whereIn('status', ['awaiting_payment', 'queued'])->exists()) {
return true;
}
return CloudJob::where('backup_id', (int) $snapshot->backup_id)
->where(static function ($query): void {
$query->where('phase', '<>', 'terminal')
->orWhere('effect_resolution', 'unknown')
->orWhere('finalization_incident', 1);
})->exists();
}
private static function assertBinding(CloudDeploymentSnapshot $snapshot,
CloudInstanceBackup $backup): void
{
if ((int) $snapshot->backup_id !== (int) $backup->id
|| (int) $snapshot->user_id !== (int) $backup->user_id
|| (int) $snapshot->source_instance_id
!== (int) $backup->source_instance_id) {
throw new CloudError('云快照与存储对象绑定不一致', 409);
}
}
private static function actorUserId(array $actor): int
{
$userId = filter_var($actor['user_id'] ?? null, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]);
if ($userId === false) {
throw new CloudError('请先登录', 401);
}
return (int) $userId;
}
private static function assertSnapshotKey(string $snapshotKey): void
{
if (preg_match('/^[a-f0-9]{32}$/D', $snapshotKey) !== 1) {
throw new CloudError('请选择有效的云快照');
}
}
private static function positiveInteger($value, int $minimum,
int $maximum): int
{
$parsed = filter_var($value, FILTER_VALIDATE_INT,
['options' => ['min_range' => $minimum,
'max_range' => $maximum]]);
if ($parsed === false) {
throw new CloudError('分页参数无效');
}
return (int) $parsed;
}
}