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/Controllers/CloudAdminController.php

513 lines
20 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Controllers;
use App\Models\CloudHost;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudAdminHostProjectionService;
use App\Services\Cloud\CloudAdminHostSchedulingService;
use App\Services\Cloud\CloudHostStorageConfigurationService;
use App\Services\Cloud\CloudCountryCatalog;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInput;
use App\Services\Cloud\CloudNetworkSelector;
use App\Services\Cloud\CloudAgentSettingsService;
use App\Services\Cloud\CloudRescueCatalogService;
use App\Services\Cloud\CloudRescueTemplateReplicaCoordinator;
use App\Services\Cloud\CloudRescueTemplateRetirementService;
use App\Services\Cloud\CloudTemplateCatalogService;
use App\Services\Cloud\CloudTemplateImportCancellation;
use App\Services\Cloud\CloudTemplateImportReadModel;
use App\Services\Cloud\CloudTemplateMultipartAcquisition;
use App\Services\Cloud\CloudTemplateRemoteAcquisition;
use App\Services\Cloud\CloudTemplateReplicaCoordinator;
use App\Services\Cloud\CloudUserIsoFeature;
final class CloudAdminController
{
private function actor($request, bool $write = false): array
{
$actor = $request->getAttribute('cloud_actor') ?? CloudAccess::actor();
if (!$actor['is_admin']) {
throw new CloudError('需要管理员权限', 403);
}
if ($write) {
CloudAccess::manage($actor);
$key = trim((string) $request->getHeaderLine(
'Idempotency-Key'
));
if ($key !== '') {
if (preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $key) !== 1) {
throw new CloudError('请求幂等标识无效', 400);
}
$actor['request_idempotency_key'] = $key;
}
}
return $actor;
}
private function host($id): CloudHost
{
$host = CloudHost::find($id);
if ($host === null) {
throw new CloudError('宿主机不存在', 404);
}
return $host;
}
public function hosts($request, $response, $args = [])
{
$write = $request->getMethod() !== 'GET';
$this->actor($request, $write);
if (!$write && !isset($args['id'])) {
return $response->withJson(
CloudAdminHostProjectionService::listing()
)->withHeader('Cache-Control', 'no-store');
}
if (!$write) {
return $response->withJson(CloudAdminHostProjectionService::one(
$this->host($args['id'])
))
->withHeader('Cache-Control', 'no-store');
}
$body = CloudInput::object($request);
CloudInput::only($body, [
'name', 'enabled', 'default_network', 'region', 'country_code',
]);
$name = $body['name'] ?? '';
if (!is_string($name) || trim($name) === '' || mb_strlen($name) > 80) {
throw new CloudError('宿主机名称需为 1 至 80 字符');
}
$enabled = filter_var($body['enabled'] ?? true, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if ($enabled === null) {
throw new CloudError('启用状态无效');
}
$region = $body['region'] ?? '';
if (!is_string($region) || trim($region) === '' || mb_strlen(trim($region)) > 64) {
throw new CloudError('具体地区需为 1 至 64 字符,例如 HongKong 或 Tokyo');
}
$body['region'] = trim($region);
$countryCode = CloudCountryCatalog::normalize($body['country_code'] ?? null);
$network = $body['default_network'] ?? '';
if (!CloudNetworkSelector::isValid($network)) {
throw new CloudError(
'默认网络必须填写 bridge:网桥名 或 network:libvirt网络名;网桥名最多15字符,网络名最多64字符'
);
}
$isUpdate = isset($args['id']);
$hostId = $isUpdate ? (int) $args['id'] : 0;
$connection = (new CloudHost())->getConnection();
$host = $connection->transaction(static function () use (
$isUpdate, $hostId, $name, $body, $countryCode, $network, $enabled
): CloudHost {
$host = $isUpdate
? CloudHost::query()->where('id', $hostId)->lockForUpdate()->first()
: new CloudHost();
if ($host === null) {
throw new CloudError('宿主机不存在', 404);
}
$networkChanged = $host->exists
&& (string) $host->default_network !== $network;
if (!$host->exists) {
$host->created_at = $host->updated_at = time();
}
$host->name = trim($name);
$host->region = $body['region'];
$host->country_code = $countryCode;
$host->default_network = $network;
$host->enabled = $enabled;
$host->updated_at = time();
$host->save();
if ($networkChanged) {
CloudAgentSettingsService::invalidateForNetworkSelectorChange(
(int) $host->id
);
}
return $host;
});
return $response->withJson($host->toArray(), $isUpdate ? 200 : 201)
->withHeader('Cache-Control', 'no-store');
}
public function hostScheduling($request, $response, $args)
{
$write = $request->getMethod() !== 'GET';
$this->actor($request, $write);
$hostId = (int) $args['id'];
if (!$write) {
$result = CloudAdminHostSchedulingService::read($hostId);
} else {
$body = CloudInput::object($request);
CloudInput::only($body, [
'resource_pool_id', 'scheduler_state',
'configured_cpu_cores', 'configured_memory_mib',
'configured_disk_gib', 'safety_cpu_cores',
'safety_memory_mib', 'safety_disk_gib', 'max_instances',
]);
$result = CloudAdminHostSchedulingService::save($hostId, $body);
}
return $response->withJson($result)
->withHeader('Cache-Control', 'no-store');
}
public function hostStorageConfiguration($request, $response, $args)
{
// Host filesystem paths and libvirt pool registration are restricted
// to super administrators for reads as well as writes.
$actor = $this->actor($request, true);
$hostId = (int) ($args['id'] ?? 0);
$result = $request->getMethod() === 'GET'
? CloudHostStorageConfigurationService::read($hostId)
: CloudHostStorageConfigurationService::save(
$hostId,
CloudInput::object($request, 32768),
$actor
);
return $response->withJson(
$result,
$request->getMethod() === 'GET' ? 200 : 202
)
->withHeader('Cache-Control', 'no-store');
}
public function userIsoSettings($request, $response)
{
$write = $request->getMethod() !== 'GET';
$this->actor($request, $write);
if (!$write) {
return $response->withJson(['enabled' => CloudUserIsoFeature::enabled()]);
}
$body = CloudInput::object($request);
CloudInput::only($body, ['enabled']);
$enabled = filter_var($body['enabled'] ?? null, FILTER_VALIDATE_BOOLEAN,
FILTER_NULL_ON_FAILURE);
if ($enabled === null) {
throw new CloudError('用户 ISO 开关状态无效');
}
CloudUserIsoFeature::save($enabled);
return $response->withJson(['enabled' => $enabled]);
}
public function templateStartupScript($request, $response, $args = [])
{
$write = $request->getMethod() !== 'GET';
$this->actor($request, $write);
$templateId = CloudInput::template((string) ($args['id'] ?? ''));
if (!$write) {
$payload = CloudTemplateCatalogService::startupScript($templateId);
} else {
// JSON escaping can expand a valid 32 KiB UTF-8 script considerably.
$body = CloudInput::object($request, 262144);
CloudInput::only($body, [
'script', 'expected_revision', 'generation_token',
]);
$payload = CloudTemplateCatalogService::saveStartupScript(
$templateId,
$body['script'] ?? null,
$body['expected_revision'] ?? null,
$body['generation_token'] ?? null
);
}
return $response->withJson($payload)
->withHeader('Cache-Control', 'no-store');
}
public function templateReplicaRepair($request, $response, $args = [])
{
$actor = $this->actor($request, true);
$body = CloudInput::object($request);
CloudInput::only($body, []);
$templateId = CloudInput::template((string) ($args['id'] ?? ''));
$hostId = filter_var(
$args['host_id'] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]
);
if ($hostId === false) {
throw new CloudError('宿主机标识无效');
}
$this->host((int) $hostId);
$result = CloudTemplateReplicaCoordinator::repairHost(
$templateId,
(int) $hostId,
$actor
);
return $response->withJson(
$result,
($result['scheduled'] ?? false) === true ? 202 : 200
)->withHeader('Cache-Control', 'no-store');
}
public function rescueTemplateReplicaRepair(
$request,
$response,
$args = []
) {
$actor = $this->actor($request, true);
$body = CloudInput::object($request);
CloudInput::only($body, []);
$templateId = strtolower((string) ($args['id'] ?? ''));
if (preg_match('/^[a-f0-9]{32}$/D', $templateId) !== 1) {
throw new CloudError('救援 ISO 标识无效');
}
$hostId = filter_var(
$args['host_id'] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]
);
if ($hostId === false) {
throw new CloudError('宿主机标识无效');
}
$this->host((int) $hostId);
$result = CloudRescueTemplateReplicaCoordinator::syncHost(
$templateId,
(int) $hostId,
$actor,
'admin_repair'
);
return $response->withJson(
$result,
($result['scheduled'] ?? false) === true ? 202 : 200
)->withHeader('Cache-Control', 'no-store');
}
public function templates($request, $response, $args = [])
{
$method = $request->getMethod();
$actor = $this->actor($request, $method !== 'GET');
$body = in_array($method, ['POST', 'PATCH', 'PUT'], true)
? CloudInput::object($request) : null;
$kind = (string) ($args['kind'] ?? '');
if ($kind === 'cloud') {
$templateId = isset($args['id'])
? CloudInput::template((string) $args['id']) : null;
if ($method === 'GET' && $templateId === null) {
return $response->withJson(
CloudTemplateCatalogService::adminCatalog()
)->withHeader('Cache-Control', 'no-store');
}
if ($method === 'PATCH' && $templateId !== null) {
CloudInput::only($body, [
'name', 'expected_revision', 'generation_token',
]);
return $response->withJson(
CloudTemplateCatalogService::rename(
$templateId,
$body['name'] ?? null,
$body['expected_revision'] ?? null,
$body['generation_token'] ?? null,
$actor
), 202
)->withHeader('Cache-Control', 'no-store');
}
if ($method === 'DELETE' && $templateId !== null) {
$body = CloudInput::object($request);
CloudInput::only($body, [
'expected_revision', 'generation_token',
]);
return $response->withJson(CloudTemplateCatalogService::delete(
$templateId,
$body['expected_revision'] ?? null,
$body['generation_token'] ?? null,
$actor
), 202)->withHeader('Cache-Control', 'no-store');
}
throw new CloudError('云镜像请求不存在', 404);
}
if ($kind === 'rescue' && $method === 'DELETE'
&& isset($args['id'])) {
$templateId = strtolower((string) $args['id']);
if (preg_match('/^[a-f0-9]{32}$/D', $templateId) !== 1) {
throw new CloudError('救援 ISO 标识无效');
}
$body = CloudInput::object($request);
CloudInput::only($body, [
'expected_revision', 'generation_token',
]);
return $response->withJson(
CloudRescueTemplateRetirementService::retire(
$templateId,
$body['expected_revision'] ?? null,
$body['generation_token'] ?? null,
$actor
),
202
)->withHeader('Cache-Control', 'no-store');
}
if ($kind === 'rescue' && !isset($args['id'])) {
if ($method === 'GET') {
return $response->withJson(
CloudRescueCatalogService::adminCatalog()
)->withHeader('Cache-Control', 'no-store');
}
if ($method === 'POST') {
$result = CloudRescueCatalogService::importRemote(
$body,
$actor
);
try {
$validation =
CloudRescueTemplateReplicaCoordinator::beginValidation(
(string) $result['template_id'],
(int) $result['validation_host_id'],
$actor
);
$result = array_merge($result, $validation, [
'validation_scheduled' =>
($validation['scheduled'] ?? false) === true,
]);
} catch (\Throwable $exception) {
error_log(sprintf(
'rescue catalog validation scheduling deferred: %s: %s',
(string) $result['template_id'],
$exception->getMessage()
));
$result['validation_scheduled'] = false;
}
return $response->withJson($result, 202)
->withHeader('Cache-Control', 'no-store');
}
}
throw new CloudError('救援镜像请求不存在', 404);
}
public function cloudTemplateImportIntents($request, $response)
{
$write = $request->getMethod() === 'POST';
$actor = $this->actor($request, $write);
if (!$write) {
return $response->withJson(
(new CloudTemplateImportReadModel())->active($actor)
)
->withHeader('Cache-Control', 'no-store');
}
$result = (new CloudTemplateMultipartAcquisition())->beginUpload(
CloudInput::object($request),
$actor
);
return $response->withJson(
$result['intent'],
$result['created'] ? 201 : 200
)->withHeader('Cache-Control', 'no-store');
}
public function cloudTemplateImportRemote($request, $response)
{
$actor = $this->actor($request, true);
return $response->withJson(
(new CloudTemplateRemoteAcquisition())->importRemote(
CloudInput::object($request),
$actor
),
202
)->withHeader('Cache-Control', 'no-store');
}
public function cloudTemplateImportIntent($request, $response, $args)
{
$actor = $this->actor($request);
return $response->withJson(
(new CloudTemplateImportReadModel())->one(
(string) ($args['id'] ?? ''),
$actor
)['intent']
)->withHeader('Cache-Control', 'no-store');
}
public function cloudTemplateImportResume($request, $response, $args)
{
$actor = $this->actor($request, true);
return $response->withJson(
(new CloudTemplateRemoteAcquisition())->resumeRemote(
(string) ($args['id'] ?? ''),
$actor
),
202
)->withHeader('Cache-Control', 'no-store');
}
public function cloudTemplateImportCancel($request, $response, $args)
{
$actor = $this->actor($request, true);
return $response->withJson(
(new CloudTemplateImportCancellation())->cancel(
(string) ($args['id'] ?? ''),
$actor
)
)->withHeader('Cache-Control', 'no-store');
}
public function cloudTemplateImportUpload($request, $response, $args)
{
$actor = $this->actor($request, true);
return $response->withJson(
(new CloudTemplateMultipartAcquisition())->startUpload(
(string) ($args['id'] ?? ''),
$actor
)
)->withHeader('Cache-Control', 'no-store');
}
public function cloudTemplateImportPart($request, $response, $args)
{
$actor = $this->actor($request, true);
return $response->withJson(
(new CloudTemplateMultipartAcquisition())->recordPart(
(string) ($args['id'] ?? ''),
(int) ($args['part'] ?? 0),
CloudInput::object($request),
$actor
)
)->withHeader('Cache-Control', 'no-store');
}
public function cloudTemplateImportComplete($request, $response, $args)
{
$actor = $this->actor($request, true);
return $response->withJson(
(new CloudTemplateMultipartAcquisition())->completeUpload(
(string) ($args['id'] ?? ''),
CloudInput::object($request),
$actor
),
202
)->withHeader('Cache-Control', 'no-store');
}
private static function catalogName($value): string
{
if (!is_string($value) || preg_match('//u', $value) !== 1) {
throw new CloudError('模板名称应为 1 至 64 个字符');
}
$value = trim($value);
if ($value === '' || mb_strlen($value, 'UTF-8') > 64
|| preg_match('/[\x00-\x1f\x7f]/u', $value) === 1) {
throw new CloudError('模板名称应为 1 至 64 个字符');
}
return $value;
}
private static function catalogUrl($value, string $extension): string
{
if (!is_string($value) || strlen($value) > 2048) {
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;
}
}