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

593 lines
33 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\Services\Cloud;
use App\Services\Config;
use GuzzleHttp\Client;
final class CloudEngineClient
{
private float $timeoutSeconds;
public function __construct(private ?Client $client = null, float $timeoutSeconds = 20.0)
{
if ($timeoutSeconds < 1 || $timeoutSeconds > 900) {
throw new \InvalidArgumentException('Engine timeout is outside the supported range');
}
$this->timeoutSeconds = $timeoutSeconds;
$this->client ??= new Client(['connect_timeout' => 3, 'timeout' => $timeoutSeconds, 'http_errors' => false,
'allow_redirects' => false]);
}
public static function canonical(string $method, string $path, string $body, string $timestamp, string $nonce, string $actor): string
{
return self::canonicalDigest($method, $path, hash('sha256', $body), $timestamp, $nonce, $actor);
}
public static function canonicalDigest(string $method, string $path, string $digest, string $timestamp, string $nonce, string $actor): string
{
return strtoupper($method) . "\n" . $path . "\n" . $digest . "\n"
. $timestamp . "\n" . $nonce . "\n" . $actor;
}
public static function headers(string $method, string $path, string $body, array $actor, ?int $now = null, ?string $nonce = null): array
{
$encoded = rtrim(strtr(base64_encode(json_encode($actor, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES)), '+/', '-_'), '=');
$timestamp = (string) ($now ?? time());
$nonce ??= bin2hex(random_bytes(16));
return ['X-Cloud-Timestamp' => $timestamp, 'X-Cloud-Nonce' => $nonce, 'X-Cloud-Actor' => $encoded,
'X-Cloud-Signature' => hash_hmac('sha256', self::canonical($method, $path, $body, $timestamp, $nonce, $encoded),
CloudSecrets::key('engine_hmac_key')), 'Content-Type' => 'application/json'];
}
public function request(string $method, string $path, array $actor, ?array $payload = null,
?string $expectedOperationId = null): array
{
$base = $this->base($path);
$body = $payload === null ? '' : json_encode($payload === [] ? (object) [] : $payload,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
return $this->send($method, $base . $path, [
'headers' => self::headers($method, $path, $body, $actor), 'body' => $body,
], $expectedOperationId, $path);
}
private function base(string $path): string
{
$base = rtrim((string) Config::get('cloud_engine_url', 'http://127.0.0.1:8000'), '/');
$url = parse_url($base);
if (!is_array($url) || ($url['scheme'] ?? '') !== 'http'
|| !in_array($url['host'] ?? '', ['127.0.0.1', '[::1]', '::1'], true)
|| isset($url['user']) || isset($url['pass']) || isset($url['query']) || isset($url['fragment'])
|| (($url['path'] ?? '') !== '' && ($url['path'] ?? '') !== '/')
|| !str_starts_with($path, '/internal/v1/') || preg_match('/[\r\n\\\\]/', $path)) {
throw new CloudError('引擎地址必须为固定本机回环地址', 503);
}
return $base;
}
private function send(string $method, string $url, array $options,
?string $expectedOperationId = null, ?string $signedPath = null): array
{
try {
$response = $this->client->request($method, $url, $options + [
'allow_redirects' => false, 'http_errors' => false, 'proxy' => '',
]);
} catch (\GuzzleHttp\Exception\ConnectException $exception) {
throw new CloudError('虚拟化引擎连接失败或请求超时,正在核对结果', 502);
} catch (\Throwable $exception) {
throw new CloudError('虚拟化引擎响应不确定,请等待任务核对', 502);
}
$result = json_decode((string) $response->getBody(), true);
if (!is_array($result)) {
throw new CloudError('虚拟化引擎响应不确定,请等待任务核对', 502);
}
if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) {
// A VM mutation can return a non-2xx HTTP status together with a
// durable, signed operation outcome. Only the worker that knows
// the exact operation ID may consume it; all ordinary API callers
// still receive an exception for every non-2xx response.
if ($expectedOperationId !== null
&& preg_match('/^[A-Za-z0-9_-]{8,80}$/D', $expectedOperationId) === 1
&& ($result['operation_id'] ?? null) === $expectedOperationId
&& in_array($result['status'] ?? null, ['failed', 'uncertain'], true)
&& is_bool($result['safe_to_refund'] ?? null)) {
$result['_engine_http_status'] = $response->getStatusCode();
return $result;
}
$safeVpcServerErrorCode = self::safeVpcServerErrorCode(
$method, $signedPath, $result, $response->getStatusCode()
);
if ($safeVpcServerErrorCode === 'vpc_delete_incomplete') {
throw new CloudError(
'VPC 宿主机清理尚未全部确认,请稍后重新核对',
503,
$safeVpcServerErrorCode
);
}
// Only explicitly reviewed endpoint-specific policies return
// short, credential-free guidance useful to the caller. Do not
// turn this into a general engine-error passthrough: arbitrary
// errors may contain host paths, credentials or private data.
$safeError = self::safeAllowlistedError(
$signedPath, $result, $response->getStatusCode()
);
if ($safeError !== null) {
throw new CloudError($safeError, $response->getStatusCode());
}
// Never expose engine tracebacks, host credentials or arbitrary upstream strings.
throw new CloudError('虚拟化操作未成功(引擎状态 ' . $response->getStatusCode() . ')',
$response->getStatusCode() === 404 ? 404 : 502);
}
return $result;
}
private static function safeVpcServerErrorCode(
string $method, ?string $path, array $result, ?int $status = null
): ?string
{
if (strtoupper($method) !== 'POST' || $status !== 503 || $path === null
|| ($result['error_code'] ?? null) !== 'vpc_delete_incomplete') {
return null;
}
return preg_match(
'#^/internal/v1/vpcs/[0-9a-f]{32}/delete$#D', $path
) === 1 ? 'vpc_delete_incomplete' : null;
}
private static function safeAllowlistedError(?string $path, array $result, ?int $status = null): ?string
{
if ($path === null) {
return null;
}
$parts = explode('?', $path, 2);
$route = $parts[0];
if (count($parts) === 2
&& $route !== '/internal/v1/vm-templates/upload') {
return null;
}
$update = preg_match(
'#^/internal/v1/update/(?:settings|check|apply|jobs/[A-Za-z0-9_-]{16,64})$#D', $route
) === 1;
$userIso = preg_match(
'#^/internal/v1/user-isos(?:/import|/[0-9a-f]{32}|/import-jobs/[A-Za-z0-9_-]{8,80})?$#D',
$route
) === 1;
$vmTemplate = preg_match(
'#^/internal/v1/vm-templates(?:/(?:import|upload)|/[A-Za-z0-9_-]{8,80}|/import-jobs/[A-Za-z0-9_-]{8,80})?$#D',
$route
) === 1;
$host = preg_match(
'#^/internal/v1/hosts/[1-9][0-9]*/host(?:/test)?$#D', $route
) === 1;
$hostNetworkPool = preg_match(
'#^/internal/v1/hosts/[1-9][0-9]*/host/network-pools/[0-9a-f]{32}$#D',
$route
) === 1;
$vpc = preg_match(
'#^/internal/v1/vpcs(?:/(?:apply|[0-9a-f]{32}(?:/(?:reconcile|delete))?))?$#D',
$route
) === 1;
$fabric = preg_match(
'#^/internal/v1/fabric(?:/(?:probe|apply|[A-Za-z0-9][A-Za-z0-9_.-]{0,63}/reconcile|[A-Za-z0-9][A-Za-z0-9_.-]{0,63}))?$#D',
$route
) === 1;
if (!$update && !$userIso && !$vmTemplate && !$host
&& !$hostNetworkPool && !$vpc && !$fabric) {
return null;
}
if ($hostNetworkPool) {
// Preserve only reviewed validation/conflict statuses so the
// desired-state service can distinguish a definitive rejection
// from an ambiguous transport failure. Never expose free-form
// engine detail, which can contain host-specific diagnostics.
return in_array($status, [400, 409, 422], true)
? '公网地址池配置未通过引擎校验'
: null;
}
if ($vpc) {
return in_array($status, [400, 404, 409, 422], true)
? self::safeVpcErrorMessage($result['error_code'] ?? null)
: null;
}
if ($fabric) {
return in_array($status, [400, 404, 409, 422], true)
? self::safeFabricErrorMessage($result['error_code'] ?? null)
: null;
}
if ($host) {
// Host errors may describe validation failures, SSH transport
// failures or damaged engine state with the same fallback code.
// Only reviewed client-error statuses may cross this boundary;
// 5xx responses keep the generic 502 message below.
if (!in_array($status, [400, 409, 422], true)) {
return null;
}
return self::safeHostErrorMessage($result['error_code'] ?? null);
}
$detail = $result['error'] ?? ($result['detail'] ?? null);
if (!is_string($detail)) {
return null;
}
$detail = trim($detail);
if ($detail === '' || strlen($detail) > 500 || preg_match('//u', $detail) !== 1
|| preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', $detail) === 1) {
return null;
}
if ($userIso) {
return self::safeUserIsoMessage($detail)
?? '用户 ISO 操作未成功,请稍后重试或联系管理员';
}
if ($vmTemplate) {
return self::safeVmTemplateMessage($detail);
}
// Update responses are administrator-only, but the upstream message
// can still contain a checkout path, remote URL, token or command.
// Keep the useful bounded summary while applying the same unconditional
// redaction boundary used by the operation DTOs.
return CloudOperationErrorCatalog::adminSummary(null, null, $detail)
?? '在线更新请求未成功,请查看更新任务日志';
}
private static function safeHostErrorMessage($value): ?string
{
if (!is_string($value)) {
return null;
}
return [
'host_configuration_invalid' => '宿主机配置无效,请检查地址、端口、存储目录和默认网络',
'host_private_key_required' => '首次添加宿主机必须提供现有 SSH 私钥',
'host_private_key_format_invalid' => 'SSH 私钥格式无效,请提供 PEM 或 OpenSSH 格式私钥',
'host_private_key_passphrase_required' => 'SSH 私钥已加密,请填写私钥解锁口令',
'host_private_key_invalid' => 'SSH 私钥或解锁口令无效,请检查后重试',
'host_public_pool_invalid' => '公网地址池配置无效,请完整填写可路由的 IPv4 网段、网关和 DNS(网段前缀 /24 至 /30)',
'host_public_gateway_invalid' => '公网网关无效,必须位于所配置的公网地址池内',
'host_public_dns_invalid' => '公网 DNS 无效,请填写最多 4 个可路由的 IPv4 地址',
'host_public_reserved_ip_invalid' => '保留 IP 配置无效,请填写地址池内的 IPv4 地址,最多 254 个',
'host_vm_prefix_invalid' => '客户机网络前缀无效,必须介于 /24 和地址池前缀之间',
'host_fabric_endpoint_invalid' => 'Fabric 传输地址无效,请填写可用的公网或内网 IPv4 地址',
'host_fabric_endpoint_not_local' => 'Fabric 传输地址不属于该宿主机,请填写宿主机实际持有的 IPv4 地址',
][$value] ?? null;
}
private static function safeVpcErrorMessage($value): ?string
{
if (!is_string($value)) {
return null;
}
return [
'vpc_invalid' => 'VPC 目标策略无效',
'vpc_not_found' => 'VPC 不存在',
'vpc_fabric_inactive' => '宿主机 WireGuard Fabric 尚未全部就绪',
'vpc_fabric_revision_conflict' => '宿主机 Fabric 版本不一致,请稍后重试',
'vpc_fabric_region_mismatch' => 'VPC 与宿主机 Fabric 地区不一致',
'vpc_fabric_revision_mismatch' => '宿主机 Fabric 版本不一致,请稍后重试',
'vpc_fabric_not_active' => '宿主机 WireGuard Fabric 尚未全部就绪',
'vpc_fabric_host_missing' => 'VPC 参与宿主机不在 Fabric 中',
'vpc_fabric_endpoint_overlap' => 'VPC CIDR 与 Fabric 传输地址冲突,请先调整地址规划',
'vpc_dataplane_firewall_mode_conflict' => '宿主机防火墙与 VPC 数据面模式冲突',
'vpc_dataplane_network_manager_conflict' => '宿主机网络管理器与 VPC 数据面模式冲突',
'vpc_no_participating_hosts' => 'VPC 尚未绑定参与宿主机',
'vpc_no_members' => 'VPC 尚未绑定私网成员',
'vpc_operation_required' => 'VPC 操作身份缺失,请刷新后重试',
'vpc_revision_conflict' => 'VPC 目标版本已变化,请刷新后重试',
'vpc_digest_conflict' => 'VPC 目标摘要不一致,请刷新后重试',
'vpc_observed_host_invalid' => 'VPC 宿主机回读不完整,请稍后重试',
'vpc_host_observation_missing' => 'VPC 宿主机回读不完整,正在核对',
'vpc_record_corrupt' => 'VPC 控制面记录损坏,请联系管理员',
'vpc_observation_incomplete' => 'VPC 宿主机回读未完成,正在核对',
'vpc_data_plane_deferred' => 'VPC 私网数据面尚未启用',
'vpc_private_dataplane_unverified' => 'VPC 私网数据面回读未通过,正在核对',
'vpc_private_readback_missing' => 'VPC 私网宿主机回读缺失,正在核对',
'vpc_private_readback_mismatch' => 'VPC 私网宿主机回读不一致,正在核对',
'vpc_private_nic_readback_mismatch' => 'VPC 私网网卡回读不一致,正在核对',
'vpc_private_route_readback_mismatch' => 'VPC 私网路由回读不一致,正在核对',
'vpc_private_wireguard_readback_missing' => 'VPC WireGuard 私网回读缺失,正在核对',
'vpc_private_wireguard_readback_mismatch' => 'VPC WireGuard 私网路由回读不一致,正在核对',
'vpc_private_dataplane_readback_mismatch' => 'VPC 私网数据面回读不一致,正在核对',
'vpc_operation_mismatch' => 'VPC 引擎结果身份不一致,正在核对',
'vpc_delete_manifest_invalid' => 'VPC 删除成员清单无效,请刷新后重试',
'vpc_delete_manifest_mismatch' => 'VPC 删除成员清单与当前目标不一致,正在核对',
'vpc_delete_target_not_empty' => 'VPC 删除目标仍包含活动资源,请刷新后重试',
'vpc_delete_host_set_mismatch' => 'VPC 删除宿主机集合不一致,正在核对',
'vpc_delete_receipt_conflict' => 'VPC 删除回执与当前操作冲突,请联系管理员',
'vpc_private_remove_requires_stopped' => 'VPC 成员虚拟机仍在运行,请先关机后重试删除',
'vpc_private_remove_unsafe' => 'VPC 成员存在 managed-save 或原生快照,暂不能移除私网',
'vpc_private_interface_conflict' => 'VPC 私网网卡身份不一致,请联系管理员核对',
'vpc_seed_missing' => 'VPC 成员 cloud-init 配置盘缺失,无法确认私网清理',
'vpc_seed_readback_invalid' => 'VPC 成员 cloud-init 配置盘无法核对,请联系管理员',
'vpc_seed_network_policy_migration_required' => 'VPC 成员仍使用旧版 cloud-init 网络策略,需要迁移后再删除',
'vpc_private_xml_invalid' => 'VPC 成员持久化 XML 无效,无法确认私网清理',
'vpc_deleted' => 'VPC 已删除,不能重新应用旧目标',
'vpc_deleting' => 'VPC 正在删除,不能应用普通变更',
][$value] ?? null;
}
private static function safeFabricErrorMessage($value): ?string
{
if (!is_string($value)) {
return null;
}
return [
'fabric_invalid' => 'Fabric 计划无效',
'fabric_not_found' => 'Fabric 不存在',
'fabric_record_corrupt' => 'Fabric 持久化记录损坏,请联系管理员处理',
'fabric_revision_conflict' => 'Fabric 版本冲突,请提升 revision 后重试',
'fabric_region_conflict' => 'Fabric 地区不能直接变更,请走迁移流程',
'fabric_membership_conflict' => 'Fabric 参与宿主机集合不能直接变更',
'fabric_host_interface_conflict' => '参与宿主机已加入其他 Fabric',
'fabric_overlay_conflict' => 'Fabric overlay 网段与已有 Fabric 冲突',
'fabric_host_unavailable' => 'Fabric 参与宿主机暂不可用',
'fabric_host_capability_probe_unsupported' => '宿主机不支持能力重新探测',
'fabric_host_capability_probe_failed' => '宿主机能力重新探测失败',
'fabric_host_capability_probe_invalid' => '宿主机能力探测结果无效',
'fabric_probe_busy' => '已有地区宿主机检测正在运行,请稍后重试',
'fabric_host_not_configured' => 'Fabric 参与宿主机尚未完成配置',
'fabric_host_identity_mismatch' => 'Fabric 宿主机身份不一致',
'fabric_host_capability_missing' => '宿主机未通过 Fabric 能力核验',
'fabric_endpoint_invalid' => 'Fabric 传输地址配置无效',
'fabric_endpoint_missing' => 'Fabric 宿主机缺少可用的 IPv4 传输地址',
'fabric_endpoint_mismatch' => 'Fabric 固定计划与宿主机当前传输地址不一致,需要迁移',
'fabric_endpoint_not_local' => 'Fabric 传输地址不属于对应宿主机',
'fabric_endpoint_interface_unverified' => '无法唯一确认 Fabric 传输地址对应的宿主机接口',
'fabric_endpoint_interface_unsafe_or_drifted' => 'Fabric 传输接口不安全或与当前配置不一致',
'fabric_endpoint_rp_filter_unverified' => '无法确认 Fabric 传输接口的 rp_filter',
'fabric_endpoint_vpc_conflict' => 'Fabric 传输地址与现有 VPC CIDR 冲突',
'fabric_vpc_record_corrupt' => 'VPC 资源目录损坏,无法确认 Fabric 地址安全性',
'firewalld_unsupported_requires_maintenance' => 'firewalld 不再受支持;请在维护窗口清理旧所有权状态并启用原生 nftables',
'legacy_firewalld_state_requires_cleanup' => '检测到旧 firewalld 规则或事务状态;必须在维护窗口备份并清理后重建原生 nftables 数据面',
'firewall_transaction_requires_recovery_or_cleanup' => '检测到未收敛的防火墙事务;请先完成恢复或在维护窗口清理',
'legacy_firewall_evidence_invalid' => '无法安全核验宿主的旧防火墙状态;已禁止 VPC 变更',
'fabric_host_firewall_mode_conflict' => '宿主机防火墙与 Fabric 部署模式冲突',
'fabric_host_network_manager_conflict' => '宿主机网络管理器与 Fabric 部署模式冲突',
'fabric_identity_conflict' => 'Fabric 宿主机公钥身份冲突',
'fabric_identity_invalid' => 'Fabric 宿主机公钥回读无效',
'fabric_apply_unconfirmed' => '宿主机未确认 Fabric 应用结果',
'fabric_readback_invalid' => 'Fabric 宿主机回读结果无效',
'fabric_host_connection_failed' => 'Fabric 宿主机连接失败',
'fabric_host_key_locked' => 'Fabric 宿主机 SSH 私钥仍锁定',
'fabric_runner_unsupported' => '宿主机不支持 Fabric 执行器',
'fabric_operation_busy' => '该 Fabric 已有宿主机任务正在执行,请等待状态回读',
'fabric_operation_invalid' => 'Fabric operation 标识或类型无效',
'fabric_operation_limit' => '宿主机 Fabric operation 记录已达安全上限,请先核对状态',
'fabric_operation_not_found' => '宿主机已无法读取该 Fabric operation 状态',
'fabric_operation_reconcile_required' => '上次 Fabric operation 结果仍需按原标识核对',
'fabric_operation_status_invalid' => '宿主机 Fabric operation 状态记录无效',
'fabric_operation_status_timeout' => 'Fabric operation 状态回读超时,请按原标识继续核对',
'fabric_operation_interrupted' => 'Fabric operation 协调过程被中断,请按原标识重新核对',
'fabric_readback_mismatch' => '宿主机 Fabric 最终回读与固定方案不一致',
'fabric_remote_command_failed' => '宿主机 Fabric 命令执行失败',
'fabric_plan_corrupt' => 'Fabric 计划损坏',
][$value] ?? null;
}
public static function safeVmTemplateMessage($value): ?string
{
if (!is_string($value)) {
return null;
}
$value = trim($value);
$allowed = [
'云镜像导入参数无效', '云镜像名称无效', '云镜像地址无效',
'仅支持 AlmaLinux 官方仓库的 9/10 x86_64 GenericCloud qcow2 镜像',
'仅支持 AlmaLinux、Debian、Ubuntu 和 CentOS Stream 官方 x86_64 云镜像直链',
'官方镜像地址发生重定向,请使用最终的官方 HTTPS 直链',
'官方云镜像地址无法解析', '官方云镜像地址解析结果无效',
'官方云镜像地址解析到非公网地址',
'无法连接官方云镜像下载地址', '官方云镜像重定向目标不安全',
'官方云镜像重定向次数过多', '官方云镜像下载服务器返回异常状态',
'官方云镜像下载响应格式无效',
'模板名称应为 1 至 64 个字符', '模板名称不能包含控制字符',
'云镜像系统版本无效', '模板标识无效', '云镜像模板范围无效',
'云镜像上传参数无效', '云镜像系统或版本不受支持',
'云镜像上传请求头重复',
'云镜像上传必须使用 application/octet-stream',
'云镜像上传内容不能压缩', '云镜像上传长度无效',
'云镜像上传内容超过声明长度', '云镜像上传内容不完整',
'云镜像上传已中断',
'云镜像上传请求无效', '云镜像上传超时',
'云镜像文件不能小于 1 MiB',
'云镜像摘要与签名不匹配',
'上传文件不是有效的 qcow2 镜像',
'面板未安装 qemu-img,无法验证云镜像',
'云镜像完整性检查失败',
'云镜像 SHA-256 格式无效',
'SHA-256 可留空;填写时必须为 64 位十六进制校验值',
'云镜像导入任务不存在', '云镜像模板不存在',
'云镜像正在导入,请稍后修改模板名称',
'云镜像正在导入,请稍后删除模板',
'云镜像正在同步到宿主机,请稍后删除',
'云镜像删除参数无效',
'云镜像版本已变化,请刷新后重试',
'云镜像目录记录损坏,无法安全删除',
'云镜像源文件无法安全删除',
'云镜像源文件删除失败,请联系管理员',
'云镜像缓存清理记录损坏,请联系管理员',
'云镜像版本记录损坏,请联系管理员',
'旧云镜像缓存仍在清理,请稍后重新导入',
'此云镜像已经导入', '已有同名云镜像模板', '该云镜像正在导入',
'已有云镜像正在导入,请等待完成后再提交',
'引擎正在停止,无法开始云镜像导入',
'面板在云镜像导入期间重启;请重新提交导入',
'下载官方云镜像失败,请检查面板服务器网络',
'云镜像下载超过 60 分钟,请检查面板服务器网络',
'云镜像下载内容不完整', '云镜像超过 4 GiB 限制',
'云镜像 SHA-256 不匹配,已丢弃下载内容',
'下载文件不是有效的 qcow2 镜像', '云镜像 qcow2 版本或簇大小不受支持',
'云镜像 qcow2 头部不完整', '云镜像包含不受支持或外部依赖的 qcow2 特性',
'云镜像含外部依赖、加密或容量超出支持范围',
'云镜像无法保存到持久目录', '面板云镜像持久目录空间不足',
'云镜像导入失败,请查看引擎日志',
'云镜像下载或保存失败,请联系管理员查看日志',
];
return in_array($value, $allowed, true) ? $value : null;
}
public static function safeUserIsoMessage($value): ?string
{
if (!is_string($value)) {
return null;
}
$value = trim($value);
$allowed = [
'ISO 标识无效', 'ISO 名称应为 1 至 64 个字符', 'ISO 名称不能包含控制字符',
'ISO 下载地址无效', 'ISO 仅支持无账号、无跳转的 HTTPS 443 直链',
'ISO 下载地址的文件名必须以 .iso 结尾',
'ISO 下载地址必须使用 ASCII/百分号编码', 'ISO 下载地址包含无效字符',
'ISO 下载地址无法解析', 'ISO 下载地址解析结果无效',
'ISO 下载地址不能指向内网、回环或保留地址', '无法连接 ISO 下载地址',
'ISO 下载响应长度无效', 'ISO 大小必须在 1 MiB 至可用配额之间',
'下载文件不是有效的 ISO 9660 镜像', 'ISO 未包含可识别的 El Torito 启动记录',
'SHA-256 可留空;填写时必须为 64 位十六进制校验值', '用户 ISO 可用配额不足',
'ISO 下载地址发生重定向,请使用最终 HTTPS 直链', 'ISO 下载响应不能使用内容压缩',
'ISO 超过用户目录的 10 GiB 总配额或剩余容量',
'ISO 超过用户全局目录的 10 GiB 配额或剩余容量',
'ISO 下载超时', 'ISO 下载内容不完整',
'ISO 的 SHA-256 校验值不匹配', 'ISO 不存在或不属于当前用户',
'ISO 导入任务不存在', '每个宿主机最多保存 5 个用户 ISO',
'每个用户最多保存 5 个 ISO',
'用户 ISO 目录的 10 GiB 存储配额已用完', '用户 ISO 目录总容量不能超过 10 GiB',
'用户 ISO 全局目录的 10 GiB 存储配额已用完', '用户 ISO 全局目录总容量不能超过 10 GiB',
'面板用户 ISO 持久目录空间不足', 'ISO 无法保存到面板持久目录',
'当前宿主机已有同名用户 ISO', '当前用户已有同名 ISO',
'已有用户 ISO 正在导入,请等待完成', '用户 ISO 正在导入,请稍后删除',
'ISO 正在同步到宿主机,请稍后删除', '宿主机用户 ISO 存储空间不足',
'用户 ISO 存储目录不可用,请联系管理员', '用户 ISO 仍被虚拟机安装过程引用,不能删除',
'引擎正在停止,无法开始 ISO 导入', 'ISO 下载或导入失败,请联系管理员查看日志',
'ISO 下载或保存失败,请联系管理员查看日志',
'面板在 ISO 下载期间重启;请重新提交导入',
'面板在任务执行期间重启;请检查宿主机实际状态,勿直接重复提交',
];
if (in_array($value, $allowed, true)
|| preg_match('/^ISO 下载服务器返回 HTTP [1-5][0-9]{2}$/D', $value) === 1) {
return $value;
}
return null;
}
public function upload(string $path, array $actor, string $filename): array
{
$base = $this->base($path);
$digest = hash_file('sha256', $filename);
if ($digest === false) {
throw new CloudError('上传文件无法读取', 503);
}
$headers = self::headers('POST', $path, '', $actor);
$headers['X-Cloud-Signature'] = hash_hmac('sha256', self::canonicalDigest('POST', $path, $digest,
$headers['X-Cloud-Timestamp'], $headers['X-Cloud-Nonce'], $headers['X-Cloud-Actor']), CloudSecrets::key('engine_hmac_key'));
$headers['X-Cloud-Content-SHA256'] = $digest;
$headers['Content-Type'] = 'application/octet-stream';
$stream = fopen($filename, 'rb');
if ($stream === false) {
throw new CloudError('上传文件无法读取', 503);
}
try {
return $this->send('POST', $base . $path, ['headers' => $headers, 'body' => $stream, 'timeout' => 900], null, $path);
} finally {
// Guzzle's PSR-7 stream owns and may close the supplied resource
// before request() returns. Avoid replacing the real engine
// response with a PHP 8 TypeError from closing it a second time.
if (is_resource($stream)) {
fclose($stream);
}
}
}
public function host(int $hostId, string $method, string $resource, array $actor,
?array $payload = null, ?string $expectedOperationId = null): array
{
if ($hostId < 1) {
throw new CloudError('宿主机不存在', 404);
}
return $this->request($method, '/internal/v1/hosts/' . $hostId . '/' . $resource,
$actor, $payload, $expectedOperationId);
}
/**
* Global, tenant-scoped VPC control-plane endpoint. Unlike host(), the
* resource is never interpolated with a host id and cannot reuse the
* public network_change route.
*/
public function vpc(string $method, string $resource, array $actor,
?array $payload = null, ?string $expectedOperationId = null): array
{
if (!preg_match(
'#^/internal/v1/vpcs(?:/(?:apply|[0-9a-f]{32}(?:/(?:reconcile|delete))?))?$#D',
$resource
)) {
throw new CloudError('VPC 引擎资源路径无效', 422);
}
return $this->request($method, $resource, $actor, $payload, $expectedOperationId);
}
/**
* Read engine-global Fabric status through the bounded admin route.
* Read access is available to administrators; mutation methods below
* enforce the separate super-admin/manage capability.
*/
public function fabricStatuses(array $actor): array
{
if (!($actor['is_admin'] ?? false)) {
throw new CloudError('Fabric 状态查询参数无效', 422);
}
return $this->request('GET', '/internal/v1/fabric', $actor);
}
public function fabricStatus(string $fabricId, array $actor): array
{
if (!preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/D', $fabricId)
|| !($actor['is_admin'] ?? false)) {
throw new CloudError('Fabric 状态查询参数无效', 422);
}
return $this->request('GET', '/internal/v1/fabric/' . $fabricId, $actor);
}
public function fabricApply(array $plan, array $actor): array
{
self::assertFabricWriteActor($actor);
return $this->request('POST', '/internal/v1/fabric/apply', $actor, $plan);
}
public function fabricProbe(array $hostIds, array $actor): array
{
self::assertFabricWriteActor($actor);
if ($hostIds === [] || count($hostIds) > 64) {
throw new CloudError('地区宿主机数量必须介于 1 到 64 台', 422);
}
$normalized = [];
foreach ($hostIds as $hostId) {
$value = is_int($hostId) ? (string) $hostId : $hostId;
if (!is_string($value)
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/D', $value) !== 1
|| isset($normalized[$value])) {
throw new CloudError('地区宿主机标识无效或重复', 422);
}
$normalized[$value] = true;
}
return $this->request('POST', '/internal/v1/fabric/probe', $actor, [
// PHP coerces numeric-string array keys to integers, while the
// engine contract intentionally accepts only stable string IDs.
'host_ids' => array_map('strval', array_keys($normalized)),
]);
}
public function fabricReconcile(string $fabricId, array $actor): array
{
if (!preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/D', $fabricId)) {
throw new CloudError('Fabric 标识无效', 422);
}
self::assertFabricWriteActor($actor);
return $this->request(
'POST', '/internal/v1/fabric/' . $fabricId . '/reconcile', $actor, []
);
}
private static function assertFabricWriteActor(array $actor): void
{
if (!($actor['is_admin'] ?? false)
|| !($actor['is_super_admin'] ?? false)
|| !($actor['can_manage'] ?? false)) {
throw new CloudError('仅超级管理员可以修改 Fabric', 403);
}
}
}