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

298 lines
14 KiB
PHP

<?php
namespace App\Controllers;
use App\Models\CloudHost;
use App\Models\CloudInstance;
use App\Models\CloudJob;
use App\Models\CloudOrder;
use App\Models\CloudSSHKey;
use App\Models\Shop;
use App\Services\Auth;
use App\Services\AdminCsrf;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudEngineClient;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInput;
use App\Services\Cloud\CloudJobService;
use App\Services\Cloud\CloudOrderService;
use App\Services\Cloud\CloudSecrets;
use App\Services\Cloud\CloudSSHKeys;
final class CloudApiController
{
private function actor($request): array
{
return $request->getAttribute('cloud_actor') ?? CloudAccess::actor();
}
private function json($response, array $value, int $status = 200)
{
return $response->withJson($value, $status)->withHeader('Cache-Control', 'no-store');
}
public function session($request, $response)
{
try {
$actor = CloudAccess::actor();
$user = Auth::getUser();
return $this->json($response, ['authenticated' => true, 'username' => $user->user_name,
'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 = [];
foreach (Shop::where('status', 1)->orderBy('sort')->orderBy('id')->get() as $plan) {
$host = CloudHost::where('id', $plan->host_id)->where('enabled', 1)->first();
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,
'stock' => (int) $plan->stock, 'host_id' => (int) $host->id, 'host_name' => $host->name, 'region' => $host->region];
}
}
return $this->json($response, ['plans' => $plans]);
}
public function orders($request, $response)
{
$actor = $this->actor($request);
if ($request->getMethod() === 'POST') {
$order = CloudOrderService::purchase(CloudInput::object($request), $actor);
$display = CloudOrderService::display($order);
return $this->json($response, ['order' => $display, 'job_id' => $display['job_id'],
'status_url' => '/api/v1/jobs/' . $display['job_id']], 202);
}
$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 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 vmData(CloudInstance $instance, array $actor): array
{
$spec = json_decode($instance->spec_json, true) ?: [];
try {
$vm = (new CloudEngineClient())->host((int) $instance->host_id, 'GET', 'vms/' . rawurlencode($instance->uuid), $actor);
} catch (CloudError $error) {
$vm = ['name' => $instance->name, 'state' => 'unknown', 'detail' => '宿主机暂时无法连接'];
}
$host = CloudHost::find($instance->host_id);
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' => gmdate('Y-m-d\TH:i:s\Z', (int) $instance->created_at),
'has_initial_root_password' => $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']);
}
return $this->json($response, ['vms' => $query->orderByDesc('id')->limit(200)->get()->map(
fn ($instance) => $this->vmData($instance, $actor))->all()]);
}
public function vm($request, $response, $args)
{
$actor = $this->actor($request);
return $this->json($response, $this->vmData(CloudAccess::instance($args['id'], $actor), $actor));
}
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 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);
$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('操作无效');
}
$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);
$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));
}
$body = CloudInput::object($request);
CloudInput::only($body, ['template_id', 'confirmation_name', 'ack_data_loss']);
if (($body['confirmation_name'] ?? '') !== $instance->name) {
throw new CloudError('请填写虚拟机名称确认操作');
}
$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);
}
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'] ?? false, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if ($deleteDisks === null) {
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();
if (isset($query['vm_id'])) {
$hostId = (int) CloudAccess::instance($query['vm_id'], $actor)->host_id;
} else {
$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);
}
}
$engine = new CloudEngineClient();
$value = $engine->host($hostId, 'GET', 'resources', $actor);
$templates = $engine->host($hostId, 'GET', 'vm-templates', $actor);
$rescue = $engine->host($hostId, 'GET', 'rescue-templates', $actor);
$value['templates'] = $templates['templates'] ?? [];
$value['rescue_templates'] = $rescue['templates'] ?? [];
$value['host_id'] = $hostId;
return $this->json($response, $value);
}
}