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/Services/Cloud/CloudAdminResourceService.php

919 lines
41 KiB
PHTML

<?php
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudHostCapacityPolicy;
use App\Models\CloudHostResourcePoolMembership;
use App\Models\CloudNetworkLine;
use App\Models\CloudOffer;
use App\Models\CloudPublicIp;
use App\Models\CloudRegion;
use App\Models\CloudResourcePool;
use App\Models\CloudResourceReservation;
/** Database-only administrator projections for regions, lines, pools and reservations. */
final class CloudAdminResourceService
{
private const VIEWS = ['overview', 'regions', 'lines', 'pools', 'reservations'];
private const REGION_STATUSES = ['active', 'disabled'];
private const LINE_STATUSES = ['active', 'disabled'];
private const POOL_STATUSES = ['active', 'draining', 'disabled'];
private const RESERVATION_STATES = ['held', 'committed', 'released', 'uncertain'];
private const PAGE_SIZES = [20, 50, 100];
public static function page(array $query = []): array
{
$requested = $query['view'] ?? 'overview';
$view = is_string($requested) && in_array($requested, self::VIEWS, true)
? $requested : 'overview';
$catalog = self::catalog();
$reservationPage = $view === 'reservations'
? self::reservations($query)
: self::emptyReservationPage();
return array_merge($catalog, [
'view' => $view,
'line_feature_enabled' => CloudNetworkLineFeature::enabled(),
'country_options' => CloudCountryCatalog::options(),
'reservations' => $reservationPage,
'generated_at' => time(),
]);
}
public static function settings(): array
{
return ['network_lines_enabled' => CloudNetworkLineFeature::enabled()];
}
public static function saveSettings(array $body): array
{
$enabled = filter_var($body['network_lines_enabled'] ?? null,
FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if ($enabled === null) {
throw new CloudError('线路功能开关无效');
}
foreach (CloudRegion::where('status', 'active')->get(['id', 'name']) as $region) {
$defaults = CloudNetworkLine::where('region_id', (int) $region->id)
->where('status', 'active')->where('is_default', 1)->count();
if ($defaults !== 1) {
throw new CloudError('保存线路设置前,每个启用地区必须恰好有一条启用的默认线路:'
. self::safeText((string) $region->name, 80), 409);
}
}
CloudNetworkLineFeature::save($enabled);
return self::settings();
}
public static function regions(array $query = []): array
{
$catalog = self::catalog();
return ['items' => $catalog['regions'], 'total' => count($catalog['regions'])];
}
public static function region(string $id): array
{
$regionId = self::positiveId($id, '地区');
foreach (self::catalog()['regions'] as $region) {
if ((int) $region['id'] === $regionId) {
return ['item' => $region];
}
}
throw new CloudError('地区不存在', 404);
}
public static function networkLines(array $query = []): array
{
$catalog = self::catalog();
return ['items' => $catalog['lines'], 'total' => count($catalog['lines'])];
}
public static function networkLine(string $id): array
{
$lineId = self::positiveId($id, '线路');
foreach (self::catalog()['lines'] as $line) {
if ((int) $line['id'] === $lineId) {
return ['item' => $line];
}
}
throw new CloudError('线路不存在', 404);
}
public static function resourcePools(array $query = []): array
{
$catalog = self::catalog();
return ['items' => $catalog['pools'], 'total' => count($catalog['pools'])];
}
public static function resourcePool(string $id): array
{
$poolId = self::positiveId($id, '资源池');
foreach (self::catalog()['pools'] as $pool) {
if ((int) $pool['id'] === $poolId) {
return ['item' => $pool];
}
}
throw new CloudError('资源池不存在', 404);
}
public static function saveRegion(?string $id, array $body): array
{
$region = $id === null ? new CloudRegion() : self::findRegion($id);
$code = self::code(self::value($body, 'code', $region, $id === null), 32, '地区代码');
$name = self::name(self::value($body, 'name', $region, $id === null), 80, '地区名称');
$countryCode = CloudCountryCatalog::normalize(
self::value($body, 'country_code', $region, $id === null)
);
$status = self::choice(self::value($body, 'status', $region, $id === null),
self::REGION_STATUSES, '地区状态');
$sort = self::sort(self::value($body, 'sort', $region, false, 0));
$duplicate = CloudRegion::where('code', $code);
if ($region->exists) {
$duplicate->where('id', '<>', (int) $region->id);
}
if ($duplicate->exists()) {
throw new CloudError('地区代码已存在', 409);
}
if ($status === 'active') {
if (!$region->exists) {
throw new CloudError('请先以停用状态创建地区,配置一条启用的默认线路后再启用地区', 409);
}
$defaults = CloudNetworkLine::where('region_id', (int) $region->id)
->where('status', 'active')->where('is_default', 1)->count();
if ($defaults !== 1) {
throw new CloudError('启用地区前必须恰好配置一条启用的默认线路', 409);
}
}
$now = time();
$region->code = $code;
$region->name = $name;
$region->country_code = $countryCode;
$region->status = $status;
$region->sort = $sort;
if (!$region->exists) {
$region->created_at = $now;
}
$region->updated_at = $now;
$region->save();
return self::region((string) $region->id);
}
public static function saveNetworkLine(?string $id, array $body): array
{
$line = $id === null ? new CloudNetworkLine() : self::findLine($id);
$regionId = self::positiveId((string) self::value(
$body, 'region_id', $line, $id === null), '地区');
if (CloudRegion::find($regionId) === null) {
throw new CloudError('所选地区不存在', 409);
}
if ($line->exists && (int) $line->region_id !== $regionId
&& CloudResourcePool::where('line_id', (int) $line->id)->exists()) {
throw new CloudError('已有资源池的线路不能更换地区', 409);
}
if ($line->exists && (int) $line->region_id !== $regionId
&& (bool) $line->is_default) {
throw new CloudError('默认线路不能直接更换地区,请先为原地区设置另一条默认线路', 409);
}
$code = self::code(self::value($body, 'code', $line, $id === null), 32, '线路代码');
$name = self::name(self::value($body, 'name', $line, $id === null), 80, '线路名称');
$status = self::choice(self::value($body, 'status', $line, $id === null),
self::LINE_STATUSES, '线路状态');
$isDefault = self::boolean(self::value($body, 'is_default', $line, false, false),
'默认线路状态');
if (!$line->exists && !CloudNetworkLine::where('region_id', $regionId)->exists()) {
$isDefault = true;
}
if ($line->exists && (bool) $line->is_default && !$isDefault) {
throw new CloudError('请先将同地区的另一条线路设为默认,不能直接取消当前默认线路', 409);
}
if ($isDefault && $status !== 'active') {
throw new CloudError('默认线路必须处于启用状态', 409);
}
$sort = self::sort(self::value($body, 'sort', $line, false, 0));
$duplicate = CloudNetworkLine::where('region_id', $regionId)->where('code', $code);
if ($line->exists) {
$duplicate->where('id', '<>', (int) $line->id);
}
if ($duplicate->exists()) {
throw new CloudError('该地区已存在相同线路代码', 409);
}
$connection = $line->getConnection();
$connection->transaction(function () use ($line, $regionId, $code, $name,
$status, $isDefault, $sort): void {
// Serialize default-line changes through the parent region row.
if (CloudRegion::where('id', $regionId)->lockForUpdate()->first() === null) {
throw new CloudError('所选地区不存在', 409);
}
if ($isDefault) {
CloudNetworkLine::where('region_id', $regionId)
->when($line->exists, static function ($query) use ($line) {
$query->where('id', '<>', (int) $line->id);
})->update(['is_default' => 0, 'updated_at' => time()]);
}
$now = time();
$line->region_id = $regionId;
$line->code = $code;
$line->name = $name;
$line->is_default = $isDefault;
$line->status = $status;
$line->sort = $sort;
if (!$line->exists) {
$line->created_at = $now;
}
$line->updated_at = $now;
$line->save();
});
return self::networkLine((string) $line->id);
}
public static function saveResourcePool(?string $id, array $body): array
{
$pool = $id === null ? new CloudResourcePool() : self::findPool($id);
$lineId = self::positiveId((string) self::value(
$body, 'line_id', $pool, $id === null), '线路');
$selectedLine = CloudNetworkLine::find($lineId);
if ($selectedLine === null) {
throw new CloudError('所选线路不存在', 409);
}
if ($pool->exists && (int) $pool->line_id !== $lineId
&& (CloudHostResourcePoolMembership::where(
'resource_pool_id', (int) $pool->id)->exists()
|| CloudHost::where('resource_pool_id', (int) $pool->id)->exists()
|| CloudOffer::where('resource_pool_id', (int) $pool->id)->exists()
|| CloudResourceReservation::where('resource_pool_id', (int) $pool->id)->exists())) {
throw new CloudError('已被节点、销售方案或预留引用的资源池不能更换线路', 409);
}
$code = self::code(self::value($body, 'code', $pool, $id === null), 32, '资源池代码');
$name = self::name(self::value($body, 'name', $pool, $id === null), 80, '资源池名称');
$status = self::choice(self::value($body, 'status', $pool, $id === null),
self::POOL_STATUSES, '资源池状态');
if ($status === 'active') {
$selectedRegion = CloudRegion::find((int) $selectedLine->region_id);
if ((string) $selectedLine->status !== 'active'
|| $selectedRegion === null || (string) $selectedRegion->status !== 'active') {
throw new CloudError('启用资源池前,所属地区和线路都必须处于启用状态', 409);
}
}
$policy = self::choice(self::value($body, 'scheduling_policy', $pool, false, 'balanced'),
['balanced'], '调度策略');
$sort = self::sort(self::value($body, 'sort', $pool, false, 0));
$duplicate = CloudResourcePool::where('line_id', $lineId)->where('code', $code);
if ($pool->exists) {
$duplicate->where('id', '<>', (int) $pool->id);
}
if ($duplicate->exists()) {
throw new CloudError('该线路已存在相同资源池代码', 409);
}
$now = time();
$pool->line_id = $lineId;
$pool->code = $code;
$pool->name = $name;
$pool->status = $status;
$pool->scheduling_policy = $policy;
$pool->sort = $sort;
if (!$pool->exists) {
$pool->created_at = $now;
}
$pool->updated_at = $now;
$pool->save();
return self::resourcePool((string) $pool->id);
}
public static function reservations(array $query = []): array
{
$state = isset($query['state']) && is_string($query['state'])
&& in_array($query['state'], self::RESERVATION_STATES, true)
? $query['state'] : '';
$poolId = filter_var($query['pool_id'] ?? null, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]) ?: null;
$q = is_string($query['q'] ?? null)
? self::safeText(trim($query['q']), 80) : '';
$page = max(1, filter_var($query['page'] ?? 1, FILTER_VALIDATE_INT) ?: 1);
$perPage = filter_var($query['per_page'] ?? 20, FILTER_VALIDATE_INT) ?: 20;
if (!in_array($perPage, self::PAGE_SIZES, true)) {
$perPage = 20;
}
$builder = CloudResourceReservation::query();
if ($state !== '') {
$builder->where('state', $state);
}
if ($poolId !== null) {
$builder->where('resource_pool_id', $poolId);
}
if ($q !== '') {
$builder->where(function ($inner) use ($q): void {
$inner->where('reservation_key', 'like', '%' . $q . '%');
if (ctype_digit($q)) {
foreach (['id', 'order_id', 'offer_id', 'host_id', 'user_id',
'instance_id', 'public_ip_id'] as $column) {
$inner->orWhere($column, (int) $q);
}
}
});
}
$total = (clone $builder)->count();
$totalPages = max(1, (int) ceil($total / $perPage));
$page = min($page, $totalPages);
$rows = $builder->orderByDesc('id')->offset(($page - 1) * $perPage)
->limit($perPage)->get();
$lookups = self::reservationLookups($rows);
$items = [];
foreach ($rows as $row) {
$items[] = self::reservationRow($row, $lookups);
}
return [
'items' => $items,
'filters' => ['state' => $state, 'pool_id' => $poolId, 'q' => $q],
'pagination' => [
'page' => $page,
'per_page' => $perPage,
'total' => $total,
'total_pages' => $totalPages,
'from' => $total === 0 ? 0 : (($page - 1) * $perPage) + 1,
'to' => $total === 0 ? 0 : min($total, $page * $perPage),
],
];
}
public static function reservation(string $id): array
{
$reservation = CloudResourceReservation::find(
self::positiveId($id, '资源预留'));
if ($reservation === null) {
throw new CloudError('资源预留不存在', 404);
}
$rows = CloudResourceReservation::where('id', (int) $reservation->id)->get();
return ['item' => self::reservationRow($reservation,
self::reservationLookups($rows))];
}
private static function catalog(): array
{
$lineFeatureEnabled = CloudNetworkLineFeature::enabled();
$regions = CloudRegion::orderBy('sort')->orderBy('id')->get();
$lines = CloudNetworkLine::orderBy('sort')->orderBy('id')->get();
$pools = CloudResourcePool::orderBy('sort')->orderBy('id')->get();
$regionById = self::keyById($regions);
$lineById = self::keyById($lines);
$offerCounts = [];
foreach (CloudOffer::selectRaw('resource_pool_id, COUNT(*) AS row_count')
->groupBy('resource_pool_id')->get() as $row) {
$offerCounts[(int) $row->resource_pool_id] = (int) $row->row_count;
}
$memberships = CloudHostResourcePoolMembership::orderBy('host_id')
->orderBy('resource_pool_id')->orderBy('id')->get();
$hostIds = $memberships->pluck('host_id')->map(
static fn ($id): int => (int) $id
)->unique()->values()->all();
$hosts = $hostIds === [] ? collect()
: CloudHost::whereIn('id', $hostIds)->orderBy('id')->get();
$hostById = self::keyById($hosts);
$policies = $hostIds === [] ? collect() : CloudHostCapacityPolicy::whereIn('host_id', $hostIds)->get();
$policyByHost = self::keyBy($policies, 'host_id');
$usageByHost = CloudPanelUsageService::forHosts($hostIds);
$reservationAgg = [];
foreach (CloudResourceReservation::selectRaw(
'resource_pool_id, host_id, state, COUNT(*) AS row_count, '
. 'COALESCE(SUM(cpu_cores),0) AS cpu_sum, '
. 'COALESCE(SUM(memory_mib),0) AS memory_sum, '
. 'COALESCE(SUM(disk_gib),0) AS disk_sum')
->whereIn('state', ['held', 'committed', 'uncertain'])
->groupBy('resource_pool_id', 'host_id', 'state')->get() as $row) {
$poolId = (int) $row->resource_pool_id;
$hostId = (int) $row->host_id;
$reservationAgg[$poolId][$hostId][(string) $row->state] = [
'count' => (int) $row->row_count,
'cpu' => (int) $row->cpu_sum,
'memory' => (int) $row->memory_sum,
'disk' => (int) $row->disk_sum,
];
}
$ipAgg = [];
if ($hostIds !== []) {
foreach (CloudPublicIp::query()->join(
'cloud_public_ip_pools as public_pool',
'public_pool.id', '=', 'cloud_public_ips.public_ip_pool_id'
)->join(
'cloud_host_network_attachments as network_attachment',
'network_attachment.id', '=', 'public_pool.network_attachment_id'
)->join(
'cloud_hosts as eligible_host',
'eligible_host.id', '=', 'cloud_public_ips.host_id'
)->whereIn('cloud_public_ips.host_id', $hostIds)
->whereColumn('public_pool.host_id', 'cloud_public_ips.host_id')
->whereColumn('network_attachment.host_id',
'cloud_public_ips.host_id')
// Gateway, DNS and management addresses are disabled while
// materializing the pool's reserved_ips ledger.
->whereColumn('network_attachment.network_selector',
'eligible_host.default_network')
->where(function ($query): void {
$query->where('cloud_public_ips.state', '<>', 'available')
->orWhere(function ($available): void {
$available->where('cloud_public_ips.state', 'available')
->whereNull('cloud_public_ips.reservation_id')
->whereNull('cloud_public_ips.instance_id')
->whereNull('cloud_public_ips.operation_id');
});
})
->selectRaw(
'cloud_public_ips.host_id, network_attachment.line_id, '
. 'cloud_public_ips.state, COUNT(*) AS row_count'
)->groupBy('cloud_public_ips.host_id',
'network_attachment.line_id', 'cloud_public_ips.state')->get() as $row) {
$ipAgg[(int) $row->host_id][(int) $row->line_id][(string) $row->state]
= (int) $row->row_count;
}
}
// Only addresses whose attachment and public pool are applied at
// their desired revisions can be advertised as sellable capacity.
$networkReadyByHostLine = [];
$networkReadyIpCountByHostLine = [];
if ($hostIds !== []) {
$networkRows = CloudPublicIp::query()->join(
'cloud_public_ip_pools as public_pool',
'public_pool.id', '=', 'cloud_public_ips.public_ip_pool_id'
)->join(
'cloud_host_network_attachments as network_attachment',
'network_attachment.id', '=', 'public_pool.network_attachment_id'
)->join(
'cloud_hosts as eligible_host',
'eligible_host.id', '=', 'cloud_public_ips.host_id'
)->whereIn('cloud_public_ips.host_id', $hostIds)
->where('cloud_public_ips.state', 'available')
->whereNull('cloud_public_ips.reservation_id')
->whereNull('cloud_public_ips.instance_id')
->whereNull('cloud_public_ips.operation_id')
->whereColumn('cloud_public_ips.host_id', 'public_pool.host_id')
->whereColumn('cloud_public_ips.prefix_length',
'public_pool.guest_prefix_length')
->whereColumn('network_attachment.host_id',
'cloud_public_ips.host_id')
->whereColumn('network_attachment.network_selector',
'eligible_host.default_network')
->where('network_attachment.state', 'active')
->where('network_attachment.sync_state', 'applied')
->whereColumn('network_attachment.observed_revision', '>=',
'network_attachment.desired_revision')
->where('public_pool.state', 'active')
->where('public_pool.sync_state', 'applied')
->whereColumn('public_pool.observed_revision', '>=',
'public_pool.desired_revision')
->get([
'cloud_public_ips.id as ip_id',
'cloud_public_ips.host_id', 'network_attachment.line_id',
]);
foreach ($networkRows as $row) {
$networkReadyByHostLine[(int) $row->host_id][(int) $row->line_id] = true;
$hostId = (int) $row->host_id;
$lineId = (int) $row->line_id;
$networkReadyIpCountByHostLine[$hostId][$lineId] =
($networkReadyIpCountByHostLine[$hostId][$lineId] ?? 0) + 1;
}
}
$poolHosts = [];
foreach ($memberships->groupBy('host_id') as $hostId => $rows) {
$host = $hostById[(int) $hostId] ?? null;
if ($host === null) {
continue;
}
$membership = CloudHostPoolMembershipService::selected($host, $rows);
if ($membership !== null) {
$poolHosts[(int) $membership->resource_pool_id][] = [
'host' => $host,
'membership' => $membership,
];
}
}
$poolRows = [];
foreach ($pools as $pool) {
$poolId = (int) $pool->id;
$line = $lineById[(int) $pool->line_id] ?? null;
$region = $line === null ? null : ($regionById[(int) $line->region_id] ?? null);
$capacity = self::emptyCapacity();
$schedulable = 0;
$syncState = 'configured';
foreach ($poolHosts[$poolId] ?? [] as $placement) {
$host = $placement['host'];
$membership = $placement['membership'];
$hostId = (int) $host->id;
$policy = $policyByHost[$hostId] ?? null;
$configured = [
'cpu' => (int) ($policy->configured_cpu_cores ?? 0),
'memory' => (int) ($policy->configured_memory_mib ?? 0),
'disk' => (int) ($policy->configured_disk_gib ?? 0),
];
$safety = [
'cpu' => (int) ($policy->safety_cpu_cores ?? 0),
'memory' => (int) ($policy->safety_memory_mib ?? 0),
'disk' => (int) ($policy->safety_disk_gib ?? 0),
];
$hostResources = [];
$hostUsage = $usageByHost[$hostId] ?? CloudPanelUsageService::emptyUsage();
foreach (['cpu', 'memory', 'disk'] as $resource) {
$allocated = (int) ($hostUsage[$resource]['allocated'] ?? 0);
$reserved = (int) ($hostUsage[$resource]['reserved'] ?? 0);
$allocatable = max(0, $configured[$resource] - $safety[$resource]);
$free = max(0, $allocatable - $allocated - $reserved);
$capacity[$resource]['configured'] += $configured[$resource];
$capacity[$resource]['safety'] += $safety[$resource];
$capacity[$resource]['allocatable'] += $allocatable;
$capacity[$resource]['allocated'] += $allocated;
$capacity[$resource]['reserved'] += $reserved;
$capacity[$resource]['free'] += $free;
$hostResources[$resource] = $free;
}
$states = $ipAgg[$hostId][(int) $pool->line_id] ?? [];
$networkReady = isset(
$networkReadyByHostLine[$hostId][(int) $pool->line_id]
);
$hostIpFree = $networkReady
? (int) ($networkReadyIpCountByHostLine[$hostId]
[(int) $pool->line_id] ?? 0) : 0;
$capacity['ip']['total'] += array_sum($states);
$capacity['ip']['allocated'] += (int) ($states['assigned'] ?? 0);
$capacity['ip']['reserved'] += (int) ($states['reserved'] ?? 0)
+ (int) ($states['changing'] ?? 0) + (int) ($states['uncertain'] ?? 0);
$capacity['ip']['disabled'] += (int) ($states['disabled'] ?? 0);
$capacity['ip']['free'] += $hostIpFree;
$capacity['max_host_free']['cpu'] = max($capacity['max_host_free']['cpu'], $hostResources['cpu']);
$capacity['max_host_free']['memory'] = max($capacity['max_host_free']['memory'], $hostResources['memory']);
$capacity['max_host_free']['disk'] = max($capacity['max_host_free']['disk'], $hostResources['disk']);
$capacity['max_host_free']['ip'] = max($capacity['max_host_free']['ip'], $hostIpFree);
$instanceCount = (int) ($hostUsage['instance_count'] ?? 0);
$maxInstances = (int) ($policy->max_instances ?? 0);
if ((string) $pool->status === 'active'
&& $line !== null && (string) $line->status === 'active'
&& ($lineFeatureEnabled || (bool) $line->is_default)
&& $region !== null && (string) $region->status === 'active'
&& (bool) $host->enabled
&& (string) $host->scheduler_state === 'active'
&& (string) $membership->scheduler_state === 'active'
&& $networkReady
&& (int) ($hostUsage['unknown'] ?? 0) === 0
&& ($maxInstances <= 0 || $instanceCount < $maxInstances)
&& $hostResources['cpu'] > 0 && $hostResources['memory'] > 0
&& $hostResources['disk'] > 0 && $hostIpFree > 0) {
$schedulable++;
}
}
$held = 0;
$uncertain = 0;
foreach ($reservationAgg[$poolId] ?? [] as $states) {
$held += (int) ($states['held']['count'] ?? 0);
$uncertain += (int) ($states['uncertain']['count'] ?? 0);
}
$poolRows[] = [
'id' => $poolId,
'line_id' => (int) $pool->line_id,
'line_code' => (string) ($line->code ?? ''),
'line_name' => (string) ($line->name ?? '线路已缺失'),
'line_status' => (string) ($line->status ?? 'disabled'),
'region_id' => (int) ($region->id ?? 0),
'region_code' => (string) ($region->code ?? ''),
'region_name' => (string) ($region->name ?? '地区已缺失'),
'region_status' => (string) ($region->status ?? 'disabled'),
'code' => (string) $pool->code,
'name' => (string) $pool->name,
'status' => (string) $pool->status,
'scheduling_policy' => (string) $pool->scheduling_policy,
'sort' => (int) $pool->sort,
'host_count' => count($poolHosts[$poolId] ?? []),
'schedulable_host_count' => $schedulable,
'offer_count' => $offerCounts[$poolId] ?? 0,
'held_reservation_count' => $held,
'uncertain_reservation_count' => $uncertain,
'capacity' => $capacity,
'sync_state' => count($poolHosts[$poolId] ?? []) === 0 ? 'unconfigured' : $syncState,
'created_at' => (int) $pool->created_at,
'updated_at' => (int) $pool->updated_at,
];
}
$linePoolCounts = [];
$regionPoolCounts = [];
$regionOfferCounts = [];
foreach ($poolRows as $pool) {
$linePoolCounts[$pool['line_id']] = ($linePoolCounts[$pool['line_id']] ?? 0) + 1;
$regionPoolCounts[$pool['region_id']] = ($regionPoolCounts[$pool['region_id']] ?? 0) + 1;
$regionOfferCounts[$pool['region_id']] = ($regionOfferCounts[$pool['region_id']] ?? 0) + $pool['offer_count'];
}
$lineRows = [];
$regionLineCounts = [];
$regionDefaultCounts = [];
foreach ($lines as $line) {
$regionId = (int) $line->region_id;
$region = $regionById[$regionId] ?? null;
$regionLineCounts[$regionId] = ($regionLineCounts[$regionId] ?? 0) + 1;
if ((bool) $line->is_default && (string) $line->status === 'active') {
$regionDefaultCounts[$regionId] = ($regionDefaultCounts[$regionId] ?? 0) + 1;
}
$offers = 0;
foreach ($poolRows as $pool) {
if ($pool['line_id'] === (int) $line->id) {
$offers += $pool['offer_count'];
}
}
$lineRows[] = [
'id' => (int) $line->id,
'region_id' => $regionId,
'region_code' => (string) ($region->code ?? ''),
'region_name' => (string) ($region->name ?? '地区已缺失'),
'code' => (string) $line->code,
'name' => (string) $line->name,
'is_default' => (bool) $line->is_default,
'status' => (string) $line->status,
'sort' => (int) $line->sort,
'pool_count' => $linePoolCounts[(int) $line->id] ?? 0,
'offer_count' => $offers,
'created_at' => (int) $line->created_at,
'updated_at' => (int) $line->updated_at,
];
}
$regionRows = [];
foreach ($regions as $region) {
$regionId = (int) $region->id;
$country = CloudCountryCatalog::option((string) $region->country_code);
$regionRows[] = [
'id' => $regionId,
'code' => (string) $region->code,
'name' => (string) $region->name,
'country_code' => $country['code'],
'country_name' => $country['name'],
'country_flag' => $country['flag'],
'status' => (string) $region->status,
'sort' => (int) $region->sort,
'line_count' => $regionLineCounts[$regionId] ?? 0,
'active_default_line_count' => $regionDefaultCounts[$regionId] ?? 0,
'pool_count' => $regionPoolCounts[$regionId] ?? 0,
'offer_count' => $regionOfferCounts[$regionId] ?? 0,
'created_at' => (int) $region->created_at,
'updated_at' => (int) $region->updated_at,
];
}
return [
'summary' => self::summary($regionRows, $lineRows, $poolRows),
'regions' => $regionRows,
'lines' => $lineRows,
'pools' => $poolRows,
];
}
private static function summary(array $regions, array $lines, array $pools): array
{
$summary = [
'regions' => count($regions),
'active_regions' => count(array_filter($regions,
static fn (array $row): bool => $row['status'] === 'active')),
'lines' => count($lines),
'active_pools' => 0,
'hosts' => 0,
'schedulable_hosts' => 0,
'held_reservations' => 0,
'uncertain_reservations' => 0,
'capacity' => self::emptyCapacity(),
];
foreach ($pools as $pool) {
if ($pool['status'] === 'active') {
$summary['active_pools']++;
}
$summary['hosts'] += $pool['host_count'];
$summary['schedulable_hosts'] += $pool['schedulable_host_count'];
$summary['held_reservations'] += $pool['held_reservation_count'];
$summary['uncertain_reservations'] += $pool['uncertain_reservation_count'];
foreach (['cpu', 'memory', 'disk'] as $resource) {
foreach (['configured', 'safety', 'allocatable', 'allocated', 'reserved', 'free'] as $field) {
$summary['capacity'][$resource][$field] += $pool['capacity'][$resource][$field];
}
$summary['capacity']['max_host_free'][$resource] = max(
$summary['capacity']['max_host_free'][$resource],
$pool['capacity']['max_host_free'][$resource]
);
}
foreach (['total', 'allocated', 'reserved', 'disabled', 'free'] as $field) {
$summary['capacity']['ip'][$field] += $pool['capacity']['ip'][$field];
}
$summary['capacity']['max_host_free']['ip'] = max(
$summary['capacity']['max_host_free']['ip'],
$pool['capacity']['max_host_free']['ip']
);
}
return $summary;
}
private static function reservationLookups($rows): array
{
$poolIds = $rows->pluck('resource_pool_id')->filter()->unique()->all();
$offerIds = $rows->pluck('offer_id')->filter()->unique()->all();
$hostIds = $rows->pluck('host_id')->filter()->unique()->all();
$ipIds = $rows->pluck('public_ip_id')->filter()->unique()->all();
$pools = $poolIds === [] ? collect() : CloudResourcePool::whereIn('id', $poolIds)->get();
$lines = $pools->isEmpty() ? collect() : CloudNetworkLine::whereIn('id',
$pools->pluck('line_id')->unique()->all())->get();
$regions = $lines->isEmpty() ? collect() : CloudRegion::whereIn('id',
$lines->pluck('region_id')->unique()->all())->get();
return [
'pools' => self::keyById($pools),
'lines' => self::keyById($lines),
'regions' => self::keyById($regions),
'offers' => self::keyById($offerIds === [] ? collect() : CloudOffer::whereIn('id', $offerIds)->get()),
'hosts' => self::keyById($hostIds === [] ? collect() : CloudHost::whereIn('id', $hostIds)->get()),
'ips' => self::keyById($ipIds === [] ? collect() : CloudPublicIp::whereIn('id', $ipIds)->get()),
];
}
private static function reservationRow(CloudResourceReservation $row, array $lookups): array
{
$pool = $lookups['pools'][(int) $row->resource_pool_id] ?? null;
$line = $pool === null ? null : ($lookups['lines'][(int) $pool->line_id] ?? null);
$region = $line === null ? null : ($lookups['regions'][(int) $line->region_id] ?? null);
$offer = $lookups['offers'][(int) $row->offer_id] ?? null;
$host = $lookups['hosts'][(int) $row->host_id] ?? null;
$ip = $lookups['ips'][(int) $row->public_ip_id] ?? null;
return [
'id' => (int) $row->id,
'reservation_key' => (string) $row->reservation_key,
'order_id' => $row->order_id === null ? null : (int) $row->order_id,
'offer_id' => $row->offer_id === null ? null : (int) $row->offer_id,
'offer_name' => (string) ($offer->name ?? ''),
'resource_pool_id' => (int) $row->resource_pool_id,
'resource_pool_name' => (string) ($pool->name ?? '资源池已缺失'),
'line_name' => (string) ($line->name ?? '线路已缺失'),
'region_name' => (string) ($region->name ?? '地区已缺失'),
'host_id' => $row->host_id === null ? null : (int) $row->host_id,
'host_name' => (string) ($host->name ?? ''),
'user_id' => (int) $row->user_id,
'instance_id' => $row->instance_id === null ? null : (int) $row->instance_id,
'public_ip_id' => $row->public_ip_id === null ? null : (int) $row->public_ip_id,
'public_ip' => (string) ($ip->address ?? ''),
'operation_id' => (string) ($row->operation_id ?? ''),
'cpu_cores' => (int) $row->cpu_cores,
'memory_mib' => (int) $row->memory_mib,
'disk_gib' => (int) $row->disk_gib,
'state' => (string) $row->state,
'expires_at' => $row->expires_at === null ? null : (int) $row->expires_at,
'released_at' => $row->released_at === null ? null : (int) $row->released_at,
'release_reason' => self::safeText((string) ($row->release_reason ?? ''), 255),
'created_at' => (int) $row->created_at,
'updated_at' => (int) $row->updated_at,
];
}
private static function emptyReservationPage(): array
{
return [
'items' => [],
'filters' => ['state' => '', 'pool_id' => null, 'q' => ''],
'pagination' => ['page' => 1, 'per_page' => 20, 'total' => 0,
'total_pages' => 1, 'from' => 0, 'to' => 0],
];
}
private static function emptyCapacity(): array
{
$resource = ['configured' => 0, 'safety' => 0, 'allocatable' => 0,
'allocated' => 0, 'reserved' => 0, 'free' => 0];
return [
'cpu' => $resource,
'memory' => $resource,
'disk' => $resource,
'ip' => ['total' => 0, 'allocated' => 0, 'reserved' => 0,
'disabled' => 0, 'free' => 0],
'max_host_free' => ['cpu' => 0, 'memory' => 0, 'disk' => 0, 'ip' => 0],
];
}
private static function findRegion(string $id): CloudRegion
{
$row = CloudRegion::find(self::positiveId($id, '地区'));
if ($row === null) {
throw new CloudError('地区不存在', 404);
}
return $row;
}
private static function findLine(string $id): CloudNetworkLine
{
$row = CloudNetworkLine::find(self::positiveId($id, '线路'));
if ($row === null) {
throw new CloudError('线路不存在', 404);
}
return $row;
}
private static function findPool(string $id): CloudResourcePool
{
$row = CloudResourcePool::find(self::positiveId($id, '资源池'));
if ($row === null) {
throw new CloudError('资源池不存在', 404);
}
return $row;
}
private static function value(array $body, string $key, $model,
bool $required, $default = null)
{
if (array_key_exists($key, $body)) {
return $body[$key];
}
if ($model->exists) {
return $model->{$key};
}
if ($required) {
throw new CloudError('缺少必填字段:' . $key);
}
return $default;
}
private static function positiveId(string $value, string $label): int
{
if (preg_match('/^[1-9][0-9]*$/D', $value) !== 1
|| (int) $value < 1) {
throw new CloudError($label . ' ID 无效');
}
return (int) $value;
}
private static function code($value, int $max, string $label): string
{
if (!is_string($value)) {
throw new CloudError($label . '无效');
}
$value = strtolower(trim($value));
if (strlen($value) > $max
|| preg_match('/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/D', $value) !== 1) {
throw new CloudError($label . '只能包含小写字母、数字和中划线,且不能以中划线开头或结尾');
}
return $value;
}
private static function name($value, int $max, string $label): string
{
if (!is_string($value)) {
throw new CloudError($label . '无效');
}
$value = trim($value);
if ($value === '' || mb_strlen($value) > $max
|| preg_match('/[\x00-\x1f\x7f]/u', $value) === 1) {
throw new CloudError($label . '需为 1 至 ' . $max . ' 个字符,且不能包含控制字符');
}
return $value;
}
private static function choice($value, array $allowed, string $label): string
{
if (!is_string($value) || !in_array($value, $allowed, true)) {
throw new CloudError($label . '无效');
}
return $value;
}
private static function boolean($value, string $label): bool
{
$result = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if ($result === null) {
throw new CloudError($label . '无效');
}
return $result;
}
private static function sort($value): int
{
$result = filter_var($value, FILTER_VALIDATE_INT);
if ($result === false || $result < -1000000 || $result > 1000000) {
throw new CloudError('排序值必须为 -1000000 至 1000000 的整数');
}
return (int) $result;
}
private static function safeText(string $value, int $max): string
{
$value = preg_replace('/[\x00-\x1f\x7f]/u', '', $value) ?? '';
return mb_substr(trim($value), 0, $max);
}
private static function keyById($rows): array
{
return self::keyBy($rows, 'id');
}
private static function keyBy($rows, string $column): array
{
$result = [];
foreach ($rows as $row) {
$result[(int) $row->{$column}] = $row;
}
return $result;
}
}