feat: add durable cloud snapshot deployment flow
parent
2c28497775
commit
3ad0a97ecd
@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
/** User-owned durable deployment source promoted from one cloud backup. */
|
||||
final class CloudDeploymentSnapshot extends Model
|
||||
{
|
||||
protected $connection = 'default';
|
||||
protected $table = 'cloud_deployment_snapshots';
|
||||
protected $hidden = ['request_hash'];
|
||||
protected $casts = [
|
||||
'id' => 'int',
|
||||
'user_id' => 'int',
|
||||
'backup_id' => 'int',
|
||||
'source_instance_id' => 'int',
|
||||
'ready_at' => 'int',
|
||||
'deleted_at' => 'int',
|
||||
'created_at' => 'int',
|
||||
'updated_at' => 'int',
|
||||
];
|
||||
}
|
||||
@ -0,0 +1,444 @@
|
||||
<?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', '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) {
|
||||
$locked->state = 'delete_uncertain';
|
||||
$locked->error_code = '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_string($backup->sealed_storage_runtime)
|
||||
|| trim((string) $backup->sealed_storage_runtime) === ''
|
||||
|| !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);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,262 @@
|
||||
const assetVersion = new URL(import.meta.url).searchParams.get('v');
|
||||
|
||||
function versionedModuleUrl(path) {
|
||||
const url = new URL(path, import.meta.url);
|
||||
url.search = '';
|
||||
if (assetVersion) url.searchParams.set('v', assetVersion);
|
||||
return url.href;
|
||||
}
|
||||
|
||||
const {
|
||||
api, byId, initializeSession, readBootstrap, showError, toast,
|
||||
} = await import(versionedModuleUrl('./runtime.js'));
|
||||
|
||||
const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options)
|
||||
?? Promise.resolve(false);
|
||||
|
||||
const state = {
|
||||
items: [], page: 1, totalPages: 1, total: 0, loading: false,
|
||||
controller: null, deleting: new Set(), hashFocused: false,
|
||||
};
|
||||
|
||||
function element(tag, className = '', content) {
|
||||
const value = document.createElement(tag);
|
||||
if (className) value.className = className;
|
||||
if (content !== undefined) value.textContent = String(content);
|
||||
return value;
|
||||
}
|
||||
|
||||
function firstText(...values) {
|
||||
for (const value of values) {
|
||||
if (value !== null && value !== undefined && String(value).trim() !== '') {
|
||||
return String(value).trim();
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function formatDate(value) {
|
||||
const raw = Number(value);
|
||||
const timestamp = Number.isFinite(raw) && raw > 0
|
||||
? (raw < 1e12 ? raw * 1000 : raw) : Date.parse(String(value || ''));
|
||||
const date = new Date(timestamp);
|
||||
return Number.isFinite(date.getTime())
|
||||
? date.toLocaleString('zh-CN', { hour12: false }) : '时间未记录';
|
||||
}
|
||||
|
||||
function formatBytes(value) {
|
||||
let amount = Number(value);
|
||||
if (!Number.isFinite(amount) || amount < 0) return '等待完成';
|
||||
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
|
||||
let index = 0;
|
||||
while (amount >= 1024 && index < units.length - 1) {
|
||||
amount /= 1024;
|
||||
index += 1;
|
||||
}
|
||||
const precision = index === 0 ? 0 : amount >= 100 ? 0 : amount >= 10 ? 1 : 2;
|
||||
return `${amount.toFixed(precision)} ${units[index]}`;
|
||||
}
|
||||
|
||||
function snapshotState(value) {
|
||||
const normalized = String(value || '').toLowerCase();
|
||||
const values = {
|
||||
ready: ['可用', 'running'], promoting: ['正在保存', 'warning'],
|
||||
deleting: ['正在删除', 'warning'],
|
||||
delete_uncertain: ['删除待核对', 'warning'], failed: ['保存失败', 'stopped'],
|
||||
};
|
||||
return values[normalized] || [normalized || '状态未知', 'other'];
|
||||
}
|
||||
|
||||
function normalizeItems(payload) {
|
||||
const values = Array.isArray(payload?.items) ? payload.items
|
||||
: Array.isArray(payload?.snapshots) ? payload.snapshots : [];
|
||||
return values.filter(item => item && typeof item === 'object'
|
||||
&& /^[a-f0-9]{32}$/.test(String(item.snapshot_key ?? item.key ?? '')));
|
||||
}
|
||||
|
||||
function sourceInstance(snapshot) {
|
||||
const source = snapshot?.source_instance && typeof snapshot.source_instance === 'object'
|
||||
? snapshot.source_instance : {};
|
||||
return {
|
||||
id: String(source.id ?? source.instance_id ?? snapshot.source_instance_id ?? ''),
|
||||
name: firstText(source.name, source.instance_name, snapshot.source_instance_name),
|
||||
};
|
||||
}
|
||||
|
||||
function render() {
|
||||
const container = byId('cloud-snapshots-list');
|
||||
container.replaceChildren();
|
||||
if (!state.items.length) {
|
||||
const empty = element('div', 'cloud-backups-empty cloud-snapshots-empty');
|
||||
empty.append(element('strong', '', '还没有云快照'),
|
||||
element('span', '', '可前往“云备份”将一份可用备份保存为云快照。'));
|
||||
container.append(empty);
|
||||
}
|
||||
for (const snapshot of state.items) {
|
||||
const key = String(snapshot.snapshot_key ?? snapshot.key);
|
||||
const source = sourceInstance(snapshot);
|
||||
const [stateLabel, stateClass] = snapshotState(snapshot.state ?? snapshot.status);
|
||||
const card = element('article', 'cloud-backup-card cloud-snapshot-card');
|
||||
card.id = `cloud-snapshot-${key}`;
|
||||
const heading = element('div', 'cloud-backup-card-heading');
|
||||
const title = element('div', 'cloud-backup-title');
|
||||
const pendingInvoices = Math.max(0, Number(snapshot.active_invoice_count) || 0);
|
||||
title.append(element('span', 'cloud-backup-icon cloud-snapshot-icon', '◆'),
|
||||
element('div', '', firstText(snapshot.name, `云快照 ${key.slice(0, 8)}`)));
|
||||
const sourceLabel = source.name || (source.id ? `实例 #${source.id}` : '来源实例未记录');
|
||||
title.lastElementChild.append(element('small', '', pendingInvoices > 0
|
||||
? `来源:${sourceLabel} · ${pendingInvoices} 张待支付账单`
|
||||
: `来源:${sourceLabel}`));
|
||||
heading.append(title, element('span', `state-pill ${stateClass}`, stateLabel));
|
||||
|
||||
const facts = element('dl', 'cloud-backup-facts cloud-snapshot-facts');
|
||||
const rows = [
|
||||
['保存时间', formatDate(snapshot.ready_at ?? snapshot.created_at)],
|
||||
['操作系统', firstText(snapshot.os_name, '系统未记录')],
|
||||
['对象大小', formatBytes(snapshot.object_size_bytes)],
|
||||
['磁盘容量', formatBytes(snapshot.virtual_size_bytes)],
|
||||
];
|
||||
for (const [label, value] of rows) {
|
||||
const row = document.createElement('div');
|
||||
row.append(element('dt', '', label), element('dd', '', value));
|
||||
facts.append(row);
|
||||
}
|
||||
|
||||
const actions = element('div', 'cloud-backup-actions cloud-snapshot-actions');
|
||||
if (snapshot.can_create_instance === true) {
|
||||
const create = element('a', 'button button-primary small', '创建实例');
|
||||
create.href = `/user/cloud/deploy?cloud_snapshot=${encodeURIComponent(key)}`;
|
||||
actions.append(create);
|
||||
}
|
||||
const remove = element('button', 'button button-outline small danger',
|
||||
state.deleting.has(key) ? '正在处理…' : '删除');
|
||||
remove.type = 'button';
|
||||
remove.disabled = snapshot.can_delete !== true || state.deleting.has(key);
|
||||
if (snapshot.can_delete !== true) {
|
||||
remove.title = pendingInvoices > 0
|
||||
? '存在待支付账单,请先支付或等待账单失效后再删除。'
|
||||
: '云快照当前状态不允许删除。';
|
||||
}
|
||||
remove.addEventListener('click', () => void deleteSnapshot(snapshot));
|
||||
actions.append(remove);
|
||||
card.append(heading, facts, actions);
|
||||
container.append(card);
|
||||
}
|
||||
byId('cloud-snapshots-count').textContent = `${state.total} 个`;
|
||||
byId('cloud-snapshots-page').textContent = `第 ${state.page} / ${state.totalPages} 页`;
|
||||
byId('cloud-snapshots-previous').disabled = state.loading || state.page <= 1;
|
||||
byId('cloud-snapshots-next').disabled = state.loading || state.page >= state.totalPages;
|
||||
if (!state.hashFocused && location.hash.startsWith('#cloud-snapshot-')) {
|
||||
state.hashFocused = true;
|
||||
requestAnimationFrame(() => document.getElementById(location.hash.slice(1))
|
||||
?.scrollIntoView({ block: 'center' }));
|
||||
}
|
||||
}
|
||||
|
||||
function applyPayload(payload) {
|
||||
state.items = normalizeItems(payload);
|
||||
const pagination = payload?.pagination && typeof payload.pagination === 'object'
|
||||
? payload.pagination : {};
|
||||
state.page = Math.max(1, Number(pagination.page ?? payload?.page) || 1);
|
||||
state.totalPages = Math.max(1,
|
||||
Number(pagination.total_pages ?? payload?.total_pages) || 1);
|
||||
state.total = Math.max(0,
|
||||
Number(pagination.total ?? payload?.total) || state.items.length);
|
||||
render();
|
||||
}
|
||||
|
||||
async function load(page = 1) {
|
||||
if (state.loading) return;
|
||||
state.loading = true;
|
||||
state.controller?.abort();
|
||||
const controller = new AbortController();
|
||||
state.controller = controller;
|
||||
const status = byId('cloud-snapshots-status');
|
||||
status.hidden = false;
|
||||
status.className = 'vm-settings-status';
|
||||
status.textContent = '正在读取云快照…';
|
||||
render();
|
||||
try {
|
||||
const payload = await api(`/api/v1/cloud-snapshots?page=${encodeURIComponent(Math.max(1, page))}&per_page=20`, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (controller.signal.aborted) return;
|
||||
applyPayload(payload);
|
||||
status.hidden = true;
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) return;
|
||||
status.className = 'vm-settings-status error';
|
||||
status.textContent = error?.message || '云快照读取失败,请稍后重试。';
|
||||
} finally {
|
||||
if (state.controller === controller) state.controller = null;
|
||||
state.loading = false;
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSnapshot(snapshot) {
|
||||
const key = String(snapshot?.snapshot_key ?? snapshot?.key ?? '');
|
||||
if (!/^[a-f0-9]{32}$/.test(key) || state.deleting.has(key)) return;
|
||||
const name = firstText(snapshot?.name, `云快照 ${key.slice(0, 8)}`);
|
||||
const pendingInvoices = Math.max(0, Number(snapshot?.active_invoice_count) || 0);
|
||||
if (pendingInvoices > 0) {
|
||||
toast('云快照存在待支付账单,请先支付或等待账单失效。', 'error');
|
||||
return;
|
||||
}
|
||||
const confirmed = await requestUserConfirmation({
|
||||
title: '删除云快照',
|
||||
message: `确定永久删除“${name}”?删除后不能再用它创建实例,且无法恢复。`,
|
||||
confirmText: '删除云快照',
|
||||
tone: 'danger',
|
||||
});
|
||||
if (!confirmed) return;
|
||||
state.deleting.add(key);
|
||||
render();
|
||||
try {
|
||||
const payload = await api(`/api/v1/cloud-snapshots/${encodeURIComponent(key)}`, {
|
||||
method: 'DELETE',
|
||||
expectedStatus: 200,
|
||||
headers: { 'Idempotency-Key': crypto.randomUUID() },
|
||||
});
|
||||
const resultState = String(payload?.snapshot?.state || '').toLowerCase();
|
||||
if (resultState === 'deleted') {
|
||||
toast('云快照已删除。', 'success');
|
||||
} else if (resultState === 'delete_uncertain') {
|
||||
toast('删除结果待核对,请再次点击删除;系统只会读取对象状态,不会重复发送删除请求。', 'warning');
|
||||
} else {
|
||||
toast('云快照正在删除,请稍后刷新状态。', 'warning');
|
||||
}
|
||||
await load(state.page);
|
||||
} catch (error) {
|
||||
const status = byId('cloud-snapshots-status');
|
||||
status.hidden = false;
|
||||
status.className = 'vm-settings-status error';
|
||||
status.textContent = error?.message || '云快照删除失败,请稍后重试。';
|
||||
} finally {
|
||||
state.deleting.delete(key);
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
export async function initialize() {
|
||||
try {
|
||||
const bootstrap = readBootstrap('cloud-snapshots-bootstrap');
|
||||
if (!await initializeSession('cloud-snapshots', bootstrap?.user)) return;
|
||||
if (Array.isArray(bootstrap?.items) || Array.isArray(bootstrap?.snapshots)) {
|
||||
applyPayload(bootstrap);
|
||||
byId('cloud-snapshots-status').hidden = true;
|
||||
} else {
|
||||
await load(1);
|
||||
}
|
||||
byId('cloud-snapshots-refresh')?.addEventListener('click',
|
||||
() => void load(state.page));
|
||||
byId('cloud-snapshots-previous')?.addEventListener('click',
|
||||
() => void load(state.page - 1));
|
||||
byId('cloud-snapshots-next')?.addEventListener('click',
|
||||
() => void load(state.page + 1));
|
||||
window.addEventListener('pagehide', () => state.controller?.abort());
|
||||
} catch (error) {
|
||||
showError('cloud-page-error',
|
||||
error?.message || '云快照页面加载失败,请刷新后重试。');
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
<div id="cloud-snapshots-workspace">
|
||||
<div class="page-heading"><div><span class="eyebrow">CLOUD SNAPSHOTS</span><h1>云快照</h1><p>长期保存由云备份转换而来的系统盘,并用于创建新的实例。</p></div>
|
||||
<button id="cloud-snapshots-refresh" class="button button-outline" type="button"><span aria-hidden="true">↻</span> 刷新</button>
|
||||
</div>
|
||||
<div class="vm-settings-notice cloud-snapshots-notice"><strong>与在线快照不同</strong><span>云快照独立存放在对象存储中,不随源实例或自动备份轮换删除;只有手动删除后才会释放其存储对象。</span></div>
|
||||
<section class="inventory-panel cloud-backups-panel cloud-snapshots-panel" aria-labelledby="cloud-snapshots-list-title">
|
||||
<div class="panel-heading"><div><h2 id="cloud-snapshots-list-title">全部云快照</h2><p>从云快照创建的新实例会使用新的 UUID、网络标识和公网 IP。</p></div><span id="cloud-snapshots-count" class="state-pill other">0 个</span></div>
|
||||
<p id="cloud-snapshots-status" class="vm-settings-status" role="status" aria-live="polite">正在读取云快照…</p>
|
||||
<div id="cloud-snapshots-list" class="cloud-backups-list cloud-snapshots-list" aria-live="polite"></div>
|
||||
<nav class="cloud-backups-pagination cloud-snapshots-pagination" aria-label="云快照分页">
|
||||
<button id="cloud-snapshots-previous" class="button button-outline small" type="button" disabled>上一页</button>
|
||||
<span id="cloud-snapshots-page">第 1 / 1 页</span>
|
||||
<button id="cloud-snapshots-next" class="button button-outline small" type="button" disabled>下一页</button>
|
||||
</nav>
|
||||
</section>
|
||||
<noscript><p class="resource-warning">查看、创建实例和删除云快照需要启用 JavaScript。</p></noscript>
|
||||
</div>
|
||||
<script id="cloud-snapshots-bootstrap" type="application/json">{$cloud_snapshot_bootstrap_json|default:'{}' nofilter}</script>
|
||||
@ -1,2 +1,2 @@
|
||||
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
|
||||
{assign var=venix_asset_version value='2026102606' scope='global'}
|
||||
{assign var=venix_asset_version value='2026102607' scope='global'}
|
||||
|
||||
@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$read = static function (string $path) use ($root): string {
|
||||
$full = $root . '/' . $path;
|
||||
return is_file($full) ? (string) file_get_contents($full) : '';
|
||||
};
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$section = static function (string $source, string $start,
|
||||
string $end): string {
|
||||
$offset = strpos($source, $start);
|
||||
if ($offset === false) {
|
||||
return '';
|
||||
}
|
||||
$finish = strpos($source, $end, $offset + strlen($start));
|
||||
return $finish === false ? substr($source, $offset)
|
||||
: substr($source, $offset, $finish - $offset);
|
||||
};
|
||||
|
||||
$schema = $read('sql/cloud.sql');
|
||||
$orders = $read('app/Services/Cloud/CloudOrderService.php');
|
||||
$backups = $read('app/Services/Cloud/CloudBackupService.php');
|
||||
$recovery = $read(
|
||||
'app/Services/Cloud/CloudOperationRecoveryIdentity.php'
|
||||
);
|
||||
$placement = $read('app/Services/Cloud/CloudPlacementService.php');
|
||||
$worker = $read('app/Services/Cloud/CloudWorkerService.php');
|
||||
$catalog = $read('app/Services/Cloud/CloudDeploymentSnapshotService.php')
|
||||
. $read('app/Services/Cloud/CloudDeploymentSnapshotCatalog.php');
|
||||
$purchase = $section($orders, 'public static function purchase(',
|
||||
'private static function createPurchaseItems(');
|
||||
$payment = $section($orders, 'public static function queuePaidProvision(',
|
||||
'/** Release a finite plan reservation exactly once. */');
|
||||
|
||||
$assert($purchase !== ''
|
||||
&& str_contains($purchase, "['cloud', 'deployment_snapshot']")
|
||||
&& str_contains($purchase, "'cloud_snapshot_key'")
|
||||
&& str_contains($purchase, "'deployment_snapshot'")
|
||||
&& str_contains($purchase, "array_key_exists('backup_id', \$input)")
|
||||
&& !str_contains($purchase, "['cloud', 'backup']")
|
||||
&& !str_contains($purchase, "\$source === 'backup'"),
|
||||
'Public provisioning must accept a cloud snapshot key and must not accept a cloud backup as an instance source.');
|
||||
|
||||
$assert(str_contains($schema, 'CREATE TABLE cloud_deployment_snapshots')
|
||||
&& str_contains($schema,
|
||||
'deployment_snapshot_id BIGINT UNSIGNED DEFAULT NULL')
|
||||
&& str_contains($schema, 'cloud_order_deployment_snapshot')
|
||||
&& str_contains($orders, '$order->deployment_snapshot_id')
|
||||
&& str_contains($orders, '$sourceSnapshot->id'),
|
||||
'Provisioning orders must persist the selected deployment snapshot instead of relying on a request-only source key.');
|
||||
|
||||
$assert(str_contains($purchase, "'deployment_snapshot_id'")
|
||||
&& str_contains($purchase, "'cloud_snapshot_key'")
|
||||
&& str_contains($purchase, "'backing_backup_id'")
|
||||
&& str_contains($purchase, "'backing_backup_key'")
|
||||
&& str_contains($purchase, "'backing_backup_size_bytes'")
|
||||
&& str_contains($purchase, "'backing_backup_virtual_size_bytes'")
|
||||
&& str_contains($purchase, "'backing_backup_sha256'")
|
||||
&& str_contains($purchase, "'backing_backup_identity'"),
|
||||
'The safe order snapshot must freeze both the public cloud snapshot and its immutable backing object identity.');
|
||||
|
||||
$jobBound = str_contains($schema,
|
||||
'deployment_snapshot_id BIGINT UNSIGNED DEFAULT NULL')
|
||||
&& str_contains($schema, 'cloud_job_deployment_snapshot')
|
||||
&& str_contains($orders, '$job->deployment_snapshot_id')
|
||||
|| (str_contains($orders, '$job->backup_id')
|
||||
&& str_contains($payment, 'backing_backup_id'));
|
||||
$assert($jobBound,
|
||||
'Provisioning jobs must remain audibly bound to the deployment snapshot or its frozen backing backup.');
|
||||
|
||||
$assert(str_contains($recovery, "!== 'deployment_snapshot'")
|
||||
&& !str_contains($recovery, "!== 'backup'")
|
||||
&& str_contains($placement, "=== 'deployment_snapshot'")
|
||||
&& !str_contains($placement, "=== 'backup'"),
|
||||
'Placement and operation recovery must use the cloud snapshot source contract while preserving the internal restore-backup protocol.');
|
||||
|
||||
$assert(!str_contains($orders, 'backup_sealed_credential')
|
||||
&& !str_contains($recovery, 'backup_sealed_credential')
|
||||
&& str_contains($worker, '$instance->sealed_credential = null;'),
|
||||
'Cloud-snapshot provisioning must preserve the system-disk password and must not expose the historical panel credential as current.');
|
||||
|
||||
$assert($catalog !== ''
|
||||
&& substr_count($catalog, 'lockForUpdate()') >= 2
|
||||
&& str_contains($catalog, "'ready'")
|
||||
&& str_contains($catalog, 'sha256')
|
||||
&& str_contains($catalog, 'object_size_bytes')
|
||||
&& str_contains($catalog, 'virtual_size_bytes')
|
||||
&& str_contains($purchase, 'CloudDeploymentSnapshot')
|
||||
&& str_contains($payment, 'CloudDeploymentSnapshot'),
|
||||
'Purchase and paid provisioning must both re-lock a ready snapshot and validate the immutable object identity.');
|
||||
|
||||
$automaticCapacity = $section($backups,
|
||||
'$usedQuery = CloudInstanceBackup::where(',
|
||||
'$used = (int) $usedQuery->count');
|
||||
$assert(str_contains($automaticCapacity, 'whereNotExists')
|
||||
&& str_contains($automaticCapacity, 'cloud_deployment_snapshots')
|
||||
&& str_contains($automaticCapacity, 'cloud_deployment_snapshots.state')
|
||||
&& str_contains($automaticCapacity, "'deleted'"),
|
||||
'Promoted snapshot backings must not consume the rolling automatic-backup retention capacity.');
|
||||
|
||||
$assert(str_contains($catalog, 'CloudOrder')
|
||||
&& str_contains($catalog, 'deployment_snapshot_id')
|
||||
&& str_contains($catalog, "'awaiting_payment'")
|
||||
&& str_contains($catalog, "'queued'")
|
||||
&& str_contains($catalog, 'effect_resolution')
|
||||
&& str_contains($catalog, "'unknown'")
|
||||
&& str_contains($catalog, 'finalization_incident'),
|
||||
'Snapshot deletion must remain fenced by unpaid, queued, and unknown-effect provisioning references.');
|
||||
|
||||
$assert(!preg_match(
|
||||
"/whereIn\\('status',\\s*\\[[^]]*'succeeded'[^]]*\\]\\)/s",
|
||||
$catalog
|
||||
)
|
||||
&& !preg_match(
|
||||
"/whereIn\\('status',\\s*\\[[^]]*'expired'[^]]*\\]\\)/s",
|
||||
$catalog
|
||||
),
|
||||
'Terminal safe and expired provisioning orders must not permanently block manual snapshot deletion.');
|
||||
|
||||
echo "Cloud deployment snapshot order and deletion contracts passed.\n";
|
||||
@ -0,0 +1,460 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services {
|
||||
final class Config
|
||||
{
|
||||
public static string $dataKey = '';
|
||||
|
||||
public static function get($name, $default = null)
|
||||
{
|
||||
return $name === 'cloud_data_key' ? self::$dataKey : $default;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Models\CloudInstanceBackup;
|
||||
use App\Services\Config;
|
||||
use App\Services\Cloud\CloudDeploymentSnapshotService;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudObjectStorageS3Client;
|
||||
use App\Services\Cloud\CloudSecrets;
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Exception\ConnectException;
|
||||
use GuzzleHttp\Handler\MockHandler;
|
||||
use GuzzleHttp\HandlerStack;
|
||||
use GuzzleHttp\Middleware;
|
||||
use GuzzleHttp\Psr7\Request;
|
||||
use GuzzleHttp\Psr7\Response;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$expect = static function (int $status, callable $callback) use (
|
||||
$assert
|
||||
): void {
|
||||
try {
|
||||
$callback();
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === $status,
|
||||
'Cloud snapshot failure returned the wrong status.');
|
||||
return;
|
||||
}
|
||||
throw new RuntimeException('Expected cloud snapshot failure.');
|
||||
};
|
||||
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection([
|
||||
'driver' => 'sqlite', 'database' => ':memory:',
|
||||
], 'default');
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
$schema = $capsule->schema('default');
|
||||
$schema->create('user', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('enable');
|
||||
});
|
||||
$schema->create('cloud_instances', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('user_id');
|
||||
$table->string('name');
|
||||
$table->string('status');
|
||||
});
|
||||
$schema->create('cloud_backup_subscriptions',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
});
|
||||
$schema->create('cloud_backup_period_entitlements',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('subscription_id');
|
||||
$table->integer('ends_at');
|
||||
});
|
||||
$schema->create('cloud_instance_backups',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('backup_key')->unique();
|
||||
$table->integer('source_instance_id');
|
||||
$table->integer('source_host_id');
|
||||
$table->integer('user_id');
|
||||
$table->string('source_uuid');
|
||||
$table->string('name');
|
||||
$table->string('purpose');
|
||||
$table->string('source');
|
||||
$table->integer('subscription_id')->nullable();
|
||||
$table->integer('scheduled_for')->nullable();
|
||||
$table->string('state');
|
||||
$table->string('consistency');
|
||||
$table->string('object_key')->unique();
|
||||
$table->integer('object_size_bytes');
|
||||
$table->integer('virtual_size_bytes');
|
||||
$table->string('sha256');
|
||||
$table->text('spec_json');
|
||||
$table->text('sealed_storage_runtime');
|
||||
$table->text('sealed_credential')->nullable();
|
||||
$table->integer('storage_revision');
|
||||
$table->integer('active_job_id')->nullable();
|
||||
$table->string('last_operation_id')->nullable();
|
||||
$table->string('error_code');
|
||||
$table->integer('ready_at')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
$schema->create('cloud_deployment_snapshots',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('snapshot_key')->unique();
|
||||
$table->integer('user_id');
|
||||
$table->integer('backup_id')->unique();
|
||||
$table->integer('source_instance_id');
|
||||
$table->string('name');
|
||||
$table->string('state');
|
||||
$table->string('idempotency_key');
|
||||
$table->string('request_hash');
|
||||
$table->string('error_code');
|
||||
$table->integer('ready_at');
|
||||
$table->integer('deleted_at')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
$table->unique(['user_id', 'idempotency_key']);
|
||||
});
|
||||
$schema->create('cloud_orders', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('user_id');
|
||||
$table->integer('deployment_snapshot_id')->nullable();
|
||||
$table->string('status');
|
||||
});
|
||||
$schema->create('cloud_backup_restores',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('backup_id');
|
||||
$table->string('state');
|
||||
});
|
||||
$schema->create('cloud_backup_recoveries',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('backup_id');
|
||||
$table->string('state');
|
||||
});
|
||||
$schema->create('cloud_jobs', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('backup_id')->nullable();
|
||||
$table->string('phase');
|
||||
$table->string('effect_resolution');
|
||||
$table->integer('finalization_incident')->default(0);
|
||||
});
|
||||
|
||||
$now = time();
|
||||
$capsule->table('user')->insert([
|
||||
['id' => 7, 'enable' => 1],
|
||||
['id' => 8, 'enable' => 1],
|
||||
]);
|
||||
$capsule->table('cloud_instances')->insert([
|
||||
'id' => 50, 'user_id' => 7, 'name' => 'source-vm',
|
||||
'status' => 'active',
|
||||
]);
|
||||
foreach ([1, 2, 3, 4] as $subscriptionId) {
|
||||
$capsule->table('cloud_backup_subscriptions')->insert([
|
||||
'id' => $subscriptionId,
|
||||
]);
|
||||
}
|
||||
$capsule->table('cloud_backup_period_entitlements')->insert([
|
||||
['subscription_id' => 1, 'ends_at' => $now + 86400],
|
||||
['subscription_id' => 2, 'ends_at' => $now - 4 * 86400],
|
||||
['subscription_id' => 3, 'ends_at' => $now + 86400],
|
||||
['subscription_id' => 4, 'ends_at' => $now + 86400],
|
||||
]);
|
||||
|
||||
Config::$dataKey = base64_encode(str_repeat('d', 32));
|
||||
$sealedRuntime = function_exists(
|
||||
'sodium_crypto_aead_xchacha20poly1305_ietf_encrypt'
|
||||
) ? CloudSecrets::encrypt([
|
||||
'config' => [
|
||||
'endpoint' => 'https://objects.example.com',
|
||||
'region' => 'us-east-1',
|
||||
'bucket' => 'backup-bucket',
|
||||
'prefix' => 'virt',
|
||||
'path_style' => true,
|
||||
],
|
||||
'credentials' => [
|
||||
'access_key_id' => 'SNAPSHOTACCESS',
|
||||
'secret_access_key' => 'snapshot-secret-value',
|
||||
],
|
||||
'revision' => 1,
|
||||
], 'object-storage-backup-runtime') : 'sealed-runtime-test-double';
|
||||
$newBackup = static function (int $id, int $userId, int $subscriptionId,
|
||||
string $state = 'ready') use ($now, $sealedRuntime): CloudInstanceBackup {
|
||||
$backup = new CloudInstanceBackup();
|
||||
$backup->id = $id;
|
||||
$backup->backup_key = str_pad(dechex($id), 32, '0', STR_PAD_LEFT);
|
||||
$backup->source_instance_id = 50;
|
||||
$backup->source_host_id = 3;
|
||||
$backup->user_id = $userId;
|
||||
$backup->source_uuid = '11111111-1111-4111-8111-111111111111';
|
||||
$backup->name = 'backup-' . $id;
|
||||
$backup->purpose = 'portable';
|
||||
$backup->source = 'automatic';
|
||||
$backup->subscription_id = $subscriptionId;
|
||||
$backup->scheduled_for = $now - 60;
|
||||
$backup->state = $state;
|
||||
$backup->consistency = 'filesystem';
|
||||
$backup->object_key = 'virt/vm-backups/' . $id . '/system.qcow2';
|
||||
$backup->object_size_bytes = 1024;
|
||||
$backup->virtual_size_bytes = 2048;
|
||||
$backup->sha256 = str_repeat(dechex(($id % 15) + 1), 64);
|
||||
$backup->spec_json = json_encode([
|
||||
'managed' => true,
|
||||
'os_source' => 'cloud_template',
|
||||
'os_name' => 'Debian 13',
|
||||
'login_name' => 'root',
|
||||
'debian_12_network_fix' => false,
|
||||
], JSON_THROW_ON_ERROR);
|
||||
$backup->sealed_storage_runtime = $sealedRuntime;
|
||||
$backup->sealed_credential = 'sealed-credential';
|
||||
$backup->storage_revision = 1;
|
||||
$backup->active_job_id = null;
|
||||
$backup->last_operation_id = null;
|
||||
$backup->error_code = '';
|
||||
$backup->ready_at = $now;
|
||||
$backup->created_at = $backup->updated_at = $now;
|
||||
$backup->save();
|
||||
return $backup;
|
||||
};
|
||||
|
||||
$actor = ['user_id' => 7];
|
||||
$good = $newBackup(11, 7, 1);
|
||||
$good->sealed_credential = null;
|
||||
$good->save();
|
||||
$snapshot = CloudDeploymentSnapshotService::promote(11, [
|
||||
'name' => '生产恢复点',
|
||||
'idempotency_key' => 'snapshot-promote-0001',
|
||||
], $actor);
|
||||
$replayed = CloudDeploymentSnapshotService::promote(11, [
|
||||
'name' => '生产恢复点',
|
||||
'idempotency_key' => 'snapshot-promote-0001',
|
||||
], $actor);
|
||||
$assert((int) $snapshot->id === (int) $replayed->id
|
||||
&& preg_match('/^[a-f0-9]{32}$/D',
|
||||
(string) $snapshot->snapshot_key) === 1,
|
||||
'Cloud backup promotion was not idempotent.');
|
||||
$expect(409, static fn () =>
|
||||
CloudDeploymentSnapshotService::promote(11, [
|
||||
'name' => '不同名称',
|
||||
'idempotency_key' => 'snapshot-promote-0001',
|
||||
], $actor));
|
||||
|
||||
$library = CloudDeploymentSnapshotService::library($actor, [
|
||||
'page' => 1, 'per_page' => 20,
|
||||
]);
|
||||
$item = $library['items'][0] ?? [];
|
||||
$assert(($library['pagination']['total'] ?? 0) === 1
|
||||
&& ($item['snapshot_key'] ?? '') === (string) $snapshot->snapshot_key
|
||||
&& ($item['name'] ?? '') === '生产恢复点'
|
||||
&& ($item['os_name'] ?? '') === 'Debian 13'
|
||||
&& ($item['source_instance']['name'] ?? '') === 'source-vm'
|
||||
&& !array_key_exists('backup_id', $item)
|
||||
&& !array_key_exists('object_key', $item)
|
||||
&& !array_key_exists('sha256', $item)
|
||||
&& !array_key_exists('sealed_storage_runtime', $item),
|
||||
'Cloud snapshot library leaked backing identity or omitted display data.');
|
||||
|
||||
$capsule->table('cloud_backup_period_entitlements')
|
||||
->where('subscription_id', 1)->update(['ends_at' => $now - 5 * 86400]);
|
||||
$resolved = CloudDeploymentSnapshotService::resolveForOrder(
|
||||
(string) $snapshot->snapshot_key, 7
|
||||
);
|
||||
$assert((int) $resolved['backup']->id === (int) $good->id,
|
||||
'A promoted cloud snapshot incorrectly followed later backup entitlement expiry.');
|
||||
$deploymentSource = CloudDeploymentSnapshotService::deploymentSource(
|
||||
(string) $snapshot->snapshot_key, $actor
|
||||
);
|
||||
$assert(($deploymentSource['snapshot_key'] ?? '')
|
||||
=== (string) $snapshot->snapshot_key
|
||||
&& ($deploymentSource['can_create_instance'] ?? false) === true
|
||||
&& !array_key_exists('object_key', $deploymentSource),
|
||||
'Deployment bootstrap did not resolve a safe owner snapshot projection.');
|
||||
$capsule->table('cloud_instance_backups')->where('id', (int) $good->id)
|
||||
->update(['state' => 'failed']);
|
||||
foreach ([
|
||||
static fn () => CloudDeploymentSnapshotService::resolveForOrder(
|
||||
(string) $snapshot->snapshot_key, 7
|
||||
),
|
||||
static fn () => CloudDeploymentSnapshotService::deploymentSource(
|
||||
(string) $snapshot->snapshot_key, $actor
|
||||
),
|
||||
] as $invalidDeploymentSource) {
|
||||
try {
|
||||
$invalidDeploymentSource();
|
||||
throw new RuntimeException(
|
||||
'Invalid backing unexpectedly remained deployable.'
|
||||
);
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->getMessage()
|
||||
=== '云快照不存在或当前不可用于部署',
|
||||
'Deployment used the backup-promotion error vocabulary.');
|
||||
}
|
||||
}
|
||||
$capsule->table('cloud_instance_backups')->where('id', (int) $good->id)
|
||||
->update(['state' => 'ready']);
|
||||
$capsule->table('cloud_deployment_snapshots')
|
||||
->where('id', (int) $snapshot->id)
|
||||
->update(['source_instance_id' => 999]);
|
||||
$expect(409, static fn () =>
|
||||
CloudDeploymentSnapshotService::resolveForOrder(
|
||||
(string) $snapshot->snapshot_key, 7
|
||||
));
|
||||
$expect(409, static fn () =>
|
||||
CloudDeploymentSnapshotService::deploymentSource(
|
||||
(string) $snapshot->snapshot_key, $actor
|
||||
));
|
||||
$capsule->table('cloud_deployment_snapshots')
|
||||
->where('id', (int) $snapshot->id)
|
||||
->update(['source_instance_id' => (int) $good->source_instance_id]);
|
||||
|
||||
$wrongOwner = $newBackup(12, 8, 3);
|
||||
$expect(409, static fn () =>
|
||||
CloudDeploymentSnapshotService::promote((int) $wrongOwner->id, [
|
||||
'idempotency_key' => 'snapshot-promote-0002',
|
||||
], $actor));
|
||||
$failed = $newBackup(13, 7, 3, 'failed');
|
||||
$expect(409, static fn () =>
|
||||
CloudDeploymentSnapshotService::promote((int) $failed->id, [
|
||||
'idempotency_key' => 'snapshot-promote-0003',
|
||||
], $actor));
|
||||
$expired = $newBackup(14, 7, 2);
|
||||
$expect(409, static fn () =>
|
||||
CloudDeploymentSnapshotService::promote((int) $expired->id, [
|
||||
'idempotency_key' => 'snapshot-promote-0004',
|
||||
], $actor));
|
||||
|
||||
$capsule->table('cloud_orders')->insert([
|
||||
'id' => 91,
|
||||
'user_id' => 7,
|
||||
'deployment_snapshot_id' => (int) $snapshot->id,
|
||||
'status' => 'awaiting_payment',
|
||||
]);
|
||||
$expect(409, static fn () => CloudDeploymentSnapshotService::delete(
|
||||
(string) $snapshot->snapshot_key, $actor
|
||||
));
|
||||
$capsule->table('cloud_orders')->where('id', 91)
|
||||
->update(['status' => 'expired']);
|
||||
$capsule->table('cloud_jobs')->insert([
|
||||
'id' => 81,
|
||||
'backup_id' => (int) $good->id,
|
||||
'phase' => 'accepted',
|
||||
'effect_resolution' => 'not_applicable',
|
||||
'finalization_incident' => 0,
|
||||
]);
|
||||
$expect(409, static fn () => CloudDeploymentSnapshotService::delete(
|
||||
(string) $snapshot->snapshot_key, $actor
|
||||
));
|
||||
$capsule->table('cloud_jobs')->where('id', 81)->update([
|
||||
'phase' => 'terminal',
|
||||
'effect_resolution' => 'applied',
|
||||
]);
|
||||
$capsule->table('cloud_jobs')->insert([
|
||||
'id' => 82,
|
||||
'backup_id' => (int) $good->id,
|
||||
'phase' => 'terminal',
|
||||
'effect_resolution' => 'unknown',
|
||||
'finalization_incident' => 0,
|
||||
]);
|
||||
$expect(409, static fn () => CloudDeploymentSnapshotService::delete(
|
||||
(string) $snapshot->snapshot_key, $actor
|
||||
));
|
||||
$capsule->table('cloud_jobs')->where('id', 82)->update([
|
||||
'effect_resolution' => 'not_applied',
|
||||
]);
|
||||
$capsule->table('cloud_jobs')->insert([
|
||||
'id' => 83,
|
||||
'backup_id' => (int) $good->id,
|
||||
'phase' => 'terminal',
|
||||
'effect_resolution' => 'applied',
|
||||
'finalization_incident' => 1,
|
||||
]);
|
||||
$expect(409, static fn () => CloudDeploymentSnapshotService::delete(
|
||||
(string) $snapshot->snapshot_key, $actor
|
||||
));
|
||||
$capsule->table('cloud_jobs')->where('id', 83)->update([
|
||||
'finalization_incident' => 0,
|
||||
]);
|
||||
|
||||
if (function_exists('sodium_crypto_aead_xchacha20poly1305_ietf_encrypt')) {
|
||||
$client = static function (array $responses,
|
||||
array &$history): CloudObjectStorageS3Client {
|
||||
$stack = HandlerStack::create(new MockHandler($responses));
|
||||
$stack->push(Middleware::history($history));
|
||||
return new CloudObjectStorageS3Client(new Client([
|
||||
'handler' => $stack,
|
||||
]));
|
||||
};
|
||||
$history = [];
|
||||
$deleted = CloudDeploymentSnapshotService::delete(
|
||||
(string) $snapshot->snapshot_key,
|
||||
$actor,
|
||||
$client([new Response(204)], $history)
|
||||
);
|
||||
$good->refresh();
|
||||
$assert(($deleted['state'] ?? '') === 'deleted'
|
||||
&& (string) $good->state === 'deleted'
|
||||
&& count($history) === 1
|
||||
&& $history[0]['request']->getMethod() === 'DELETE',
|
||||
'Cloud snapshot deletion did not converge its backing object.');
|
||||
|
||||
$uncertainBackup = $newBackup(15, 7, 3);
|
||||
$uncertainSnapshot = CloudDeploymentSnapshotService::promote(15, [
|
||||
'idempotency_key' => 'snapshot-promote-0005',
|
||||
], $actor);
|
||||
$uncertainHistory = [];
|
||||
$uncertain = CloudDeploymentSnapshotService::delete(
|
||||
(string) $uncertainSnapshot->snapshot_key,
|
||||
$actor,
|
||||
$client([new ConnectException(
|
||||
'timeout', new Request('DELETE', 'https://objects.example.com')
|
||||
)], $uncertainHistory)
|
||||
);
|
||||
$assert(($uncertain['state'] ?? '') === 'delete_uncertain'
|
||||
&& count($uncertainHistory) === 1
|
||||
&& $uncertainHistory[0]['request']->getMethod() === 'DELETE',
|
||||
'Unknown object deletion was not reflected by the cloud snapshot.');
|
||||
$reconcileHistory = [];
|
||||
$reconciled = CloudDeploymentSnapshotService::delete(
|
||||
(string) $uncertainSnapshot->snapshot_key,
|
||||
$actor,
|
||||
$client([new Response(404)], $reconcileHistory)
|
||||
);
|
||||
$assert(($reconciled['state'] ?? '') === 'deleted'
|
||||
&& count($reconcileHistory) === 1
|
||||
&& $reconcileHistory[0]['request']->getMethod() === 'HEAD',
|
||||
'Cloud snapshot reconciliation replayed DeleteObject.');
|
||||
} else {
|
||||
$capsule->table('cloud_deployment_snapshots')
|
||||
->where('id', (int) $snapshot->id)->update([
|
||||
'state' => 'deleted', 'deleted_at' => $now,
|
||||
]);
|
||||
$capsule->table('cloud_instance_backups')
|
||||
->where('id', (int) $good->id)->update(['state' => 'deleted']);
|
||||
}
|
||||
|
||||
$second = $newBackup(16, 7, 3);
|
||||
CloudDeploymentSnapshotService::promote((int) $second->id, [
|
||||
'idempotency_key' => 'snapshot-promote-0006',
|
||||
], $actor);
|
||||
$third = $newBackup(17, 7, 4);
|
||||
CloudDeploymentSnapshotService::promote((int) $third->id, [
|
||||
'idempotency_key' => 'snapshot-promote-0007',
|
||||
], $actor);
|
||||
$fourth = $newBackup(18, 7, 4);
|
||||
$expect(409, static fn () =>
|
||||
CloudDeploymentSnapshotService::promote((int) $fourth->id, [
|
||||
'idempotency_key' => 'snapshot-promote-0008',
|
||||
], $actor));
|
||||
|
||||
echo "Cloud deployment snapshot service tests passed.\n";
|
||||
}
|
||||
Loading…
Reference in New Issue