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([ 'hosts' => CloudAdminHostProjectionService::all(), ])->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 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'); } if ($method === 'POST' && $templateId === null) { return $response->withJson( CloudTemplateCatalogService::importRemote($body, $actor), 202 )->withHeader('Cache-Control', 'no-store'); } throw new CloudError('云镜像请求不存在', 404); } $query = $request->getQueryParams(); $hostId = filter_var( $query['host_id'] ?? ($body['host_id'] ?? null), FILTER_VALIDATE_INT ); if (!$hostId) { throw new CloudError('请选择宿主机'); } $this->host($hostId); if ($method === 'GET' && !isset($args['id'])) { return $response->withJson( CloudRescueTemplateImportService::catalog((int) $hostId) )->withHeader('Cache-Control', 'no-store'); } if ($method === 'POST' && !isset($args['id'])) { CloudInput::only($body, ['host_id', 'name', 'url', 'sha256']); $name = self::catalogName($body['name'] ?? null); $url = self::catalogUrl($body['url'] ?? null, 'iso'); $digest = strtolower(trim((string) ($body['sha256'] ?? ''))); if ($digest !== '' && preg_match('/^[a-f0-9]{64}$/D', $digest) !== 1) { throw new CloudError('SHA-256 格式无效'); } return $response->withJson( CloudRescueTemplateImportService::start( (int) $hostId, 'remote', $name, $url, '', $digest, $actor ), 202 )->withHeader('Cache-Control', 'no-store'); } if ($method === 'DELETE' && isset($args['id'])) { $id = (string) $args['id']; return $response->withJson( CloudRescueTemplateDeletionService::delete( (int) $hostId, $id, $actor ), 202 )->withHeader('Cache-Control', 'no-store'); } throw new CloudError('救援镜像请求不存在', 404); } public function rescueUpload($request, $response) { $actor = $this->actor($request, true); $query = $request->getQueryParams(); CloudInput::only($query, ['host_id', 'name']); $hostId = filter_var($query['host_id'] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); if ($hostId === false) { throw new CloudError('请选择宿主机'); } $this->host((int) $hostId); $name = self::catalogName($query['name'] ?? null); $file = CloudUploadStagingService::capture( $request, 'iso', 32768, 8 * 1024 * 1024 * 1024 ); try { $staging = CloudUploadStagingService::issue( $file, (int) $hostId, 'rescue-template' ); return $response->withJson( CloudRescueTemplateImportService::start( (int) $hostId, 'upload', $name, (string) $staging['url'], (string) $staging['token'], (string) $staging['sha256'], $actor ), 202 )->withHeader('Cache-Control', 'no-store'); } finally { CloudUploadStagingService::discard($file); } } public function cloudTemplateUpload($request, $response) { $actor = $this->actor($request, true); $query = $request->getQueryParams(); CloudInput::only($query, [ 'name', 'os_family', 'os_version', 'filename', ]); $filename = $query['filename'] ?? null; if (!is_string($filename) || strlen($filename) > 255 || str_contains($filename, "\0") || preg_match('/\.qcow2$/iD', $filename) !== 1) { throw new CloudError('请选择扩展名为 .qcow2 的云镜像文件'); } $file = CloudUploadStagingService::capture( $request, 'qcow2', 1024 * 1024, 4 * 1024 * 1024 * 1024 ); try { $job = CloudTemplateCatalogService::importUpload([ 'name' => $query['name'] ?? null, 'os_family' => $query['os_family'] ?? null, 'os_version' => $query['os_version'] ?? null, ], $file, $actor); return $response->withJson($job, 202) ->withHeader('Cache-Control', 'no-store'); } finally { CloudUploadStagingService::discard($file); } } 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; } }