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

310 lines
11 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudTemplateImportIntent;
use App\Models\CloudTemplateImportPart;
/**
* Shared invariant kernel for the cloud-template import modules.
*
* HTTP orchestration stays in the concrete modules. This class only owns the
* frozen storage ledger, identifiers, validation and the public projection.
*/
abstract class CloudTemplateImportModule
{
public const MIN_UPLOAD_BYTES = 1048576;
public const MAX_UPLOAD_BYTES = 4294967296;
protected const INTENT_TTL_SECONDS = 86400;
protected const SOURCE_PURPOSE = 'template-import-source';
protected const RUNTIME_PURPOSE = 'template-import-runtime';
/** @var callable():array<string,mixed> */
protected $runtimeProvider;
/** @var callable():int */
protected $clock;
public function __construct(
?callable $runtimeProvider = null,
?callable $clock = null
) {
$this->runtimeProvider = $runtimeProvider
?? static fn (): array => CloudObjectStorageConfig::runtime(true);
$this->clock = $clock ?? time(...);
}
protected static function lockIntent(string $id): CloudTemplateImportIntent
{
$intent = CloudTemplateImportIntent::query()
->where('id', $id)->lockForUpdate()->first();
if ($intent === null) {
throw new CloudError('云镜像导入记录不存在', 404);
}
return $intent;
}
protected static function runtime(CloudTemplateImportIntent $intent): array
{
$runtime = CloudSecrets::decrypt(
(string) $intent->sealed_storage_runtime,
self::RUNTIME_PURPOSE
);
$config = $runtime['config'] ?? null;
$credentials = $runtime['credentials'] ?? null;
$revision = $runtime['revision'] ?? null;
if (!is_array($config) || array_is_list($config)
|| !is_array($credentials) || array_is_list($credentials)
|| !is_int($revision) || $revision < 1
|| $revision !== (int) $intent->storage_revision) {
throw new CloudError('模板对象存储运行时无效', 503);
}
foreach (['endpoint', 'region', 'bucket', 'prefix'] as $field) {
if (!is_string($config[$field] ?? null)) {
throw new CloudError('模板对象存储运行时无效', 503);
}
}
if (!is_bool($config['path_style'] ?? null)
|| !is_string($credentials['access_key_id'] ?? null)
|| (string) $credentials['access_key_id'] === ''
|| !is_string($credentials['secret_access_key'] ?? null)
|| (string) $credentials['secret_access_key'] === '') {
throw new CloudError('模板对象存储运行时无效', 503);
}
return [
'config' => $config,
'credentials' => $credentials,
'revision' => $revision,
];
}
protected static function dto(CloudTemplateImportIntent $intent): array
{
$parts = CloudTemplateImportPart::query()
->where('intent_id', (string) $intent->id)
->orderBy('part_number')->get()->map(
static fn (CloudTemplateImportPart $part): array => [
'part_number' => (int) $part->part_number,
'size_bytes' => (int) $part->size_bytes,
]
)->all();
$uploadedParts = count($parts);
$uploadedBytes = array_sum(array_column($parts, 'size_bytes'));
$state = (string) $intent->state;
$capabilities = CloudTemplateImportStateMachine::capabilities($intent);
return [
'id' => (string) $intent->id,
'source_kind' => (string) $intent->source_kind,
'name' => (string) $intent->name,
'os_family' => (string) $intent->os_family,
'os_version' => (string) $intent->os_version,
'source_filename' => (string) $intent->source_filename,
'source_size_bytes' => (int) $intent->source_size_bytes,
'source_last_modified' => (int) $intent->source_last_modified,
'source_sha256' => (string) $intent->source_sha256,
'template_id' => (string) $intent->template_id,
'state' => $state,
'uploaded_parts' => $uploadedParts,
'uploaded_bytes' => $uploadedBytes,
'parts' => $parts,
'part_count' => (int) $intent->multipart_part_count,
'part_size_bytes' => (int) $intent->multipart_part_size_bytes,
'can_resume' => $capabilities['can_resume'],
'can_cancel' => $capabilities['can_cancel'],
'task_id' => $intent->active_job_id === null
? null : (int) $intent->active_job_id,
'error_code' => (string) $intent->error_code,
'expires_at' => (int) $intent->expires_at,
'completed_at' => $intent->completed_at === null
? null : (int) $intent->completed_at,
'created_at' => (int) $intent->created_at,
'updated_at' => (int) $intent->updated_at,
];
}
protected static function assertAdministrator(array $actor): void
{
if (($actor['is_admin'] ?? false) !== true) {
throw new CloudError('需要管理员权限', 403);
}
}
protected static function requestKey(array $actor): string
{
$key = $actor['request_idempotency_key'] ?? null;
if (!is_string($key)
|| preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $key) !== 1) {
throw new CloudError('请求幂等标识无效', 400);
}
return $key;
}
protected static function intentId(string $id): string
{
if (preg_match('/^[a-f0-9]{32}$/D', $id) !== 1) {
throw new CloudError('云镜像导入标识无效', 422);
}
return $id;
}
protected static function fingerprint(array $canonical): string
{
ksort($canonical, SORT_STRING);
return hash('sha256', json_encode(
$canonical,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
));
}
protected static function remoteSource(
CloudTemplateImportIntent $intent
): array {
$source = CloudSecrets::decrypt(
(string) $intent->sealed_source,
self::SOURCE_PURPOSE
);
if (($source['kind'] ?? null) !== 'remote'
|| !is_string($source['url'] ?? null)
|| !is_string($source['expected_sha256'] ?? null)) {
throw new CloudError('远程云镜像来源账本无效', 503);
}
$url = self::remoteUrl($source['url']);
$sha256 = strtolower(trim($source['expected_sha256']));
if ($sha256 !== ''
&& preg_match('/^[a-f0-9]{64}$/D', $sha256) !== 1) {
throw new CloudError('远程云镜像来源账本无效', 503);
}
return ['url' => $url, 'expected_sha256' => $sha256];
}
protected static function remoteUrl($value): string
{
if (!is_string($value) || strlen($value) > 2048
|| preg_match('//u', $value) !== 1) {
throw new CloudError('云镜像地址无效');
}
$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'] ?? '')),
'.qcow2')) {
throw new CloudError(
'请填写无需账号、使用 443 端口的 HTTPS 镜像直链'
);
}
return $value;
}
protected static function inferRemoteSystem(
string $url,
string $name
): array {
$haystack = strtolower($url . ' ' . $name);
$families = [
'AlmaLinux' => ['almalinux', ['10', '9', '8']],
'Debian' => ['debian', ['13', '12', '11']],
'Ubuntu' => ['ubuntu', ['26.04', '25.10', '25.04', '24.04',
'22.04', '20.04']],
'CentOS Stream' => ['centos', ['10', '9']],
];
foreach ($families as $family => [$needle, $versions]) {
if (!str_contains($haystack, $needle)) {
continue;
}
foreach ($versions as $version) {
if (preg_match('/(?:^|[^0-9])' . preg_quote($version, '/')
. '(?:[^0-9]|$)/', $haystack) === 1) {
return [$family, $version];
}
}
}
throw new CloudError(
'无法从名称或官方地址识别受支持的系统版本'
);
}
protected static function remoteFilename(string $url): string
{
$path = parse_url($url, PHP_URL_PATH);
$filename = is_string($path) ? basename($path) : '';
if ($filename === '' || strlen($filename) > 255
|| preg_match('/\.qcow2$/iD', $filename) !== 1) {
throw new CloudError('官方云镜像文件名无效', 422);
}
return $filename;
}
protected static function filename($value): string
{
if (!is_string($value) || strlen($value) > 255
|| str_contains($value, "\0")
|| preg_match('/\.qcow2$/iD', $value) !== 1) {
throw new CloudError('请选择扩展名为 .qcow2 的云镜像文件');
}
return $value;
}
protected static function label($value, string $label, int $maximum): string
{
if (!is_string($value) || preg_match('//u', $value) !== 1) {
throw new CloudError($label . '无效');
}
$value = trim($value);
if ($value === '' || mb_strlen($value, 'UTF-8') > $maximum
|| preg_match('/[\x00-\x1f\x7f]/u', $value) === 1) {
throw new CloudError($label . '无效');
}
return $value;
}
protected static function integer(
$value,
int $minimum,
int $maximum,
string $message
): int {
$integer = filter_var($value, FILTER_VALIDATE_INT, [
'options' => ['min_range' => $minimum, 'max_range' => $maximum],
]);
if ($integer === false) {
throw new CloudError($message, 422);
}
return (int) $integer;
}
protected static function newTemplateId(string $family,
string $version): string
{
$prefix = strtolower(preg_replace('/[^A-Za-z0-9]+/', '-',
$family . '-' . $version) ?? 'image');
return substr(trim($prefix, '-'), 0, 55) . '-'
. bin2hex(random_bytes(8));
}
protected static function catalogKey(string $family, string $version): string
{
$key = strtolower(preg_replace('/[^A-Za-z0-9]+/', '-',
$family . '-' . $version) ?? 'image');
$key = trim($key, '-');
if ($key === '' || strlen($key) > 80) {
throw new CloudError('云镜像目录标识无效', 422);
}
return $key;
}
protected static function runtimeRevision(array $runtime): int
{
$revision = $runtime['revision'] ?? null;
if (!is_int($revision) || $revision < 1) {
throw new CloudError('模板对象存储运行时无效', 503);
}
return $revision;
}
}