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.
298 lines
12 KiB
PHP
298 lines
12 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Cloud;
|
|
|
|
use App\Models\CloudRegion;
|
|
use App\Models\CloudVpc;
|
|
use App\Models\CloudVpcCidrPool;
|
|
use App\Models\CloudVpcHostState;
|
|
use App\Models\CloudVpcPort;
|
|
|
|
/** User-owned VPC lifecycle and region-serialized IPv4 prefix allocation. */
|
|
final class CloudVpcService
|
|
{
|
|
private const MAX_VPCS_PER_USER = 16;
|
|
|
|
public static function library(array $actor): array
|
|
{
|
|
$userId = self::userId($actor);
|
|
$portCounts = CloudVpcPort::query()->where('active_claim', 1)
|
|
->selectRaw('vpc_id, COUNT(*) AS row_count')->groupBy('vpc_id')
|
|
->pluck('row_count', 'vpc_id');
|
|
$regions = CloudVpcRegionReadiness::catalog();
|
|
$regionNames = [];
|
|
foreach ($regions as $region) {
|
|
$regionNames[(int) $region['id']] = (string) $region['name'];
|
|
}
|
|
$items = CloudVpc::query()->where('user_id', $userId)
|
|
->where('active_claim', 1)->orderByDesc('id')->get()
|
|
->map(static fn ($vpc): array => self::dto(
|
|
$vpc,
|
|
(string) ($regionNames[(int) $vpc->region_id]
|
|
?? '地区已不可用'),
|
|
(int) ($portCounts[(int) $vpc->id] ?? 0)
|
|
))->all();
|
|
return [
|
|
'items' => $items,
|
|
'instances' => CloudVpcPortService::managementListing($actor),
|
|
'membership_batches' =>
|
|
CloudVpcMembershipBatchService::activeForOwner($userId),
|
|
'regions' => $regions,
|
|
'maximum' => self::MAX_VPCS_PER_USER,
|
|
'used' => count($items),
|
|
];
|
|
}
|
|
|
|
public static function create(array $actor, array $input): array
|
|
{
|
|
$userId = self::userId($actor);
|
|
$requestKey = $actor['request_idempotency_key'] ?? null;
|
|
if (!is_string($requestKey)
|
|
|| preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $requestKey) !== 1) {
|
|
throw new CloudError('创建 VPC 必须提供有效的请求幂等标识', 400);
|
|
}
|
|
CloudInput::only($input, ['name', 'region_id']);
|
|
$name = self::name($input['name'] ?? null);
|
|
$regionId = $input['region_id'] ?? null;
|
|
if (is_bool($regionId) || !is_int($regionId) || $regionId < 1) {
|
|
throw new CloudError('请选择可用的 VPC 地区');
|
|
}
|
|
$vpcKey = substr(hash('sha256', "user-vpc\0" . $userId . "\0"
|
|
. $requestKey), 0, 32);
|
|
|
|
$connection = (new CloudVpc())->getConnection();
|
|
$vpc = $connection->transaction(static function () use (
|
|
$userId, $regionId, $name, $vpcKey
|
|
): CloudVpc {
|
|
$region = CloudRegion::query()->where('id', $regionId)
|
|
->lockForUpdate()->first();
|
|
if ($region === null || (string) $region->status !== 'active') {
|
|
throw new CloudError('所选 VPC 地区当前不可用', 409);
|
|
}
|
|
if (!in_array($regionId,
|
|
CloudVpcRegionReadiness::eligibleRegionIds(), true)) {
|
|
throw new CloudError(
|
|
'所选地区暂无已验证就绪的 VPC 计算节点', 409
|
|
);
|
|
}
|
|
$pools = CloudVpcCidrPool::query()->where('region_id', $regionId)
|
|
->where('state', 'active')->orderBy('id')
|
|
->lockForUpdate()->get();
|
|
if ($pools->isEmpty()) {
|
|
throw new CloudError('所选地区暂无可分配的 VPC 地址池', 409);
|
|
}
|
|
|
|
$owned = CloudVpc::query()->where('user_id', $userId)
|
|
->orderBy('id')->lockForUpdate()->get();
|
|
$existing = $owned->first(static fn ($row): bool =>
|
|
hash_equals((string) $row->vpc_key, $vpcKey));
|
|
if ($existing !== null) {
|
|
if ((int) $existing->region_id === $regionId
|
|
&& hash_equals((string) $existing->name, $name)) {
|
|
return $existing;
|
|
}
|
|
throw new CloudError(
|
|
'同一请求幂等标识不能用于不同的 VPC 配置', 409
|
|
);
|
|
}
|
|
if ($owned->filter(static fn ($row): bool =>
|
|
(int) ($row->active_claim ?? 0) === 1)->count()
|
|
>= self::MAX_VPCS_PER_USER) {
|
|
throw new CloudError('每个账户最多创建 16 个 VPC', 409);
|
|
}
|
|
|
|
$allocation = null;
|
|
foreach ($pools as $pool) {
|
|
$rows = CloudVpc::query()
|
|
->where('cidr_pool_id', (int) $pool->id)
|
|
->where('active_claim', 1)->orderBy('id')
|
|
->lockForUpdate()->get(['id', 'cidr', 'prefix_length']);
|
|
$cidr = self::firstAvailableCidr($pool, $rows->all());
|
|
if ($cidr !== null) {
|
|
$allocation = [$pool, $cidr];
|
|
break;
|
|
}
|
|
}
|
|
if ($allocation === null) {
|
|
throw new CloudError('所选地区的 VPC 地址空间已用尽', 409);
|
|
}
|
|
[$pool, $cidr] = $allocation;
|
|
[$network, $prefix] = explode('/', $cidr, 2);
|
|
$now = time();
|
|
$vpc = new CloudVpc();
|
|
$vpc->vpc_key = $vpcKey;
|
|
$vpc->user_id = $userId;
|
|
$vpc->region_id = $regionId;
|
|
$vpc->cidr_pool_id = (int) $pool->id;
|
|
$vpc->name = $name;
|
|
$vpc->cidr = $cidr;
|
|
$vpc->prefix_length = (int) $prefix;
|
|
$vpc->gateway = long2ip(self::number($network) + 1);
|
|
$vpc->active_claim = 1;
|
|
$vpc->state = 'active';
|
|
$vpc->desired_revision = 1;
|
|
$vpc->deleted_at = null;
|
|
$vpc->created_at = $now;
|
|
$vpc->updated_at = $now;
|
|
$vpc->save();
|
|
return $vpc;
|
|
}, 3);
|
|
|
|
$region = CloudRegion::find((int) $vpc->region_id);
|
|
return ['vpc' => self::dto(
|
|
$vpc, (string) ($region?->name ?? '地区已不可用'), 0
|
|
)];
|
|
}
|
|
|
|
public static function delete(array $actor, string $vpcKey): array
|
|
{
|
|
$userId = self::userId($actor);
|
|
if (preg_match('/^[0-9a-f]{32}$/D', $vpcKey) !== 1) {
|
|
throw new CloudError('VPC 标识无效', 404);
|
|
}
|
|
$connection = (new CloudVpc())->getConnection();
|
|
$vpc = $connection->transaction(static function () use (
|
|
$userId, $vpcKey
|
|
): CloudVpc {
|
|
$vpc = CloudVpc::query()->where('user_id', $userId)
|
|
->where('vpc_key', $vpcKey)->lockForUpdate()->first();
|
|
if ($vpc === null) {
|
|
throw new CloudError('VPC 不存在', 404);
|
|
}
|
|
if ((string) $vpc->state === 'deleted'
|
|
&& $vpc->active_claim === null) {
|
|
return $vpc;
|
|
}
|
|
$ports = CloudVpcPort::query()->where('vpc_id', (int) $vpc->id)
|
|
->where('active_claim', 1)->orderBy('id')
|
|
->lockForUpdate()->get(['id']);
|
|
if (!$ports->isEmpty()) {
|
|
throw new CloudError('请先断开该 VPC 中的全部实例', 409);
|
|
}
|
|
$hostStates = CloudVpcHostState::query()
|
|
->where('vpc_id', (int) $vpc->id)->orderBy('id')
|
|
->lockForUpdate()->get(['id']);
|
|
if (!$hostStates->isEmpty()) {
|
|
throw new CloudError(
|
|
'该 VPC 仍有宿主机路由状态,需完成清理后再删除', 409
|
|
);
|
|
}
|
|
$now = time();
|
|
$vpc->active_claim = null;
|
|
$vpc->state = 'deleted';
|
|
$vpc->deleted_at = $now;
|
|
$vpc->desired_revision = (int) $vpc->desired_revision + 1;
|
|
$vpc->updated_at = $now;
|
|
$vpc->save();
|
|
return $vpc;
|
|
});
|
|
$region = CloudRegion::find((int) $vpc->region_id);
|
|
return ['vpc' => self::dto(
|
|
$vpc, (string) ($region?->name ?? '地区已不可用'), 0
|
|
)];
|
|
}
|
|
|
|
private static function firstAvailableCidr(CloudVpcCidrPool $pool,
|
|
array $rows): ?string
|
|
{
|
|
$prefix = (int) $pool->allocation_prefix;
|
|
$poolPrefix = (int) $pool->prefix_length;
|
|
if ($prefix < max(16, $poolPrefix) || $prefix > 28) {
|
|
throw new CloudError('VPC 地址池分配前缀异常', 503);
|
|
}
|
|
[$poolAddress] = explode('/', (string) $pool->cidr, 2);
|
|
$base = self::number($poolAddress) & self::mask($poolPrefix);
|
|
$block = 1 << (32 - $prefix);
|
|
$capacity = 1 << ($prefix - $poolPrefix);
|
|
$occupied = [];
|
|
foreach ($rows as $row) {
|
|
if ((int) $row->prefix_length !== $prefix) {
|
|
throw new CloudError('VPC 地址账本前缀异常', 503);
|
|
}
|
|
[$address] = explode('/', (string) $row->cidr, 2);
|
|
$number = self::number($address);
|
|
$offset = $number - $base;
|
|
if ($offset < 0 || $offset % $block !== 0) {
|
|
throw new CloudError('VPC 地址账本范围异常', 503);
|
|
}
|
|
$index = intdiv($offset, $block);
|
|
if ($index < 0 || $index >= $capacity || isset($occupied[$index])) {
|
|
throw new CloudError('VPC 地址账本存在冲突', 503);
|
|
}
|
|
$occupied[$index] = true;
|
|
}
|
|
$candidate = 0;
|
|
if ($occupied !== []) {
|
|
$indexes = array_keys($occupied);
|
|
sort($indexes, SORT_NUMERIC);
|
|
foreach ($indexes as $index) {
|
|
if ($index === $candidate) {
|
|
$candidate++;
|
|
} elseif ($index > $candidate) {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
return $candidate >= $capacity ? null
|
|
: long2ip($base + $candidate * $block) . '/' . $prefix;
|
|
}
|
|
|
|
private static function name(mixed $value): string
|
|
{
|
|
if (!is_string($value) || ($value = trim($value)) === ''
|
|
|| mb_strlen($value) > 80
|
|
|| preg_match('/[\x00-\x1f\x7f]/u', $value) === 1) {
|
|
throw new CloudError('VPC 名称需为 1 至 80 个字符');
|
|
}
|
|
return $value;
|
|
}
|
|
|
|
private static function userId(array $actor): int
|
|
{
|
|
$userId = (int) ($actor['user_id'] ?? 0);
|
|
if ($userId < 1) {
|
|
throw new CloudError('请先登录', 401);
|
|
}
|
|
return $userId;
|
|
}
|
|
|
|
private static function number(string $address): int
|
|
{
|
|
$packed = inet_pton($address);
|
|
if ($packed === false || strlen($packed) !== 4) {
|
|
throw new CloudError('VPC IPv4 地址账本异常', 503);
|
|
}
|
|
return (int) unpack('Naddress', $packed)['address'];
|
|
}
|
|
|
|
private static function mask(int $prefix): int
|
|
{
|
|
return (0xffffffff << (32 - $prefix)) & 0xffffffff;
|
|
}
|
|
|
|
private static function dto(CloudVpc $vpc, string $regionName,
|
|
int $portCount): array
|
|
{
|
|
return [
|
|
'id' => (int) $vpc->id,
|
|
'vpc_key' => (string) $vpc->vpc_key,
|
|
'name' => (string) $vpc->name,
|
|
'region_id' => (int) $vpc->region_id,
|
|
'region_name' => $regionName,
|
|
'cidr' => (string) $vpc->cidr,
|
|
'prefix_length' => (int) $vpc->prefix_length,
|
|
'gateway' => (string) $vpc->gateway,
|
|
'state' => (string) $vpc->state,
|
|
'revision' => (int) $vpc->desired_revision,
|
|
'port_count' => $portCount,
|
|
'can_delete' => $portCount === 0
|
|
&& in_array((string) $vpc->state,
|
|
['active', 'degraded', 'deleted'], true),
|
|
'created_at' => (int) $vpc->created_at,
|
|
'updated_at' => (int) $vpc->updated_at,
|
|
'deleted_at' => $vpc->deleted_at === null
|
|
? null : (int) $vpc->deleted_at,
|
|
];
|
|
}
|
|
}
|