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/CloudPanelUsageService.php

256 lines
10 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudInstance;
use App\Models\CloudResourceReservation;
/**
* Panel-owned host usage. Reservations cover current provisioning and paid
* instances; older panel rows without a reservation are counted from their
* immutable metadata so retiring inventory cannot create phantom capacity.
*/
final class CloudPanelUsageService
{
private const GIB = 1073741824;
/**
* The panel deliberately does not persist an Agent management address in
* cloud_hosts. Operators must put a management IPv4 in the public-pool
* reserved_ips list, which is materialized into the ledger.
*/
public static function managementAddress(?CloudHost $host): ?string
{
return null;
}
public static function managementAddressFromValue($value): ?string
{
$address = trim((string) ($value ?? ''));
return filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false
? null : $address;
}
public static function forHost(int $hostId, $reservationRows = null): array
{
$usage = self::emptyUsage();
$reservationRows ??= CloudResourceReservation::where('host_id', $hostId)
->whereIn('state', ['held', 'uncertain', 'committed'])
->get(['state', 'instance_id', 'cpu_cores', 'memory_mib', 'disk_gib']);
$coveredInstances = [];
foreach ($reservationRows as $row) {
$state = (string) $row->state;
$bucket = $state === 'committed' ? 'allocated' : 'reserved';
$usage['instances'][$bucket]++;
$usage['cpu'][$bucket] += max(0, (int) $row->cpu_cores);
$usage['memory'][$bucket] += max(0, (int) $row->memory_mib);
$usage['disk'][$bucket] += max(0, (int) $row->disk_gib);
if ($row->instance_id !== null) {
$coveredInstances[(int) $row->instance_id] = true;
}
}
$instances = CloudInstance::where('cloud_instances.host_id', $hostId)
->where('cloud_instances.status', '<>', 'deleted')
->leftJoin(
'cloud_instance_snapshots as capacity_snapshots',
static function ($join): void {
$join->on(
'capacity_snapshots.instance_id',
'=',
'cloud_instances.id'
)->whereColumn(
'capacity_snapshots.host_id',
'cloud_instances.host_id'
)->whereIn('capacity_snapshots.state', [
'creating', 'ready', 'restoring',
'deleting', 'uncertain',
])->whereNotNull('capacity_snapshots.size_bytes');
}
)->groupBy('cloud_instances.id', 'cloud_instances.spec_json')
->select([
'cloud_instances.id',
'cloud_instances.spec_json',
])->selectRaw(
'COALESCE(SUM(capacity_snapshots.size_bytes), 0)'
. ' AS snapshot_bytes'
)->get();
$snapshotBytes = 0;
foreach ($instances as $instance) {
$snapshotBytes += max(0, (int) ($instance->snapshot_bytes ?? 0));
if (isset($coveredInstances[(int) $instance->id])) {
continue;
}
$spec = self::spec((string) $instance->spec_json);
if ($spec === null) {
$usage['unknown']++;
continue;
}
$usage['instances']['allocated']++;
$usage['cpu']['allocated'] += $spec['cpu'];
$usage['memory']['allocated'] += $spec['memory'];
$usage['disk']['allocated'] += $spec['disk'];
}
return self::finalizeUsage($usage, $snapshotBytes);
}
public static function forHosts(array $hostIds): array
{
$hostIds = array_values(array_unique(array_filter(
array_map('intval', $hostIds), static fn (int $id): bool => $id > 0
)));
sort($hostIds, SORT_NUMERIC);
$result = [];
foreach ($hostIds as $hostId) {
$result[$hostId] = self::emptyUsage();
}
if ($hostIds === []) {
return $result;
}
$coveredInstances = [];
foreach (CloudResourceReservation::whereIn('host_id', $hostIds)
->whereIn('state', ['held', 'uncertain', 'committed'])
->orderBy('host_id')->orderBy('id')
->get(['host_id', 'state', 'instance_id', 'cpu_cores',
'memory_mib', 'disk_gib']) as $row) {
$hostId = (int) $row->host_id;
$bucket = (string) $row->state === 'committed'
? 'allocated' : 'reserved';
$result[$hostId]['instances'][$bucket]++;
$result[$hostId]['cpu'][$bucket] += max(0, (int) $row->cpu_cores);
$result[$hostId]['memory'][$bucket] += max(0, (int) $row->memory_mib);
$result[$hostId]['disk'][$bucket] += max(0, (int) $row->disk_gib);
if ($row->instance_id !== null) {
$coveredInstances[$hostId][(int) $row->instance_id] = true;
}
}
$snapshotBytes = array_fill_keys($hostIds, 0);
$instances = CloudInstance::whereIn('cloud_instances.host_id', $hostIds)
->where('cloud_instances.status', '<>', 'deleted')
->leftJoin(
'cloud_instance_snapshots as capacity_snapshots',
static function ($join): void {
$join->on(
'capacity_snapshots.instance_id',
'=',
'cloud_instances.id'
)->whereColumn(
'capacity_snapshots.host_id',
'cloud_instances.host_id'
)->whereIn('capacity_snapshots.state', [
'creating', 'ready', 'restoring',
'deleting', 'uncertain',
])->whereNotNull('capacity_snapshots.size_bytes');
}
)->groupBy('cloud_instances.host_id', 'cloud_instances.id',
'cloud_instances.spec_json')
->select([
'cloud_instances.id', 'cloud_instances.host_id',
'cloud_instances.spec_json',
])->selectRaw(
'COALESCE(SUM(capacity_snapshots.size_bytes), 0)'
. ' AS snapshot_bytes'
)->orderBy('cloud_instances.host_id')->orderBy('cloud_instances.id')
->get();
foreach ($instances as $instance) {
$hostId = (int) $instance->host_id;
$snapshotBytes[$hostId] += max(
0, (int) ($instance->snapshot_bytes ?? 0)
);
if (isset($coveredInstances[$hostId][(int) $instance->id])) {
continue;
}
$spec = self::spec((string) $instance->spec_json);
if ($spec === null) {
$result[$hostId]['unknown']++;
continue;
}
$result[$hostId]['instances']['allocated']++;
$result[$hostId]['cpu']['allocated'] += $spec['cpu'];
$result[$hostId]['memory']['allocated'] += $spec['memory'];
$result[$hostId]['disk']['allocated'] += $spec['disk'];
}
foreach ($hostIds as $hostId) {
$result[$hostId] = self::finalizeUsage(
$result[$hostId], $snapshotBytes[$hostId]
);
}
return $result;
}
public static function emptyUsage(): array
{
return [
'cpu' => ['allocated' => 0, 'reserved' => 0],
'memory' => ['allocated' => 0, 'reserved' => 0],
'disk' => ['allocated' => 0, 'reserved' => 0],
'instances' => ['allocated' => 0, 'reserved' => 0],
'unknown' => 0,
];
}
private static function finalizeUsage(array $usage,
int $snapshotBytes): array
{
$usage['disk']['allocated'] +=
(int) ceil(max(0, $snapshotBytes) / self::GIB);
$usage['cpu_sum'] = $usage['cpu']['allocated']
+ $usage['cpu']['reserved'];
$usage['memory_sum'] = $usage['memory']['allocated']
+ $usage['memory']['reserved'];
$usage['disk_sum'] = $usage['disk']['allocated']
+ $usage['disk']['reserved'];
$usage['instance_count'] = $usage['instances']['allocated']
+ $usage['instances']['reserved'];
return $usage;
}
private static function spec(string $encoded): ?array
{
try {
$value = json_decode($encoded, true, 32, JSON_THROW_ON_ERROR);
} catch (\Throwable $error) {
return null;
}
if (!is_array($value) || array_is_list($value)) {
return null;
}
$cpu = self::positiveNumber($value['vcpu'] ?? $value['cpu_cores'] ?? null);
$memory = self::positiveNumber($value['memory_mib'] ?? $value['ram_mib'] ?? null);
$disk = self::positiveNumber($value['disk_gib'] ?? null);
if ($disk === null && is_array($value['disks'] ?? null)) {
$sum = 0.0;
foreach ($value['disks'] as $row) {
if (!is_array($row)) {
return null;
}
$capacity = self::positiveNumber($row['capacity_gib'] ?? $row['size_gib'] ?? null);
if ($capacity === null) {
return null;
}
$sum += $capacity;
}
$disk = $sum > 0 ? $sum : null;
}
return $cpu === null || $memory === null || $disk === null ? null : [
'cpu' => (int) ceil($cpu),
'memory' => (int) ceil($memory),
'disk' => (int) ceil($disk),
];
}
private static function positiveNumber($value): ?float
{
if (is_bool($value) || (!is_int($value) && !is_float($value)
&& !(is_string($value) && is_numeric($value)))) {
return null;
}
$number = (float) $value;
return is_finite($number) && $number > 0 ? $number : null;
}
}