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

459 lines
19 KiB
PHTML

<?php
namespace App\Controllers;
use App\Models\CloudInstanceBackup;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudAdminInstanceService;
use App\Services\Cloud\CloudBackupService;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInput;
use App\Services\Cloud\CloudInstanceMigrationService;
use App\Services\Cloud\CloudJobService;
use App\Services\Cloud\CloudNetworkChangeOptionsService;
use App\Services\Cloud\CloudPublicNetworkTransitionCommand;
use App\Services\Cloud\CloudPublicNetworkTransitionWorkflow;
use App\Services\Cloud\CloudInstanceSettingsGuard;
use App\Services\Cloud\CloudSecrets;
use App\Services\Cloud\CloudSSHKeys;
/** Administrator projections plus explicitly queued VM mutations. */
final class CloudAdminInstanceController
{
private function actor($request, bool $write = false): array
{
$actor = $request->getAttribute('cloud_actor')
?? CloudAccess::actor(false);
if (!$write) {
return $actor;
}
CloudAccess::manage($actor);
$key = trim((string) $request->getHeaderLine('Idempotency-Key'));
if ($key === ''
|| preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $key) !== 1) {
throw new CloudError('管理员写操作需要有效的幂等标识', 400);
}
$actor['request_idempotency_key'] = $key;
return $actor;
}
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');
}
/** Read the portable backup catalog or queue one object-storage backup. */
public function backups($request, $response, $args)
{
$write = $request->getMethod() === 'POST';
$actor = $this->actor($request, $write);
$instance = CloudAccess::instance(
(string) ($args['id'] ?? ''),
$actor,
$write
);
if (!$write) {
return $response->withJson(
CloudBackupService::listing($instance, $actor)
)->withHeader('Cache-Control', 'private, no-store');
}
$queued = CloudBackupService::create(
$instance,
$actor,
CloudInput::object($request)
);
$job = $queued['job'] ?? null;
if (!is_object($job) || !isset($job->id)) {
throw new CloudError('备份任务回执无效,必须人工核查', 503);
}
return $response->withJson(CloudJobService::acknowledgement($job), 202)
->withHeader('Cache-Control', 'no-store');
}
public function startMaintenanceMigration($request, $response, $args)
{
$actor = $this->actor($request, true);
$instance = CloudAccess::instance(
(string) ($args['id'] ?? ''),
$actor,
true
);
$queued = CloudInstanceMigrationService::start(
$instance,
$actor,
CloudInput::object($request)
);
$job = $queued['job'] ?? null;
if (!is_object($job) || !isset($job->id)) {
throw new CloudError('维护迁移任务回执无效,必须人工核查', 503);
}
return $response->withJson(CloudJobService::acknowledgement($job), 202)
->withHeader('Cache-Control', 'no-store');
}
public function cleanupMaintenanceMigration($request, $response, $args)
{
$actor = $this->actor($request, true);
$instance = CloudAccess::instance(
(string) ($args['id'] ?? ''),
$actor,
true
);
$job = CloudInstanceMigrationService::cleanupRetained(
$instance,
$actor,
CloudInput::object($request)
);
return $response->withJson(CloudJobService::acknowledgement($job), 202)
->withHeader('Cache-Control', 'no-store');
}
public function recoverMaintenanceMigration($request, $response, $args)
{
$actor = $this->actor($request, true);
$instance = CloudAccess::instance(
(string) ($args['id'] ?? ''),
$actor,
true
);
$job = CloudInstanceMigrationService::recover(
$instance,
$actor,
CloudInput::object($request)
);
return $response->withJson(CloudJobService::acknowledgement($job), 202)
->withHeader('Cache-Control', 'no-store');
}
/** Backup-ledger catalog which remains available after source VM removal. */
public function backupLibrary($request, $response)
{
return $response->withJson(CloudBackupService::library(
$this->actor($request),
$request->getQueryParams()
))->withHeader('Cache-Control', 'private, no-store');
}
public function restoreLibraryBackup($request, $response, $args)
{
$actor = $this->actor($request, true);
$backupId = filter_var($args['backup_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$backup = $backupId === false ? null
: CloudInstanceBackup::find((int) $backupId);
if ($backup === null || (string) $backup->state === 'deleted') {
throw new CloudError('备份不存在', 404);
}
$queued = CloudBackupService::restore(
$backup,
$actor,
CloudInput::object($request)
);
$job = $queued['job'] ?? null;
if (!is_object($job) || !isset($job->id)) {
throw new CloudError('恢复任务回执无效,必须人工核查', 503);
}
return $response->withJson(CloudJobService::acknowledgement($job), 202)
->withHeader('Cache-Control', 'no-store');
}
public function deleteLibraryBackup($request, $response, $args)
{
$actor = $this->actor($request, true);
$backupId = filter_var($args['backup_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$backup = $backupId === false ? null
: CloudInstanceBackup::find((int) $backupId);
if ($backup === null) {
throw new CloudError('备份不存在', 404);
}
$result = CloudBackupService::delete($backup, $actor);
return $response->withJson(
$result,
($result['deleted'] ?? false) === true ? 200 : 202
)->withHeader('Cache-Control', 'no-store');
}
public function cleanupLibraryBackupWorkspace($request, $response, $args)
{
$actor = $this->actor($request, true);
$backupId = filter_var($args['backup_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$backup = $backupId === false ? null
: CloudInstanceBackup::find((int) $backupId);
if ($backup === null || (string) $backup->state === 'deleted') {
throw new CloudError('备份不存在', 404);
}
$job = CloudBackupService::cleanupWorkspace($backup, $actor);
return $response->withJson(CloudJobService::acknowledgement($job), 202)
->withHeader('Cache-Control', 'no-store');
}
/** Queue a new independent VM restored from a ready portable backup. */
public function restoreBackup($request, $response, $args)
{
$actor = $this->actor($request, true);
$instance = CloudAccess::instance(
(string) ($args['id'] ?? ''),
$actor,
true
);
$backupId = filter_var($args['backup_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$backup = $backupId === false ? null
: CloudInstanceBackup::find((int) $backupId);
if ($backup === null
|| (int) $backup->source_instance_id !== (int) $instance->id) {
throw new CloudError('备份不存在', 404);
}
$queued = CloudBackupService::restore(
$backup,
$actor,
CloudInput::object($request)
);
$job = $queued['job'] ?? null;
if (!is_object($job) || !isset($job->id)) {
throw new CloudError('恢复任务回执无效,必须人工核查', 503);
}
return $response->withJson(CloudJobService::acknowledgement($job), 202)
->withHeader('Cache-Control', 'no-store');
}
/** Delete one backup object, or advance its bounded HEAD reconciliation. */
public function deleteBackup($request, $response, $args)
{
$actor = $this->actor($request, true);
$instance = CloudAccess::instance(
(string) ($args['id'] ?? ''),
$actor,
true
);
$backupId = filter_var($args['backup_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$backup = $backupId === false ? null
: CloudInstanceBackup::find((int) $backupId);
if ($backup === null
|| (int) $backup->source_instance_id !== (int) $instance->id) {
throw new CloudError('备份不存在', 404);
}
$result = CloudBackupService::delete($backup, $actor);
return $response->withJson(
$result,
($result['deleted'] ?? false) === true ? 200 : 202
)->withHeader('Cache-Control', '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
);
return $response->withJson(
CloudNetworkChangeOptionsService::adminOptions($instance)
)->withHeader('Cache-Control', 'private, no-store');
}
/**
* Queue one exact same-host dual-stack public-network transition.
*
* 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 = $this->actor($request, true);
$instance = CloudAccess::instance((string) ($args['id'] ?? ''), $actor, true);
$body = CloudInput::object($request);
CloudInput::only($body, ['targets', 'confirm_restart']);
if (($body['confirm_restart'] ?? false) !== true) {
throw new CloudError('更换公网 IP 前必须确认虚拟机会短暂重启');
}
$submitted = $body['targets'] ?? null;
if (!is_array($submitted) || array_is_list($submitted)
|| $submitted === []
|| array_diff(array_keys($submitted), ['ipv4', 'ipv6']) !== []) {
throw new CloudError('请选择有效的双栈公网目标', 422);
}
$targets = [];
foreach (['ipv4' => 4, 'ipv6' => 6] as $key => $family) {
if (!array_key_exists($key, $submitted)) {
continue;
}
$target = $submitted[$key];
if (!is_array($target) || array_is_list($target)) {
throw new CloudError('公网目标格式无效', 422);
}
CloudInput::only($target, ['pool_key', 'address_cidr']);
$targets[$family] = [
'pool_key' => $target['pool_key'] ?? null,
'address_cidr' => $target['address_cidr'] ?? null,
];
}
try {
$command = CloudPublicNetworkTransitionCommand::adminExact(
(int) $instance->id,
(int) $actor['user_id'],
(string) $actor['request_idempotency_key'],
$targets
);
} catch (\InvalidArgumentException) {
throw new CloudError('公网目标格式无效', 422);
}
$dispatch = CloudPublicNetworkTransitionWorkflow::begin($command);
return $response->withJson([
'task_id' => (string) $dispatch->jobId(),
'status_url' => '/api/v1/tasks/' . $dispatch->jobId(),
], 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'
|| !$instance->serviceAvailable()) {
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('修改实例设置前必须确认虚拟机会短暂重启');
}
CloudInstanceSettingsGuard::assertSupported($instance);
$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);
return $response->withJson([
'task_id' => (string) $job->id,
'status_url' => '/api/v1/tasks/' . $job->id,
], 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];
}
}