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

317 lines
13 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudHostAgent;
use App\Models\CloudHostStorageConfiguration;
use App\Models\CloudJob;
/** Current desired host storage layout plus its latest single-dispatch task. */
final class CloudHostStorageConfigurationService
{
private const DIRECTORY_FIELDS = [
'managed_directory', 'template_directory', 'seed_directory',
'user_iso_directory', 'rescue_directory',
];
public static function read(int $hostId): array
{
$host = self::host($hostId);
return self::dto($host, self::convergedRow($hostId));
}
public static function save(int $hostId, array $input,
array $actor): array
{
CloudAccess::manage($actor);
CloudInput::only($input, array_merge(
['expected_revision'], self::DIRECTORY_FIELDS
));
$expectedRevision = $input['expected_revision'] ?? null;
if (!is_int($expectedRevision) || $expectedRevision < 0) {
throw new CloudError('存储配置版本无效,请刷新页面后重试', 409);
}
$paths = self::paths($input);
// Reading the linked deadline and terminalizing it are local database
// operations. They never inspect the Agent and never replay the old
// mutation. The transaction below then rereads the resulting ledger.
self::convergedRow($hostId);
$connection = (new CloudHostStorageConfiguration())->getConnection();
$job = $connection->transaction(static function () use (
$hostId, $expectedRevision, $paths, $actor
): CloudJob {
$host = CloudHost::query()->where('id', $hostId)
->lockForUpdate()->first();
if ($host === null) {
throw new CloudError('宿主机不存在', 404);
}
$row = CloudHostStorageConfiguration::query()
->where('host_id', $hostId)->lockForUpdate()->first();
$actualRevision = $row === null ? 0 : (int) $row->revision;
$samePaths = $row !== null && self::samePaths($row, $paths);
if ($actualRevision !== $expectedRevision) {
throw new CloudError('存储配置已被修改,请刷新页面后重试', 409);
}
if ($row !== null) {
$prior = self::linkedJob($row);
$state = (string) $row->state;
if ($state === 'applied') {
if ($samePaths && $prior !== null
&& (string) $prior->phase === 'terminal'
&& (string) $prior->outcome === 'succeeded') {
return $prior;
}
throw new CloudError(
'宿主机存储配置已成功应用,不允许更换路径', 409
);
}
if ($state === 'applying'
&& $prior !== null
&& (string) $prior->phase !== 'terminal') {
if ($samePaths) {
return $prior;
}
throw new CloudError(
'宿主机存储配置任务正在执行,请等待终态回执', 409
);
}
if (!in_array($state, ['applying', 'failed'], true)
|| !self::isTerminalFailure($prior)) {
throw new CloudError(
'宿主机存储配置状态与任务账本不一致,请联系管理员核查', 409
);
}
}
$setting = CloudHostAgent::query()->where('host_id', $hostId)
->lockForUpdate()->first();
if ($setting === null || !(bool) $setting->enabled
|| trim((string) $setting->sealed_api_secret) === '') {
throw new CloudError('请先启用并配置宿主机 Agent API', 409);
}
// The revision describes the desired paths, not the number of
// attempts. Re-applying the same failed layout gets a new task and
// operation ID without pretending that the configuration changed.
$nextRevision = $row === null || !$samePaths
? $actualRevision + 1 : $actualRevision;
$operationId = bin2hex(random_bytes(16));
[$job, $created] = CloudJobService::reserveStandaloneAgentMutation(
$actor, $hostId, 'host_storage_configure', 'POST',
'/v1/storage/configuration', $paths,
['can_manage' => true, 'storage_revision' => $nextRevision],
[
'host_id' => $hostId,
'expected_revision' => $expectedRevision,
'paths' => $paths,
],
$operationId
);
if (!$created) {
return $job;
}
if ($row === null) {
$row = new CloudHostStorageConfiguration();
$row->host_id = $hostId;
$row->created_at = time();
}
$row->revision = $nextRevision;
self::assignPaths($row, $paths);
$row->state = 'applying';
$row->operation_id = $operationId;
$row->job_id = (int) $job->id;
$row->updated_at = time();
$row->save();
CloudAgentSettingsService::invalidateReadiness($setting);
return $job;
}, 3);
return CloudJobService::acknowledgement($job);
}
public static function finishJobLocked(
CloudJob $job,
string $status,
$result,
array $operation
): void {
if ((string) $job->kind !== 'host_storage_configure') {
return;
}
$row = CloudHostStorageConfiguration::query()
->where('host_id', (int) $job->host_id)
->lockForUpdate()->first();
if ($row === null) {
throw new CloudError('存储配置任务账本不存在', 409);
}
if (!hash_equals((string) $row->operation_id,
(string) $job->operation_id)) {
// A terminally failed generation may be superseded by an explicit
// new request. A late receipt from that old generation still
// closes its CloudJob, but must never overwrite the current row.
return;
}
if ((int) ($row->job_id ?? 0) !== (int) $job->id) {
throw new CloudError('存储配置任务账本关联不一致', 409);
}
if (in_array((string) $row->state, ['applied', 'failed'], true)) {
return;
}
if ((string) $row->state !== 'applying') {
throw new CloudError('存储配置状态无效', 409);
}
if ($status === 'succeeded') {
if (!is_array($result) || array_is_list($result)
|| ($result['configured'] ?? null) !== true) {
throw new CloudError('Agent 存储配置回执缺少确认结果', 502);
}
$row->state = 'applied';
} else {
$row->state = 'failed';
}
$row->updated_at = time();
$row->save();
}
private static function paths(array $input): array
{
$paths = [];
foreach (self::DIRECTORY_FIELDS as $field) {
$value = $input[$field] ?? null;
if (!is_string($value)) {
throw new CloudError('五个存储目录均为必填项');
}
$paths[$field] = self::path($value);
}
$values = array_values($paths);
for ($left = 0; $left < count($values); $left++) {
for ($right = $left + 1; $right < count($values); $right++) {
if ($values[$left] === $values[$right]
|| str_starts_with($values[$left], $values[$right] . '/')
|| str_starts_with($values[$right], $values[$left] . '/')) {
throw new CloudError(
'五个存储目录必须相互独立,不能相同或互为父子目录'
);
}
}
}
return $paths;
}
private static function path(string $value): string
{
if (strlen($value) > 4096
|| preg_match('#^/(?:[A-Za-z0-9._-]+)(?:/[A-Za-z0-9._-]+)*$#D',
$value) !== 1) {
throw new CloudError(
'存储目录必须是规范绝对路径,仅可包含英文、数字、点、下划线和短横线'
);
}
foreach (explode('/', substr($value, 1)) as $segment) {
if ($segment === '.' || $segment === '..') {
throw new CloudError('存储目录不能包含 . 或 .. 路径段');
}
}
return $value;
}
private static function samePaths($row, array $paths): bool
{
foreach (self::DIRECTORY_FIELDS as $field) {
if ((string) $row->{$field} !== $paths[$field]) {
return false;
}
}
return true;
}
private static function linkedJob($row): ?CloudJob
{
$jobId = (int) ($row->job_id ?? 0);
if ($jobId < 1 || trim((string) $row->operation_id) === '') {
return null;
}
$job = CloudJob::find($jobId);
if ($job === null
|| (int) $job->host_id !== (int) $row->host_id
|| (string) $job->kind !== 'host_storage_configure'
|| !hash_equals((string) $row->operation_id,
(string) $job->operation_id)) {
return null;
}
return $job;
}
private static function convergedRow(
int $hostId
): ?CloudHostStorageConfiguration {
$row = CloudHostStorageConfiguration::find($hostId);
$job = $row === null ? null : self::linkedJob($row);
if ($job !== null && (string) $job->phase !== 'terminal'
&& CloudJobService::activeDeadlineReached($job)) {
CloudWorkerService::expireDueTaskForAdmin((int) $job->id);
// The local finalizer updates both the immutable job and this
// projection in one transaction. Never render or save from the
// stale model instance that preceded that transaction.
$row = CloudHostStorageConfiguration::find($hostId);
}
return $row;
}
private static function isTerminalFailure(?CloudJob $job): bool
{
return $job !== null
&& (string) $job->phase === 'terminal'
&& (string) $job->outcome === 'failed';
}
private static function assignPaths($row, array $paths): void
{
foreach (self::DIRECTORY_FIELDS as $field) {
$row->{$field} = $paths[$field];
}
}
private static function host(int $hostId): CloudHost
{
if ($hostId < 1 || ($host = CloudHost::find($hostId)) === null) {
throw new CloudError('宿主机不存在', 404);
}
return $host;
}
private static function dto(CloudHost $host, $row): array
{
$setting = CloudHostAgent::find((int) $host->id);
$state = $row === null ? 'unconfigured' : (string) $row->state;
$linkedJob = $row === null ? null : self::linkedJob($row);
$terminalFailure = self::isTerminalFailure($linkedJob);
// A worker may terminalize its CloudJob after a local finalization
// incident left this projection at applying. The immutable task ledger
// is authoritative, so present that condition as failed and recoverable.
if ($state === 'applying' && $terminalFailure) {
$state = 'failed';
}
$canSubmit = $row === null || ($state === 'failed' && $terminalFailure);
$activeTask = $state === 'applying' && $linkedJob !== null
&& (string) $linkedJob->phase !== 'terminal';
$result = [
'host_id' => (int) $host->id,
'host_name' => (string) $host->name,
'revision' => $row === null ? 0 : (int) $row->revision,
'state' => $state,
'configured' => $state === 'applied',
'can_submit' => $canSubmit,
'operation_id' => $row === null
? null : (string) $row->operation_id,
'task_id' => $activeTask ? (string) $linkedJob->id : null,
'status_url' => $activeTask
? '/api/v1/tasks/' . (int) $linkedJob->id : null,
'requires_agent_retest' => $state === 'applied'
&& ($setting === null || !$setting->isReady()),
];
foreach (self::DIRECTORY_FIELDS as $field) {
$result[$field] = $row === null ? '' : (string) $row->{$field};
}
return $result;
}
}