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

1638 lines
70 KiB
PHP

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden 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\CloudInstance;
use App\Models\CloudInvoice;
use App\Models\CloudJob;
use App\Models\CloudOrder;
use App\Models\CloudServicePeriod;
use App\Models\CloudSSHKey;
use App\Models\User;
use App\Services\Auth;
use App\Services\AdminCsrf;
use App\Services\Config;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudDeploymentPageService;
use App\Services\Cloud\CloudAgentSettingsService;
use App\Services\Cloud\CloudConsoleTicketService;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudFirewallService;
use App\Services\Cloud\CloudInput;
use App\Services\Cloud\CloudIpChangeBillingService;
use App\Services\Cloud\CloudInstanceMetadata;
use App\Services\Cloud\CloudInstanceNameService;
use App\Services\Cloud\CloudInstancePageService;
use App\Services\Cloud\CloudInstanceRuntimeService;
use App\Services\Cloud\CloudJobService;
use App\Services\Cloud\CloudMoney;
use App\Services\Cloud\CloudNetworkChangeOptionsService;
use App\Services\Cloud\CloudOperationCatalog;
use App\Services\Cloud\CloudRescueTemplateImportService;
use App\Services\Cloud\CloudInvoiceDetailPageService;
use App\Services\Cloud\CloudInvoicePageService;
use App\Services\Cloud\CloudInvoicePaymentService;
use App\Services\Cloud\CloudInvoiceService;
use App\Services\Cloud\CloudOrderService;
use App\Services\Cloud\CloudPlanUpgradeService;
use App\Services\Cloud\CloudSecrets;
use App\Services\Cloud\CloudSSHKeys;
use App\Services\Cloud\CloudSnapshotService;
use App\Services\Cloud\CloudTrafficService;
use App\Services\Cloud\CloudUserIsoFeature;
use App\Services\Cloud\CloudUserIsoService;
use App\Services\Cloud\CloudWorkerService;
final class CloudApiController
{
private function actor($request): array
{
$actor = $request->getAttribute('cloud_actor') ?? CloudAccess::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 billingActor($request): array
{
return $request->getAttribute('cloud_actor') ?? CloudAccess::actor(false);
}
private function user($request): User
{
$user = $request->getAttribute('auth_user');
return $user instanceof User ? $user : Auth::getUser();
}
private function json($response, array $value, int $status = 200)
{
return $response->withJson($value, $status)->withHeader('Cache-Control', 'no-store');
}
private function userIsoImportAllowed(array $actor, bool $throw = false): bool
{
$user = User::where('id', $actor['user_id'])->first();
$allowed = $user !== null && (int) $user->enable === 1;
if (!$allowed && $throw) {
throw new CloudError('账户ä¸<C3A4>å<EFBFBD>¯ç”¨ï¼Œæ— æ³•导入 ISO', 403);
}
return $allowed;
}
/**
* Keep the user rescue-status endpoint a fixed DTO even if a future
* Agent release adds diagnostics, volume names, or arbitrary messages.
*/
private function publicRescueStatus($value): array
{
if (!is_array($value)) {
return ['active' => false, 'staged' => false, 'power_state' => 'unknown',
'template_id' => null, 'template_name' => null, 'status' => null,
'can_exit' => false];
}
$templateId = is_string($value['template_id'] ?? null)
&& preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D',
$value['template_id']) === 1
? $value['template_id'] : null;
$status = $value['status'] ?? null;
$status = is_string($status) && in_array(strtolower(trim($status)),
['queued', 'running', 'staged', 'active', 'exiting', 'failed'], true)
? strtolower(trim($status)) : null;
$name = is_string($value['template_name'] ?? null)
? trim($value['template_name']) : '';
$name = $name !== '' && preg_match('//u', $name) === 1
&& preg_match('/[\x00-\x1F\x7F]/u', $name) !== 1
? mb_substr($name, 0, 128) : null;
return [
'active' => ($value['active'] ?? false) === true,
'staged' => ($value['staged'] ?? false) === true,
'power_state' => CloudInstanceMetadata::state($value['power_state'] ?? null),
'template_id' => $templateId,
'template_name' => $name,
'status' => $status,
'can_exit' => ($value['can_exit'] ?? false) === true,
];
}
/** Public rescue catalog fields; volume names and checksums stay private. */
private function publicRescueTemplates($value): array
{
$templates = [];
foreach (is_array($value) ? $value : [] as $item) {
if (!is_array($item)
|| !is_string($item['id'] ?? null)
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D',
$item['id']) !== 1
|| !is_string($item['name'] ?? null)) {
continue;
}
$name = trim($item['name']);
if ($name === '' || preg_match('//u', $name) !== 1
|| preg_match('/[\x00-\x1F\x7F]/u', $name) === 1) {
continue;
}
$templates[] = ['id' => $item['id'],
'name' => mb_substr($name, 0, 128)];
}
return $templates;
}
public function session($request, $response)
{
try {
$actor = CloudAccess::actor();
$user = $this->user($request);
return $this->json($response, ['authenticated' => true, 'username' => $user->user_name,
'user_id' => (int) $user->id, 'email' => $user->email,
'admin' => $actor['is_admin'], 'can_manage' => $actor['can_manage'],
'approved' => true, 'csrf_token' => AdminCsrf::token(), 'balance' => (string) $user->money]);
} catch (CloudError $error) {
return $this->json($response, ['authenticated' => false, 'detail' => $error->getMessage()], $error->httpStatus === 401 ? 200 : $error->httpStatus);
}
}
public function catalog($request, $response)
{
return $this->json($response, CloudDeploymentPageService::saleCatalog());
}
public function orders($request, $response)
{
$actor = $this->actor($request);
$query = CloudOrder::query();
if (!$actor['is_admin']) {
$query->where('user_id', $actor['user_id']);
}
return $this->json($response, ['orders' => $query->orderByDesc('id')->limit(200)->get()->map(
fn ($order) => CloudOrderService::display($order))->all()]);
}
public function order($request, $response, $args)
{
$actor = $this->actor($request);
$query = CloudOrder::where('id', $args['id']);
if (!$actor['is_admin']) {
$query->where('user_id', $actor['user_id']);
}
$order = $query->first();
if ($order === null) {
throw new CloudError('订å<C2A2>•ä¸<C3A4>存在', 404);
}
return $this->json($response, ['order' => CloudOrderService::display($order)]);
}
public function orderRequest($request, $response, $args)
{
$actor = $this->actor($request);
$key = (string) ($args['key'] ?? '');
if (preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $key) !== 1) {
throw new CloudError('订å<C2A2>•请求标识无效');
}
// Deliberately owner-only even for administrators: this endpoint is
// used to reconcile a browser's possibly lost purchase response.
$order = CloudOrder::where('user_id', $actor['user_id'])
->where('idempotency_key', $key)->first();
if ($order === null) {
throw new CloudError('订å<C2A2>•请求尚未建立', 404);
}
return $this->json($response, ['order' => CloudOrderService::display($order)]);
}
public function invoiceRequest($request, $response, $args)
{
$actor = $this->billingActor($request);
$key = (string) ($args['key'] ?? '');
if (preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $key) !== 1) {
throw new CloudError('è´¦å<C2A6>•请求标识无效');
}
$order = CloudOrder::where('user_id', $actor['user_id'])
->where('idempotency_key', $key)->first();
$invoice = $order === null ? null
: CloudInvoice::where('order_id', $order->id)->first();
if ($invoice === null || (string) ($invoice->purpose ?: 'renewal') !== 'provision') {
throw new CloudError('è´¦å<C2A6>•请求尚未建立', 404);
}
return $this->json($response,
['invoice' => CloudInvoiceService::display($invoice)]);
}
public function invoices($request, $response)
{
$actor = $this->billingActor($request);
if ($request->getMethod() === 'POST') {
return $this->createProvisionInvoice($request, $response, $actor);
}
$user = $this->user($request);
$query = $request->getQueryParams();
$pageValue = $query['page'] ?? '1';
if (is_array($pageValue)
|| preg_match('/^[1-9][0-9]{0,8}$/D', (string) $pageValue) !== 1) {
throw new CloudError('è´¦å<C2A6>•页ç <C3A7>无效');
}
$purpose = CloudInvoicePageService::normalizePurpose(
$query['purpose'] ?? 'all'
);
$payload = CloudInvoicePageService::forUser(
(int) $actor['user_id'], (int) $pageValue,
CloudInvoicePageService::USER_PAGE_SIZE, $purpose
);
$payload['balance'] = (string) $user->money;
return $this->json($response, $payload);
}
private function createProvisionInvoice($request, $response, array $actor)
{
$order = CloudOrderService::purchase(CloudInput::object($request), $actor);
$invoice = CloudInvoice::where('order_id', $order->id)->first();
if ($invoice === null) {
throw new \RuntimeException('开通账å<C2A6>•创建失败');
}
return $this->json($response,
['invoice' => CloudInvoiceService::display($invoice)], 201);
}
public function invoice($request, $response, $args)
{
$actor = $this->billingActor($request);
$user = $this->user($request);
return $this->json($response, CloudInvoiceDetailPageService::forUser(
(int) $args['id'], (int) $actor['user_id'], $user,
(bool) $actor['is_admin']
));
}
public function invoiceStatus($request, $response, $args)
{
$actor = $this->billingActor($request);
return $this->json($response, [
'invoice' => CloudInvoiceDetailPageService::statusForUser(
(int) $args['id'], (int) $actor['user_id']
),
]);
}
public function payInvoice($request, $response, $args)
{
$actor = $this->billingActor($request);
$invoice = CloudInvoice::where('id', $args['id'])
->where('user_id', $actor['user_id'])->first();
if ($invoice === null) {
throw new CloudError('è´¦å<C2A6>•ä¸<C3A4>存在', 404);
}
$body = CloudInput::object($request);
CloudInput::only($body, ['idempotency_key']);
$paid = CloudInvoiceService::payBalanceResult($invoice, $actor,
trim((string) ($body['idempotency_key'] ?? '')));
if ($paid['job'] instanceof CloudJob) {
return $this->json($response,
CloudJobService::acknowledgement($paid['job']), 202);
}
$user = $this->user($request)->fresh();
return $this->json($response, ['invoice' => CloudInvoiceService::display($paid['invoice']),
'balance' => (string) $user->money]);
}
public function createInvoicePayment($request, $response, $args)
{
$actor = $this->billingActor($request);
$invoice = CloudInvoice::where('id', $args['id'])
->where('user_id', $actor['user_id'])->first();
if ($invoice === null) {
throw new CloudError('è´¦å<C2A6>•ä¸<C3A4>存在', 404);
}
$job = CloudInvoicePaymentService::enqueue($invoice, $this->user($request),
CloudInput::object($request),
(string) $request->getServerParam('REMOTE_ADDR', ''),
(string) $request->getHeaderLine('User-Agent'));
return $this->json($response, [
'task_id' => (string) $job->id,
'status_url' => '/api/v1/tasks/' . (int) $job->id,
], 202);
}
public function job($request, $response, $args)
{
$actor = $this->actor($request);
CloudWorkerService::expireDueTasksForOwner(
(int) $actor['user_id'], (int) $args['id'], 1
);
$query = CloudJob::where('id', $args['id'])
->where('user_id', (int) $actor['user_id'])
->whereNull('parent_job_id');
$job = $query->first();
if ($job === null) {
throw new CloudError('任务ä¸<C3A4>存在', 404);
}
$payload = CloudJobService::display($job,
(bool) ($actor['is_admin'] ?? false));
return $this->json($response, $payload,
($payload['completed'] ?? false) === true ? 200 : 202);
}
public function readTasks($request, $response)
{
$actor = $this->actor($request);
$body = CloudInput::object($request);
CloudInput::only($body, ['ids']);
$ids = $body['ids'] ?? null;
if (!is_array($ids) || array_is_list($ids) === false
|| count($ids) < 1 || count($ids) > 50) {
throw new CloudError('任务编å<E28093>·åˆ—表无效', 400);
}
$normalized = [];
foreach ($ids as $id) {
if (!is_string($id)
|| preg_match('/^[1-9][0-9]{0,18}$/D', $id) !== 1) {
throw new CloudError('任务编å<E28093>·åˆ—表无效', 400);
}
$normalized[(int) $id] = (int) $id;
}
$query = CloudJob::whereIn('id', array_values($normalized))
->where('user_id', (int) $actor['user_id'])
->whereNull('parent_job_id')
->where('phase', 'terminal')->whereNull('read_at');
$updated = $query->update(['read_at' => time()]);
return $this->json($response, [
'read_count' => (int) $updated,
'unread_count' => CloudJobService::unreadCount($actor),
]);
}
public function tasks($request, $response)
{
$actor = $this->actor($request);
$query = $request->getQueryParams();
$state = $query['state'] ?? null;
if (!is_string($state) || !in_array($state,
['active', 'completed'], true)) {
throw new CloudError('任务状æ€<C3A6>筛选无效', 400);
}
$cursor = $query['cursor'] ?? null;
if ($cursor !== null && (!is_string($cursor)
|| preg_match('/^[1-9][0-9]{0,18}$/D', $cursor) !== 1)) {
throw new CloudError('任务游标无效', 400);
}
$limit = $query['limit'] ?? '20';
if (!is_string($limit)
|| preg_match('/^[1-9][0-9]?$/D', $limit) !== 1
|| (int) $limit > 50) {
throw new CloudError('任务分页大å°<C3A5>无效', 400);
}
return $this->json($response, CloudJobService::tasks(
$actor,
$state,
$cursor === null ? null : (int) $cursor,
(int) $limit
));
}
private function unavailableVm(CloudInstance $instance): array
{
return ['name' => $instance->name, 'state' => 'unknown',
'detail' => '宿主机暂时无法连接'];
}
/**
* Convert one host-Agent VM row into the public live metadata DTO.
*
* Never merge the Agent response directly into vmData: it contains
* storage source paths, console ports, rescue volume names and credential
* generation markers. CloudInstanceMetadata owns the static allowlist;
* this boundary adds only the explicitly public, UUID-checked power state
* and the validated discovery timestamp needed by the detail view.
*/
private function publicVmMetadata(CloudInstance $instance, array $live): array
{
$snapshot = [
'id' => (string) $instance->id,
'api_id' => (string) $instance->id,
'uuid' => (string) $instance->uuid,
'name' => (string) $instance->name,
];
$view = CloudInstanceMetadata::publicView($snapshot, $live);
$snapshotUuid = strtolower(trim((string) $snapshot['uuid']));
$liveUuid = is_string($live['uuid'] ?? null)
? strtolower(trim($live['uuid'])) : '';
$matches = $snapshotUuid !== '' && $liveUuid !== ''
&& hash_equals($snapshotUuid, $liveUuid);
$view['state'] = $matches
? CloudInstanceMetadata::state(
$live['status'] ?? ($live['state'] ?? null)
) : 'unknown';
if ($matches && is_string($live['created_at'] ?? null)
&& preg_match('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/D',
$live['created_at']) === 1) {
// The Agent emits UTC seconds. Keep the exact format instead of
// exposing arbitrary metadata or normalising an invalid date.
$view['created_at'] = $live['created_at'];
}
return $view;
}
/**
* Keep the durable business snapshot behind the same public boundary.
* CloudInput::safeResult() only removes credential-looking names; it is
* not an allowlist and therefore must never be returned as-is.
*/
private function publicVmSpec(array $spec): array
{
return CloudInstanceMetadata::publicSpec($spec);
}
/**
* Keep the metrics response bounded to the fields rendered by the user
* charts. Agent JSON is authenticated, but its schema is host-controlled
* and must not be forwarded as a future arbitrary-field channel.
*/
private function publicMetrics($value, string $uuid, string $range): array
{
$result = is_array($value) ? $value : [];
$interval = filter_var($result['interval_seconds'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 86400]]);
$points = [];
foreach (is_array($result['points'] ?? null) ? $result['points'] : [] as $point) {
if (!is_array($point) || array_is_list($point)) {
continue;
}
$timestamp = filter_var($point['timestamp'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => 4102444800]]);
if ($timestamp === false) {
continue;
}
$safe = ['timestamp' => (int) $timestamp];
foreach ([
'cpu_percent' => 100.0,
'memory_used_mib' => 1000000000.0,
'memory_total_mib' => 1000000000.0,
'disk_read_bps' => 1000000000000000.0,
'disk_write_bps' => 1000000000000000.0,
'network_rx_bps' => 1000000000000000.0,
'network_tx_bps' => 1000000000000000.0,
] as $key => $maximum) {
if (!array_key_exists($key, $point)) {
continue;
}
$metric = $point[$key];
if ($metric === null) {
$safe[$key] = null;
continue;
}
if (is_string($metric)) {
$metric = trim($metric);
if ($metric === '' || !is_numeric($metric)) {
continue;
}
}
if ((!is_int($metric) && !is_float($metric) && !is_string($metric))
|| is_bool($metric) || !is_finite((float) $metric)
|| (float) $metric < 0 || (float) $metric > $maximum) {
continue;
}
$safe[$key] = (float) $metric;
}
$points[] = $safe;
if (count($points) >= 600) {
break;
}
}
return ['vm_id' => $uuid, 'range' => $range,
'interval_seconds' => $interval === false ? 60 : (int) $interval,
'points' => $points];
}
/** Keep daily traffic to UTC day buckets and bounded byte counters. */
private function publicDailyTraffic($value, string $uuid, int $days): array
{
$result = is_array($value) ? $value : [];
$points = [];
foreach (is_array($result['traffic'] ?? null) ? $result['traffic'] : [] as $point) {
if (!is_array($point) || array_is_list($point)) {
continue;
}
$date = $point['date'] ?? null;
if (!is_string($date)
|| preg_match('/^\d{4}-\d{2}-\d{2}$/D', $date) !== 1) {
continue;
}
$parsed = \DateTimeImmutable::createFromFormat('!Y-m-d', $date,
new \DateTimeZone('UTC'));
if ($parsed === false || $parsed->format('Y-m-d') !== $date) {
continue;
}
$bytesByDirection = [];
foreach (['download_bytes' => 'rx_bytes', 'upload_bytes' => 'tx_bytes']
as $publicKey => $agentKey) {
$bytes = $point[$agentKey] ?? null;
if (is_string($bytes) && preg_match('/^[0-9]+$/D', $bytes) !== 1) {
$bytes = null;
}
if (is_bool($bytes) || (!is_int($bytes) && !is_string($bytes))
|| (int) $bytes < 0 || (int) $bytes > 9000000000000000) {
$bytes = null;
}
$bytesByDirection[$publicKey] = $bytes === null ? null : (int) $bytes;
}
$safe = ['date' => $date, 'day_start' => $parsed->getTimestamp()]
+ $bytesByDirection;
$safe['total_bytes'] = $safe['download_bytes'] === null
|| $safe['upload_bytes'] === null
? null : $safe['download_bytes'] + $safe['upload_bytes'];
$points[] = $safe;
if (count($points) >= $days) {
break;
}
}
$from = $points === [] ? null : $points[0]['day_start'];
$until = $points === [] ? null
: $points[count($points) - 1]['day_start'] + 86400;
return ['vm_id' => $uuid, 'days' => $days, 'timezone' => 'UTC',
'from' => $from, 'until' => $until,
'points' => $points];
}
/**
* Resolve list-only VM dependencies in fixed-size database queries and
* targeted Agent reads. The database collection is authoritative; a
* live row is requested only for the UUID already present in the
* actor-scoped instance collection, so this path never inventories a host.
*/
private function vmListContexts($instances, array $actor): array
{
if ($instances->isEmpty()) {
return [];
}
$instanceIds = $instances->pluck('id')->map(fn ($id) => (int) $id)->all();
$periodIds = $instances->pluck('current_period_id')->filter(
fn ($id) => $id !== null)->map(fn ($id) => (int) $id)->unique()->values()->all();
$periods = [];
if ($periodIds !== []) {
foreach (CloudServicePeriod::whereIn('id', $periodIds)
->whereIn('instance_id', $instanceIds)->get() as $period) {
$periods[(int) $period->id] = $period;
}
}
$futurePeriods = [];
foreach (CloudServicePeriod::whereIn('instance_id', $instanceIds)
->where('status', 'scheduled')
->selectRaw('instance_id, COUNT(*) AS period_count')
->groupBy('instance_id')->get() as $row) {
$futurePeriods[(int) $row->instance_id] = (int) $row->period_count;
}
$liveByInstance = [];
foreach ($instances as $instance) {
$instanceId = (int) $instance->id;
$liveByInstance[$instanceId] = $this->unavailableVm($instance);
try {
$uuid = rawurlencode((string) $instance->uuid);
$live = CloudAgentSettingsService::clientForHost(
(int) $instance->host_id,
5.0
)->request('GET', '/v1/vms/' . $uuid, $actor);
if (is_array($live) && is_string($live['uuid'] ?? null)
&& hash_equals(strtolower((string) $instance->uuid),
strtolower(trim($live['uuid'])))) {
$liveByInstance[$instanceId] = $live;
}
} catch (CloudError $error) {
// Preserve a useful database-backed row when this host or
// targeted UUID is unavailable; other instances remain visible.
}
}
$contexts = [];
foreach ($instances as $instance) {
$period = $instance->current_period_id === null
? null : ($periods[(int) $instance->current_period_id] ?? null);
if ($period !== null && (int) $period->instance_id !== (int) $instance->id) {
$period = null;
}
$contexts[(int) $instance->id] = [
'vm' => $liveByInstance[(int) $instance->id] ?? $this->unavailableVm($instance),
'period' => $period,
'future_periods' => (int) ($futurePeriods[(int) $instance->id] ?? 0),
];
}
return $contexts;
}
private function vmData(CloudInstance $instance, array $actor, ?array $context = null): array
{
$owner = (int) $instance->user_id === (int) $actor['user_id'];
$global = ($actor['is_admin'] ?? false) && ($actor['is_super_admin'] ?? false)
&& ($actor['can_manage'] ?? false);
$decodedSpec = json_decode((string) $instance->spec_json, true);
$spec = is_array($decodedSpec) && !array_is_list($decodedSpec)
? $decodedSpec : [];
if ($context === null) {
try {
$vm = CloudAgentSettingsService::clientForHost(
(int) $instance->host_id,
5.0
)->request('GET', '/v1/vms/'
. rawurlencode((string) $instance->uuid), $actor);
} catch (CloudError $error) {
$vm = $this->unavailableVm($instance);
}
$period = $instance->current_period_id === null ? null
: CloudServicePeriod::where('id', $instance->current_period_id)
->where('instance_id', $instance->id)->first();
$futurePeriods = CloudServicePeriod::where('instance_id', $instance->id)
->where('status', 'scheduled')->count();
} else {
$vm = is_array($context['vm'] ?? null)
? $context['vm'] : $this->unavailableVm($instance);
$period = $context['period'] ?? null;
$futurePeriods = max(0, (int) ($context['future_periods'] ?? 0));
}
$publicVm = $this->publicVmMetadata($instance,
is_array($vm) ? $vm : []);
$createdAt = ($spec['record_source'] ?? '') === 'discovered'
? ($publicVm['created_at'] ?? null)
: gmdate('Y-m-d\TH:i:s\Z', (int) $instance->created_at);
$maximumFuturePeriods = max(1, min(120,
(int) Config::get('cloud_max_renewal_periods_ahead', 24)));
$lifecycleActive = (string) $instance->status === 'active';
$canDelete = $lifecycleActive && ($owner || $global);
// Traffic quota enforcement only disconnects guest NICs. It must not
// remove power, console or maintenance controls while the paid service
// period itself is still active.
$canOperate = $canDelete && $instance->serviceAvailable();
return array_merge(
$this->publicVmSpec($spec),
$publicVm,
['id' => (string) $instance->id, 'uuid' => $instance->uuid,
'name' => (string) $instance->name,
'user_id' => (int) $instance->user_id, 'owner_user_id' => (int) $instance->user_id,
'display_uuid' => $instance->uuid,
'created_at' => $createdAt,
'instance_status' => (string) $instance->status,
'service_status' => (string) $instance->service_status,
'network_status' => (string) $instance->network_status,
'service_expires_at' => $instance->expires_at === null ? null : (int) $instance->expires_at,
'current_period_started_at' => $period === null ? null : (int) $period->starts_at,
'current_period_ends_at' => $period === null ? null : (int) $period->ends_at,
'prepaid_periods' => $futurePeriods,
'traffic_download_bytes' => (int) $instance->traffic_download_bytes,
'traffic_upload_bytes' => (int) $instance->traffic_upload_bytes,
'traffic_used_bytes' => (int) $instance->traffic_download_bytes + (int) $instance->traffic_upload_bytes,
'traffic_quota_bytes' => (int) $instance->traffic_quota_bytes,
'renewal_price' => $instance->renewal_price === null ? null : (string) $instance->renewal_price,
'renewal_days' => (int) $instance->renewal_days,
'renewal_traffic_bytes' => (int) $instance->renewal_traffic_bytes,
'is_owner' => $owner,
'can_operate' => $canOperate,
'can_delete' => $canDelete,
'can_rename' => $canDelete,
'can_view_credential' => $owner || $global,
'can_renew' => $lifecycleActive && $owner
&& $instance->expires_at !== null && (int) $instance->renewal_days > 0
&& $instance->renewal_price !== null && $futurePeriods < $maximumFuturePeriods,
'has_initial_root_password' => ($owner || $global)
&& $instance->sealed_credential !== null]);
}
public function vms($request, $response)
{
$actor = $this->actor($request);
$query = CloudInstance::where('status', '<>', 'deleted');
if (!$actor['is_admin']) {
$query->where('user_id', $actor['user_id']);
}
$instances = $query->orderByDesc('id')->limit(200)->get();
$contexts = $this->vmListContexts($instances, $actor);
return $this->json($response, ['vms' => $instances->map(
fn ($instance) => $this->vmData($instance, $actor,
$contexts[(int) $instance->id] ?? []))->all()]);
}
/** Database-only paginated instance rows used after the SSR first page. */
public function vmPage($request, $response)
{
$actor = $this->billingActor($request);
$value = $request->getQueryParams()['page'] ?? '1';
if (is_array($value)
|| preg_match('/^[1-9][0-9]{0,8}$/D', (string) $value) !== 1) {
throw new CloudError('实例页ç <C3A7>无效');
}
return $this->json($response, CloudInstancePageService::forActor(
$actor, (int) $value, 20
));
}
/**
* Load immutable libvirt metadata for only the actor-visible rows on the
* current page. This is intentionally separate from the frequent power
* state poll: XML and disk inspection happens once after SSR, then the
* sanitized result is cached in cloud_instances.spec_json.
*/
public function vmMetadata($request, $response)
{
$actor = $this->actor($request);
$raw = $request->getQueryParams()['ids'] ?? '';
if (is_array($raw) || preg_match('/^[1-9][0-9]*(?:,[1-9][0-9]*){0,19}$/D',
(string) $raw) !== 1) {
throw new CloudError('实例编å<E28093>·åˆ—表无效');
}
$ids = array_values(array_unique(array_map('intval', explode(',', (string) $raw))));
return $this->json($response, ['vms' => $this->vmMetadataRows($actor, $ids)]);
}
/** Load one detail page's static metadata without returning credentials. */
public function vmMetadataOne($request, $response, $args)
{
$actor = $this->actor($request);
$id = filter_var($args['id'] ?? null, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]);
if ($id === false) {
throw new CloudError('实例编å<E28093>·æ— æ•ˆ');
}
$rows = $this->vmMetadataRows($actor, [(int) $id]);
if ($rows === []) {
// The actor-scoped database lookup deliberately does not disclose
// whether a foreign instance exists.
throw new CloudError('虚拟机ä¸<C3A4>存在或无æ<C2A0>ƒè®¿é—®', 404);
}
return $this->json($response, $rows[0]);
}
private function vmMetadataRows(array $actor, array $ids): array
{
$snapshots = CloudInstancePageService::forActorIds($actor, $ids);
$targets = $this->vmProbeTargets($actor, $ids);
$live = [];
foreach ($this->vmSnapshotsByHost($snapshots, $targets) as $hostId => $group) {
$hostLive = [];
try {
$agent = CloudAgentSettingsService::clientForHost(
(int) $hostId,
5.0
);
foreach ($group as $snapshot) {
$uuid = strtolower((string) $snapshot['uuid']);
try {
$item = $agent->request(
'GET',
'/v1/vms/' . rawurlencode($uuid) . '/metadata',
$actor
);
if (is_string($item['uuid'] ?? null)
&& hash_equals($uuid,
strtolower(trim($item['uuid'])))) {
$hostLive[$uuid] = $item;
$live[(int) $hostId . ':' . $uuid] = $item;
}
} catch (CloudError $error) {
// One missing/offline VM must not hide other rows.
}
}
} catch (CloudError $error) {
// Static database fields stay usable when one host is offline;
// another host's metadata can still be returned and cached.
}
CloudInstanceMetadata::persistBatch($group, $hostLive);
}
$rows = [];
foreach ($snapshots as $snapshot) {
$uuid = strtolower((string) $snapshot['uuid']);
$target = $targets[(int) $snapshot['id']] ?? null;
$key = is_array($target) ? (int) $target['host_id'] . ':' . $uuid : '';
// Return the actor-visible identity even while its host is
// offline. The browser keeps the SSR fields and can distinguish
// temporary metadata unavailability from a missing instance.
$rows[] = CloudInstanceMetadata::publicView(
$snapshot, $live[$key] ?? []
);
}
return $rows;
}
/**
* Lightweight live state for the visible list page. Database ownership is
* resolved before any Agent response is considered; each Agent request
* contains only the already actor-scoped UUIDs and never lists a host.
*/
public function vmStatuses($request, $response)
{
$actor = $this->actor($request);
$raw = $request->getQueryParams()['ids'] ?? '';
if (is_array($raw) || preg_match('/^[1-9][0-9]*(?:,[1-9][0-9]*){0,99}$/D',
(string) $raw) !== 1) {
throw new CloudError('实例编å<E28093>·åˆ—表无效');
}
$ids = array_values(array_unique(array_map('intval', explode(',', (string) $raw))));
$snapshots = CloudInstancePageService::forActorIds($actor, $ids);
// Normal list refreshes are cache-only and therefore return without
// waiting on any host. An explicit live=1 request is reserved for a
// bounded convergence check or diagnostics.
$liveRequested = ($request->getQueryParams()['live'] ?? '') === '1';
if (!$liveRequested) {
$statuses = [];
foreach ($snapshots as $snapshot) {
$statuses[] = CloudInstancePageService::powerStatus($snapshot);
}
return $this->json($response, ['vms' => $statuses]);
}
$targets = $this->vmProbeTargets($actor, $ids);
$live = [];
foreach ($this->vmSnapshotsByHost($snapshots, $targets) as $hostId => $group) {
try {
$agent = CloudAgentSettingsService::clientForHost(
(int) $hostId,
5.0
);
foreach ($group as $snapshot) {
$uuid = strtolower((string) $snapshot['uuid']);
$runtimeRevision = null;
try {
$runtimeRevision =
CloudInstanceRuntimeService::beginCurrentObservation(
(int) $snapshot['id'],
(int) $hostId,
$uuid
);
} catch (\Throwable $error) {
// A live response remains useful during a rolling
// schema update, but an unclaimed result cannot write.
}
try {
$item = $agent->request(
'GET',
'/v1/vms/' . rawurlencode($uuid) . '/state',
$actor
);
$observedState = is_array($item)
? CloudInstanceRuntimeService::normalizeState(
$item['state'] ?? ($item['power_state'] ?? null)
) : 'unknown';
if (is_string($item['uuid'] ?? null)
&& hash_equals($uuid,
strtolower(trim($item['uuid'])))
&& $observedState !== 'unknown') {
$item['state'] = $observedState;
try {
if ($runtimeRevision !== null) {
CloudInstanceRuntimeService::markObserved(
(int) $snapshot['id'],
(int) $hostId,
$uuid,
$observedState,
null,
$runtimeRevision
);
}
} catch (\Throwable $error) {
error_log('cloud list live runtime write unavailable: '
. get_class($error));
}
$live[(int) $hostId . ':' . $uuid] = $item;
}
} catch (CloudError $error) {
// Continue with the last observation for this VM.
}
}
} catch (CloudError $error) {
// The database rows remain visible with an unknown state; one
// offline host must not hide instances from another host.
}
}
$statuses = [];
foreach ($snapshots as $snapshot) {
$uuid = strtolower((string) $snapshot['uuid']);
$target = $targets[(int) $snapshot['id']] ?? null;
$key = is_array($target) ? (int) $target['host_id'] . ':' . $uuid : '';
$statuses[] = CloudInstancePageService::powerStatus(
$snapshot, $live[$key] ?? []
);
}
return $this->json($response, ['vms' => $statuses]);
}
/** Cache-first state for one owner-scoped detail page. */
public function vmStatus($request, $response, $args)
{
$actor = $this->actor($request);
$snapshot = CloudInstancePageService::statusForActor($actor, $args['id']);
$live = [];
// Detail pages use the runtime cache by default, so opening a VM does
// not wait for a potentially slow/offline host. Explicit live=1
// refreshes use a short deadline and write a valid observation through.
if (($request->getQueryParams()['live'] ?? '') === '1') {
try {
$instance = CloudAccess::instance($args['id'], $actor);
if (!hash_equals(strtolower((string) $snapshot['uuid']),
strtolower((string) $instance->uuid))) {
throw new CloudError('虚拟机状æ€<C3A6>å·²å<C2B2>˜æ›´ï¼Œè¯·åˆ·æ–°å<C2B0>Žé‡<C3A9>试', 409);
}
$runtimeRevision = null;
try {
// Seed and claim against a locked current instance row.
// The potentially slow host request stays outside that
// short transaction; a later worker write or delete then
// invalidates this revision.
$runtimeRevision = CloudInstanceRuntimeService::beginCurrentObservation(
(int) $instance->id,
(int) $instance->host_id,
(string) $instance->uuid
);
} catch (\Throwable $error) {
// Live state remains useful during a rolling schema
// update, but an unclaimed response must not write back.
}
$candidate = CloudAgentSettingsService::clientForHost(
(int) $instance->host_id,
5.0
)->request(
'GET',
'/v1/vms/' . rawurlencode((string) $snapshot['uuid'])
. '/state',
$actor
);
$observedState = is_array($candidate)
? CloudInstanceRuntimeService::normalizeState(
$candidate['state'] ?? ($candidate['power_state'] ?? null)
) : 'unknown';
if (is_array($candidate)
&& is_string($candidate['uuid'] ?? null)
&& hash_equals(strtolower((string) $snapshot['uuid']),
strtolower(trim($candidate['uuid'])))
&& $observedState !== 'unknown') {
$candidate['state'] = $observedState;
try {
// The same database identity used for authorisation is
// also the cache-write key. Only the revision claimed
// before the host request may publish this response.
if ($runtimeRevision !== null) {
CloudInstanceRuntimeService::markObserved(
(int) $instance->id,
(int) $instance->host_id,
(string) $instance->uuid,
$observedState,
null,
$runtimeRevision
);
}
} catch (\Throwable $error) {
// Runtime persistence is a write-through optimisation;
// a live observation remains useful during a rolling
// schema update, while the previous cache stays intact.
error_log('cloud live runtime write unavailable: '
. get_class($error));
}
$live = $candidate;
}
} catch (CloudError $error) {
// Preserve the identity-checked runtime snapshot when the
// optional live probe cannot reach the host.
}
}
return $this->json($response,
CloudInstancePageService::status($snapshot, $live));
}
public function vm($request, $response, $args)
{
$actor = $this->actor($request);
return $this->json($response, $this->vmData(CloudAccess::instance($args['id'], $actor), $actor));
}
/** Rename only the PHP-owned display label; no Agent operation is sent. */
public function displayName($request, $response, $args)
{
$body = CloudInput::object($request);
CloudInput::only($body, ['name']);
return $this->json($response, CloudInstanceNameService::rename(
$args['id'] ?? null,
$this->actor($request),
$body['name'] ?? null
));
}
public function operationLogs($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor);
$rawPage = $request->getQueryParams()['page'] ?? '1';
$page = is_string($rawPage) || is_int($rawPage)
? filter_var((string) $rawPage, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1, 'max_range' => 1000000]])
: false;
if ($page === false) {
throw new CloudError('æ“<C3A6>作日志页ç <C3A7>无效', 400);
}
return $this->json($response, array_merge(
CloudJobService::operationLogs($instance, (int) $page, 10),
['instance_id' => (string) $instance->id]
));
}
/** Database-only read and revisioned whole-policy firewall replacement. */
public function firewall($request, $response, $args)
{
$actor = $this->actor($request);
$write = $request->getMethod() === 'PUT';
$instance = CloudAccess::instance($args['id'], $actor, $write);
if (!$write) {
return $this->json($response,
CloudFirewallService::listing($instance, $actor));
}
$queued = CloudFirewallService::apply(
$instance, $actor, CloudInput::object($request)
);
$job = $queued['job'];
return $this->json($response, [
'task_id' => (string) $job->id,
'status_url' => '/api/v1/tasks/' . $job->id,
], 202);
}
/** Database-only catalog read; create is queued through the durable worker. */
public function snapshots($request, $response, $args)
{
$actor = $this->actor($request);
$write = $request->getMethod() === 'POST';
$instance = CloudAccess::instance($args['id'], $actor, $write);
if (!$write) {
return $this->json($response,
CloudSnapshotService::listing($instance, $actor));
}
$created = CloudSnapshotService::create(
$instance, $actor, CloudInput::object($request)
);
$job = $created['job'];
return $this->json($response, [
'task_id' => (string) $job->id,
'status_url' => '/api/v1/tasks/' . $job->id,
], 202);
}
public function restoreSnapshot($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor, true);
$queued = CloudSnapshotService::restore($instance, $actor,
(string) $args['snapshot_key'], CloudInput::object($request));
$job = $queued['job'];
return $this->json($response, [
'task_id' => (string) $job->id,
'status_url' => '/api/v1/tasks/' . $job->id,
], 202);
}
public function deleteSnapshot($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor, true);
$queued = CloudSnapshotService::delete($instance, $actor,
(string) $args['snapshot_key'], CloudInput::object($request));
$job = $queued['job'];
return $this->json($response, [
'task_id' => (string) $job->id,
'status_url' => '/api/v1/tasks/' . $job->id,
], 202);
}
/**
* Server-only placement targets for an already bounded list of actor-visible
* instances. These rows are never serialized into a user response.
*/
private function vmProbeTargets(array $actor, array $ids): array
{
$ids = array_values(array_unique(array_filter(array_map(
static fn ($id): int => max(0, (int) $id), $ids
))));
if ($ids === []) {
return [];
}
$query = CloudInstance::where('status', '<>', 'deleted')->whereIn('id', $ids);
if (!($actor['is_admin'] ?? false)) {
$query->where('user_id', (int) $actor['user_id']);
}
$targets = [];
foreach ($query->get(['id', 'uuid', 'host_id']) as $instance) {
$targets[(int) $instance->id] = [
'uuid' => strtolower((string) $instance->uuid),
'host_id' => (int) $instance->host_id,
];
}
return $targets;
}
private function vmSnapshotsByHost(array $snapshots, array $targets): array
{
$groups = [];
foreach ($snapshots as $snapshot) {
$target = $targets[(int) ($snapshot['id'] ?? 0)] ?? null;
$uuid = strtolower((string) ($snapshot['uuid'] ?? ''));
$hostId = is_array($target) ? max(0, (int) ($target['host_id'] ?? 0)) : 0;
if ($hostId > 0 && $uuid !== ''
&& hash_equals((string) ($target['uuid'] ?? ''), $uuid)) {
$groups[$hostId][] = $snapshot;
}
}
return $groups;
}
public function metrics($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor);
$query = $request->getQueryParams();
$range = $query['range'] ?? '1h';
if (!in_array($range, ['1h', '24h', '7d', '30d'], true)) {
throw new CloudError('指标时间范围无效');
}
$value = CloudTrafficService::metrics($instance, $range);
return $this->json($response, $this->publicMetrics($value,
strtolower((string) $instance->uuid), $range));
}
public function dailyTraffic($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor);
$rawDays = $request->getQueryParams()['days'] ?? '30';
if (!is_string($rawDays) && !is_int($rawDays)) {
throw new CloudError('æµ<C3A6>é‡<C3A9>统计天数无效');
}
$days = filter_var((string) $rawDays, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1, 'max_range' => 30]]);
if ($days === false) {
throw new CloudError('æµ<C3A6>é‡<C3A9>统计天数必须为 1 至 30');
}
$value = CloudAgentSettingsService::clientForHost(
(int) $instance->host_id
)->request('GET', '/v1/vms/' . rawurlencode((string) $instance->uuid)
. '/traffic/daily?days=' . (int) $days, $actor);
return $this->json($response, $this->publicDailyTraffic($value,
strtolower((string) $instance->uuid), (int) $days));
}
public function credential($request, $response, $args)
{
$instance = CloudAccess::instance($args['id'], $this->actor($request), true);
if ($instance->sealed_credential === null) {
throw new CloudError('该虚拟机没有é<E280B0>¢æ<C2A2>¿ä¿<C3A4>存的åˆ<C3A5>始密ç <C3A7>', 404);
}
return $this->json($response, CloudSecrets::decrypt(
$instance->sealed_credential,
'instance-credential'
));
}
public function consoleTicket($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor, true);
$this->requireService($instance, $actor);
$actor = CloudAccess::vmActor($instance, $actor);
$value = CloudAgentSettingsService::clientForHost(
(int) $instance->host_id
)->request('POST', '/v1/vms/' . rawurlencode((string) $instance->uuid)
. '/console-ticket', $actor, []);
return $this->json($response, CloudConsoleTicketService::issue(
$instance,
$actor,
$value
));
}
public function actions($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor, true);
$actor = CloudAccess::vmActor($instance, $actor);
$body = CloudInput::object($request);
CloudInput::only($body, ['action']);
$action = $body['action'] ?? null;
if (!is_string($action) || !CloudOperationCatalog::isPowerAction($action)) {
throw new CloudError('æ“<C3A6>作无效');
}
if (in_array($action, ['start', 'reboot', 'reset'], true)) {
$this->requireService($instance, $actor);
}
$job = CloudJobService::enqueue($instance, $actor, 'action', 'POST', '/actions', $body);
return $this->json($response, [
'task_id' => (string) $job->id,
'status_url' => '/api/v1/tasks/' . $job->id,
], 202);
}
public function reinstall($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor, true);
$this->requireService($instance, $actor);
$body = CloudInput::object($request);
CloudInput::only($body, ['template_id', 'ssh_key_id', 'root_password', 'confirmation_name']);
if (($body['confirmation_name'] ?? '') !== $instance->name) {
throw new CloudError('请填写虚拟机å<C2BA><C3A5>称确认é‡<C3A9>装');
}
// Browser-only confirmation must never cross the strict Go Agent DTO.
unset($body['confirmation_name']);
$body['template_id'] = CloudInput::template($body['template_id'] ?? null);
$key = CloudSSHKeys::owned($body['ssh_key_id'] ?? null, $actor['user_id']);
unset($body['ssh_key_id']);
$body['ssh_public_key'] = $key?->public_key ?? '';
$requestedPassword = $body['root_password'] ?? null;
$body['root_password'] = CloudInput::password($requestedPassword);
$job = CloudJobService::enqueue($instance, $actor, 'reinstall', 'POST', '/reinstall', $body,
['password' => $body['root_password'], 'login_name' => 'root', 'auth_mode' => $key ? 'password_and_key' : 'password']);
// The acknowledgement exposes only task identity. On success the
// owner can retrieve the newly persisted credential through the
// dedicated credential endpoint.
return $this->json($response, [
'task_id' => (string) $job->id,
'status_url' => '/api/v1/tasks/' . $job->id,
], 202);
}
/**
* Queue one owner-scoped instance setting at a time. Passwords are
* generated server-side and kept in the encrypted credential path; the
* asynchronous acknowledgement and task DTO contain no plaintext secret.
*/
public function settings($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor, true);
$this->requireService($instance, $actor);
$body = CloudInput::object($request);
CloudInput::only($body, ['hostname', 'ssh_key_id', 'reset_password', 'confirm_restart']);
if (($body['confirm_restart'] ?? false) !== true) {
throw new CloudError('修改实例设置å‰<C3A5>必须确认虚拟机会短暂é‡<C3A9>å<EFBFBD>¯');
}
$hasHostname = array_key_exists('hostname', $body);
$hasPassword = array_key_exists('reset_password', $body);
$hasKey = array_key_exists('ssh_key_id', $body);
if ((int) $hasHostname + (int) $hasPassword + (int) $hasKey !== 1) {
throw new CloudError('æ¯<C3A6>次å<C2A1>ªèƒ½æ<C2BD><C3A6>交一项实例设置');
}
$jobBody = ['confirm_restart' => true];
$credential = null;
$initialPassword = null;
if ($hasHostname) {
$jobBody['hostname'] = CloudInput::hostname($body['hostname']);
} elseif ($hasPassword) {
if ($body['reset_password'] !== true) {
throw new CloudError('请确认生æˆ<C3A6>新密ç <C3A7>å¹¶é‡<C3A9>å<EFBFBD>¯å®žä¾‹');
}
$initialPassword = CloudInput::password(null);
$jobBody['root_password'] = $initialPassword;
$credential = [
'password' => $initialPassword,
'login_name' => 'root',
'auth_mode' => 'password',
];
} else {
// The browser submits only an identifier. Resolve it against the
// instance owner so a privileged viewer cannot attach another
// account's key to this guest.
$key = CloudSSHKeys::owned($body['ssh_key_id'] ?? null, (int) $instance->user_id);
if ($key === null) {
throw new CloudError('请选择è¦<C3A8>使用的 SSH 公钥');
}
$jobBody['ssh_public_key'] = $key->public_key;
}
$job = CloudJobService::enqueue($instance, $actor, 'instance_settings', 'POST',
'/settings', $jobBody, $credential);
return $this->json($response, [
'task_id' => (string) $job->id,
'status_url' => '/api/v1/tasks/' . $job->id,
], 202);
}
/** Tenant-safe paid IP-change quote without exposing host IP inventory. */
public function networkOptions($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor);
if ((int) $instance->user_id !== (int) $actor['user_id']) {
throw new CloudError('å<>ªèƒ½ä¸ºè‡ªå·±æŒ<C3A6>有的实例更æ<C2B4>¢ IP', 403);
}
$this->requireService($instance, $actor);
$options = CloudNetworkChangeOptionsService::forInstance($instance);
$user = User::where('id', (int) $actor['user_id'])->first();
if ($user === null || (int) $user->enable !== 1) {
throw new CloudError('账户ä¸<C3A4>å<EFBFBD>¯ç”¨', 403);
}
$price = CloudIpChangeBillingService::price();
$priceCents = CloudMoney::cents($price);
$balance = CloudMoney::decimal(
CloudMoney::cents((string) $user->money)
);
$balanceSufficient = CloudMoney::cents($balance) >= $priceCents;
$enabled = $priceCents > 0;
$canChange = ($options['can_change'] ?? false) === true
&& $enabled && $balanceSufficient;
$message = (string) ($options['message'] ?? '');
if (!$enabled) {
$message = '管ç<C2A1>†å‘˜å°šæœªå<C2AA>¯ç”¨ä»˜è´¹æ›´æ<C2B4>¢ IP。';
} elseif (!$balanceSufficient) {
$message = '账户余é¢<C3A9>ä¸<C3A4>足,请先充值。';
}
return $this->json($response, [
'instance_id' => (string) $instance->id,
'active_job' => $options['active_job'] ?? null,
'configuration_state' =>
(string) ($options['configuration_state'] ?? 'invalid'),
'price' => $price,
'currency' => 'USD',
'enabled' => $enabled,
'balance_sufficient' => $balanceSufficient,
'can_change' => $canChange,
'message' => $message,
]);
}
/** Quote owner-only, grow-only plans for this instance and billing period. */
public function upgradeOptions($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor);
if ((int) $instance->user_id !== (int) $actor['user_id']) {
throw new CloudError('å<>ªèƒ½å<C2BD>‡çº§è‡ªå·±æŒ<C3A6>有的实例', 403);
}
$this->requireService($instance, $actor);
return $this->json(
$response,
CloudPlanUpgradeService::options($instance, $this->user($request))
);
}
/** Charge the exact current quote and queue one durable grow-only resize. */
public function upgrade($request, $response, $args)
{
$actor = $this->actor($request);
if (!isset($actor['request_idempotency_key'])) {
throw new CloudError('实例å<E280B9>‡çº§å¿…é¡»æ<C2BB><C3A6>供请求幂等标识', 400);
}
$instance = CloudAccess::instance($args['id'], $actor, true);
if ((int) $instance->user_id !== (int) $actor['user_id']) {
throw new CloudError('å<>ªèƒ½å<C2BD>‡çº§è‡ªå·±æŒ<C3A6>有的实例', 403);
}
$this->requireService($instance, $actor);
$body = CloudInput::object($request);
CloudInput::only($body, [
'offer_id', 'expected_amount', 'confirm_shutdown',
]);
if (($body['confirm_shutdown'] ?? false) !== true) {
throw new CloudError('请确认授æ<CB86>ƒç³»ç»Ÿè‡ªåŠ¨æ­£å¸¸å…³æœºå¹¶å®Œæˆ<C3A6>冷å<C2B7>¯åЍå<C2A8>‡çº§');
}
$offerId = filter_var(
$body['offer_id'] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]
);
if ($offerId === false || !is_string($body['expected_amount'] ?? null)) {
throw new CloudError('请选择有效的å<E2809E>‡çº§å¥—é¤<C3A9>');
}
$job = CloudPlanUpgradeService::enqueue(
$instance,
$this->user($request),
$actor,
(int) $offerId,
(string) $body['expected_amount']
);
return $this->json($response, [
'task_id' => (string) $job->id,
'status_url' => '/api/v1/tasks/' . $job->id,
], 202);
}
/** Queue one paid public IPv4 replacement using the exact quoted price. */
public function network($request, $response, $args)
{
$actor = $this->actor($request);
if (!isset($actor['request_idempotency_key'])) {
throw new CloudError('付费更æ<C2B4>¢ IP å¿…é¡»æ<C2BB><C3A6>供请求幂等标识', 400);
}
$instance = CloudAccess::instance($args['id'], $actor, true);
if ((int) $instance->user_id !== (int) $actor['user_id']) {
throw new CloudError('å<>ªèƒ½ä¸ºè‡ªå·±æŒ<C3A6>有的实例更æ<C2B4>¢ IP', 403);
}
$body = CloudInput::object($request);
CloudInput::only($body, ['expected_amount', 'confirm_restart']);
if (($body['confirm_restart'] ?? false) !== true) {
throw new CloudError('æ›´æ<C2B4>¢å…¬ç½‘ IP å‰<C3A5>必须确认虚拟机会短暂é‡<C3A9>å<EFBFBD>¯');
}
try {
$expectedAmount = CloudIpChangeBillingService::normalizePrice(
$body['expected_amount'] ?? null
);
} catch (\InvalidArgumentException $error) {
throw new CloudError($error->getMessage(), 422);
}
$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(
'当å‰<C3A5>虚拟机ä¸<C3A4>是支æŒ<C3A6>网络é…<C3A9>置的é<E2809E>¢æ<C2A2>¿äº‘镜åƒ<C3A5>实例',
409
);
}
$job = CloudJobService::enqueue(
$instance,
$actor,
'network_change',
'POST',
'/network',
['confirm_restart' => true],
null,
$expectedAmount
);
return $this->json($response, [
'task_id' => (string) $job->id,
'status_url' => '/api/v1/tasks/' . $job->id,
], 202);
}
public function rescue($request, $response, $args)
{
$actor = $this->actor($request);
$write = $request->getMethod() !== 'GET';
$instance = CloudAccess::instance($args['id'], $actor, $write);
$action = (string) ($args['rescue_action'] ?? '');
if (!$write) {
$status = CloudAgentSettingsService::clientForHost(
(int) $instance->host_id
)->request('GET', '/v1/vms/'
. rawurlencode((string) $instance->uuid) . '/rescue', $actor);
return $this->json($response, $this->publicRescueStatus($status));
}
$this->requireService($instance, $actor);
$body = CloudInput::object($request);
CloudInput::only($body, ['template_id', 'ack_data_loss']);
if ($action === '/exit') {
if (($body['ack_data_loss'] ?? false) !== true) {
throw new CloudError('退出救æ<E28098>´å¹¶é‡<C3A9>å<EFBFBD>¯å‰<C3A5>必须确认强制断电风险');
}
$suffix = '/rescue/exit';
// Rescue XML may have been saved before a billing/quota block.
// Sign the current desired NIC state so the Agent cannot restore
// an out-of-date link-up snapshot while returning to normal boot.
$body = [
'network_suspended' => in_array(
(string) $instance->network_status,
['blocking', 'blocking_expired', 'blocked_traffic',
'blocked_expired', 'block_failed'],
true
),
'ack_data_loss' => true,
];
} elseif ($action === '/force-start') {
if (($body['ack_data_loss'] ?? false) !== true) {
throw new CloudError('强制å<C2B6>¯åŠ¨æ•‘æ<E28098>´çŽ¯å¢ƒå‰<C3A5>必须确认数æ<C2B0>®é£Žé™©');
}
$suffix = '/rescue/force-start';
$body = ['ack_data_loss' => true];
} else {
if (($body['ack_data_loss'] ?? false) !== true) {
throw new CloudError('进入救æ<E28098>´æ¨¡å¼<C3A5>å‰<C3A5>必须确认数æ<C2B0>®é£Žé™©');
}
$suffix = '/rescue/enter';
$body = [
'template_id' => CloudInput::template(
$body['template_id'] ?? null
),
];
}
$job = CloudJobService::enqueue($instance, $actor, 'rescue', 'POST', $suffix, $body);
return $this->json($response, ['task_id' => (string) $job->id,
'status_url' => '/api/v1/tasks/' . $job->id], 202);
}
private function requireService(CloudInstance $instance, array $actor): void
{
$global = ($actor['is_super_admin'] ?? false) && ($actor['can_manage'] ?? false);
if (!$global && !$instance->serviceAvailable()) {
throw new CloudError('实例æœ<C3A6>务已到期或正在æ<C2A8>¢å¤<C3A5>,请先续费并等待æ<E280A6>¢å¤<C3A5>完æˆ<C3A6>', 409);
}
}
public function delete($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor, true);
$body = CloudInput::object($request);
CloudInput::only($body, ['confirmation_name', 'delete_disks']);
if (($body['confirmation_name'] ?? '') !== $instance->name) {
throw new CloudError('请填写虚拟机å<C2BA><C3A5>称确认删除');
}
$deleteDisks = filter_var($body['delete_disks'] ?? true,
FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if ($deleteDisks === null
|| ((string) $instance->service_status !== 'exempt' && !$deleteDisks)) {
throw new CloudError('销售实例删除必须å<C2BB>Œæ­¥åˆ é™¤é<C2A4>¢æ<C2A2>¿ç®¡ç<C2A1>†çš„虚拟ç£<C3A7>盘');
}
$job = CloudJobService::enqueue($instance, $actor, 'delete', 'DELETE',
'', ['remove_managed_disks' => $deleteDisks]);
return $this->json($response, ['task_id' => (string) $job->id,
'status_url' => '/api/v1/tasks/' . $job->id], 202);
}
public function sshKeys($request, $response)
{
$actor = $this->actor($request);
if ($request->getMethod() === 'POST') {
$body = CloudInput::object($request);
CloudInput::only($body, ['name', 'public_key']);
$name = $body['name'] ?? '';
if (!is_string($name) || trim($name) === '' || mb_strlen($name) > 80) {
throw new CloudError('公钥å<C2A5><C3A5>称需为 1 至 80 字符');
}
$parsed = CloudSSHKeys::parse($body['public_key'] ?? '');
if (CloudSSHKey::where('user_id', $actor['user_id'])->where('fingerprint', $parsed['fingerprint'])->exists()) {
throw new CloudError('该公钥已ç»<C3A7>添加', 409);
}
$key = new CloudSSHKey();
$key->user_id = $actor['user_id'];
$key->name = trim($name);
$key->public_key = $parsed['public_key'];
$key->fingerprint = $parsed['fingerprint'];
$key->created_at = time();
$key->save();
return $this->json($response, ['id' => (int) $key->id, 'name' => $key->name, 'fingerprint' => $key->fingerprint], 201);
}
return $this->json($response, [
'keys' => CloudDeploymentPageService::sshKeys((int) $actor['user_id']),
]);
}
public function deleteKey($request, $response, $args)
{
$key = CloudSSHKeys::owned($args['id'], $this->actor($request)['user_id']);
$key->delete();
return $this->json($response, ['deleted' => true]);
}
public function resources($request, $response)
{
$actor = $this->actor($request);
$query = $request->getQueryParams();
// Cloud images are a PHP-owned panel-wide catalog. Per-host replica
// state is tracked by PHP and fulfilled by each target Agent; neither
// detail belongs in the tenant image picker.
$catalog = CloudDeploymentPageService::freshTemplateCatalog($actor);
$templatePayload = [
'templates' => is_array($catalog['templates'] ?? null)
? $catalog['templates'] : [],
];
// Replication state is a host-internal catalog detail. It can contain
// pool names, source paths, or future Agent fields and is not needed
// by the user image picker, so never copy it into a public response.
if (!isset($query['vm_id'])) {
return $this->json($response, $templatePayload);
}
$hostId = (int) CloudAccess::instance($query['vm_id'], $actor)->host_id;
$rescue = CloudRescueTemplateImportService::catalog($hostId);
// The rescue response can contain host paths or future internal fields.
// The browser only needs display names, so construct a fixed DTO instead
// of unsetting a few currently-known fields and exposing future ones.
$public = $templatePayload;
$public['rescue_templates'] = $this->publicRescueTemplates(
$rescue['templates'] ?? []
);
return $this->json($response, $public);
}
public function userIsos($request, $response)
{
$actor = $this->actor($request);
CloudUserIsoFeature::assertEnabled();
if ($request->getMethod() === 'POST') {
$this->userIsoImportAllowed($actor, true);
$job = CloudUserIsoService::import(
CloudInput::object($request), $actor
);
return $this->json($response, $job, 202);
}
$result = CloudUserIsoService::listing((int) $actor['user_id']);
$result['can_import'] = $this->userIsoImportAllowed($actor);
return $this->json($response, $result);
}
public function deleteUserIso($request, $response, $args)
{
$actor = $this->actor($request);
CloudUserIsoFeature::assertEnabled();
$isoId = (string) ($args['id'] ?? '');
if (preg_match('/^[a-f0-9]{32}$/D', $isoId) !== 1) {
throw new CloudError('ISO 镜åƒ<C3A5>标识无效');
}
return $this->json($response,
CloudUserIsoService::delete($isoId, $actor), 202);
}
}