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.
344 lines
13 KiB
PHP
344 lines
13 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Cloud;
|
|
|
|
use App\Models\CloudOffer;
|
|
use App\Models\CloudSSHKey;
|
|
|
|
/**
|
|
* Database-backed first-paint data for instance deployment and reinstall.
|
|
*
|
|
* The PHP-owned template catalog exposes only public labels and identifiers.
|
|
* Host paths, replica locations, credentials and checksums never cross this
|
|
* boundary.
|
|
*/
|
|
final class CloudDeploymentPageService
|
|
{
|
|
private const GIB = 1073741824;
|
|
/**
|
|
* Build the public Region -> Line -> Offer sale catalog.
|
|
*
|
|
* Hosts are not part of the sale catalog. Pools are read only to validate
|
|
* the active offer chain, and neither placement identity enters this DTO.
|
|
* Sellability is delegated to the exact-pool placement advisory so this
|
|
* projection shares its current Agent/network/IP evidence contract.
|
|
*/
|
|
public static function saleCatalog(): array
|
|
{
|
|
$linesEnabled = CloudNetworkLineFeature::enabled();
|
|
$query = CloudOffer::query()->from('cloud_offers as offer')
|
|
->join('shop as plan', 'plan.id', '=', 'offer.plan_id')
|
|
->join('cloud_resource_pools as pool', 'pool.id', '=', 'offer.resource_pool_id')
|
|
->join('cloud_network_lines as line', 'line.id', '=', 'pool.line_id')
|
|
->join('cloud_regions as region', 'region.id', '=', 'line.region_id')
|
|
->where('offer.status', 1)
|
|
->where('offer.currency', 'USD')
|
|
->where('plan.status', 1)
|
|
->where('pool.status', 'active')
|
|
->where('line.status', 'active')
|
|
->where('region.status', 'active');
|
|
if (!$linesEnabled) {
|
|
$query->where('line.is_default', 1);
|
|
}
|
|
|
|
$rows = $query->orderByDesc('region.sort')->orderBy('region.id')
|
|
->orderByDesc('line.sort')->orderBy('line.id')
|
|
->orderByDesc('offer.sort')->orderBy('offer.id')
|
|
->get([
|
|
'offer.id as offer_id', 'offer.name as offer_name',
|
|
'offer.price as offer_price', 'offer.stock as offer_stock',
|
|
'offer.backup_price',
|
|
'plan.cpu_cores', 'plan.memory_mib', 'plan.bandwidth_mbps',
|
|
'plan.disk_gib', 'plan.validity_days', 'plan.traffic_quota_bytes',
|
|
'pool.id as internal_pool_id',
|
|
'line.id as line_id', 'line.name as line_name', 'line.is_default',
|
|
'region.id as region_id', 'region.name as region_name',
|
|
'region.country_code',
|
|
]);
|
|
|
|
$capacityKey = static fn ($row): string => implode(':', [
|
|
(int) $row->internal_pool_id,
|
|
(int) $row->cpu_cores,
|
|
(int) $row->memory_mib,
|
|
(int) $row->disk_gib,
|
|
]);
|
|
$capacityRequests = [];
|
|
foreach ($rows as $row) {
|
|
$capacityRequests[$capacityKey($row)] = [
|
|
'pool_id' => (int) $row->internal_pool_id,
|
|
'cpu_cores' => (int) $row->cpu_cores,
|
|
'memory_mib' => (int) $row->memory_mib,
|
|
'disk_gib' => (int) $row->disk_gib,
|
|
];
|
|
}
|
|
$placementAvailability =
|
|
CloudPlacementService::poolCapacityAvailability(
|
|
$capacityRequests
|
|
);
|
|
$regions = [];
|
|
$lines = [];
|
|
$offers = [];
|
|
foreach ($rows as $row) {
|
|
$regionId = (int) $row->region_id;
|
|
$lineId = (int) $row->line_id;
|
|
if (!isset($regions[$regionId])) {
|
|
$countryCode = strtoupper(trim((string) $row->country_code));
|
|
$regions[$regionId] = [
|
|
'id' => $regionId,
|
|
'name' => trim((string) $row->region_name),
|
|
'country_code' => $countryCode,
|
|
'flag' => self::countryFlag($countryCode),
|
|
];
|
|
}
|
|
if (!isset($lines[$lineId])) {
|
|
$lines[$lineId] = [
|
|
'id' => $lineId,
|
|
'region_id' => $regionId,
|
|
'name' => trim((string) $row->line_name),
|
|
'is_default' => (bool) $row->is_default,
|
|
];
|
|
}
|
|
$trafficBytes = max(0, (int) $row->traffic_quota_bytes);
|
|
$trafficGiB = intdiv($trafficBytes, self::GIB);
|
|
$offerCapacityKey = $capacityKey($row);
|
|
$offers[] = [
|
|
'id' => (int) $row->offer_id,
|
|
'name' => trim((string) $row->offer_name),
|
|
'price' => number_format((float) $row->offer_price, 2, '.', ''),
|
|
'backup_price' => number_format(
|
|
(float) $row->backup_price,
|
|
2,
|
|
'.',
|
|
''
|
|
),
|
|
'currency' => 'USD',
|
|
'region_id' => $regionId,
|
|
'line_id' => $lineId,
|
|
'cpu_cores' => (int) $row->cpu_cores,
|
|
'memory_mib' => (int) $row->memory_mib,
|
|
'bandwidth_mbps' => (int) $row->bandwidth_mbps,
|
|
'disk_gib' => (int) $row->disk_gib,
|
|
'validity_days' => (int) $row->validity_days,
|
|
'traffic_quota_bytes' => $trafficBytes,
|
|
'traffic_gib' => $trafficGiB,
|
|
'traffic_tib' => self::formatDecimalUnit($trafficGiB, 1024, 10),
|
|
'sellable' => (int) $row->offer_stock !== 0
|
|
&& ($placementAvailability[$offerCapacityKey] ?? false),
|
|
];
|
|
}
|
|
|
|
return [
|
|
'lines_enabled' => $linesEnabled,
|
|
'regions' => array_values($regions),
|
|
'lines' => array_values($lines),
|
|
'offers' => $offers,
|
|
];
|
|
}
|
|
|
|
public static function sshKeys(int $userId): array
|
|
{
|
|
return CloudSSHKey::where('user_id', $userId)->orderBy('id')->get([
|
|
'id', 'name', 'fingerprint', 'created_at',
|
|
])->map(static fn ($key): array => [
|
|
'id' => (int) $key->id,
|
|
'name' => (string) $key->name,
|
|
'fingerprint' => (string) $key->fingerprint,
|
|
'created_at' => (int) $key->created_at,
|
|
])->all();
|
|
}
|
|
|
|
/**
|
|
* Return the PHP-owned public catalog for SSR without a host round trip.
|
|
*/
|
|
public static function templateCatalogForPage(array $actor): array
|
|
{
|
|
return CloudTemplateCatalogService::publicCatalog() + [
|
|
'catalog_stale' => false,
|
|
'catalog_unavailable' => false,
|
|
];
|
|
}
|
|
|
|
public static function templateCatalogForHost(
|
|
int $hostId,
|
|
array $actor
|
|
): array {
|
|
return CloudTemplateCatalogService::publicCatalogForHost($hostId) + [
|
|
'catalog_stale' => false,
|
|
'catalog_unavailable' => false,
|
|
];
|
|
}
|
|
|
|
/** Kept as the public live-read entry point used by API controllers. */
|
|
public static function freshTemplateCatalog(array $actor, float $timeoutSeconds = 20.0): array
|
|
{
|
|
return self::templateCatalogForPage($actor);
|
|
}
|
|
|
|
public static function freshTemplateCatalogForHost(
|
|
int $hostId,
|
|
array $actor,
|
|
float $timeoutSeconds = 20.0
|
|
): array {
|
|
return self::templateCatalogForHost($hostId, $actor);
|
|
}
|
|
|
|
public static function templateGroups(
|
|
array $templates,
|
|
?int $offerId = null
|
|
): array
|
|
{
|
|
$groups = [];
|
|
foreach (self::sanitizeTemplates($templates) as $template) {
|
|
if ($offerId !== null
|
|
&& !in_array($offerId, $template['offer_ids'], true)) {
|
|
continue;
|
|
}
|
|
[$family, $version] = self::templateSystem($template);
|
|
if (!isset($groups[$family])) {
|
|
$groups[$family] = [
|
|
'family' => $family,
|
|
'icon_path' => self::templateIcon($family),
|
|
'templates' => [],
|
|
];
|
|
}
|
|
$template['display_version'] = $version;
|
|
$groups[$family]['templates'][] = $template;
|
|
}
|
|
foreach ($groups as &$group) {
|
|
usort($group['templates'], static function (array $left, array $right): int {
|
|
$version = version_compare(
|
|
(string) ($right['display_version'] ?? '0'),
|
|
(string) ($left['display_version'] ?? '0')
|
|
);
|
|
return $version !== 0 ? $version
|
|
: strnatcasecmp((string) $left['name'], (string) $right['name']);
|
|
});
|
|
}
|
|
unset($group);
|
|
$order = ['AlmaLinux' => 0, 'Debian' => 1, 'CentOS Stream' => 2, 'Ubuntu' => 3];
|
|
uasort($groups, static fn (array $left, array $right): int =>
|
|
($order[$left['family']] ?? 100) <=> ($order[$right['family']] ?? 100)
|
|
?: strcasecmp($left['family'], $right['family']));
|
|
|
|
return array_values($groups);
|
|
}
|
|
|
|
private static function sanitizeTemplates($values): array
|
|
{
|
|
if (!is_array($values)) {
|
|
return [];
|
|
}
|
|
$templates = [];
|
|
foreach (array_slice($values, 0, 256) as $value) {
|
|
if (!is_array($value)) {
|
|
continue;
|
|
}
|
|
$id = $value['id'] ?? null;
|
|
$name = $value['name'] ?? null;
|
|
$family = $value['os_family'] ?? '';
|
|
$version = $value['os_version'] ?? '';
|
|
if (!is_string($id)
|
|
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D', $id) !== 1
|
|
|| !self::plainLabel($name, 64)
|
|
|| !self::plainLabel($family, 40)
|
|
|| !is_string($version)
|
|
|| preg_match('/^[0-9]{1,4}(?:\.[0-9]{1,4}){0,2}$/D', $version) !== 1) {
|
|
continue;
|
|
}
|
|
$templates[$id] = [
|
|
'id' => $id,
|
|
'name' => trim($name),
|
|
'os_family' => trim($family),
|
|
'os_version' => $version,
|
|
'offer_ids' => self::positiveIds(
|
|
$value['offer_ids'] ?? []
|
|
),
|
|
'region_ids' => self::positiveIds(
|
|
$value['region_ids'] ?? []
|
|
),
|
|
];
|
|
}
|
|
return array_values($templates);
|
|
}
|
|
|
|
/** @return list<int> */
|
|
private static function positiveIds($values): array
|
|
{
|
|
if (!is_array($values) || count($values) > 1024) {
|
|
return [];
|
|
}
|
|
$ids = [];
|
|
foreach ($values as $value) {
|
|
$id = filter_var($value, FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]);
|
|
if ($id !== false) {
|
|
$ids[(int) $id] = true;
|
|
}
|
|
}
|
|
$ids = array_keys($ids);
|
|
sort($ids, SORT_NUMERIC);
|
|
return $ids;
|
|
}
|
|
|
|
private static function plainLabel($value, int $maximum): bool
|
|
{
|
|
return is_string($value) && trim($value) !== '' && mb_strlen($value) <= $maximum
|
|
&& preg_match('//u', $value) === 1
|
|
&& preg_match('/[\x00-\x1F\x7F]/u', $value) !== 1;
|
|
}
|
|
|
|
private static function templateSystem(array $template): array
|
|
{
|
|
$familyKey = strtolower((string) preg_replace(
|
|
'/[\s_-]+/', '', (string) ($template['os_family'] ?? '')
|
|
));
|
|
$family = [
|
|
'alma' => 'AlmaLinux', 'almalinux' => 'AlmaLinux',
|
|
'debian' => 'Debian', 'centos' => 'CentOS Stream',
|
|
'centosstream' => 'CentOS Stream', 'ubuntu' => 'Ubuntu',
|
|
][$familyKey] ?? '';
|
|
$idVersion = '';
|
|
if (preg_match('/^(alma|debian|ubuntu|centosstream)([0-9]{1,4})-/i',
|
|
(string) $template['id'], $match) === 1) {
|
|
$family = $family ?: [
|
|
'alma' => 'AlmaLinux', 'debian' => 'Debian',
|
|
'ubuntu' => 'Ubuntu', 'centosstream' => 'CentOS Stream',
|
|
][strtolower($match[1])];
|
|
$idVersion = $match[2];
|
|
if (strtolower($match[1]) === 'ubuntu' && strlen($idVersion) === 4) {
|
|
$idVersion = substr($idVersion, 0, 2) . '.' . substr($idVersion, 2);
|
|
}
|
|
}
|
|
return [
|
|
$family ?: '其他系统',
|
|
(string) ($template['os_version'] ?: $idVersion),
|
|
];
|
|
}
|
|
|
|
private static function templateIcon(string $family): string
|
|
{
|
|
return [
|
|
'AlmaLinux' => '/cloud/almalinux-icon.svg',
|
|
'Debian' => '/cloud/debian-icon.svg',
|
|
'CentOS Stream' => '/cloud/centos-icon.svg',
|
|
'Ubuntu' => '/cloud/ubuntu-icon.svg',
|
|
][$family] ?? '';
|
|
}
|
|
|
|
private static function countryFlag(string $countryCode): string
|
|
{
|
|
if (preg_match('/^[A-Z]{2}$/D', $countryCode) !== 1) {
|
|
return '🌐';
|
|
}
|
|
return mb_chr(127397 + ord($countryCode[0]), 'UTF-8')
|
|
. mb_chr(127397 + ord($countryCode[1]), 'UTF-8');
|
|
}
|
|
|
|
private static function formatDecimalUnit(int $value, int $unit, int $precision): string
|
|
{
|
|
$formatted = number_format($value / $unit, $precision, '.', '');
|
|
$formatted = rtrim(rtrim($formatted, '0'), '.');
|
|
return $formatted === '' ? '0' : $formatted;
|
|
}
|
|
}
|