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

1008 lines
46 KiB
PHP

<?php
namespace App\Controllers;
use App\Models\CloudHost;
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\Shop;
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\CloudEngineClient;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInput;
use App\Services\Cloud\CloudInstanceMetadata;
use App\Services\Cloud\CloudInstancePageService;
use App\Services\Cloud\CloudJobService;
use App\Services\Cloud\CloudInvoicePageService;
use App\Services\Cloud\CloudInvoicePaymentService;
use App\Services\Cloud\CloudInvoiceService;
use App\Services\Cloud\CloudOrderService;
use App\Services\Cloud\CloudSecrets;
use App\Services\Cloud\CloudSSHKeys;
use App\Services\Cloud\CloudUserIsoFeature;
final class CloudApiController
{
private function actor($request): array
{
return $request->getAttribute('cloud_actor') ?? CloudAccess::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
&& (int) $user->restrict_balance_purchase !== 1;
if (!$allowed && $throw) {
throw new CloudError('账户套餐购买及 ISO 上传服务已被管理员停用', 403);
}
return $allowed;
}
private function publicUserIsoRecord($value): ?array
{
if (!is_array($value) || preg_match('/^[0-9a-f]{32}$/D', (string) ($value['id'] ?? '')) !== 1) {
return null;
}
return ['id' => (string) $value['id'], 'name' => (string) ($value['name'] ?? ''),
'size_bytes' => max(0, (int) ($value['size_bytes'] ?? 0)),
'sha256' => preg_match('/^[0-9a-f]{64}$/D', (string) ($value['sha256'] ?? '')) === 1
? (string) $value['sha256'] : '',
'created_at' => max(0, (int) ($value['created_at'] ?? 0))];
}
private function publicUserIsoRecords($values): array
{
$records = [];
foreach (is_array($values) ? $values : [] as $value) {
$record = $this->publicUserIsoRecord($value);
if ($record !== null) {
$records[] = $record;
}
}
return $records;
}
private function publicUserIsoJob($value): ?array
{
if (!is_array($value)
|| preg_match('/^[A-Za-z0-9_-]{8,80}$/D', (string) ($value['job_id'] ?? '')) !== 1) {
return null;
}
$job = ['job_id' => (string) $value['job_id'],
'status' => (string) ($value['status'] ?? ''),
'phase' => (string) ($value['phase'] ?? ''),
'created_at' => max(0, (int) ($value['created_at'] ?? 0))];
foreach (['started_at', 'finished_at'] as $key) {
if (isset($value[$key])) {
$job[$key] = max(0, (int) $value[$key]);
}
}
if (isset($value['iso'])) {
$record = $this->publicUserIsoRecord($value['iso']);
if ($record !== null) {
$job['iso'] = $record;
}
}
if (array_key_exists('error', $value)) {
$job['error'] = CloudEngineClient::safeUserIsoMessage($value['error'])
?? 'ISO 下载或导入失败,请联系管理员查看日志';
}
return $job;
}
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 plans($request, $response)
{
$plans = [];
$available = Shop::where('status', 1)->orderBy('sort')->orderBy('id')->get();
$hostIds = $available->pluck('host_id')->map(static fn ($id) => (int) $id)
->filter(static fn ($id) => $id > 0)->unique()->values()->all();
$hosts = $hostIds === [] ? collect() : CloudHost::whereIn('id', $hostIds)
->where('enabled', 1)->get()->keyBy('id');
foreach ($available as $plan) {
if ((int) $plan->stock === 0) {
continue;
}
$host = $hosts->get((int) $plan->host_id);
if ($host !== null) {
$plans[] = ['id' => (int) $plan->id, 'name' => $plan->name, 'price' => (string) $plan->price,
'cpu_cores' => (int) $plan->cpu_cores, 'memory_mib' => (int) $plan->memory_mib,
'bandwidth_mbps' => (int) $plan->bandwidth_mbps, 'disk_gib' => (int) $plan->disk_gib,
'validity_days' => (int) $plan->validity_days,
'traffic_quota_bytes' => (int) $plan->traffic_quota_bytes,
'traffic_gib' => $plan->trafficGiB(),
'stock' => (int) $plan->stock, 'host_id' => (int) $host->id,
'host_name' => $host->name, 'country_code' => strtoupper((string) ($host->country_code ?? '')),
'region' => $host->region];
}
}
return $this->json($response, ['plans' => $plans]);
}
public function orders($request, $response)
{
$actor = $this->actor($request);
if ($request->getMethod() === 'POST') {
// Compatibility alias for a browser loaded before the unified
// billing release. It now creates only an unpaid invoice.
return $this->createProvisionInvoice($request, $response, $actor);
}
$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('订单不存在', 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('订单请求标识无效');
}
// 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('订单请求尚未建立', 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('账单请求标识无效');
}
$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('账单请求尚未建立', 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('账单页码无效');
}
$perPage = 10;
$payload = CloudInvoicePageService::forUser(
(int) $actor['user_id'], (int) $pageValue, $perPage
);
$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) {
// An idempotency key from a pre-invoice deployment can still
// resolve to its historical order after an upgrade. Do not turn
// that expected compatibility case into an opaque HTTP 500.
if ((string) $order->status !== 'awaiting_payment') {
throw new CloudError('该请求已由旧版开通流程处理,请刷新实例列表或联系管理员核对', 409);
}
throw new \RuntimeException('开通账单创建失败');
}
return $this->json($response,
['invoice' => CloudInvoiceService::display($invoice)], 201);
}
public function invoice($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('账单不存在', 404);
}
$user = $this->user($request);
$detail = CloudInvoiceService::display($invoice);
return $this->json($response, [
'invoice' => $detail,
'payment_methods' => ($detail['payable'] ?? false)
? CloudInvoicePaymentService::methods($user) : [],
'balance' => (string) $user->money,
'csrf_token' => AdminCsrf::token(),
'user_id' => (string) $user->id,
'username' => (string) ($user->user_name ?: $user->email),
'admin' => (bool) $actor['is_admin'],
]);
}
public function invoiceStatus($request, $response, $args)
{
$actor = $this->billingActor($request);
$invoice = CloudInvoice::where('id', $args['id'])
->where('user_id', $actor['user_id'])
->first(['id', 'purpose', 'instance_id', 'order_id', 'user_id',
'due_at', 'status', 'paid_at', 'paid_via', 'created_at']);
if ($invoice === null) {
throw new CloudError('账单不存在', 404);
}
return $this->json($response, [
'invoice' => CloudInvoiceService::status($invoice),
]);
}
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('账单不存在', 404);
}
$body = CloudInput::object($request);
CloudInput::only($body, ['idempotency_key']);
$paid = CloudInvoiceService::payBalance($invoice, $actor,
trim((string) ($body['idempotency_key'] ?? '')));
$user = $this->user($request)->fresh();
return $this->json($response, ['invoice' => CloudInvoiceService::display($paid),
'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('账单不存在', 404);
}
$payment = CloudInvoicePaymentService::create($invoice, $this->user($request),
CloudInput::object($request),
(string) $request->getServerParam('REMOTE_ADDR', ''),
(string) $request->getHeaderLine('User-Agent'));
return $this->json($response, ['payment' => $payment], 201);
}
public function job($request, $response, $args)
{
$actor = $this->actor($request);
$query = CloudJob::where('id', $args['id']);
if (!$actor['is_admin']) {
$query->where('user_id', $actor['user_id']);
}
$job = $query->first();
if ($job === null) {
throw new CloudError('任务不存在', 404);
}
return $this->json($response, CloudJobService::display($job));
}
private function unavailableVm(CloudInstance $instance): array
{
return ['name' => $instance->name, 'state' => 'unknown',
'detail' => '宿主机暂时无法连接'];
}
/**
* Resolve list-only VM dependencies in fixed-size database queries and one
* engine inventory request per visible host. The database collection is
* authoritative: an engine row is only merged when its UUID is present in
* the already actor-scoped instance collection.
*/
private function vmListContexts($instances, array $actor): array
{
if ($instances->isEmpty()) {
return [];
}
$instanceIds = $instances->pluck('id')->map(fn ($id) => (int) $id)->all();
$hostIds = $instances->pluck('host_id')->map(fn ($id) => (int) $id)
->unique()->values()->all();
$periodIds = $instances->pluck('current_period_id')->filter(
fn ($id) => $id !== null)->map(fn ($id) => (int) $id)->unique()->values()->all();
$hosts = [];
foreach (CloudHost::whereIn('id', $hostIds)->get() as $host) {
$hosts[(int) $host->id] = $host;
}
$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;
}
$engine = new CloudEngineClient();
$liveByInstance = [];
foreach ($instances->groupBy(fn ($instance) => (int) $instance->host_id) as $hostId => $group) {
$allowed = [];
foreach ($group as $instance) {
$allowed[strtolower((string) $instance->uuid)] = (int) $instance->id;
$liveByInstance[(int) $instance->id] = $this->unavailableVm($instance);
}
try {
$inventory = $engine->host((int) $hostId, 'GET', 'vms', $actor);
foreach (is_array($inventory['items'] ?? null) ? $inventory['items'] : [] as $vm) {
if (!is_array($vm) || !is_string($vm['uuid'] ?? null)) {
continue;
}
$instanceId = $allowed[strtolower(trim($vm['uuid']))] ?? null;
if ($instanceId !== null) {
$liveByInstance[$instanceId] = $vm;
}
}
} catch (CloudError $error) {
// Preserve a useful database-backed row when one host is down;
// another host's inventory must still 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),
'host' => $hosts[(int) $instance->host_id] ?? null,
'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);
$spec = json_decode($instance->spec_json, true) ?: [];
if ($context === null) {
try {
$vm = (new CloudEngineClient())->host((int) $instance->host_id, 'GET',
'vms/' . rawurlencode($instance->uuid), $actor);
} catch (CloudError $error) {
$vm = $this->unavailableVm($instance);
}
$host = CloudHost::find($instance->host_id);
$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);
$host = $context['host'] ?? null;
$period = $context['period'] ?? null;
$futurePeriods = max(0, (int) ($context['future_periods'] ?? 0));
}
$createdAt = ($spec['record_source'] ?? '') === 'discovered'
? (is_string($vm['created_at'] ?? null) && trim($vm['created_at']) !== '' ? $vm['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(CloudInput::safeResult($spec), CloudInput::safeResult($vm), ['id' => (string) $instance->id, 'uuid' => $instance->uuid,
'user_id' => (int) $instance->user_id, 'owner_user_id' => (int) $instance->user_id,
'display_uuid' => $instance->uuid, 'host_id' => (int) $instance->host_id, 'region' => $host?->region ?? '',
'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_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->credential_cipher !== 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('实例页码无效');
}
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('实例编号列表无效');
}
$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('实例编号无效');
}
$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('虚拟机不存在或无权访问', 404);
}
return $this->json($response, $rows[0]);
}
private function vmMetadataRows(array $actor, array $ids): array
{
$snapshots = CloudInstancePageService::forActorIds($actor, $ids);
$live = [];
$engine = new CloudEngineClient();
foreach ($this->vmSnapshotsByHost($snapshots) as $hostId => $group) {
$allowed = [];
$hostLive = [];
foreach ($group as $snapshot) {
$uuid = strtolower((string) $snapshot['uuid']);
$allowed[$uuid] = true;
}
try {
$payload = $engine->host((int) $hostId, 'GET', 'vm-metadata?ids=' .
rawurlencode(implode(',', array_keys($allowed))), $actor);
foreach (is_array($payload['items'] ?? null) ? $payload['items'] : [] as $item) {
if (!is_array($item) || !is_string($item['uuid'] ?? null)) {
continue;
}
$uuid = strtolower(trim($item['uuid']));
if (isset($allowed[$uuid])) {
$hostLive[$uuid] = $item;
$live[(int) $hostId . ':' . $uuid] = $item;
}
}
} 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']);
$key = (int) $snapshot['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 engine response is considered, and engine UUIDs are
* intersected with that owner-scoped set before being returned.
*/
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('实例编号列表无效');
}
$ids = array_values(array_unique(array_map('intval', explode(',', (string) $raw))));
$snapshots = CloudInstancePageService::forActorIds($actor, $ids);
$live = [];
$engine = new CloudEngineClient();
foreach ($this->vmSnapshotsByHost($snapshots) as $hostId => $group) {
$allowed = [];
foreach ($group as $snapshot) {
$allowed[strtolower((string) $snapshot['uuid'])] = true;
}
try {
$payload = $engine->host((int) $hostId, 'GET', 'vm-states', $actor);
foreach (is_array($payload['items'] ?? null) ? $payload['items'] : [] as $item) {
if (!is_array($item) || !is_string($item['uuid'] ?? null)) {
continue;
}
$uuid = strtolower(trim($item['uuid']));
if (isset($allowed[$uuid])) {
$live[(int) $hostId . ':' . $uuid] = $item;
}
}
} 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']);
$key = (int) $snapshot['host_id'] . ':' . $uuid;
$statuses[] = CloudInstancePageService::powerStatus(
$snapshot, $live[$key] ?? []
);
}
return $this->json($response, ['vms' => $statuses]);
}
/** Lightweight live state for one owner-scoped detail page. */
public function vmStatus($request, $response, $args)
{
$actor = $this->actor($request);
$snapshot = CloudInstancePageService::statusForActor($actor, $args['id']);
$live = [];
try {
$candidate = (new CloudEngineClient())->host(
(int) $snapshot['host_id'],
'GET',
'vms/' . rawurlencode((string) $snapshot['uuid']) . '/state',
$actor
);
if (is_array($candidate)
&& is_string($candidate['uuid'] ?? null)
&& hash_equals(strtolower((string) $snapshot['uuid']),
strtolower(trim($candidate['uuid'])))) {
$live = $candidate;
}
} catch (CloudError $error) {
// Preserve the database snapshot when the host is unavailable.
}
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));
}
private function vmSnapshotsByHost(array $snapshots): array
{
$groups = [];
foreach ($snapshots as $snapshot) {
$hostId = max(0, (int) ($snapshot['host_id'] ?? 0));
if ($hostId > 0) {
$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('指标时间范围无效');
}
$suffix = '?range=' . rawurlencode($range);
return $this->json($response, (new CloudEngineClient())->host((int) $instance->host_id, 'GET',
'vms/' . rawurlencode($instance->uuid) . '/metrics' . $suffix, $actor));
}
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('流量统计天数无效');
}
$days = filter_var((string) $rawDays, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1, 'max_range' => 30]]);
if ($days === false) {
throw new CloudError('流量统计天数必须为 1 至 30');
}
return $this->json($response, (new CloudEngineClient())->host((int) $instance->host_id,
'GET', 'vms/' . rawurlencode($instance->uuid) . '/traffic/daily?days=' . (int) $days,
$actor));
}
public function credential($request, $response, $args)
{
$instance = CloudAccess::instance($args['id'], $this->actor($request), true);
if ($instance->credential_cipher === null) {
throw new CloudError('该虚拟机没有面板保存的初始密码', 404);
}
return $this->json($response, CloudSecrets::decrypt($instance->credential_cipher));
}
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);
return $this->json($response, (new CloudEngineClient())->host((int) $instance->host_id, 'POST',
'vms/' . rawurlencode($instance->uuid) . '/console-ticket', $actor, []));
}
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']);
if (!in_array($body['action'] ?? '', ['start', 'shutdown', 'reboot', 'poweroff', 'reset'], true)) {
throw new CloudError('操作无效');
}
if (in_array($body['action'], ['start', 'reboot', 'reset'], true)) {
$this->requireService($instance, $actor);
}
$job = CloudJobService::enqueue($instance, $actor, 'action', 'POST', '/actions', $body);
return $this->json($response, ['job_id' => (string) $job->id, 'status_url' => '/api/v1/jobs/' . $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('请填写虚拟机名称确认重装');
}
$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 ?? '';
$body['root_password'] = CloudInput::password($body['root_password'] ?? null);
$job = CloudJobService::enqueue($instance, $actor, 'reinstall', 'POST', '/reinstall', $body,
['password' => $body['root_password'], 'login_name' => 'root', 'auth_mode' => $key ? 'password_and_key' : 'password']);
return $this->json($response, ['job_id' => (string) $job->id, 'status_url' => '/api/v1/jobs/' . $job->id], 202);
}
public function rescue($request, $response, $args)
{
$actor = $this->actor($request);
$write = $request->getMethod() !== 'GET';
$instance = CloudAccess::instance($args['id'], $actor, $write);
$suffix = '/rescue' . ($args['rescue_action'] ?? '');
if (!$write) {
return $this->json($response, (new CloudEngineClient())->host((int) $instance->host_id, 'GET',
'vms/' . rawurlencode($instance->uuid) . $suffix, $actor));
}
$this->requireService($instance, $actor);
$body = CloudInput::object($request);
CloudInput::only($body, ['template_id', 'confirmation_name', 'ack_data_loss']);
if (($body['confirmation_name'] ?? '') !== $instance->name) {
throw new CloudError('请填写虚拟机名称确认操作');
}
if ($suffix === '/rescue/exit') {
// The saved original XML may predate a traffic-quota block. Pass
// the current billing target so the engine restores every NIC in
// the correct link state before it starts the normal system.
$body['network_suspended'] = in_array(
(string) $instance->network_status,
['blocking', 'blocked_traffic', 'blocked_expired', 'block_failed'], true);
}
$job = CloudJobService::enqueue($instance, $actor, 'rescue', 'POST', $suffix, $body);
return $this->json($response, ['job_id' => (string) $job->id, 'status_url' => '/api/v1/jobs/' . $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('实例服务已到期或正在恢复,请先续费并等待恢复完成', 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('请填写虚拟机名称确认删除');
}
$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('销售实例删除必须同步删除面板管理的虚拟磁盘');
}
$job = CloudJobService::enqueue($instance, $actor, 'delete', 'DELETE',
'?delete_disks=' . ($deleteDisks ? 'true' : 'false'), []);
return $this->json($response, ['job_id' => (string) $job->id, 'status_url' => '/api/v1/jobs/' . $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('公钥名称需为 1 至 80 字符');
}
$parsed = CloudSSHKeys::parse($body['public_key'] ?? '');
if (CloudSSHKey::where('user_id', $actor['user_id'])->where('fingerprint', $parsed['fingerprint'])->exists()) {
throw new CloudError('该公钥已经添加', 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);
}
$keys = CloudSSHKey::where('user_id', $actor['user_id'])->orderBy('id')->get()->map(fn ($key) =>
['id' => (int) $key->id, 'name' => $key->name, 'fingerprint' => $key->fingerprint, 'created_at' => (int) $key->created_at])->all();
return $this->json($response, ['keys' => $keys]);
}
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();
$engine = new CloudEngineClient();
// Cloud images are a panel-wide catalog. Host-specific replication is
// owned by the private engine and must not make the browser reload or
// replace the catalog whenever a customer changes region or plan.
$catalog = $engine->request('GET', '/internal/v1/vm-templates', $actor);
$templatePayload = [
'templates' => is_array($catalog['templates'] ?? null)
? $catalog['templates'] : [],
];
foreach (['catalog_version', 'replicas', 'replica_states'] as $field) {
if (isset($catalog[$field])
&& (is_array($catalog[$field]) || is_string($catalog[$field]))) {
$templatePayload[$field] = $catalog[$field];
}
}
if (isset($query['vm_id'])) {
$hostId = (int) CloudAccess::instance($query['vm_id'], $actor)->host_id;
} elseif (isset($query['plan_id'])) {
// Compatibility for a browser opened before global catalogs were
// deployed. New clients request /resources once without a plan.
$plan = Shop::where('id', $query['plan_id'] ?? 0)->where('status', 1)->first();
$hostId = (int) ($plan?->host_id ?? 0);
if (!CloudHost::where('id', $hostId)->where('enabled', 1)->exists()) {
throw new CloudError('套餐宿主机不可用', 404);
}
} else {
return $this->json($response, $templatePayload);
}
if (!isset($query['vm_id'])) {
return $this->json($response, $templatePayload + ['host_id' => $hostId]);
}
$value = $engine->host($hostId, 'GET', 'resources', $actor);
$rescue = $engine->host($hostId, 'GET', 'rescue-templates', $actor);
// The configured root ISO pool can contain administrator or legacy
// files and is never exposed through this user API.
unset($value['isos'], $value['iso_images']);
$value = array_merge($value, $templatePayload);
$value['rescue_templates'] = $rescue['templates'] ?? [];
$value['host_id'] = $hostId;
return $this->json($response, $value);
}
private function userIsoWriteActor(array $actor): array
{
// Engine mutations require an explicit write grant. The engine still
// derives the storage directory and catalog owner from this user_id;
// this flag does not grant access to another account's ISO records.
$actor['can_manage'] = true;
return $actor;
}
public function userIsos($request, $response)
{
$actor = $this->actor($request);
CloudUserIsoFeature::assertEnabled();
$engine = new CloudEngineClient();
if ($request->getMethod() === 'POST') {
$this->userIsoImportAllowed($actor, true);
$body = CloudInput::object($request);
CloudInput::only($body, ['name', 'url']);
$result = $engine->request('POST', '/internal/v1/user-isos/import',
$this->userIsoWriteActor($actor), $body);
$jobId = (string) ($result['job_id'] ?? '');
if (preg_match('/^[A-Za-z0-9_-]{8,80}$/D', $jobId) !== 1) {
throw new CloudError('虚拟化引擎未返回有效的 ISO 下载任务', 502);
}
return $this->json($response, ['job_id' => $jobId, 'status' => 'queued',
'status_url' => '/api/v1/user-isos/import-jobs/'
. rawurlencode($jobId)], 202);
}
$result = $engine->request('GET', '/internal/v1/user-isos', $actor);
$public = ['isos' => $this->publicUserIsoRecords($result['isos'] ?? []),
'can_import' => $this->userIsoImportAllowed($actor)];
if (isset($result['active_import_job'])) {
$active = $this->publicUserIsoJob($result['active_import_job']);
if ($active !== null && in_array($active['status'], ['queued', 'running'], true)) {
$public['active_import_job'] = $active;
}
}
return $this->json($response, $public);
}
public function userIsoJob($request, $response, $args)
{
$actor = $this->actor($request);
CloudUserIsoFeature::assertEnabled();
$jobId = (string) ($args['job_id'] ?? '');
if (preg_match('/^[A-Za-z0-9_-]{8,80}$/D', $jobId) !== 1) {
throw new CloudError('ISO 下载任务编号无效');
}
$job = $this->publicUserIsoJob((new CloudEngineClient())->request(
'GET', '/internal/v1/user-isos/import-jobs/' . rawurlencode($jobId), $actor));
if ($job === null) {
throw new CloudError('虚拟化引擎返回了无效的 ISO 下载任务', 502);
}
return $this->json($response, $job);
}
public function deleteUserIso($request, $response, $args)
{
$actor = $this->actor($request);
CloudUserIsoFeature::assertEnabled();
$isoId = (string) ($args['id'] ?? '');
if (preg_match('/^[0-9a-f]{32}$/D', $isoId) !== 1) {
throw new CloudError('ISO 镜像标识无效');
}
$deleted = (new User())->getConnection()->transaction(function () use ($actor, $isoId) {
$user = User::where('id', $actor['user_id'])->lockForUpdate()->first();
if ($user === null || (int) $user->enable !== 1) {
throw new CloudError('账户不可用', 403);
}
foreach (CloudOrder::where('user_id', $actor['user_id'])
->whereIn('status', ['awaiting_payment', 'queued', 'running', 'uncertain'])
->get(['spec_json']) as $order) {
$spec = json_decode((string) $order->spec_json, true);
if (is_array($spec) && isset($spec['user_iso_id'])
&& is_string($spec['user_iso_id'])
&& hash_equals($isoId, $spec['user_iso_id'])) {
throw new CloudError('该 ISO 正被未完成的开通账单或创建任务使用,暂不能删除', 409);
}
}
(new CloudEngineClient())->request('DELETE',
'/internal/v1/user-isos/' . $isoId, $this->userIsoWriteActor($actor));
return ['deleted' => true];
}, 3);
return $this->json($response, $deleted);
}
}