|
|
<?php
|
|
|
|
|
|
namespace App\Services\Cloud;
|
|
|
|
|
|
use App\Models\CloudRegion;
|
|
|
use App\Models\CloudVpc;
|
|
|
use App\Models\CloudVpcCidrPool;
|
|
|
|
|
|
/** Region-scoped, non-overlapping RFC1918 allocation boundaries for VPCs. */
|
|
|
final class CloudAdminVpcCidrPoolService
|
|
|
{
|
|
|
private const STATES = ['active', 'disabled'];
|
|
|
|
|
|
public static function listing(): array
|
|
|
{
|
|
|
$regions = CloudRegion::query()->orderBy('sort')->orderBy('id')
|
|
|
->get(['id', 'code', 'name', 'country_code', 'status'])
|
|
|
->map(static fn ($region): array => [
|
|
|
'id' => (int) $region->id,
|
|
|
'code' => (string) $region->code,
|
|
|
'name' => (string) $region->name,
|
|
|
'country_code' => (string) $region->country_code,
|
|
|
'status' => (string) $region->status,
|
|
|
])->all();
|
|
|
$regionNames = [];
|
|
|
foreach ($regions as $region) {
|
|
|
$regionNames[$region['id']] = $region['name'];
|
|
|
}
|
|
|
$usage = CloudVpc::query()->where('active_claim', 1)
|
|
|
->selectRaw('cidr_pool_id, COUNT(*) AS row_count')
|
|
|
->groupBy('cidr_pool_id')->pluck('row_count', 'cidr_pool_id');
|
|
|
$items = CloudVpcCidrPool::query()->orderBy('region_id')->orderBy('id')
|
|
|
->get()->map(static fn ($pool): array => self::dto(
|
|
|
$pool,
|
|
|
(string) ($regionNames[(int) $pool->region_id]
|
|
|
?? '地区已缺失'),
|
|
|
(int) ($usage[(int) $pool->id] ?? 0)
|
|
|
))->all();
|
|
|
return [
|
|
|
'regions' => $regions,
|
|
|
'items' => $items,
|
|
|
'feature_enabled' => CloudVpcFeature::enabled(),
|
|
|
];
|
|
|
}
|
|
|
|
|
|
public static function read(int $id): array
|
|
|
{
|
|
|
$pool = self::pool($id);
|
|
|
$region = CloudRegion::find((int) $pool->region_id);
|
|
|
return ['item' => self::dto(
|
|
|
$pool,
|
|
|
(string) ($region?->name ?? '地区已缺失'),
|
|
|
self::activeUsage((int) $pool->id)
|
|
|
)];
|
|
|
}
|
|
|
|
|
|
public static function create(array $input): array
|
|
|
{
|
|
|
$requestKey = $input['request_key'] ?? null;
|
|
|
if (!is_string($requestKey)
|
|
|
|| preg_match('/^[0-9a-f]{32}$/D', $requestKey) !== 1) {
|
|
|
throw new CloudError('请提供有效的 VPC 地址池创建请求标识');
|
|
|
}
|
|
|
$desired = self::normalize($input);
|
|
|
$poolKey = substr(hash('sha256', "vpc-cidr-pool\0" . $requestKey),
|
|
|
0, 32);
|
|
|
return self::persist(null, $poolKey, 0, $desired);
|
|
|
}
|
|
|
|
|
|
public static function update(int $id, array $input): array
|
|
|
{
|
|
|
$expected = $input['expected_revision'] ?? null;
|
|
|
if (is_bool($expected) || !is_int($expected) || $expected < 1) {
|
|
|
throw new CloudError('VPC 地址池版本无效,请刷新后重试', 409);
|
|
|
}
|
|
|
return self::persist($id, '', $expected, self::normalize($input));
|
|
|
}
|
|
|
|
|
|
private static function persist(?int $id, string $poolKey,
|
|
|
int $expectedRevision, array $desired): array
|
|
|
{
|
|
|
$connection = (new CloudVpcCidrPool())->getConnection();
|
|
|
$pool = $connection->transaction(static function () use (
|
|
|
$id, $poolKey, $expectedRevision, $desired
|
|
|
): CloudVpcCidrPool {
|
|
|
$region = CloudRegion::query()->where('id', $desired['region_id'])
|
|
|
->lockForUpdate()->first();
|
|
|
if ($region === null) {
|
|
|
throw new CloudError('VPC 地址池所属地区不存在', 404);
|
|
|
}
|
|
|
$rows = CloudVpcCidrPool::query()
|
|
|
->where('region_id', $desired['region_id'])
|
|
|
->orderBy('id')->lockForUpdate()->get();
|
|
|
$pool = $id === null
|
|
|
? $rows->first(static fn ($row): bool =>
|
|
|
hash_equals((string) $row->pool_key, $poolKey))
|
|
|
: $rows->first(static fn ($row): bool =>
|
|
|
(int) $row->id === $id);
|
|
|
|
|
|
if ($id === null && $pool !== null) {
|
|
|
if (self::same($pool, $desired)) {
|
|
|
return $pool;
|
|
|
}
|
|
|
throw new CloudError(
|
|
|
'同一创建请求标识不能用于不同的 VPC 地址池配置', 409
|
|
|
);
|
|
|
}
|
|
|
if ($id !== null && $pool === null) {
|
|
|
if (CloudVpcCidrPool::find($id) !== null) {
|
|
|
throw new CloudError('VPC 地址池不允许更换所属地区', 409);
|
|
|
}
|
|
|
throw new CloudError('VPC 地址池不存在', 404);
|
|
|
}
|
|
|
if ($pool !== null
|
|
|
&& (int) $pool->revision !== $expectedRevision) {
|
|
|
throw new CloudError(
|
|
|
'VPC 地址池配置已被修改,请刷新后重试', 409
|
|
|
);
|
|
|
}
|
|
|
|
|
|
$usage = $pool === null ? 0 : CloudVpc::query()
|
|
|
->where('cidr_pool_id', (int) $pool->id)
|
|
|
->where('active_claim', 1)->orderBy('id')
|
|
|
->lockForUpdate()->get(['id'])->count();
|
|
|
if ($pool !== null && $usage > 0
|
|
|
&& ((string) $pool->cidr !== $desired['cidr']
|
|
|
|| (int) $pool->allocation_prefix
|
|
|
!== $desired['allocation_prefix'])) {
|
|
|
throw new CloudError(
|
|
|
'该地址池仍有 VPC 占用,不能修改 CIDR 或分配前缀', 409
|
|
|
);
|
|
|
}
|
|
|
foreach ($rows as $other) {
|
|
|
if ($pool !== null && (int) $other->id === (int) $pool->id) {
|
|
|
continue;
|
|
|
}
|
|
|
if (self::overlaps($desired['cidr'], (string) $other->cidr)) {
|
|
|
throw new CloudError(
|
|
|
'同一地区的 VPC 地址池不能重叠', 409
|
|
|
);
|
|
|
}
|
|
|
}
|
|
|
if ($pool !== null && self::same($pool, $desired)) {
|
|
|
return $pool;
|
|
|
}
|
|
|
$now = time();
|
|
|
if ($pool === null) {
|
|
|
$pool = new CloudVpcCidrPool();
|
|
|
$pool->pool_key = $poolKey;
|
|
|
$pool->created_at = $now;
|
|
|
$pool->revision = 1;
|
|
|
} else {
|
|
|
$pool->revision = (int) $pool->revision + 1;
|
|
|
}
|
|
|
foreach ($desired as $field => $value) {
|
|
|
$pool->{$field} = $value;
|
|
|
}
|
|
|
$pool->updated_at = $now;
|
|
|
$pool->save();
|
|
|
return $pool;
|
|
|
}, 3);
|
|
|
$region = CloudRegion::find((int) $pool->region_id);
|
|
|
return ['item' => self::dto(
|
|
|
$pool,
|
|
|
(string) ($region?->name ?? '地区已缺失'),
|
|
|
self::activeUsage((int) $pool->id)
|
|
|
)];
|
|
|
}
|
|
|
|
|
|
private static function normalize(array $input): array
|
|
|
{
|
|
|
$regionId = $input['region_id'] ?? null;
|
|
|
$name = $input['name'] ?? null;
|
|
|
$cidr = $input['cidr'] ?? null;
|
|
|
$allocationPrefix = $input['allocation_prefix'] ?? null;
|
|
|
$state = $input['state'] ?? null;
|
|
|
if (is_bool($regionId) || !is_int($regionId) || $regionId < 1) {
|
|
|
throw new CloudError('请选择有效的 VPC 地址池所属地区');
|
|
|
}
|
|
|
if (!is_string($name) || ($name = trim($name)) === ''
|
|
|
|| mb_strlen($name) > 80
|
|
|
|| preg_match('/[\x00-\x1f\x7f]/u', $name) === 1) {
|
|
|
throw new CloudError('VPC 地址池名称需为 1 至 80 个字符');
|
|
|
}
|
|
|
[$normalizedCidr, $prefix] = self::normalizeCidr($cidr);
|
|
|
if (is_bool($allocationPrefix) || !is_int($allocationPrefix)
|
|
|
|| $allocationPrefix < max(16, $prefix)
|
|
|
|| $allocationPrefix > 28) {
|
|
|
throw new CloudError(
|
|
|
'VPC 分配前缀必须为 16 至 28,且不能小于地址池前缀'
|
|
|
);
|
|
|
}
|
|
|
if (!is_string($state) || !in_array($state, self::STATES, true)) {
|
|
|
throw new CloudError('VPC 地址池状态无效');
|
|
|
}
|
|
|
return [
|
|
|
'region_id' => $regionId,
|
|
|
'name' => $name,
|
|
|
'cidr' => $normalizedCidr,
|
|
|
'prefix_length' => $prefix,
|
|
|
'allocation_prefix' => $allocationPrefix,
|
|
|
'state' => $state,
|
|
|
];
|
|
|
}
|
|
|
|
|
|
private static function normalizeCidr(mixed $value): array
|
|
|
{
|
|
|
if (!is_string($value)
|
|
|
|| preg_match('/^([^\/]+)\/([0-9]{1,2})$/D', trim($value),
|
|
|
$match) !== 1
|
|
|
|| filter_var($match[1], FILTER_VALIDATE_IP,
|
|
|
FILTER_FLAG_IPV4) === false) {
|
|
|
throw new CloudError('VPC 地址池必须填写有效的 RFC1918 IPv4 CIDR');
|
|
|
}
|
|
|
$prefix = (int) $match[2];
|
|
|
if ($prefix < 8 || $prefix > 28) {
|
|
|
throw new CloudError('VPC 地址池前缀必须为 /8 至 /28');
|
|
|
}
|
|
|
$address = self::number($match[1]);
|
|
|
$mask = self::mask($prefix);
|
|
|
$network = $address & $mask;
|
|
|
if ($network !== $address) {
|
|
|
throw new CloudError('VPC 地址池 CIDR 必须填写规范网络地址');
|
|
|
}
|
|
|
$end = $network | (~$mask & 0xffffffff);
|
|
|
if (!self::insidePrivateRange($network, $end)) {
|
|
|
throw new CloudError('VPC 地址池必须完整位于 RFC1918 私网范围');
|
|
|
}
|
|
|
return [long2ip($network) . '/' . $prefix, $prefix];
|
|
|
}
|
|
|
|
|
|
private static function insidePrivateRange(int $start, int $end): bool
|
|
|
{
|
|
|
foreach ([['10.0.0.0', 8], ['172.16.0.0', 12],
|
|
|
['192.168.0.0', 16]] as [$address, $prefix]) {
|
|
|
$base = self::number($address);
|
|
|
$last = $base | (~self::mask($prefix) & 0xffffffff);
|
|
|
if ($start >= $base && $end <= $last) {
|
|
|
return true;
|
|
|
}
|
|
|
}
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
private static function overlaps(string $left, string $right): bool
|
|
|
{
|
|
|
[$leftStart, $leftEnd] = self::bounds($left);
|
|
|
[$rightStart, $rightEnd] = self::bounds($right);
|
|
|
return $leftStart <= $rightEnd && $rightStart <= $leftEnd;
|
|
|
}
|
|
|
|
|
|
private static function bounds(string $cidr): array
|
|
|
{
|
|
|
[$address, $prefix] = explode('/', $cidr, 2);
|
|
|
$start = self::number($address) & self::mask((int) $prefix);
|
|
|
return [$start,
|
|
|
$start | (~self::mask((int) $prefix) & 0xffffffff)];
|
|
|
}
|
|
|
|
|
|
private static function number(string $address): int
|
|
|
{
|
|
|
$packed = inet_pton($address);
|
|
|
if ($packed === false || strlen($packed) !== 4) {
|
|
|
throw new CloudError('VPC IPv4 地址格式无效');
|
|
|
}
|
|
|
return (int) unpack('Naddress', $packed)['address'];
|
|
|
}
|
|
|
|
|
|
private static function mask(int $prefix): int
|
|
|
{
|
|
|
return (0xffffffff << (32 - $prefix)) & 0xffffffff;
|
|
|
}
|
|
|
|
|
|
private static function same(CloudVpcCidrPool $pool,
|
|
|
array $desired): bool
|
|
|
{
|
|
|
foreach ($desired as $field => $value) {
|
|
|
if ((string) $pool->{$field} !== (string) $value) {
|
|
|
return false;
|
|
|
}
|
|
|
}
|
|
|
return true;
|
|
|
}
|
|
|
|
|
|
private static function activeUsage(int $poolId): int
|
|
|
{
|
|
|
return (int) CloudVpc::query()->where('cidr_pool_id', $poolId)
|
|
|
->where('active_claim', 1)->count();
|
|
|
}
|
|
|
|
|
|
private static function pool(int $id): CloudVpcCidrPool
|
|
|
{
|
|
|
$pool = $id > 0 ? CloudVpcCidrPool::find($id) : null;
|
|
|
if ($pool === null) {
|
|
|
throw new CloudError('VPC 地址池不存在', 404);
|
|
|
}
|
|
|
return $pool;
|
|
|
}
|
|
|
|
|
|
private static function dto(CloudVpcCidrPool $pool, string $regionName,
|
|
|
int $used): array
|
|
|
{
|
|
|
$capacity = 1 << ((int) $pool->allocation_prefix
|
|
|
- (int) $pool->prefix_length);
|
|
|
return [
|
|
|
'id' => (int) $pool->id,
|
|
|
'pool_key' => (string) $pool->pool_key,
|
|
|
'region_id' => (int) $pool->region_id,
|
|
|
'region_name' => $regionName,
|
|
|
'name' => (string) $pool->name,
|
|
|
'cidr' => (string) $pool->cidr,
|
|
|
'prefix_length' => (int) $pool->prefix_length,
|
|
|
'allocation_prefix' => (int) $pool->allocation_prefix,
|
|
|
'state' => (string) $pool->state,
|
|
|
'revision' => (int) $pool->revision,
|
|
|
'used' => $used,
|
|
|
'capacity' => $capacity,
|
|
|
'available' => max(0, $capacity - $used),
|
|
|
'address_locked' => $used > 0,
|
|
|
'created_at' => (int) $pool->created_at,
|
|
|
'updated_at' => (int) $pool->updated_at,
|
|
|
];
|
|
|
}
|
|
|
}
|