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

509 lines
23 KiB
PHTML

<?php
namespace App\Controllers;
use App\Models\CloudHost;
use App\Models\CloudHostNetworkAttachment;
use App\Models\CloudJob;
use App\Models\CloudPublicIp;
use App\Models\CloudPublicIpPool;
use App\Models\CloudResourceReservation;
use App\Models\CloudResourcePool;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudAdminInstanceService;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInput;
use App\Services\Cloud\CloudJobService;
use App\Services\Cloud\CloudOperationCatalog;
use App\Services\Cloud\CloudSecrets;
use App\Services\Cloud\CloudPanelUsageService;
use App\Services\Cloud\CloudSSHKeys;
/** Administrator projections plus explicitly queued VM mutations. */
final class CloudAdminInstanceController
{
private const MAX_PUBLIC_POOLS = 32;
private const MAX_AVAILABLE_IPS_PER_POOL = 254;
public function index($request, $response)
{
return $response->withJson(CloudAdminInstanceService::page(
$request->getAttribute('cloud_actor') ?? CloudAccess::actor(false),
$request->getQueryParams()
))->withHeader('Cache-Control', 'private, no-store');
}
public function detail($request, $response, $args)
{
return $response->withJson(CloudAdminInstanceService::detail(
$request->getAttribute('cloud_actor') ?? CloudAccess::actor(false),
(string) ($args['id'] ?? '')
))->withHeader('Cache-Control', 'private, no-store');
}
/**
* Return current host network choices from the configured PHP ledger.
*
* The host Agent remains the final exact-IP claim authority when the job is
* executed; this read path deliberately does not perform a host capacity
* scan or require a host freshness marker.
*/
public function networkOptions($request, $response, $args)
{
$actor = $request->getAttribute('cloud_actor') ?? CloudAccess::actor(false);
CloudAccess::manage($actor);
$instance = CloudAccess::instance((string) ($args['id'] ?? ''), $actor);
$spec = json_decode((string) $instance->spec_json, true);
if (!is_array($spec) || array_is_list($spec)
|| ($spec['managed'] ?? false) !== true
|| ($spec['os_source'] ?? null) !== 'cloud_template'
|| !is_string($spec['public_ip_cidr'] ?? null)
|| trim($spec['public_ip_cidr']) === '') {
throw new CloudError('当前虚拟机不是支持网络配置的面板云镜像实例', 409);
}
$host = CloudHost::find($instance->host_id);
if ($host === null) {
throw new CloudError('虚拟机所属宿主机不存在,无法读取地址池', 409);
}
$reservation = $instance->reservation_id === null ? null
: CloudResourceReservation::find((int) $instance->reservation_id);
$currentPool = $reservation === null ? null
: CloudPublicIpPool::find((int) ($reservation->public_ip_pool_id ?? 0));
$attachment = $reservation === null ? null
: CloudHostNetworkAttachment::find(
(int) ($reservation->network_attachment_id ?? 0)
);
$currentIp = $reservation === null ? null
: CloudPublicIp::find((int) $reservation->public_ip_id);
$reservationPool = $reservation === null ? null
: CloudResourcePool::find((int) $reservation->resource_pool_id);
if ($reservation === null || $currentPool === null || $attachment === null
|| $currentIp === null || $reservationPool === null
|| (string) $reservation->state !== 'committed'
|| (int) $reservation->host_id !== (int) $host->id
|| (int) ($reservation->instance_id ?? 0) !== (int) $instance->id
|| (int) $reservation->resource_pool_id
!== (int) ($instance->resource_pool_id ?? 0)
|| (int) $attachment->line_id !== (int) $reservationPool->line_id
|| (int) $currentPool->host_id !== (int) $host->id
|| (int) $currentPool->network_attachment_id !== (int) $attachment->id
|| (int) $currentIp->host_id !== (int) $host->id
|| (int) ($currentIp->public_ip_pool_id ?? 0)
!== (int) $currentPool->id
|| (string) $currentIp->state !== 'assigned'
|| (int) ($currentIp->reservation_id ?? 0) !== (int) $reservation->id
|| (int) ($currentIp->instance_id ?? 0) !== (int) $instance->id
|| preg_match('/^[a-f0-9]{32}$/D',
(string) $currentPool->pool_key) !== 1
|| (int) $attachment->host_id !== (int) $host->id
|| (string) $attachment->network_selector
!== (string) $host->default_network
|| (string) $attachment->state !== 'active'
|| (string) $currentPool->state !== 'active'
|| (string) $attachment->sync_state !== 'applied'
|| (int) $attachment->observed_revision
< (int) $attachment->desired_revision
|| (string) $currentPool->sync_state !== 'applied'
|| (int) $currentPool->observed_revision
< (int) $currentPool->desired_revision) {
throw new CloudError('虚拟机公网 IP 资源预留不完整,暂不能更换地址', 409);
}
$profileMalformed = false;
$databasePools = CloudPublicIpPool::where('host_id', (int) $host->id)
->where('network_attachment_id', (int) $attachment->id)
->where('state', 'active')->orderBy('priority')->orderBy('id')
->where('sync_state', 'applied')
->whereColumn('observed_revision', '>=', 'desired_revision')
->limit(self::MAX_PUBLIC_POOLS + 1)->get();
if ($databasePools->count() > self::MAX_PUBLIC_POOLS) {
$profileMalformed = true;
$databasePools = $databasePools->take(self::MAX_PUBLIC_POOLS);
}
$availableOptions = [];
$safePools = [];
foreach ($databasePools as $databasePool) {
$poolKey = (string) $databasePool->pool_key;
$poolCidr = self::safeText($databasePool->cidr, 18);
$poolPrefix = self::safePrefix($databasePool->guest_prefix_length);
$poolGateway = self::safeIpv4($databasePool->gateway);
$poolDns = self::decodeIpList($databasePool->dns_servers_json, 4);
$poolReserved = self::decodeIpList($databasePool->reserved_ips_json, self::MAX_AVAILABLE_IPS_PER_POOL);
if (preg_match('/^[a-f0-9]{32}$/D', $poolKey) !== 1
|| $poolCidr === null || $poolPrefix === null
|| $poolGateway === null || $poolDns === null
|| $poolReserved === null || !self::cidrInPool(
$poolGateway . '/' . $poolPrefix, $poolCidr
)) {
$profileMalformed = true;
continue;
}
$blocked = array_values(array_unique([
$poolGateway, ...$poolDns, ...$poolReserved,
...array_filter([
CloudPanelUsageService::managementAddress($host),
]),
]));
$ips = CloudPublicIp::where('host_id', (int) $host->id)
->where('public_ip_pool_id', (int) $databasePool->id)
->where('state', 'available')
->whereNull('reservation_id')->whereNull('instance_id')
->whereNull('operation_id')->orderBy('id')
->limit(self::MAX_AVAILABLE_IPS_PER_POOL + 1)->get();
if ($ips->count() > self::MAX_AVAILABLE_IPS_PER_POOL) {
$profileMalformed = true;
$ips = $ips->take(self::MAX_AVAILABLE_IPS_PER_POOL);
}
$poolAvailable = 0;
foreach ($ips as $ip) {
$cidr = (string) $ip->address . '/' . (int) $ip->prefix_length;
if ((int) $ip->prefix_length !== $poolPrefix
|| !self::cidrInPool($cidr, $poolCidr)
|| in_array((string) $ip->address, $blocked, true)) {
continue;
}
$availableOptions[$poolKey . ':' . $cidr] = [
'public_pool_key' => $poolKey,
'public_ip_cidr' => $cidr,
];
$poolAvailable++;
}
$safePools[] = [
'public_pool_key' => $poolKey,
'pool_cidr' => $poolCidr,
'guest_prefix' => $poolPrefix,
'gateway' => $poolGateway,
'dns_servers' => $poolDns,
'available_count' => $poolAvailable,
];
}
$availableOptions = array_values($availableOptions);
$available = array_values(array_map(
static fn (array $option): string => $option['public_ip_cidr'],
$availableOptions
));
$currentCidr = self::safePublicIpCidr($spec['public_ip_cidr']);
$currentDns = self::decodeIpList($currentPool->dns_servers_json, 4);
$configurationState = $profileMalformed
? 'invalid' : ($safePools === [] ? 'not_configured' : 'ready');
$message = $profileMalformed
? '面板公网地址池配置异常,请先修复资源池和地址账本。'
: ($available === [] ? '当前公网地址池没有可用 IP。' : '');
$activeJob = CloudJob::where('instance_id', $instance->id)
->whereIn('status', ['queued', 'running', 'uncertain'])
->orderByDesc('id')->first(['id', 'kind', 'status', 'updated_at']);
$active = (string) $instance->status === 'active';
return $response->withJson([
'instance_id' => (string) $instance->id,
'host_id' => (string) $host->id,
'host_name' => (string) $host->name,
'region' => (string) $host->region,
'current_ip_cidr' => $currentCidr,
'current_public_pool_key' => (string) $currentPool->pool_key,
'pool_cidr' => self::safeText($currentPool->cidr, 32),
'guest_prefix' => self::safePrefix($currentPool->guest_prefix_length),
'gateway' => self::safeIpv4($currentPool->gateway),
'dns_servers' => $currentDns ?? [],
'available_ips' => $available,
'available_ip_options' => $availableOptions,
'available_count' => count($available),
'pools' => $safePools,
'configuration_state' => $configurationState,
'active_job' => $activeJob === null ? null : [
'id' => (string) $activeJob->id,
'kind' => (string) $activeJob->kind,
'status' => (string) $activeJob->status,
'updated_at' => max(0, (int) $activeJob->updated_at),
],
'can_change' => $active && $activeJob === null
&& $configurationState === 'ready' && $available !== [],
'message' => $message,
])->withHeader('Cache-Control', 'private, no-store');
}
/**
* Queue a controlled same-host public IPv4 replacement.
*
* PHP/IPAM owns the pool and claim swap. The Agent applies the signed
* network intent on the selected host. PHP updates spec_json only after
* the durable Agent operation confirms success.
*/
public function network($request, $response, $args)
{
$actor = $request->getAttribute('cloud_actor') ?? CloudAccess::actor(false);
CloudAccess::manage($actor);
$instance = CloudAccess::instance((string) ($args['id'] ?? ''), $actor, true);
if ((string) $instance->status !== 'active') {
throw new CloudError('只有处于活动状态的虚拟机可以更换公网 IP', 409);
}
$body = CloudInput::object($request);
CloudInput::only($body,
['public_ip_cidr', 'public_pool_key', 'confirm_restart']);
if (($body['confirm_restart'] ?? false) !== true) {
throw new CloudError('更换公网 IP 前必须确认虚拟机会短暂重启');
}
$cidr = CloudInput::publicIpCidr($body['public_ip_cidr'] ?? null);
$publicPoolKey = CloudInput::publicPoolKey(
$body['public_pool_key'] ?? null
);
$spec = json_decode((string) $instance->spec_json, true);
if (!is_array($spec) || array_is_list($spec)
|| ($spec['managed'] ?? false) !== true
|| ($spec['os_source'] ?? null) !== 'cloud_template') {
throw new CloudError('当前虚拟机不是支持网络配置的面板云镜像实例', 409);
}
$current = is_string($spec['public_ip_cidr'] ?? null)
? trim($spec['public_ip_cidr']) : '';
if ($current !== '' && $current === $cidr) {
throw new CloudError('新公网 IP 与当前配置相同', 409);
}
$job = CloudJobService::enqueue($instance, $actor, 'network_change', 'POST',
'/network', [
'public_ip_cidr' => $cidr,
'public_pool_key' => $publicPoolKey,
'confirm_restart' => true,
]);
return $response->withJson([
'job_id' => (string) $job->id,
'status_url' => '/api/v1/jobs/' . $job->id,
'public_ip_cidr' => $cidr,
'public_pool_key' => $publicPoolKey,
], 202)->withHeader('Cache-Control', 'no-store');
}
/**
* Queue a controlled guest-settings update for a panel-managed instance.
*
* The public-key field is intentionally parsed from this request only;
* unlike the tenant reinstall flow it never accepts an SSH-key id and
* never reads the owner's saved key collection. Password material stays
* in the encrypted job/credential path and is not returned to the browser.
*/
public function settings($request, $response, $args)
{
$actor = $request->getAttribute('cloud_actor') ?? CloudAccess::actor(false);
CloudAccess::manage($actor);
$instance = CloudAccess::instance((string) ($args['id'] ?? ''), $actor, true);
if ((string) $instance->status !== 'active') {
throw new CloudError('只有处于活动状态的虚拟机可以修改实例设置', 409);
}
$body = CloudInput::object($request);
CloudInput::only($body, ['hostname', 'root_password', 'ssh_public_key', 'confirm_restart']);
if (($body['confirm_restart'] ?? false) !== true) {
throw new CloudError('修改实例设置前必须确认虚拟机会短暂重启');
}
$spec = json_decode((string) $instance->spec_json, true);
if (!is_array($spec) || array_is_list($spec)
|| ($spec['managed'] ?? false) !== true
|| ($spec['os_source'] ?? null) !== 'cloud_template'
|| (!is_string($spec['public_ip_cidr'] ?? null)
&& !is_string($spec['public_ip'] ?? null))) {
throw new CloudError('当前虚拟机不是支持实例设置的面板云镜像实例', 409);
}
$agentBody = ['confirm_restart' => true];
$existingCredential = self::credentialSnapshot($instance);
$credential = null;
$changed = false;
if (array_key_exists('hostname', $body)) {
if (!is_string($body['hostname']) || trim($body['hostname']) === '') {
throw new CloudError('主机名不能为空');
}
$agentBody['hostname'] = CloudInput::hostname($body['hostname']);
$changed = true;
}
if (array_key_exists('root_password', $body)) {
if (!is_string($body['root_password']) || $body['root_password'] === '') {
throw new CloudError('实例密码不能为空');
}
$password = CloudInput::password($body['root_password']);
$agentBody['root_password'] = $password;
$credential = ['password' => $password, 'login_name' => 'root',
'auth_mode' => 'password'];
$changed = true;
}
if (array_key_exists('ssh_public_key', $body)) {
if (!is_string($body['ssh_public_key']) || trim($body['ssh_public_key']) === '') {
throw new CloudError('SSH 公钥不能为空');
}
// Direct input only. Do not call CloudSSHKeys::owned() here.
$parsed = CloudSSHKeys::parse($body['ssh_public_key']);
$agentBody['ssh_public_key'] = $parsed['public_key'];
$changed = true;
}
if (!$changed) {
throw new CloudError('请至少填写一项需要修改的实例设置');
}
// Keep PHP's reveal metadata aligned with the guest seed. A key-only
// change preserves an existing password marker, while a password-only
// change preserves the fact that the old key remains in the guest.
// The public key itself is deliberately not copied into this record.
if (array_key_exists('root_password', $agentBody)
|| array_key_exists('ssh_public_key', $agentBody)) {
$previousMode = (string) ($existingCredential['auth_mode'] ?? '');
$previousPassword = $existingCredential['password'] ?? null;
$savedPassword = array_key_exists('root_password', $agentBody)
? $agentBody['root_password'] : $previousPassword;
$hasPassword = is_string($savedPassword) && $savedPassword !== '';
$hasKey = array_key_exists('ssh_public_key', $agentBody)
|| in_array($previousMode,
['password_and_key', 'ssh_key', 'ssh_key_password'], true);
$credential = [
'password' => $hasPassword ? $savedPassword : null,
'login_name' => 'root',
'auth_mode' => $hasPassword
? ($hasKey ? 'password_and_key' : 'password') : 'ssh_key',
];
}
$job = CloudJobService::enqueue($instance, $actor, 'instance_settings', 'POST',
'/settings', $agentBody, $credential);
$labels = CloudOperationCatalog::labels((string) $job->kind);
return $response->withJson([
'job_id' => (string) $job->id,
'status_url' => '/api/v1/jobs/' . $job->id,
'kind' => (string) $job->kind,
'kind_label' => $labels['kind_label'],
], 202)->withHeader('Cache-Control', 'no-store');
}
/**
* Read only the existing non-key credential metadata needed to preserve
* login-mode state across an administrator settings update. A malformed
* encrypted record must not be silently replaced with an incomplete DTO.
*/
private static function credentialSnapshot($instance): ?array
{
if ($instance->sealed_credential === null) {
return null;
}
try {
$value = CloudSecrets::decrypt(
(string) $instance->sealed_credential,
'instance-credential'
);
} catch (\Throwable $exception) {
throw new CloudError('实例凭据记录异常,暂不能修改实例设置', 503);
}
if (!is_array($value)
|| !in_array($value['auth_mode'] ?? null,
['password', 'password_and_key', 'ssh_key', 'ssh_key_password'], true)
|| (($value['password'] ?? null) !== null
&& !is_string($value['password']))
|| (in_array($value['auth_mode'],
['password', 'password_and_key', 'ssh_key_password'], true)
&& (!is_string($value['password'] ?? null)
|| $value['password'] === ''))
|| ($value['auth_mode'] === 'ssh_key'
&& ($value['password'] ?? null) !== null)) {
throw new CloudError('实例凭据记录异常,暂不能修改实例设置', 503);
}
return ['auth_mode' => (string) $value['auth_mode'],
'password' => $value['password'] ?? null];
}
private static function safeText($value, int $length): ?string
{
if (!is_string($value) || trim($value) !== $value || $value === ''
|| strlen($value) > $length || preg_match('/[\x00-\x1f\x7f]/', $value) === 1) {
return null;
}
return $value;
}
private static function safePrefix($value): ?int
{
return is_int($value) && $value >= 24 && $value <= 30 ? $value : null;
}
private static function safeIpv4($value): ?string
{
return is_string($value) && trim($value) === $value
&& filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false
? $value : null;
}
private static function safeIpv4List($value, int $limit): array
{
if (!is_array($value)) {
return [];
}
$result = [];
foreach (array_slice($value, 0, $limit) as $item) {
$ip = self::safeIpv4($item);
if ($ip !== null) {
$result[] = $ip;
}
}
return array_values(array_unique($result));
}
private static function decodeIpList($value, int $limit): ?array
{
try {
$decoded = json_decode((string) $value, true, 16, JSON_THROW_ON_ERROR);
} catch (\Throwable $error) {
return null;
}
if (!is_array($decoded) || !array_is_list($decoded)
|| count($decoded) > $limit) {
return null;
}
$result = [];
foreach ($decoded as $item) {
$ip = self::safeIpv4($item);
if ($ip === null) {
return null;
}
$result[] = $ip;
}
return array_values(array_unique($result));
}
private static function safePublicIpCidr($value): ?string
{
try {
$cidr = CloudInput::publicIpCidr($value);
} catch (\Throwable $error) {
return null;
}
[$address, $prefix] = explode('/', $cidr, 2);
$prefix = (int) $prefix;
return $prefix >= 24 && $prefix <= 30 ? $address . '/' . $prefix : null;
}
private static function cidrInPool(string $cidr, $pool): bool
{
$target = self::ipv4Number(explode('/', $cidr, 2)[0]);
$parts = is_string($pool) ? explode('/', trim($pool), 2) : [];
$network = isset($parts[0], $parts[1]) ? self::ipv4Number($parts[0]) : null;
$prefix = isset($parts[1]) && ctype_digit($parts[1]) ? (int) $parts[1] : -1;
if ($target === null || $network === null || $prefix < 24 || $prefix > 30) {
return false;
}
$block = 2 ** (32 - $prefix);
if (floor($target / $block) !== floor($network / $block)) {
return false;
}
$networkBase = floor($network / $block) * $block;
return $target !== $networkBase && $target !== $networkBase + $block - 1;
}
private static function ipv4Number($value): ?int
{
if (!is_string($value) || filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
return null;
}
$packed = inet_pton($value);
if ($packed === false || strlen($packed) !== 4) {
return null;
}
$parts = unpack('Nnumber', $packed);
return is_array($parts) && isset($parts['number'])
? (int) sprintf('%u', $parts['number']) : null;
}
}