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.
1474 lines
64 KiB
PHP
1474 lines
64 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Cloud;
|
|
|
|
use App\Models\CloudHost;
|
|
use App\Models\CloudHostAgent;
|
|
use App\Models\CloudHostCapacityPolicy;
|
|
use App\Models\CloudHostResourcePoolMembership;
|
|
use App\Models\CloudHostStorageConfiguration;
|
|
use App\Models\CloudNetworkLine;
|
|
use App\Models\CloudOffer;
|
|
use App\Models\CloudPublicIp;
|
|
use App\Models\CloudRegion;
|
|
use App\Models\CloudResourcePool;
|
|
use App\Models\CloudResourceReservation;
|
|
use App\Models\CloudResourceReservationIp;
|
|
|
|
/** Database-only administrator projections for regions, lines, pools and reservations. */
|
|
final class CloudAdminResourceService
|
|
{
|
|
private const VIEWS = ['topology', 'capacity', 'reservations', 'traffic'];
|
|
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'] ?? 'topology';
|
|
$view = is_string($requested) && in_array($requested, self::VIEWS, true)
|
|
? $requested : 'topology';
|
|
if ($view === 'traffic') {
|
|
return [
|
|
'view' => 'traffic',
|
|
'focus' => 'all',
|
|
'traffic_pools' => CloudAdminTrafficPoolService::page($query),
|
|
'generated_at' => time(),
|
|
];
|
|
}
|
|
$catalog = self::catalog();
|
|
$focus = is_string($query['focus'] ?? null) ? $query['focus'] : 'all';
|
|
if (!in_array($focus, ['all', 'ready_pools', 'hosts', 'ready_hosts', 'cpu', 'ip'], true)) {
|
|
$focus = 'all';
|
|
}
|
|
$reservationPage = $view === 'reservations'
|
|
? self::reservations($query)
|
|
: self::emptyReservationPage();
|
|
return array_merge($catalog, self::capacitySelection($catalog, $focus), [
|
|
'view' => $view,
|
|
'focus' => $focus,
|
|
'line_feature_enabled' => CloudNetworkLineFeature::enabled(),
|
|
'country_options' => CloudCountryCatalog::options(),
|
|
'reservations' => $reservationPage,
|
|
'traffic_pools' => [
|
|
'items' => [],
|
|
'lines' => [],
|
|
'summary' => [
|
|
'groups_total' => 0,
|
|
'disabled' => 0,
|
|
'shadow' => 0,
|
|
'enforced' => 0,
|
|
'ready_to_enforce' => 0,
|
|
],
|
|
'sample_freshness_seconds' => 300,
|
|
'generated_at' => time(),
|
|
],
|
|
'generated_at' => time(),
|
|
]);
|
|
}
|
|
|
|
public static function settings(): array
|
|
{
|
|
return ['network_lines_enabled' => CloudNetworkLineFeature::enabled()];
|
|
}
|
|
|
|
/** Select from the exact projection used to compute the summary cards. */
|
|
private static function capacitySelection(array $catalog, string $focus): array
|
|
{
|
|
return [
|
|
'capacity_pools' => array_values(array_filter($catalog['pools'],
|
|
static fn (array $pool): bool => match ($focus) {
|
|
'ready_pools' => $pool['effective_state'] === 'ready',
|
|
'cpu' => (int) $pool['placement_capacity']['cpu']['free'] > 0,
|
|
'ip' => (int) $pool['placement_capacity']['ip']['bundles']
|
|
['available'] > 0,
|
|
default => true,
|
|
})),
|
|
'capacity_hosts' => array_values(array_filter($catalog['hosts'],
|
|
static fn (array $host): bool => $focus !== 'ready_hosts' || $host['placement_ready'])),
|
|
];
|
|
}
|
|
|
|
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('线路功能开关无效');
|
|
}
|
|
(new CloudRegion())->getConnection()->transaction(
|
|
function () use ($enabled): void {
|
|
// The feature row is the global serialization point shared
|
|
// with region creation. Keep this lock before every region
|
|
// lock so enable/disable and create cannot observe stale mode.
|
|
CloudNetworkLineFeature::lockedEnabled();
|
|
$regions = CloudRegion::orderBy('id')->lockForUpdate()
|
|
->get(['id', 'name', 'status']);
|
|
foreach ($regions as $region) {
|
|
$lines = CloudNetworkLine::where('region_id', (int) $region->id)
|
|
->orderBy('id')->lockForUpdate()->get();
|
|
$activeDefaults = $lines->filter(
|
|
static fn ($line): bool => (bool) $line->is_default
|
|
&& (string) $line->status === 'active'
|
|
)->values();
|
|
|
|
if (!$enabled && $activeDefaults->count() === 0) {
|
|
$default = $lines->first(
|
|
static fn ($line): bool => (bool) $line->is_default
|
|
) ?? $lines->first(
|
|
static fn ($line): bool => (string) $line->code === 'default'
|
|
);
|
|
$now = time();
|
|
if ($default === null) {
|
|
$default = new CloudNetworkLine();
|
|
$default->region_id = (int) $region->id;
|
|
$default->code = 'default';
|
|
$default->name = '默认线路';
|
|
$default->sort = 0;
|
|
$default->created_at = $now;
|
|
}
|
|
CloudNetworkLine::where('region_id', (int) $region->id)
|
|
->where('id', '<>', (int) ($default->id ?? 0))
|
|
->where('is_default', 1)
|
|
->update(['is_default' => 0, 'updated_at' => $now]);
|
|
$default->is_default = true;
|
|
$default->status = 'active';
|
|
$default->updated_at = $now;
|
|
$default->save();
|
|
$activeDefaults = collect([$default]);
|
|
}
|
|
|
|
if (!$enabled && $activeDefaults->count() === 1) {
|
|
CloudNetworkLine::where('region_id', (int) $region->id)
|
|
->where('id', '<>', (int) $activeDefaults->first()->id)
|
|
->where('is_default', 1)
|
|
->update(['is_default' => 0, 'updated_at' => time()]);
|
|
}
|
|
if ((!$enabled || (string) $region->status === 'active')
|
|
&& $activeDefaults->count() !== 1) {
|
|
throw new CloudError(
|
|
'保存线路设置前,每个'
|
|
. ($enabled ? '启用' : '')
|
|
. '地区必须恰好有一条启用的默认线路:'
|
|
. self::safeText((string) $region->name, 80),
|
|
409
|
|
);
|
|
}
|
|
}
|
|
CloudNetworkLineFeature::save($enabled);
|
|
},
|
|
3
|
|
);
|
|
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);
|
|
$name = self::name(self::value($body, 'name', $region, $id === null), 80, '地区名称');
|
|
$code = self::entityCode($body, $region, 'region', $name, 32, '地区系统标识');
|
|
$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);
|
|
}
|
|
$isNew = !$region->exists;
|
|
$region->getConnection()->transaction(function () use (
|
|
$region, $code, $name, $countryCode, $status, $sort, $isNew
|
|
): void {
|
|
$createDefaultLine = false;
|
|
if ($isNew) {
|
|
// Re-read under the same row lock used by saveSettings(); a
|
|
// pre-transaction cached value could create a hidden orphan.
|
|
$createDefaultLine = !CloudNetworkLineFeature::lockedEnabled();
|
|
if ($status === 'active' && !$createDefaultLine) {
|
|
throw new CloudError(
|
|
'请先以停用状态创建地区,配置一条启用的默认线路后再启用地区',
|
|
409
|
|
);
|
|
}
|
|
} elseif ($status === 'active') {
|
|
// Default-line mutations lock the parent region first.
|
|
CloudRegion::where('id', (int) $region->id)
|
|
->lockForUpdate()->first();
|
|
$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();
|
|
|
|
if ($createDefaultLine) {
|
|
$line = new CloudNetworkLine();
|
|
$line->region_id = (int) $region->id;
|
|
$line->code = 'default';
|
|
$line->name = '默认线路';
|
|
$line->is_default = true;
|
|
$line->status = 'active';
|
|
$line->sort = 0;
|
|
$line->created_at = $now;
|
|
$line->updated_at = $now;
|
|
$line->save();
|
|
}
|
|
}, 3);
|
|
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);
|
|
}
|
|
$name = self::name(self::value($body, 'name', $line, $id === null), 80, '线路名称');
|
|
$code = self::entityCode($body, $line, 'line', $name, 32, '线路系统标识');
|
|
$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);
|
|
}
|
|
$name = self::name(self::value($body, 'name', $pool, $id === null), 80, '资源池名称');
|
|
$code = self::entityCode($body, $pool, 'pool', $name, 32, '资源池系统标识');
|
|
$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'] as $column) {
|
|
$inner->orWhere($column, (int) $q);
|
|
}
|
|
$inner->orWhereHas(
|
|
'activePublicIpClaims',
|
|
static fn ($claims) => $claims->where(
|
|
'public_ip_id',
|
|
(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');
|
|
$agents = $hostIds === [] ? collect()
|
|
: CloudHostAgent::whereIn('host_id', $hostIds)->get();
|
|
$agentByHost = self::keyBy($agents, 'host_id');
|
|
$storageConfigurations = $hostIds === [] ? collect()
|
|
: CloudHostStorageConfiguration::whereIn('host_id', $hostIds)->get();
|
|
$storageByHost = self::keyBy($storageConfigurations, '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,
|
|
];
|
|
}
|
|
$publicNetworkCapacity =
|
|
CloudAdminPublicNetworkCapacityProjection::forHosts($hostIds);
|
|
|
|
$poolHosts = [];
|
|
foreach ($memberships as $membership) {
|
|
$host = $hostById[(int) $membership->host_id] ?? null;
|
|
if ($host === null) {
|
|
continue;
|
|
}
|
|
$poolHosts[(int) $membership->resource_pool_id][] = [
|
|
'host' => $host,
|
|
'membership' => $membership,
|
|
];
|
|
}
|
|
$poolRows = [];
|
|
$hostRows = [];
|
|
$platformCapacityByHost = [];
|
|
$platformLineCapacityByHost = [];
|
|
$platformPlacementEligibleByHost = [];
|
|
$platformPlacementLineByHost = [];
|
|
$platformReadyByHost = [];
|
|
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();
|
|
$placementCapacity = self::emptyCapacity();
|
|
$health = self::emptyPoolHealth();
|
|
$poolPathReady = (string) $pool->status === 'active'
|
|
&& $line !== null && (string) $line->status === 'active'
|
|
&& ($lineFeatureEnabled || (bool) $line->is_default)
|
|
&& $region !== null && (string) $region->status === 'active';
|
|
foreach ($poolHosts[$poolId] ?? [] as $placement) {
|
|
$host = $placement['host'];
|
|
$membership = $placement['membership'];
|
|
$hostId = (int) $host->id;
|
|
$policy = $policyByHost[$hostId] ?? null;
|
|
$agent = $agentByHost[$hostId] ?? null;
|
|
$storage = $storageByHost[$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),
|
|
];
|
|
$hostCapacity = self::emptyCapacity();
|
|
$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);
|
|
$hostCapacity[$resource] = [
|
|
'configured' => $configured[$resource],
|
|
'safety' => $safety[$resource],
|
|
'allocatable' => $allocatable,
|
|
'allocated' => $allocated,
|
|
'reserved' => $reserved,
|
|
'free' => $free,
|
|
];
|
|
$hostCapacity['max_host_free'][$resource] = $free;
|
|
$hostResources[$resource] = $free;
|
|
}
|
|
$hostCapacity['ip'] = $publicNetworkCapacity[$hostId]['lines']
|
|
[(int) $pool->line_id]
|
|
?? CloudAdminPublicNetworkCapacityProjection::empty();
|
|
$hostIpFree = (int) (
|
|
$hostCapacity['ip']['bundles']['available'] ?? 0
|
|
);
|
|
$networkReady = $hostIpFree > 0;
|
|
$hostCapacity['max_host_free']['ip'] = $hostIpFree;
|
|
self::addCapacity($capacity, $hostCapacity);
|
|
|
|
if (!isset($platformCapacityByHost[$hostId])) {
|
|
$platformCapacityByHost[$hostId] = $hostCapacity;
|
|
$platformCapacityByHost[$hostId]['ip'] =
|
|
self::emptyCapacity()['ip'];
|
|
$platformCapacityByHost[$hostId]['max_host_free']['ip'] = 0;
|
|
}
|
|
$lineId = (int) $pool->line_id;
|
|
if (!isset($platformLineCapacityByHost[$hostId][$lineId])) {
|
|
$platformLineCapacityByHost[$hostId][$lineId] =
|
|
$hostCapacity['ip'];
|
|
$platformCapacityByHost[$hostId]['ip'] =
|
|
CloudAdminPublicNetworkCapacityProjection::sum([
|
|
$platformCapacityByHost[$hostId]['ip'],
|
|
$hostCapacity['ip'],
|
|
]);
|
|
$platformCapacityByHost[$hostId]['max_host_free']['ip'] +=
|
|
$hostIpFree;
|
|
}
|
|
|
|
$hostEnabled = (bool) $host->enabled;
|
|
$schedulerActive = (string) $membership->scheduler_state === 'active';
|
|
$agentReady = $agent !== null && $agent->isReady();
|
|
$storageReady = $storage !== null && $storage->isApplied();
|
|
$instanceCount = (int) ($hostUsage['instance_count'] ?? 0);
|
|
$maxInstances = (int) ($policy->max_instances ?? 0);
|
|
$capacityConfigured = $policy !== null
|
|
&& $configured['cpu'] > 0 && $configured['memory'] > 0
|
|
&& $configured['disk'] > 0
|
|
&& $safety['cpu'] < $configured['cpu']
|
|
&& $safety['memory'] < $configured['memory']
|
|
&& $safety['disk'] < $configured['disk'];
|
|
$capacityReady = $capacityConfigured
|
|
&& (int) ($hostUsage['unknown'] ?? 0) === 0
|
|
&& ($maxInstances <= 0 || $instanceCount < $maxInstances)
|
|
&& $hostResources['cpu'] > 0 && $hostResources['memory'] > 0
|
|
&& $hostResources['disk'] > 0 && $hostIpFree > 0;
|
|
$hostBaseReady = $poolPathReady && $hostEnabled
|
|
&& $schedulerActive && $agentReady && $storageReady && $networkReady
|
|
&& $capacityConfigured
|
|
&& (int) ($hostUsage['unknown'] ?? 0) === 0
|
|
&& ($maxInstances <= 0 || $instanceCount < $maxInstances);
|
|
|
|
$health['host_count']++;
|
|
$health['enabled_host_count'] += $hostEnabled ? 1 : 0;
|
|
// Compatibility field: readiness now belongs to this exact
|
|
// host/line attachment, never the host default_network value.
|
|
$health['network_selector_ready_host_count'] +=
|
|
$networkReady ? 1 : 0;
|
|
$health['scheduler_active_host_count'] += $schedulerActive ? 1 : 0;
|
|
$health['agent_ready_host_count'] += $agentReady ? 1 : 0;
|
|
$health['storage_ready_host_count'] += $storageReady ? 1 : 0;
|
|
$health['network_ready_host_count'] += $networkReady ? 1 : 0;
|
|
$health['capacity_ready_host_count'] += $capacityReady ? 1 : 0;
|
|
if ($hostBaseReady) {
|
|
self::addCapacity($placementCapacity, $hostCapacity);
|
|
$platformPlacementEligibleByHost[$hostId] = true;
|
|
$platformPlacementLineByHost[$hostId][$lineId] = true;
|
|
}
|
|
if ($hostBaseReady && $capacityReady) {
|
|
$health['placement_ready_host_count']++;
|
|
$platformReadyByHost[$hostId] = true;
|
|
}
|
|
$hostRows[] = [
|
|
'id' => $hostId,
|
|
'name' => (string) $host->name,
|
|
'membership_id' => (int) $membership->id,
|
|
'resource_pool_id' => $poolId,
|
|
'line_id' => (int) $pool->line_id,
|
|
'scheduler_state' => (string) $membership->scheduler_state,
|
|
'priority' => (int) $membership->priority,
|
|
'weight' => (int) $membership->weight,
|
|
'revision' => max(1, (int) $membership->revision),
|
|
'pool_name' => (string) $pool->name,
|
|
'line_name' => (string) ($line->name ?? ''),
|
|
'region_name' => (string) ($region->name ?? ''),
|
|
'network_ready' => $networkReady,
|
|
'capacity_scope' => 'shared_host',
|
|
'placement_ready' => $hostBaseReady && $capacityReady,
|
|
];
|
|
}
|
|
$held = 0;
|
|
$uncertain = 0;
|
|
foreach ($reservationAgg[$poolId] ?? [] as $states) {
|
|
$held += (int) ($states['held']['count'] ?? 0);
|
|
$uncertain += (int) ($states['uncertain']['count'] ?? 0);
|
|
}
|
|
$effective = self::poolEffectiveState(
|
|
(string) $pool->status, $line, $region,
|
|
$lineFeatureEnabled, $health
|
|
);
|
|
$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,
|
|
'status_label' => self::poolStatusLabel((string) $pool->status),
|
|
'effective_state' => $effective['state'],
|
|
'effective_state_label' => self::effectiveStateLabel($effective['state']),
|
|
'blockers' => $effective['blockers'],
|
|
'scheduling_policy' => (string) $pool->scheduling_policy,
|
|
'sort' => (int) $pool->sort,
|
|
'display_path' => implode(' / ', array_filter([
|
|
(string) ($region->name ?? ''), (string) ($line->name ?? ''),
|
|
(string) $pool->name,
|
|
], static fn (string $value): bool => $value !== '')),
|
|
'system_path' => implode('/', array_filter([
|
|
(string) ($region->code ?? ''), (string) ($line->code ?? ''),
|
|
(string) $pool->code,
|
|
], static fn (string $value): bool => $value !== '')),
|
|
'health' => $health,
|
|
'offer_count' => $offerCounts[$poolId] ?? 0,
|
|
'held_reservation_count' => $held,
|
|
'uncertain_reservation_count' => $uncertain,
|
|
'capacity_scope' => 'shared_host',
|
|
'capacity_shared' => true,
|
|
'capacity_note' => '宿主机 CPU、内存和磁盘容量由该节点的全部资源池成员关系共享竞争',
|
|
'capacity' => $capacity,
|
|
'placement_capacity' => $placementCapacity,
|
|
'created_at' => (int) $pool->created_at,
|
|
'updated_at' => (int) $pool->updated_at,
|
|
];
|
|
}
|
|
|
|
$poolsByLine = [];
|
|
foreach ($poolRows as $pool) {
|
|
$poolsByLine[$pool['line_id']][] = $pool;
|
|
}
|
|
$lineRows = [];
|
|
foreach ($lines as $line) {
|
|
$regionId = (int) $line->region_id;
|
|
$region = $regionById[$regionId] ?? null;
|
|
$linePools = $poolsByLine[(int) $line->id] ?? [];
|
|
$health = self::aggregateEntityHealth($linePools);
|
|
$effective = self::lineEffectiveState(
|
|
(string) $line->status, $region, (bool) $line->is_default,
|
|
$lineFeatureEnabled, $health
|
|
);
|
|
$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,
|
|
'status_label' => self::enabledStatusLabel((string) $line->status),
|
|
'effective_state' => $effective['state'],
|
|
'effective_state_label' => self::effectiveStateLabel($effective['state']),
|
|
'blockers' => $effective['blockers'],
|
|
'sort' => (int) $line->sort,
|
|
'display_path' => implode(' / ', array_filter([
|
|
(string) ($region->name ?? ''), (string) $line->name,
|
|
], static fn (string $value): bool => $value !== '')),
|
|
'system_path' => implode('/', array_filter([
|
|
(string) ($region->code ?? ''), (string) $line->code,
|
|
], static fn (string $value): bool => $value !== '')),
|
|
'health' => $health,
|
|
'created_at' => (int) $line->created_at,
|
|
'updated_at' => (int) $line->updated_at,
|
|
];
|
|
}
|
|
$linesByRegion = [];
|
|
foreach ($lineRows as $line) {
|
|
$linesByRegion[$line['region_id']][] = $line;
|
|
}
|
|
$regionRows = [];
|
|
foreach ($regions as $region) {
|
|
$regionId = (int) $region->id;
|
|
$country = CloudCountryCatalog::option((string) $region->country_code);
|
|
$regionLines = $linesByRegion[$regionId] ?? [];
|
|
$activeDefaultLines = array_values(array_filter(
|
|
$regionLines,
|
|
static fn (array $line): bool => $line['is_default'] === true
|
|
&& $line['status'] === 'active'
|
|
));
|
|
$regionPools = [];
|
|
foreach ($regionLines as $line) {
|
|
foreach ($poolsByLine[$line['id']] ?? [] as $pool) {
|
|
$regionPools[] = $pool;
|
|
}
|
|
}
|
|
$health = self::aggregateEntityHealth($regionPools);
|
|
$health['line_count'] = count($regionLines);
|
|
$health['active_default_line_count'] = count($activeDefaultLines);
|
|
$effective = self::regionEffectiveState(
|
|
(string) $region->status, $health
|
|
);
|
|
$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,
|
|
'status_label' => self::enabledStatusLabel((string) $region->status),
|
|
'effective_state' => $effective['state'],
|
|
'effective_state_label' => self::effectiveStateLabel($effective['state']),
|
|
'blockers' => $effective['blockers'],
|
|
'sort' => (int) $region->sort,
|
|
'default_line_id' => count($activeDefaultLines) === 1
|
|
? (int) $activeDefaultLines[0]['id'] : null,
|
|
'display_path' => (string) $region->name,
|
|
'system_path' => (string) $region->code,
|
|
'health' => $health,
|
|
'created_at' => (int) $region->created_at,
|
|
'updated_at' => (int) $region->updated_at,
|
|
];
|
|
}
|
|
|
|
$platformHosts = self::platformHostSummary(
|
|
$platformCapacityByHost,
|
|
$platformLineCapacityByHost,
|
|
$platformPlacementEligibleByHost,
|
|
$platformPlacementLineByHost,
|
|
$platformReadyByHost
|
|
);
|
|
return [
|
|
'hosts' => $hostRows,
|
|
'summary' => self::summary(
|
|
$regionRows, $lineRows, $poolRows, $platformHosts
|
|
),
|
|
'topology' => self::topology(
|
|
$regionRows, $lineRows, $poolRows, $lineFeatureEnabled
|
|
),
|
|
'regions' => $regionRows,
|
|
'lines' => $lineRows,
|
|
'pools' => $poolRows,
|
|
];
|
|
}
|
|
|
|
private static function summary(array $regions, array $lines, array $pools,
|
|
array $platformHosts): array
|
|
{
|
|
$summary = [
|
|
'regions_total' => count($regions),
|
|
'lines_total' => count($lines),
|
|
'pools_total' => count($pools),
|
|
'placement_ready_pools' => 0,
|
|
'hosts_total' => (int) $platformHosts['hosts_total'],
|
|
'placement_ready_hosts' =>
|
|
(int) $platformHosts['placement_ready_hosts'],
|
|
'held_reservations' => 0,
|
|
'uncertain_reservations' => 0,
|
|
'capacity' => $platformHosts['capacity'],
|
|
'placement_capacity' => $platformHosts['placement_capacity'],
|
|
];
|
|
foreach ($pools as $pool) {
|
|
if ($pool['effective_state'] === 'ready') {
|
|
$summary['placement_ready_pools']++;
|
|
}
|
|
$summary['held_reservations'] += $pool['held_reservation_count'];
|
|
$summary['uncertain_reservations'] += $pool['uncertain_reservation_count'];
|
|
}
|
|
return $summary;
|
|
}
|
|
|
|
/** Physical host totals are counted once even when several pools share them. */
|
|
private static function platformHostSummary(array $capacityByHost,
|
|
array $lineCapacityByHost, array $placementEligibleByHost,
|
|
array $placementLineByHost, array $readyByHost): array
|
|
{
|
|
$capacity = self::emptyCapacity();
|
|
$placementCapacity = self::emptyCapacity();
|
|
foreach ($capacityByHost as $hostId => $hostCapacity) {
|
|
self::addCapacity($capacity, $hostCapacity);
|
|
if (!isset($placementEligibleByHost[$hostId])) {
|
|
continue;
|
|
}
|
|
$eligible = $hostCapacity;
|
|
$eligible['ip'] = self::emptyCapacity()['ip'];
|
|
$eligible['max_host_free']['ip'] = 0;
|
|
foreach ($placementLineByHost[$hostId] ?? [] as $lineId => $_) {
|
|
$lineIp = $lineCapacityByHost[$hostId][$lineId] ?? null;
|
|
if (!is_array($lineIp)) {
|
|
continue;
|
|
}
|
|
$eligible['ip'] =
|
|
CloudAdminPublicNetworkCapacityProjection::sum([
|
|
$eligible['ip'],
|
|
$lineIp,
|
|
]);
|
|
$eligible['max_host_free']['ip'] +=
|
|
(int) ($lineIp['bundles']['available'] ?? 0);
|
|
}
|
|
self::addCapacity($placementCapacity, $eligible);
|
|
}
|
|
return [
|
|
'hosts_total' => count($capacityByHost),
|
|
'placement_ready_hosts' => count($readyByHost),
|
|
'capacity' => $capacity,
|
|
'placement_capacity' => $placementCapacity,
|
|
];
|
|
}
|
|
|
|
private static function topology(array $regions, array $lines, array $pools,
|
|
bool $lineFeatureEnabled): array
|
|
{
|
|
$poolsByLine = [];
|
|
foreach ($pools as $pool) {
|
|
$poolsByLine[$pool['line_id']][] = $pool;
|
|
}
|
|
$linesByRegion = [];
|
|
foreach ($lines as $line) {
|
|
$node = $line;
|
|
$node['pools'] = $poolsByLine[$line['id']] ?? [];
|
|
$linesByRegion[$line['region_id']][] = $node;
|
|
}
|
|
$result = [];
|
|
foreach ($regions as $region) {
|
|
$node = $region;
|
|
$node['lines'] = $linesByRegion[$region['id']] ?? [];
|
|
$node['pools'] = [];
|
|
foreach ($node['lines'] as $line) {
|
|
if ($lineFeatureEnabled || $line['is_default'] === true) {
|
|
array_push($node['pools'], ...$line['pools']);
|
|
}
|
|
}
|
|
$result[] = $node;
|
|
}
|
|
return $result;
|
|
}
|
|
|
|
private static function aggregateEntityHealth(array $pools): array
|
|
{
|
|
$health = [
|
|
'pool_count' => count($pools),
|
|
'placement_ready_pool_count' => 0,
|
|
'host_count' => 0,
|
|
'placement_ready_host_count' => 0,
|
|
'offer_count' => 0,
|
|
'held_reservation_count' => 0,
|
|
'uncertain_reservation_count' => 0,
|
|
];
|
|
foreach ($pools as $pool) {
|
|
$health['placement_ready_pool_count'] +=
|
|
$pool['effective_state'] === 'ready' ? 1 : 0;
|
|
$health['host_count'] += $pool['health']['host_count'];
|
|
$health['placement_ready_host_count'] +=
|
|
$pool['health']['placement_ready_host_count'];
|
|
$health['offer_count'] += $pool['offer_count'];
|
|
$health['held_reservation_count'] += $pool['held_reservation_count'];
|
|
$health['uncertain_reservation_count'] +=
|
|
$pool['uncertain_reservation_count'];
|
|
}
|
|
return $health;
|
|
}
|
|
|
|
private static function poolEffectiveState(string $status, $line, $region,
|
|
bool $lineFeatureEnabled, array $health): array
|
|
{
|
|
if ($status === 'disabled') {
|
|
return self::effectiveResult('disabled', [
|
|
self::blocker('pool_disabled', '计算资源池已停用'),
|
|
]);
|
|
}
|
|
if ($status === 'draining') {
|
|
return self::effectiveResult('draining', [
|
|
self::blocker('pool_draining', '计算资源池正在排空,不接收新实例'),
|
|
]);
|
|
}
|
|
$blockers = [];
|
|
if ($line === null) {
|
|
$blockers[] = self::blocker('line_missing', '所属线路不存在');
|
|
} elseif ((string) $line->status !== 'active') {
|
|
$blockers[] = self::blocker('line_disabled', '所属线路已停用');
|
|
} elseif (!$lineFeatureEnabled && !(bool) $line->is_default) {
|
|
$blockers[] = self::blocker(
|
|
'line_not_default', '线路功能关闭时只调度地区默认线路'
|
|
);
|
|
}
|
|
if ($region === null) {
|
|
$blockers[] = self::blocker('region_missing', '所属地区不存在');
|
|
} elseif ((string) $region->status !== 'active') {
|
|
$blockers[] = self::blocker('region_disabled', '所属地区已停用');
|
|
}
|
|
if ($blockers === []) {
|
|
if ($health['host_count'] === 0) {
|
|
$blockers[] = self::blocker('no_hosts', '尚未分配计算节点');
|
|
} else {
|
|
$components = [
|
|
'enabled_host_count' => ['hosts_disabled', '没有已启用的计算节点'],
|
|
'scheduler_active_host_count' => [
|
|
'scheduler_inactive', '没有启用自动调度的计算节点',
|
|
],
|
|
'agent_ready_host_count' => [
|
|
'agent_not_ready', '没有 Agent 健康且配置已验证的计算节点',
|
|
],
|
|
'storage_ready_host_count' => [
|
|
'storage_not_ready', '没有存储配置已应用的计算节点',
|
|
],
|
|
'network_ready_host_count' => [
|
|
'network_not_ready', '没有公网网络及地址池就绪的计算节点',
|
|
],
|
|
'capacity_ready_host_count' => [
|
|
'capacity_unavailable', '没有计算容量和公网双栈容量均可用的计算节点',
|
|
],
|
|
];
|
|
foreach ($components as $field => [$code, $label]) {
|
|
if ($health[$field] === 0) {
|
|
$blockers[] = self::blocker($code, $label);
|
|
}
|
|
}
|
|
if ($health['placement_ready_host_count'] === 0) {
|
|
$blockers[] = self::blocker(
|
|
'no_placement_ready_hosts',
|
|
'没有同一节点同时满足全部基础调度条件'
|
|
);
|
|
}
|
|
}
|
|
}
|
|
return self::effectiveResult($blockers === [] ? 'ready' : 'blocked', $blockers);
|
|
}
|
|
|
|
private static function lineEffectiveState(string $status, $region,
|
|
bool $isDefault, bool $lineFeatureEnabled, array $health): array
|
|
{
|
|
if ($status !== 'active') {
|
|
return self::effectiveResult('disabled', [
|
|
self::blocker('line_disabled', '线路已停用'),
|
|
]);
|
|
}
|
|
$blockers = [];
|
|
if ($region === null) {
|
|
$blockers[] = self::blocker('region_missing', '所属地区不存在');
|
|
} elseif ((string) $region->status !== 'active') {
|
|
$blockers[] = self::blocker('region_disabled', '所属地区已停用');
|
|
}
|
|
if (!$lineFeatureEnabled && !$isDefault) {
|
|
$blockers[] = self::blocker(
|
|
'line_not_default', '线路功能关闭时只使用地区默认线路'
|
|
);
|
|
}
|
|
if ($health['pool_count'] === 0) {
|
|
$blockers[] = self::blocker('no_pools', '尚未创建计算资源池');
|
|
} elseif ($health['placement_ready_pool_count'] === 0) {
|
|
$blockers[] = self::blocker(
|
|
'no_placement_ready_pools', '没有基础条件就绪的计算资源池'
|
|
);
|
|
}
|
|
return self::effectiveResult($blockers === [] ? 'ready' : 'blocked', $blockers);
|
|
}
|
|
|
|
private static function regionEffectiveState(string $status, array $health): array
|
|
{
|
|
if ($status !== 'active') {
|
|
return self::effectiveResult('disabled', [
|
|
self::blocker('region_disabled', '地区已停用'),
|
|
]);
|
|
}
|
|
$blockers = [];
|
|
if ($health['active_default_line_count'] !== 1) {
|
|
$blockers[] = self::blocker(
|
|
'default_line_invalid', '必须恰好存在一条启用的默认线路'
|
|
);
|
|
}
|
|
if ($health['line_count'] === 0) {
|
|
$blockers[] = self::blocker('no_lines', '尚未创建线路');
|
|
}
|
|
if ($health['pool_count'] === 0) {
|
|
$blockers[] = self::blocker('no_pools', '尚未创建计算资源池');
|
|
} elseif ($health['placement_ready_pool_count'] === 0) {
|
|
$blockers[] = self::blocker(
|
|
'no_placement_ready_pools', '没有基础条件就绪的计算资源池'
|
|
);
|
|
}
|
|
return self::effectiveResult($blockers === [] ? 'ready' : 'blocked', $blockers);
|
|
}
|
|
|
|
private static function effectiveResult(string $state, array $blockers): array
|
|
{
|
|
return ['state' => $state, 'blockers' => $blockers];
|
|
}
|
|
|
|
private static function blocker(string $code, string $label): array
|
|
{
|
|
return ['code' => $code, 'label' => $label];
|
|
}
|
|
|
|
private static function enabledStatusLabel(string $status): string
|
|
{
|
|
return $status === 'active' ? '启用' : '停用';
|
|
}
|
|
|
|
private static function poolStatusLabel(string $status): string
|
|
{
|
|
return match ($status) {
|
|
'active' => '启用',
|
|
'draining' => '排空',
|
|
default => '停用',
|
|
};
|
|
}
|
|
|
|
private static function effectiveStateLabel(string $state): string
|
|
{
|
|
return match ($state) {
|
|
// Offer resources and template replicas are request-specific and
|
|
// are deliberately evaluated later by the real placement path.
|
|
'ready' => '基础就绪',
|
|
'draining' => '排空中',
|
|
'disabled' => '已停用',
|
|
default => '暂不可调度',
|
|
};
|
|
}
|
|
|
|
private static function emptyPoolHealth(): array
|
|
{
|
|
return [
|
|
'host_count' => 0,
|
|
'enabled_host_count' => 0,
|
|
'network_selector_ready_host_count' => 0,
|
|
'scheduler_active_host_count' => 0,
|
|
'agent_ready_host_count' => 0,
|
|
'storage_ready_host_count' => 0,
|
|
'network_ready_host_count' => 0,
|
|
'capacity_ready_host_count' => 0,
|
|
'placement_ready_host_count' => 0,
|
|
];
|
|
}
|
|
|
|
private static function addCapacity(array &$target, array $source): void
|
|
{
|
|
foreach (['cpu', 'memory', 'disk'] as $resource) {
|
|
foreach (['configured', 'safety', 'allocatable', 'allocated',
|
|
'reserved', 'free'] as $field) {
|
|
$target[$resource][$field] += $source[$resource][$field];
|
|
}
|
|
$target['max_host_free'][$resource] = max(
|
|
$target['max_host_free'][$resource],
|
|
$source['max_host_free'][$resource]
|
|
);
|
|
}
|
|
$target['ip'] = CloudAdminPublicNetworkCapacityProjection::sum([
|
|
$target['ip'],
|
|
$source['ip'],
|
|
]);
|
|
$target['max_host_free']['ip'] = max(
|
|
$target['max_host_free']['ip'], $source['max_host_free']['ip']
|
|
);
|
|
}
|
|
|
|
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();
|
|
$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()),
|
|
];
|
|
}
|
|
|
|
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;
|
|
$publicNetwork = self::reservationPublicNetwork($row);
|
|
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,
|
|
// These two names remain response compatibility only. Their
|
|
// values are derived from the active IPv4 claim, never from the
|
|
// retired singular reservation columns.
|
|
'public_ip_id' => $publicNetwork['ipv4']['public_ip_id'] ?? null,
|
|
'public_ip' => $publicNetwork['ipv4']['address'] ?? '',
|
|
'public_ipv4' => $publicNetwork['ipv4']['address'] ?? '',
|
|
'public_ipv6' => $publicNetwork['ipv6']['address'] ?? '',
|
|
'public_ips' => array_values($publicNetwork),
|
|
'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,
|
|
];
|
|
}
|
|
|
|
/** @return array<string,array<string,int|string>> */
|
|
private static function reservationPublicNetwork(
|
|
CloudResourceReservation $reservation
|
|
): array {
|
|
if ((string) $reservation->state === 'released') {
|
|
$claims = CloudResourceReservationIp::where(
|
|
'reservation_id',
|
|
(int) $reservation->id
|
|
);
|
|
$claimIds = (clone $claims)->pluck('id')->map(
|
|
static fn ($id): int => (int) $id
|
|
)->all();
|
|
$ipLeak = CloudPublicIp::where(function ($query) use (
|
|
$reservation,
|
|
$claimIds
|
|
): void {
|
|
$query->where(
|
|
'reservation_id',
|
|
(int) $reservation->id
|
|
);
|
|
if ($claimIds !== []) {
|
|
$query->orWhereIn(
|
|
'reservation_ip_claim_id',
|
|
$claimIds
|
|
);
|
|
}
|
|
})->exists();
|
|
if ((clone $claims)->where('active_claim', 1)->exists()
|
|
|| $ipLeak) {
|
|
throw new CloudError(
|
|
'已释放资源预留仍占用活动公网地址',
|
|
409
|
|
);
|
|
}
|
|
return [];
|
|
}
|
|
$expectedInstanceId = null;
|
|
if ((string) $reservation->state === 'committed') {
|
|
$expectedInstanceId = (int) ($reservation->instance_id ?? 0);
|
|
if ($expectedInstanceId < 1) {
|
|
throw new CloudError('已提交资源预留缺少实例归属', 409);
|
|
}
|
|
}
|
|
$claimSet = CloudPublicNetworkAllocationService::currentClaimSet(
|
|
(int) $reservation->id,
|
|
(string) $reservation->state,
|
|
$expectedInstanceId
|
|
);
|
|
$result = [];
|
|
foreach ([4 => 'ipv4', 6 => 'ipv6'] as $family => $key) {
|
|
$cidr = $claimSet->publicNetwork()->address($family);
|
|
$separator = strrpos($cidr, '/');
|
|
if ($separator === false) {
|
|
throw new CloudError('活动公网地址快照格式损坏', 409);
|
|
}
|
|
$result[$key] = [
|
|
'address_family' => $family,
|
|
'claim_id' => $claimSet->claimId($family),
|
|
'claim_generation' => $claimSet->generation($family),
|
|
'public_ip_id' => $claimSet->publicIpId($family),
|
|
'address' => substr($cidr, 0, $separator),
|
|
'address_cidr' => $cidr,
|
|
];
|
|
}
|
|
return $result;
|
|
}
|
|
|
|
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' => CloudAdminPublicNetworkCapacityProjection::empty(),
|
|
'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 entityCode(array $body, $model, string $prefix,
|
|
string $name, int $max, string $label): string
|
|
{
|
|
if ($model->exists) {
|
|
if (array_key_exists('code', $body)) {
|
|
throw new CloudError($label . '创建后不可修改', 409);
|
|
}
|
|
return (string) $model->code;
|
|
}
|
|
$provided = $body['code'] ?? null;
|
|
if ($provided !== null && $provided !== '') {
|
|
return self::code($provided, $max, $label);
|
|
}
|
|
|
|
$slug = strtolower($name);
|
|
$slug = preg_replace('/[^a-z0-9]+/', '-', $slug) ?? '';
|
|
$slug = trim($slug, '-');
|
|
if ($slug === '') {
|
|
$slug = $prefix;
|
|
}
|
|
$suffix = bin2hex(random_bytes(4));
|
|
$baseLength = max(1, $max - strlen($suffix) - 1);
|
|
$slug = rtrim(substr($slug, 0, $baseLength), '-');
|
|
if ($slug === '') {
|
|
$slug = substr($prefix, 0, $baseLength);
|
|
}
|
|
return self::code($slug . '-' . $suffix, $max, $label);
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|