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

951 lines
41 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudJob;
use App\Models\CloudOrder;
use App\Models\CloudTemplate;
use App\Models\CloudTemplateReplica;
/** PHP authority for the global template catalog and its durable replicas. */
final class CloudTemplateCatalogService
{
public const STARTUP_SCRIPT_MAX_BYTES = 32768;
public static function adminCatalog(): array
{
return ['templates' => CloudTemplate::query()
->where('state', '<>', 'retired')->orderBy('os_family')
->orderBy('os_version')->orderBy('name')->get()
->map(static fn (CloudTemplate $row): array => self::adminDto($row))
->all()];
}
public static function publicCatalog(): array
{
return ['templates' => CloudTemplate::query()->where('state', 'active')
->orderBy('os_family')->orderBy('os_version')->orderBy('name')
->get()->map(static fn (CloudTemplate $row): array => [
'id' => (string) $row->id,
'name' => (string) $row->name,
'os_family' => (string) $row->os_family,
'os_version' => (string) $row->os_version,
])->all()];
}
public static function importRemote(array $input, array $actor): array
{
CloudAccess::manage($actor);
CloudInput::only($input, ['name', 'url', 'sha256']);
$name = self::name($input['name'] ?? null);
$url = self::remoteUrl($input['url'] ?? null, 'qcow2');
$sha256 = strtolower(trim((string) ($input['sha256'] ?? '')));
if ($sha256 !== '' && preg_match('/^[a-f0-9]{64}$/D', $sha256) !== 1) {
throw new CloudError('SHA-256 必须留空或填写 64 位小写十六进制值');
}
[$family, $version] = self::inferSystem($url, $name);
return self::reserveImport($actor, $name, $family, $version,
'remote', $url, 0, $sha256,
static fn (int $hostId): array => [
'source_url' => $url,
'sha256' => $sha256,
]);
}
public static function importUpload(array $input, array $file,
array $actor): array
{
CloudAccess::manage($actor);
CloudInput::only($input, ['name', 'os_family', 'os_version']);
$name = self::name($input['name'] ?? null);
$family = self::label($input['os_family'] ?? null, '系统系列', 32);
$version = self::label($input['os_version'] ?? null, '系统版本', 32);
$digest = strtolower((string) ($file['sha256'] ?? ''));
$bytes = filter_var($file['size_bytes'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if ($bytes === false || preg_match('/^[a-f0-9]{64}$/D', $digest) !== 1) {
throw new CloudError('本地云镜像校验结果无效', 503);
}
return self::reserveImport($actor, $name, $family, $version,
'upload', '', (int) $bytes, $digest,
static function (int $hostId) use ($file): array {
return CloudUploadStagingService::issue(
$file, $hostId, 'cloud-template'
);
});
}
private static function reserveImport(array $actor, string $name,
string $family, string $version, string $sourceType,
string $sourceUrl, int $bytes, string $sha256,
callable $sourceForHost): array
{
$hosts = array_values(array_unique(array_map('intval',
CloudAgentSettingsService::enabledHostIds())));
sort($hosts, SORT_NUMERIC);
if ($hosts === []) {
throw new CloudError('没有已启用且已配置 Agent 的宿主机', 409);
}
$connection = (new CloudTemplate())->getConnection();
$parent = $connection->transaction(static function () use (
$actor, $name, $family, $version, $sourceType, $sourceUrl,
$bytes, $sha256, $hosts, $sourceForHost
): CloudJob {
[$parent, $created] = CloudJobService::reserveAggregate(
$actor, 'template_import', [
'name' => $name,
'family' => $family,
'version' => $version,
'source_type' => $sourceType,
'source_url' => $sourceUrl,
'size_bytes' => $bytes,
'sha256' => $sha256,
'host_ids' => $hosts,
]
);
if (!$created) {
return $parent;
}
$now = time();
$template = new CloudTemplate();
$template->id = self::newTemplateId($family, $version);
$template->name = $name;
$template->os_family = $family;
$template->os_version = $version;
$template->source_type = $sourceType;
$template->sealed_source_url = CloudSecrets::encrypt(
['url' => $sourceUrl], 'template-source'
);
$template->image_bytes = $bytes;
$template->sha256 = $sha256;
$template->startup_script = '';
$template->revision = 1;
$template->generation_token = bin2hex(random_bytes(16));
$template->state = 'importing';
$template->active_job_id = (int) $parent->id;
$template->created_at = $template->updated_at = $now;
$template->save();
foreach ($hosts as $hostId) {
$source = $sourceForHost($hostId);
if (!is_array($source)
|| !is_string($source['source_url'] ?? null)
|| !is_string($source['sha256'] ?? null)) {
throw new CloudError('云镜像导入源快照无效', 503);
}
$body = [
'id' => (string) $template->id,
'name' => $name,
'source_url' => $source['source_url'],
'os_family' => $family,
'version' => $version,
'architecture' => 'x86_64',
'sha256' => $source['sha256'],
'revision' => 1,
'generation_token' => (string) $template->generation_token,
];
if (is_string($source['token'] ?? null)
&& $source['token'] !== '') {
$body['source_token'] = $source['token'];
} elseif (is_string($source['source_token'] ?? null)
&& $source['source_token'] !== '') {
$body['source_token'] = $source['source_token'];
}
$operationId = bin2hex(random_bytes(16));
$child = CloudJobService::reserveAgentMutation(
$actor, $hostId, 'template_import_replica', 'POST',
'/v1/templates', $body, [
'can_manage' => true,
'template_id' => (string) $template->id,
], (int) $parent->id, $operationId
);
$replica = new CloudTemplateReplica();
$replica->host_id = $hostId;
$replica->template_id = (string) $template->id;
$replica->revision = 1;
$replica->generation_token =
(string) $template->generation_token;
$replica->state = 'importing';
$replica->image_bytes = 0;
$replica->sha256 = $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);
}
/** Rename and reserve every metadata sync in one database transaction. */
public static function rename(string $id, $name, $expectedRevision,
$generationToken, array $actor): array
{
CloudAccess::manage($actor);
$id = self::templateId($id);
$name = self::name($name);
self::validateVersion($expectedRevision, $generationToken);
$connection = (new CloudTemplate())->getConnection();
$parent = $connection->transaction(static function () use (
$id, $name, $expectedRevision, $generationToken, $actor
): CloudJob {
$template = CloudTemplate::query()->where('id', $id)
->lockForUpdate()->first();
if ($template === null || (string) $template->state === 'retired') {
throw new CloudError('云镜像模板不存在', 404);
}
if ((string) $template->state !== 'active') {
throw new CloudError('云镜像当前状态不允许修改元数据', 409);
}
self::assertMutationBoundaryLocked($template);
if ((int) $template->revision !== $expectedRevision
|| !hash_equals((string) $template->generation_token,
(string) $generationToken)) {
throw new CloudError('云镜像版本已变化,请刷新后重试', 409);
}
[$parent, $created] = CloudJobService::reserveAggregate(
$actor, 'template_metadata_sync', [
'template_id' => $id,
'name' => $name,
'expected_revision' => $expectedRevision,
'generation_token' => $generationToken,
]
);
if (!$created) {
return $parent;
}
$template->name = $name;
$template->revision = (int) $template->revision + 1;
$template->active_job_id = (int) $parent->id;
$template->updated_at = time();
$template->save();
$replicas = CloudTemplateReplica::query()
->where('template_id', $id)->whereIn('state', ['active', 'stale'])
->orderBy('host_id')->lockForUpdate()->get();
if ($replicas->isEmpty()) {
throw new CloudError('云镜像没有可同步的宿主机副本', 409);
}
foreach ($replicas as $replica) {
$operationId = bin2hex(random_bytes(16));
$child = CloudJobService::reserveAgentMutation(
$actor, (int) $replica->host_id,
'template_metadata_replica', 'PATCH',
'/v1/templates/' . rawurlencode($id), [
'name' => $name,
'revision' => (int) $template->revision,
'generation_token' =>
(string) $template->generation_token,
], [
'can_manage' => true,
'template_id' => $id,
], (int) $parent->id, $operationId
);
CloudTemplateReplica::query()
->where('host_id', (int) $replica->host_id)
->where('template_id', $id)->update([
'state' => 'syncing',
'operation_id' => $operationId,
'job_id' => (int) $child->id,
'error_code' => '',
'updated_at' => time(),
]);
}
return $parent;
}, 3);
return CloudJobService::acknowledgement($parent);
}
public static function delete(string $id, $expectedRevision,
$generationToken, array $actor): array
{
CloudAccess::manage($actor);
$id = self::templateId($id);
self::validateVersion($expectedRevision, $generationToken);
$connection = (new CloudTemplate())->getConnection();
$parent = $connection->transaction(static function () use (
$id, $expectedRevision, $generationToken, $actor
): CloudJob {
$template = CloudTemplate::query()->where('id', $id)
->lockForUpdate()->first();
if ($template === null || (string) $template->state === 'retired') {
throw new CloudError('云镜像模板不存在', 404);
}
if ((string) $template->state !== 'active') {
throw new CloudError('云镜像存在未完成或失败任务,禁止删除', 409);
}
self::assertMutationBoundaryLocked($template);
if ((int) $template->revision !== $expectedRevision
|| !hash_equals((string) $template->generation_token,
(string) $generationToken)) {
throw new CloudError('云镜像版本已变化,请刷新后重试', 409);
}
self::assertNoReferencesLocked($id);
$replicas = CloudTemplateReplica::query()
->where('template_id', $id)->orderBy('host_id')
->lockForUpdate()->get();
if ($replicas->isEmpty()
|| $replicas->contains(static fn ($row): bool =>
!in_array((string) $row->state,
['active', 'stale'], true))) {
throw new CloudError('云镜像副本账本不完整,禁止删除', 409);
}
[$parent, $created] = CloudJobService::reserveAggregate(
$actor, 'template_delete', [
'template_id' => $id,
'revision' => $expectedRevision,
'generation_token' => $generationToken,
]
);
if (!$created) {
return $parent;
}
$template->state = 'deleting';
$template->active_job_id = (int) $parent->id;
$template->updated_at = time();
$template->save();
foreach ($replicas as $replica) {
$operationId = bin2hex(random_bytes(16));
$child = CloudJobService::reserveAgentMutation(
$actor, (int) $replica->host_id,
'template_delete_replica', 'DELETE',
'/v1/templates/' . rawurlencode($id), [], [
'can_manage' => true,
'template_id' => $id,
], (int) $parent->id, $operationId
);
CloudTemplateReplica::query()
->where('host_id', (int) $replica->host_id)
->where('template_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);
}
public static function finishJobLocked(CloudJob $job, string $status,
$result, array $payload, array $operation): void
{
if (!in_array((string) $job->kind, [
'template_import_replica', 'template_metadata_replica',
'template_delete_replica',
], true)) {
return;
}
$id = is_string($payload['template_id'] ?? null)
? $payload['template_id'] : '';
$template = CloudTemplate::query()->where('id', $id)
->lockForUpdate()->first();
$replica = CloudTemplateReplica::query()
->where('host_id', (int) $job->host_id)
->where('template_id', $id)->where('job_id', (int) $job->id)
->lockForUpdate()->first();
if ($template === null || $replica === null) {
throw new CloudError('云镜像任务账本不存在', 409);
}
if ((string) $job->kind === 'template_import_replica') {
self::finishImportReplica($template, $replica, $status, $result,
$operation);
self::settleImportParent($template, (int) $job->parent_job_id,
$operation);
} elseif ((string) $job->kind === 'template_metadata_replica') {
self::finishMetadataReplica($template, $replica, $status, $result,
$operation);
self::settleMetadataParent($template, (int) $job->parent_job_id,
$operation);
} else {
self::finishDeleteReplica($template, $replica, $status,
$operation);
self::settleDeleteParent($template, (int) $job->parent_job_id,
$operation);
}
}
private static function finishImportReplica(CloudTemplate $template,
CloudTemplateReplica $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]]
) : false;
if (!is_array($result) || array_is_list($result)
|| ($result['id'] ?? null) !== (string) $template->id
|| (int) ($result['revision'] ?? 0) !== (int) $template->revision
|| ($result['generation_token'] ?? null)
!== (string) $template->generation_token
|| $bytes === false
|| preg_match('/^[a-f0-9]{64}$/D', $digest) !== 1
|| ((string) $template->sha256 !== ''
&& !hash_equals((string) $template->sha256, $digest))
|| ((int) $template->image_bytes > 0
&& (int) $template->image_bytes !== (int) $bytes)) {
throw new CloudError('Agent 云镜像成功回执与请求不匹配', 502);
}
if ((string) $template->sha256 === '') {
$template->sha256 = $digest;
$template->image_bytes = (int) $bytes;
$template->updated_at = time();
$template->save();
}
$replica->state = 'active';
$replica->revision = (int) $template->revision;
$replica->image_bytes = (int) $bytes;
$replica->sha256 = $digest;
$replica->error_code = '';
} else {
$replica->state = 'failed';
$replica->error_code = self::errorCode(
$operation, 'template_import_failed'
);
}
CloudTemplateReplica::query()
->where('host_id', (int) $replica->host_id)
->where('template_id', (string) $replica->template_id)
->where('job_id', (int) $replica->job_id)->update([
'state' => (string) $replica->state,
'revision' => (int) $replica->revision,
'image_bytes' => (int) $replica->image_bytes,
'sha256' => (string) $replica->sha256,
'error_code' => (string) $replica->error_code,
'updated_at' => time(),
]);
}
private static function settleImportParent(CloudTemplate $template,
int $parentId, array $operation): void
{
$replicas = self::lockedReplicas((string) $template->id);
if ($replicas->isEmpty() || $replicas->contains(static fn ($row): bool =>
(string) $row->state === 'importing')) {
return;
}
$parent = self::parent($parentId, 'template_import');
$success = !$replicas->contains(static fn ($row): bool =>
(string) $row->state !== 'active');
if ($success) {
$template->state = 'active';
$template->updated_at = time();
$template->save();
CloudJobService::completeAggregateLocked($parent, 'succeeded',
true, false, '', ['template_id' => (string) $template->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();
$template->state = 'error';
$template->updated_at = time();
$template->save();
CloudJobService::completeAggregateLocked($parent, 'failed', $effect,
false, 'template_import_failed');
}
private static function finishMetadataReplica(CloudTemplate $template,
CloudTemplateReplica $replica, string $status, $result,
array $operation): void
{
if ((string) $replica->state !== 'syncing') {
return;
}
if ($status === 'succeeded') {
if (!is_array($result) || array_is_list($result)
|| ($result['id'] ?? null) !== (string) $template->id
|| ($result['name'] ?? null) !== (string) $template->name
|| (int) ($result['revision'] ?? 0) !== (int) $template->revision
|| ($result['generation_token'] ?? null)
!== (string) $template->generation_token) {
throw new CloudError('Agent 元数据同步回执与请求不匹配', 502);
}
$replica->state = 'active';
$replica->revision = (int) $template->revision;
$replica->error_code = '';
} else {
$replica->state = 'stale';
$replica->error_code = self::errorCode(
$operation, 'template_metadata_sync_failed'
);
}
CloudTemplateReplica::query()
->where('host_id', (int) $replica->host_id)
->where('template_id', (string) $replica->template_id)
->where('job_id', (int) $replica->job_id)->update([
'state' => (string) $replica->state,
'revision' => (int) $replica->revision,
'error_code' => (string) $replica->error_code,
'updated_at' => time(),
]);
}
private static function settleMetadataParent(CloudTemplate $template,
int $parentId, array $operation): void
{
$replicas = self::lockedReplicas((string) $template->id);
if ($replicas->isEmpty() || $replicas->contains(static fn ($row): bool =>
(string) $row->state === 'syncing')) {
return;
}
$parent = self::parent($parentId, 'template_metadata_sync');
$success = !$replicas->contains(static fn ($row): bool =>
(string) $row->state !== 'active'
|| (int) $row->revision !== (int) $template->revision);
if ($success) {
CloudJobService::completeAggregateLocked($parent, 'succeeded',
true, false, '', ['template_id' => (string) $template->id]);
return;
}
$effect = $replicas->contains(static fn ($row): bool =>
(string) $row->state === 'active'
&& (int) $row->revision === (int) $template->revision)
|| ($operation['effect_may_have_applied'] ?? false) === true
|| CloudJob::where('parent_job_id', $parentId)
->where('effect_may_have_applied', 1)->exists();
CloudJobService::completeAggregateLocked($parent, 'failed', $effect,
false, 'template_metadata_sync_failed');
}
private static function finishDeleteReplica(CloudTemplate $template,
CloudTemplateReplica $replica, string $status,
array $operation): void
{
if ((string) $replica->state !== 'deleting') {
return;
}
if ($status === 'succeeded') {
if (!CloudAgentCatalogDeletion::confirms(
$operation, 'template', (string) $template->id
)) {
throw new CloudError('Agent 云镜像删除回执缺少清理证据', 502);
}
$replica->state = 'delete_succeeded';
$replica->error_code = '';
} else {
$replica->state = 'delete_failed';
$replica->error_code = self::errorCode(
$operation, 'template_delete_failed'
);
}
CloudTemplateReplica::query()
->where('host_id', (int) $replica->host_id)
->where('template_id', (string) $replica->template_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(CloudTemplate $template,
int $parentId, array $operation): void
{
$replicas = self::lockedReplicas((string) $template->id);
if ($replicas->isEmpty() || $replicas->contains(static fn ($row): bool =>
(string) $row->state === 'deleting')) {
return;
}
$parent = self::parent($parentId, 'template_delete');
$success = !$replicas->contains(static fn ($row): bool =>
(string) $row->state !== 'delete_succeeded');
if ($success) {
CloudTemplateReplica::query()->where(
'template_id', (string) $template->id
)->delete();
$template->state = 'retired';
$template->revision = (int) $template->revision + 1;
$template->updated_at = time();
$template->save();
CloudJobService::completeAggregateLocked($parent, 'succeeded',
true, false, '', [
'template_id' => (string) $template->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();
$template->state = 'delete_failed';
$template->updated_at = time();
$template->save();
CloudJobService::completeAggregateLocked($parent, 'failed', $effect,
false, 'template_delete_failed');
}
public static function expireAggregateLocked(CloudJob $parent): void
{
if (!in_array((string) $parent->kind, [
'template_import', 'template_metadata_sync', 'template_delete',
], true) || (string) $parent->phase === 'terminal') {
return;
}
$template = CloudTemplate::query()
->where('active_job_id', (int) $parent->id)
->lockForUpdate()->first();
if ($template === 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);
$from = match ((string) $parent->kind) {
'template_import' => 'importing',
'template_metadata_sync' => 'syncing',
default => 'deleting',
};
$to = match ((string) $parent->kind) {
'template_import' => 'failed',
'template_metadata_sync' => 'stale',
default => 'delete_failed',
};
CloudTemplateReplica::query()
->where('template_id', (string) $template->id)
->where('state', $from)->update([
'state' => $to,
'error_code' => 'aggregate_deadline_exceeded',
'updated_at' => time(),
]);
if ((string) $parent->kind === 'template_import') {
$template->state = 'error';
} elseif ((string) $parent->kind === 'template_delete') {
$template->state = 'delete_failed';
}
$template->updated_at = time();
$template->save();
CloudJobService::completeAggregateLocked($parent, 'failed', $effect,
!$effect, 'aggregate_deadline_exceeded');
}
public static function startupScript(string $id): array
{
return self::scriptDto(self::find($id));
}
public static function applyProvisioningSnapshot(array $body,
bool $includeStartupScript = true): array
{
$template = CloudTemplate::query()
->where('id', self::templateId($body['template_id'] ?? ''))
->where('state', 'active')->lockForUpdate()->first();
if ($template === null) {
throw new CloudError('云镜像模板不存在或暂不可用', 409);
}
unset($body['startup_script'], $body['template_revision'],
$body['template_generation_token']);
$body['template_id'] = (string) $template->id;
$body['template_revision'] = (int) $template->revision;
$body['template_generation_token'] =
(string) $template->generation_token;
if ($includeStartupScript) {
$body['startup_script'] = (string) $template->startup_script;
}
return $body;
}
public static function templateMetadataSnapshot(array $body): array
{
$id = self::templateId($body['template_id'] ?? '');
$revision = filter_var($body['template_revision'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$generation = $body['template_generation_token'] ?? null;
$template = CloudTemplate::query()->where('id', $id)
->where('state', 'active')->lockForUpdate()->first();
if ($template === null || $revision === false
|| !is_string($generation)
|| !hash_equals((string) $template->generation_token, $generation)
|| (int) $template->revision !== (int) $revision) {
throw new CloudError('云镜像模板版本已变化,请重新提交', 409);
}
return ['template_id' => $id, 'os_source' => 'cloud_template',
'os_name' => self::name((string) $template->name),
'login_name' => 'root'];
}
public static function assertProvisionable(string $id): void
{
if (!CloudTemplate::query()->where('id', self::templateId($id))
->where('state', 'active')->exists()) {
throw new CloudError('云镜像模板不存在或暂不可用', 409);
}
}
public static function saveStartupScript(string $id, $script,
$expectedRevision, $generationToken): array
{
$normalized = self::normalizeScript($script);
self::validateVersion($expectedRevision, $generationToken);
return (new CloudTemplate())->getConnection()->transaction(
static function () use (
$id, $normalized, $expectedRevision, $generationToken
): array {
$template = CloudTemplate::query()
->where('id', self::templateId($id))
->lockForUpdate()->first();
if ($template === null || (string) $template->state === 'retired') {
throw new CloudError('云镜像模板不存在', 404);
}
if ((string) $template->state !== 'active'
|| (int) $template->revision !== $expectedRevision
|| !hash_equals((string) $template->generation_token,
(string) $generationToken)) {
throw new CloudError('初始化脚本已被修改,请重新打开对话框', 409);
}
self::assertMutationBoundaryLocked($template);
$template->startup_script = $normalized;
$template->revision = (int) $template->revision + 1;
$template->updated_at = time();
$template->save();
CloudTemplateReplica::query()
->where('template_id', (string) $template->id)
->where('generation_token',
(string) $template->generation_token)
->where('state', 'active')->update([
'revision' => (int) $template->revision,
'updated_at' => time(),
]);
return self::scriptDto($template);
}, 3
);
}
public static function normalizeScript($script): string
{
if (!is_string($script) || preg_match('//u', $script) !== 1
|| str_contains($script, "\0")) {
throw new CloudError('启动脚本必须是有效 UTF-8 文本,且不能包含 NUL 字符', 422);
}
$script = str_replace("\r\n", "\n", $script);
if (strlen($script) > self::STARTUP_SCRIPT_MAX_BYTES) {
throw new CloudError('启动脚本不能超过 32 KiB', 422);
}
return $script;
}
private static function assertNoReferencesLocked(string $templateId): void
{
foreach (CloudOrder::query()->whereIn('status', [
'awaiting_payment', 'queued', 'running',
])->lockForUpdate()->get(['id', 'spec_json']) as $order) {
$spec = json_decode((string) $order->spec_json, true);
if (is_array($spec) && !array_is_list($spec)
&& ($spec['template_id'] ?? null) === $templateId) {
throw new CloudError('云镜像仍被未完成订单使用,暂不能删除', 409);
}
}
$jobs = CloudJob::query()->whereIn('kind', ['create', 'reinstall'])
->where(static function ($query): void {
$query->where('phase', '<>', 'terminal')
->orWhere(static function ($failed): void {
$failed->where('phase', 'terminal')
->where('outcome', 'failed')
->where('effect_resolution', 'unknown');
});
})->lockForUpdate()->get(['sealed_payload']);
foreach ($jobs as $job) {
$payload = CloudSecrets::decrypt(
(string) $job->sealed_payload, 'job-payload'
);
if (($payload['body']['template_id'] ?? null) === $templateId) {
throw new CloudError('云镜像仍被虚拟机任务使用,暂不能删除', 409);
}
}
}
/** Do not overlap a new mutation with an active or unresolved effect. */
private static function assertMutationBoundaryLocked(
CloudTemplate $template
): void {
$jobId = (int) ($template->active_job_id ?? 0);
if ($jobId < 1) {
return;
}
$job = CloudJob::where('id', $jobId)->lockForUpdate()->first();
if ($job === null
|| (string) $job->phase !== 'terminal'
|| ((string) $job->outcome === 'failed'
&& (string) $job->effect_resolution === 'unknown')) {
throw new CloudError(
'云镜像上一任务尚未安全收敛,禁止提交新的修改', 409
);
}
}
private static function lockedReplicas(string $id)
{
return CloudTemplateReplica::query()->where('template_id', $id)
->orderBy('host_id')->lockForUpdate()->get();
}
private static function parent(int $id, string $kind): CloudJob
{
$job = CloudJob::where('id', $id)->where('kind', $kind)
->lockForUpdate()->first();
if ($job === null) {
throw new CloudError('云镜像聚合任务不存在', 409);
}
return $job;
}
private static function find(string $id): CloudTemplate
{
$row = CloudTemplate::find(self::templateId($id));
if ($row === null || (string) $row->state === 'retired') {
throw new CloudError('云镜像模板不存在', 404);
}
return $row;
}
private static function adminDto(CloudTemplate $row): array
{
$replicas = CloudTemplateReplica::query()
->where('template_id', (string) $row->id)->orderBy('host_id')
->get()->map(static fn (CloudTemplateReplica $replica): array => [
'host_id' => (int) $replica->host_id,
'state' => (string) $replica->state,
'error_code' => (string) $replica->error_code,
])->all();
return [
'id' => (string) $row->id,
'name' => (string) $row->name,
'os_family' => (string) $row->os_family,
'os_version' => (string) $row->os_version,
'source_type' => (string) $row->source_type,
'image_bytes' => (int) $row->image_bytes,
'sha256' => (string) $row->sha256,
'state' => (string) $row->state,
'startup_script_configured' => (string) $row->startup_script !== '',
'revision' => (int) $row->revision,
'generation_token' => (string) $row->generation_token,
'created_at' => (int) $row->created_at,
'updated_at' => (int) $row->updated_at,
'replicas' => $replicas,
];
}
private static function scriptDto(CloudTemplate $row): array
{
return ['id' => (string) $row->id,
'startup_script' => (string) $row->startup_script,
'revision' => (int) $row->revision,
'generation_token' => (string) $row->generation_token];
}
private static function validateVersion($revision, $generation): void
{
if (!is_int($revision) || $revision < 1
|| !is_string($generation)
|| preg_match('/^[a-f0-9]{32}$/D', $generation) !== 1) {
throw new CloudError('云镜像版本无效,请刷新后重试', 422);
}
}
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 remoteUrl($value, string $extension): 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'] ?? '')),
'.' . $extension)) {
throw new CloudError('请填写无需账号、使用 443 端口的 HTTPS 镜像直链');
}
return $value;
}
private static function inferSystem(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('无法从名称或官方地址识别受支持的系统版本');
}
private 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));
}
private static function templateId($value): string
{
if (!is_string($value)
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D', $value) !== 1) {
throw new CloudError('请选择有效的云镜像模板');
}
return $value;
}
private static function name($value): string
{
return self::label($value, '模板名称', 64);
}
private 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;
}
}