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

526 lines
21 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudJob;
use App\Models\CloudUserIso;
use App\Models\CloudUserIsoReplica;
/** PHP-owned personal ISO catalog backed by single-dispatch replica jobs. */
final class CloudUserIsoService
{
private const MAX_ISOS = 5;
private const MAX_TOTAL_BYTES = 10 * 1024 * 1024 * 1024;
public static function listing(int $userId): array
{
$rows = CloudUserIso::query()->where('user_id', $userId)
->whereIn('state', [
'importing', 'active', 'import_failed', 'deleting',
'delete_failed',
])->orderByDesc('created_at')->get()
->map(static fn (CloudUserIso $iso): array => self::dto($iso))
->all();
$active = CloudUserIso::query()->where('user_id', $userId)
->where('state', 'importing')->orderByDesc('created_at')->first();
$result = ['isos' => $rows];
if ($active !== null && (int) ($active->active_job_id ?? 0) > 0) {
$task = CloudJob::find((int) $active->active_job_id);
if ($task !== null && $task->parent_job_id === null) {
$result['active_import_job'] =
CloudJobService::acknowledgement($task);
}
}
return $result;
}
public static function import(array $input, array $actor): array
{
CloudInput::only($input, ['name', 'url']);
$userId = (int) ($actor['user_id'] ?? 0);
if ($userId < 1) {
throw new CloudError('账户身份无效', 401);
}
$name = self::name($input['name'] ?? null);
$url = self::remoteUrl($input['url'] ?? null);
$hosts = array_values(array_unique(array_map('intval',
CloudAgentSettingsService::enabledHostIds())));
sort($hosts, SORT_NUMERIC);
if ($hosts === []) {
throw new CloudError('没有可用的宿主机 Agent', 503);
}
$connection = (new CloudUserIso())->getConnection();
$parent = $connection->transaction(static function () use (
$actor, $userId, $name, $url, $hosts
): CloudJob {
[$parent, $created] = CloudJobService::reserveAggregate(
$actor, 'user_iso_import', [
'name' => $name,
'url' => $url,
'host_ids' => $hosts,
]
);
if (!$created) {
return $parent;
}
$rows = CloudUserIso::query()->where('user_id', $userId)
->where('state', '<>', 'retired')->lockForUpdate()->get();
foreach ($rows as $row) {
$jobId = (int) ($row->active_job_id ?? 0);
if ($jobId < 1) {
continue;
}
$prior = CloudJob::where('id', $jobId)
->lockForUpdate()->first();
if ($prior === null
|| (string) $prior->phase !== 'terminal'
|| (string) $prior->effect_resolution === 'unknown') {
throw new CloudError(
'已有用户 ISO 任务尚未安全收敛', 409
);
}
}
if ($rows->count() >= self::MAX_ISOS) {
throw new CloudError('每个用户最多保存 5 个 ISO', 409);
}
if ($rows->contains(static fn ($row): bool => in_array(
(string) $row->state, ['importing', 'deleting'], true
))) {
throw new CloudError('已有用户 ISO 任务正在执行', 409);
}
$now = time();
$iso = new CloudUserIso();
$iso->id = bin2hex(random_bytes(16));
$iso->user_id = $userId;
$iso->name = $name;
$iso->sealed_source_url = CloudSecrets::encrypt(
['url' => $url], 'user-iso-source'
);
$iso->size_bytes = 0;
$iso->sha256 = '';
$iso->state = 'importing';
$iso->import_operation_id = (string) $parent->operation_id;
$iso->active_job_id = (int) $parent->id;
$iso->created_at = $iso->updated_at = $now;
$iso->save();
foreach ($hosts as $hostId) {
$operationId = bin2hex(random_bytes(16));
$child = CloudJobService::reserveAgentMutation(
$actor, $hostId, 'user_iso_import_replica', 'POST',
'/v1/user-isos', [
'id' => (string) $iso->id,
'owner_id' => $userId,
'name' => $name,
'source_url' => $url,
], [
'owner_id' => $userId,
'user_iso_id' => (string) $iso->id,
], (int) $parent->id, $operationId
);
$replica = new CloudUserIsoReplica();
$replica->host_id = $hostId;
$replica->user_iso_id = (string) $iso->id;
$replica->user_id = $userId;
$replica->state = 'importing';
$replica->size_bytes = 0;
$replica->sha256 = '';
$replica->operation_id = $operationId;
$replica->job_id = (int) $child->id;
$replica->error_code = '';
$replica->created_at = $replica->updated_at = $now;
$replica->save();
}
return $parent;
}, 3);
return CloudJobService::acknowledgement($parent);
}
public static function delete(string $id, array $actor): array
{
if (preg_match('/^[a-f0-9]{32}$/D', $id) !== 1) {
throw new CloudError('ISO 镜像标识无效');
}
$userId = (int) ($actor['user_id'] ?? 0);
$connection = (new CloudUserIso())->getConnection();
$parent = $connection->transaction(static function () use (
$id, $actor, $userId
): CloudJob {
$iso = CloudUserIso::query()->where('id', $id)
->where('user_id', $userId)->lockForUpdate()->first();
if ($iso === null || (string) $iso->state === 'retired') {
throw new CloudError('ISO 不存在或不属于当前用户', 404);
}
if ((string) $iso->state !== 'active') {
throw new CloudError(
'ISO 尚有未确认或失败的任务,禁止重复下发删除', 409
);
}
[$parent, $created] = CloudJobService::reserveAggregate(
$actor, 'user_iso_delete', ['iso_id' => $id]
);
if (!$created) {
return $parent;
}
$replicas = CloudUserIsoReplica::query()
->where('user_iso_id', $id)->orderBy('host_id')
->lockForUpdate()->get();
if ($replicas->isEmpty()
|| $replicas->contains(static fn ($row): bool =>
(string) $row->state !== 'active')) {
throw new CloudError('ISO 副本账本不完整,禁止删除', 409);
}
$iso->state = 'deleting';
$iso->active_job_id = (int) $parent->id;
$iso->updated_at = time();
$iso->save();
foreach ($replicas as $replica) {
$operationId = bin2hex(random_bytes(16));
$child = CloudJobService::reserveAgentMutation(
$actor, (int) $replica->host_id,
'user_iso_delete_replica', 'DELETE',
'/v1/user-isos/' . rawurlencode($id)
. '?owner_id=' . $userId,
[], [
'owner_id' => $userId,
'user_iso_id' => $id,
], (int) $parent->id, $operationId
);
CloudUserIsoReplica::query()
->where('host_id', (int) $replica->host_id)
->where('user_iso_id', $id)->update([
'state' => 'deleting',
'operation_id' => $operationId,
'job_id' => (int) $child->id,
'error_code' => '',
'updated_at' => time(),
]);
}
return $parent;
}, 3);
return CloudJobService::acknowledgement($parent);
}
/** Called from the worker transaction for both receipts and deadlines. */
public static function finishJobLocked(
CloudJob $job,
string $status,
$result,
array $payload,
array $operation
): void {
if (!in_array((string) $job->kind, [
'user_iso_import_replica', 'user_iso_delete_replica',
], true)) {
return;
}
$isoId = is_string($payload['user_iso_id'] ?? null)
? $payload['user_iso_id'] : '';
$iso = CloudUserIso::query()->where('id', $isoId)
->lockForUpdate()->first();
$replica = CloudUserIsoReplica::query()
->where('host_id', (int) $job->host_id)
->where('user_iso_id', $isoId)
->where('job_id', (int) $job->id)->lockForUpdate()->first();
if ($iso === null || $replica === null) {
throw new CloudError('ISO 任务账本不存在', 409);
}
if ((string) $job->kind === 'user_iso_import_replica') {
self::finishImportReplica($iso, $replica, $status, $result,
$operation);
self::settleImportParent($iso, (int) $job->parent_job_id,
$operation);
return;
}
self::finishDeleteReplica($iso, $replica, $status, $operation);
self::settleDeleteParent($iso, (int) $job->parent_job_id,
$operation);
}
/** Close a batch whose absolute parent deadline elapsed. */
public static function expireAggregateLocked(CloudJob $parent): void
{
if (!in_array((string) $parent->kind,
['user_iso_import', 'user_iso_delete'], true)
|| (string) $parent->phase === 'terminal') {
return;
}
$iso = CloudUserIso::query()
->where('active_job_id', (int) $parent->id)
->lockForUpdate()->first();
if ($iso === null) {
CloudJobService::completeAggregateLocked(
$parent, 'failed', true, false,
'aggregate_ledger_missing'
);
return;
}
$children = CloudJob::where('parent_job_id', (int) $parent->id)
->lockForUpdate()->get();
$effect = $children->contains(static fn ($child): bool =>
(int) $child->dispatch_attempts === 1
|| (bool) $child->effect_may_have_applied);
if ((string) $parent->kind === 'user_iso_import') {
CloudUserIsoReplica::query()
->where('user_iso_id', (string) $iso->id)
->where('state', 'importing')->update([
'state' => 'failed',
'error_code' => 'aggregate_deadline_exceeded',
'updated_at' => time(),
]);
$iso->state = 'import_failed';
} else {
CloudUserIsoReplica::query()
->where('user_iso_id', (string) $iso->id)
->where('state', 'deleting')->update([
'state' => 'delete_failed',
'error_code' => 'aggregate_deadline_exceeded',
'updated_at' => time(),
]);
$iso->state = 'delete_failed';
}
$iso->updated_at = time();
$iso->save();
CloudJobService::completeAggregateLocked(
$parent, 'failed', $effect, !$effect,
'aggregate_deadline_exceeded'
);
}
private static function finishImportReplica(CloudUserIso $iso,
CloudUserIsoReplica $replica, string $status, $result,
array $operation): void
{
if ((string) $replica->state !== 'importing') {
return;
}
if ($status === 'succeeded') {
$digest = is_array($result)
? strtolower((string) ($result['sha256'] ?? '')) : '';
$bytes = is_array($result) ? filter_var(
$result['size_bytes'] ?? null,
FILTER_VALIDATE_INT,
['options' => [
'min_range' => 1,
'max_range' => self::MAX_TOTAL_BYTES,
]]
) : false;
if (!is_array($result) || array_is_list($result)
|| ($result['id'] ?? null) !== (string) $iso->id
|| (int) ($result['owner_id'] ?? 0) !== (int) $iso->user_id
|| ($result['name'] ?? null) !== (string) $iso->name
|| $bytes === false
|| preg_match('/^[a-f0-9]{64}$/D', $digest) !== 1
|| ((string) $iso->sha256 !== ''
&& !hash_equals((string) $iso->sha256, $digest))
|| ((int) $iso->size_bytes > 0
&& (int) $iso->size_bytes !== (int) $bytes)) {
throw new CloudError('Agent ISO 成功回执与请求不匹配', 502);
}
if ((string) $iso->sha256 === '') {
$iso->sha256 = $digest;
$iso->size_bytes = (int) $bytes;
$iso->updated_at = time();
$iso->save();
}
$replica->state = 'active';
$replica->size_bytes = (int) $bytes;
$replica->sha256 = $digest;
$replica->error_code = '';
} else {
$replica->state = 'failed';
$replica->error_code = self::errorCode(
$operation, 'user_iso_import_failed'
);
}
CloudUserIsoReplica::query()
->where('host_id', (int) $replica->host_id)
->where('user_iso_id', (string) $replica->user_iso_id)
->where('job_id', (int) $replica->job_id)->update([
'state' => (string) $replica->state,
'size_bytes' => (int) $replica->size_bytes,
'sha256' => (string) $replica->sha256,
'error_code' => (string) $replica->error_code,
'updated_at' => time(),
]);
}
private static function settleImportParent(CloudUserIso $iso,
int $parentId, array $operation): void
{
$replicas = CloudUserIsoReplica::query()
->where('user_iso_id', (string) $iso->id)->orderBy('host_id')
->lockForUpdate()->get();
if ($replicas->isEmpty() || $replicas->contains(
static fn ($row): bool => (string) $row->state === 'importing'
)) {
return;
}
$parent = CloudJob::where('id', $parentId)->lockForUpdate()->first();
if ($parent === null || (string) $parent->kind !== 'user_iso_import') {
throw new CloudError('ISO 聚合任务不存在', 409);
}
$allActive = !$replicas->contains(static fn ($row): bool =>
(string) $row->state !== 'active');
$quotaUsed = (int) CloudUserIso::query()
->where('user_id', (int) $iso->user_id)
->where('id', '<>', (string) $iso->id)
->where('state', 'active')->sum('size_bytes');
$quotaOkay = $quotaUsed + (int) $iso->size_bytes
<= self::MAX_TOTAL_BYTES;
if ($allActive && $quotaOkay) {
$iso->state = 'active';
$iso->updated_at = time();
$iso->save();
CloudJobService::completeAggregateLocked(
$parent, 'succeeded', true, false, '',
['iso_id' => (string) $iso->id]
);
return;
}
$effect = $replicas->contains(static fn ($row): bool =>
(string) $row->state === 'active')
|| ($operation['effect_may_have_applied'] ?? false) === true
|| CloudJob::where('parent_job_id', $parentId)
->where('effect_may_have_applied', 1)->exists();
$iso->state = 'import_failed';
$iso->updated_at = time();
$iso->save();
CloudJobService::completeAggregateLocked(
$parent, 'failed', $effect, false,
$quotaOkay ? 'user_iso_import_failed' : 'user_iso_quota_exceeded'
);
}
private static function finishDeleteReplica(CloudUserIso $iso,
CloudUserIsoReplica $replica, string $status,
array $operation): void
{
if ((string) $replica->state !== 'deleting') {
return;
}
if ($status === 'succeeded') {
if (!CloudAgentCatalogDeletion::confirms(
$operation, 'user_iso', (string) $iso->id,
(int) $iso->user_id
)) {
throw new CloudError('Agent ISO 删除回执缺少清理证据', 502);
}
$replica->state = 'delete_succeeded';
$replica->error_code = '';
} else {
$replica->state = 'delete_failed';
$replica->error_code = self::errorCode(
$operation, 'user_iso_delete_failed'
);
}
CloudUserIsoReplica::query()
->where('host_id', (int) $replica->host_id)
->where('user_iso_id', (string) $replica->user_iso_id)
->where('job_id', (int) $replica->job_id)->update([
'state' => (string) $replica->state,
'error_code' => (string) $replica->error_code,
'updated_at' => time(),
]);
}
private static function settleDeleteParent(CloudUserIso $iso,
int $parentId, array $operation): void
{
$replicas = CloudUserIsoReplica::query()
->where('user_iso_id', (string) $iso->id)->orderBy('host_id')
->lockForUpdate()->get();
if ($replicas->isEmpty() || $replicas->contains(static fn ($row): bool =>
(string) $row->state === 'deleting')) {
return;
}
$parent = CloudJob::where('id', $parentId)->lockForUpdate()->first();
if ($parent === null || (string) $parent->kind !== 'user_iso_delete') {
throw new CloudError('ISO 删除聚合任务不存在', 409);
}
$allDeleted = !$replicas->contains(static fn ($row): bool =>
(string) $row->state !== 'delete_succeeded');
if ($allDeleted) {
CloudUserIsoReplica::query()->where(
'user_iso_id', (string) $iso->id
)->delete();
$iso->name = '';
$iso->sealed_source_url = '';
$iso->size_bytes = 0;
$iso->sha256 = '';
$iso->state = 'retired';
$iso->updated_at = time();
$iso->save();
CloudJobService::completeAggregateLocked(
$parent, 'succeeded', true, false, '',
['iso_id' => (string) $iso->id, 'deleted' => true]
);
return;
}
$effect = $replicas->contains(static fn ($row): bool =>
(string) $row->state === 'delete_succeeded')
|| ($operation['effect_may_have_applied'] ?? false) === true
|| CloudJob::where('parent_job_id', $parentId)
->where('effect_may_have_applied', 1)->exists();
$iso->state = 'delete_failed';
$iso->updated_at = time();
$iso->save();
CloudJobService::completeAggregateLocked(
$parent, 'failed', $effect, false, 'user_iso_delete_failed'
);
}
private static function dto(CloudUserIso $iso): array
{
return [
'id' => (string) $iso->id,
'name' => (string) $iso->name,
'size_bytes' => (int) $iso->size_bytes,
'sha256' => (string) $iso->sha256,
'state' => (string) $iso->state,
'created_at' => (int) $iso->created_at,
];
}
private static function errorCode(array $operation, string $fallback): string
{
$code = $operation['error_code'] ?? null;
return is_string($code)
&& preg_match('/^[a-z][a-z0-9_]{0,63}$/D', $code) === 1
? $code : $fallback;
}
private static function name($value): string
{
if (!is_string($value) || preg_match('//u', $value) !== 1) {
throw new CloudError('ISO 名称应为 1 至 64 个字符');
}
$value = trim($value);
if ($value === '' || mb_strlen($value, 'UTF-8') > 64
|| preg_match('/[\x00-\x1f\x7f]/u', $value) === 1) {
throw new CloudError('ISO 名称应为 1 至 64 个字符');
}
return $value;
}
private static function remoteUrl($value): string
{
if (!is_string($value) || strlen($value) > 2048) {
throw new CloudError('ISO 下载地址无效');
}
$value = trim($value);
$parts = parse_url($value);
if (!is_array($parts)
|| strtolower((string) ($parts['scheme'] ?? '')) !== 'https'
|| !is_string($parts['host'] ?? null) || $parts['host'] === ''
|| isset($parts['user']) || isset($parts['pass'])
|| isset($parts['fragment'])
|| (isset($parts['port']) && (int) $parts['port'] !== 443)
|| !str_ends_with(strtolower((string) ($parts['path'] ?? '')),
'.iso')) {
throw new CloudError('ISO 仅支持无需账号、使用 443 端口的 HTTPS 直链');
}
return $value;
}
}