feat: configure host placement policies
parent
d6b6d390d5
commit
74cd779901
@ -0,0 +1,307 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudHost;
|
||||
use App\Models\CloudHostCapacityPolicy;
|
||||
use App\Models\CloudHostCapacitySnapshot;
|
||||
use App\Models\CloudNetworkLine;
|
||||
use App\Models\CloudRegion;
|
||||
use App\Models\CloudResourcePool;
|
||||
use App\Services\Config;
|
||||
|
||||
/** Database-owned administrator settings for one compute host. */
|
||||
final class CloudAdminHostSchedulingService
|
||||
{
|
||||
private const SCHEDULER_STATES = ['active', 'draining', 'disabled'];
|
||||
|
||||
public static function read(int $hostId): array
|
||||
{
|
||||
$host = CloudHost::find($hostId);
|
||||
if ($host === null) {
|
||||
throw new CloudError('宿主机不存在', 404);
|
||||
}
|
||||
|
||||
$policy = CloudHostCapacityPolicy::find($hostId);
|
||||
$snapshot = CloudHostCapacitySnapshot::find($hostId);
|
||||
$pools = self::poolOptions();
|
||||
$selected = null;
|
||||
foreach ($pools as $pool) {
|
||||
if ((int) $pool['id'] === (int) ($host->resource_pool_id ?? 0)) {
|
||||
$selected = $pool;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$snapshotDto = self::snapshotDto($snapshot);
|
||||
return [
|
||||
'host' => [
|
||||
'id' => (int) $host->id,
|
||||
'name' => self::safeText((string) $host->name, 80),
|
||||
'enabled' => (bool) $host->enabled,
|
||||
'resource_pool_id' => $host->resource_pool_id === null
|
||||
? null : (int) $host->resource_pool_id,
|
||||
'scheduler_state' => in_array((string) $host->scheduler_state,
|
||||
self::SCHEDULER_STATES, true)
|
||||
? (string) $host->scheduler_state : 'disabled',
|
||||
'health_state' => self::safeText((string) ($host->health_state ?? 'unknown'), 32),
|
||||
'last_seen_at' => self::nullableInt($host->last_seen_at),
|
||||
'health_checked_at' => self::nullableInt($host->health_checked_at),
|
||||
'health_error_code' => self::safeText((string) ($host->health_error_code ?? ''), 64),
|
||||
],
|
||||
'policy' => self::policyDto($policy),
|
||||
'snapshot' => $snapshotDto,
|
||||
'placement' => $selected,
|
||||
'pools' => $pools,
|
||||
'network_lines_enabled' => CloudNetworkLineFeature::enabled(),
|
||||
'warnings' => self::warnings($host, $snapshotDto, $selected),
|
||||
'generated_at' => time(),
|
||||
];
|
||||
}
|
||||
|
||||
public static function save(int $hostId, array $body): array
|
||||
{
|
||||
$poolId = self::nullablePositiveId($body['resource_pool_id'] ?? null);
|
||||
$schedulerState = $body['scheduler_state'] ?? null;
|
||||
if (!is_string($schedulerState)
|
||||
|| !in_array($schedulerState, self::SCHEDULER_STATES, true)) {
|
||||
throw new CloudError('调度状态无效');
|
||||
}
|
||||
$values = [
|
||||
'configured_cpu_cores' => self::integer($body, 'configured_cpu_cores', 0, 65535, '配置 CPU'),
|
||||
'configured_memory_mib' => self::integer($body, 'configured_memory_mib', 0, 2147483647, '配置内存'),
|
||||
'configured_disk_gib' => self::integer($body, 'configured_disk_gib', 0, 2147483647, '配置磁盘'),
|
||||
'safety_cpu_cores' => self::integer($body, 'safety_cpu_cores', 0, 65535, 'CPU 安全预留'),
|
||||
'safety_memory_mib' => self::integer($body, 'safety_memory_mib', 0, 2147483647, '内存安全预留'),
|
||||
'safety_disk_gib' => self::integer($body, 'safety_disk_gib', 0, 2147483647, '磁盘安全预留'),
|
||||
'max_instances' => self::integer($body, 'max_instances', 0, 2147483647, '最大实例数'),
|
||||
];
|
||||
|
||||
(new CloudHost())->getConnection()->transaction(
|
||||
function () use ($hostId, $poolId, $schedulerState, $values): void {
|
||||
// All capacity writers use host -> policy order. Keep this
|
||||
// order aligned with inventory and placement reconciliation.
|
||||
$host = CloudHost::where('id', $hostId)->lockForUpdate()->first();
|
||||
if ($host === null) {
|
||||
throw new CloudError('宿主机不存在', 404);
|
||||
}
|
||||
$policy = CloudHostCapacityPolicy::where('host_id', $hostId)
|
||||
->lockForUpdate()->first();
|
||||
if ($policy === null) {
|
||||
$policy = new CloudHostCapacityPolicy();
|
||||
$policy->host_id = $hostId;
|
||||
$policy->created_at = time();
|
||||
}
|
||||
|
||||
$pool = $poolId === null ? null : CloudResourcePool::find($poolId);
|
||||
$line = $pool === null ? null : CloudNetworkLine::find((int) $pool->line_id);
|
||||
$region = $line === null ? null : CloudRegion::find((int) $line->region_id);
|
||||
if ($poolId !== null && $pool === null) {
|
||||
throw new CloudError('所选资源池不存在', 409);
|
||||
}
|
||||
if ($schedulerState === 'active') {
|
||||
self::validateActive($host, $pool, $line, $region, $values);
|
||||
}
|
||||
|
||||
$now = time();
|
||||
$host->resource_pool_id = $poolId;
|
||||
$host->scheduler_state = $schedulerState;
|
||||
$host->updated_at = $now;
|
||||
$host->save();
|
||||
foreach ($values as $field => $value) {
|
||||
$policy->{$field} = $value;
|
||||
}
|
||||
$policy->updated_at = $now;
|
||||
$policy->save();
|
||||
}, 3
|
||||
);
|
||||
|
||||
return self::read($hostId);
|
||||
}
|
||||
|
||||
public static function sync(int $hostId): array
|
||||
{
|
||||
if (CloudHost::find($hostId) === null) {
|
||||
throw new CloudError('宿主机不存在', 404);
|
||||
}
|
||||
return [
|
||||
'sync' => (new CloudHostInventorySyncService())->syncOne($hostId),
|
||||
'scheduling' => self::read($hostId),
|
||||
];
|
||||
}
|
||||
|
||||
private static function validateActive(CloudHost $host, $pool, $line,
|
||||
$region, array $values): void
|
||||
{
|
||||
if (!(bool) $host->enabled) {
|
||||
throw new CloudError('宿主机连接未启用,不能启用自动调度', 409);
|
||||
}
|
||||
if ($pool === null || (string) $pool->status !== 'active') {
|
||||
throw new CloudError('启用调度前必须选择启用的资源池', 409);
|
||||
}
|
||||
if ($line === null || (string) $line->status !== 'active'
|
||||
|| $region === null || (string) $region->status !== 'active') {
|
||||
throw new CloudError('资源池所属地区或线路未启用', 409);
|
||||
}
|
||||
if (!CloudNetworkLineFeature::enabled() && !(bool) $line->is_default) {
|
||||
throw new CloudError('线路功能关闭时只能使用地区默认线路', 409);
|
||||
}
|
||||
foreach (['cpu_cores' => 'CPU', 'memory_mib' => '内存', 'disk_gib' => '磁盘'] as $suffix => $label) {
|
||||
$configured = (int) $values['configured_' . $suffix];
|
||||
$safety = (int) $values['safety_' . $suffix];
|
||||
if ($configured <= 0) {
|
||||
throw new CloudError('启用调度前' . $label . '配置容量必须大于 0', 409);
|
||||
}
|
||||
if ($safety >= $configured) {
|
||||
throw new CloudError($label . '安全预留必须小于配置容量', 409);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static function poolOptions(): array
|
||||
{
|
||||
$lines = [];
|
||||
foreach (CloudNetworkLine::orderBy('sort')->orderBy('id')->get() as $line) {
|
||||
$lines[(int) $line->id] = $line;
|
||||
}
|
||||
$regions = [];
|
||||
foreach (CloudRegion::orderBy('sort')->orderBy('id')->get() as $region) {
|
||||
$regions[(int) $region->id] = $region;
|
||||
}
|
||||
$result = [];
|
||||
foreach (CloudResourcePool::orderBy('sort')->orderBy('id')->get() as $pool) {
|
||||
$line = $lines[(int) $pool->line_id] ?? null;
|
||||
$region = $line === null ? null : ($regions[(int) $line->region_id] ?? null);
|
||||
$result[] = [
|
||||
'id' => (int) $pool->id,
|
||||
'name' => self::safeText((string) $pool->name, 80),
|
||||
'status' => self::safeText((string) $pool->status, 16),
|
||||
'scheduling_policy' => self::safeText((string) $pool->scheduling_policy, 32),
|
||||
'line_id' => $line === null ? null : (int) $line->id,
|
||||
'line_name' => $line === null ? '线路已缺失' : self::safeText((string) $line->name, 80),
|
||||
'line_status' => $line === null ? 'missing' : self::safeText((string) $line->status, 16),
|
||||
'line_is_default' => $line !== null && (bool) $line->is_default,
|
||||
'region_id' => $region === null ? null : (int) $region->id,
|
||||
'region_name' => $region === null ? '地区已缺失' : self::safeText((string) $region->name, 80),
|
||||
'region_status' => $region === null ? 'missing' : self::safeText((string) $region->status, 16),
|
||||
];
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function policyDto($policy): array
|
||||
{
|
||||
$fields = ['configured_cpu_cores', 'configured_memory_mib',
|
||||
'configured_disk_gib', 'safety_cpu_cores', 'safety_memory_mib',
|
||||
'safety_disk_gib', 'max_instances'];
|
||||
$result = [];
|
||||
foreach ($fields as $field) {
|
||||
$result[$field] = $policy === null ? 0 : max(0, (int) $policy->{$field});
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function snapshotDto($snapshot): ?array
|
||||
{
|
||||
if ($snapshot === null) {
|
||||
return null;
|
||||
}
|
||||
$observed = self::nullableInt($snapshot->observed_at);
|
||||
$age = $observed === null ? null : max(0, time() - $observed);
|
||||
return [
|
||||
'sync_state' => self::safeText((string) ($snapshot->sync_state ?? 'never'), 16),
|
||||
'observed_at' => $observed,
|
||||
'last_attempt_at' => self::nullableInt($snapshot->last_attempt_at),
|
||||
'revision' => max(0, (int) $snapshot->revision),
|
||||
'last_error_code' => self::safeText((string) ($snapshot->last_error_code ?? ''), 64),
|
||||
'age_seconds' => $age,
|
||||
'stale' => $age === null || $age > self::freshnessSeconds()
|
||||
|| (string) $snapshot->sync_state !== 'fresh',
|
||||
'cpu_total_cores' => max(0, (int) $snapshot->cpu_total_cores),
|
||||
'cpu_allocated_cores' => max(0, (int) $snapshot->cpu_allocated_cores),
|
||||
'cpu_available_cores' => max(0, (int) $snapshot->cpu_available_cores),
|
||||
'memory_total_mib' => max(0, (int) $snapshot->memory_total_mib),
|
||||
'memory_allocated_mib' => max(0, (int) $snapshot->memory_allocated_mib),
|
||||
'memory_available_mib' => max(0, (int) $snapshot->memory_available_mib),
|
||||
'storage_total_bytes' => max(0, (int) $snapshot->storage_total_bytes),
|
||||
'storage_allocated_bytes' => max(0, (int) $snapshot->storage_allocated_bytes),
|
||||
'storage_available_bytes' => max(0, (int) $snapshot->storage_available_bytes),
|
||||
'instance_total_count' => max(0, (int) $snapshot->instance_total_count),
|
||||
'instance_running_count' => max(0, (int) $snapshot->instance_running_count),
|
||||
'public_ip_configured' => (bool) $snapshot->public_ip_configured,
|
||||
'public_ip_total_count' => max(0, (int) $snapshot->public_ip_total_count),
|
||||
'public_ip_reserved_count' => max(0, (int) $snapshot->public_ip_reserved_count),
|
||||
'public_ip_allocated_count' => max(0, (int) $snapshot->public_ip_allocated_count),
|
||||
'public_ip_available_count' => max(0, (int) $snapshot->public_ip_available_count),
|
||||
];
|
||||
}
|
||||
|
||||
private static function warnings(CloudHost $host, ?array $snapshot,
|
||||
?array $placement): array
|
||||
{
|
||||
$warnings = [];
|
||||
if ((string) ($host->health_state ?? 'unknown') !== 'healthy') {
|
||||
$warnings[] = '宿主机健康状态不是“正常”;可以保存配置,但调度器会拒绝放置实例。';
|
||||
}
|
||||
if ($snapshot === null) {
|
||||
$warnings[] = '尚未同步容量快照;可以保存配置,但调度器会拒绝放置实例。';
|
||||
} elseif ($snapshot['stale']) {
|
||||
$warnings[] = '容量快照已过期或同步失败;可以保存配置,请先手动同步再启用销售。';
|
||||
}
|
||||
if ($placement === null && (string) $host->scheduler_state === 'active') {
|
||||
$warnings[] = '当前资源池已缺失,调度器不会选择此宿主机。';
|
||||
} elseif ($placement !== null
|
||||
&& (string) $host->scheduler_state === 'active'
|
||||
&& ((string) $placement['status'] !== 'active'
|
||||
|| (string) $placement['line_status'] !== 'active'
|
||||
|| (string) $placement['region_status'] !== 'active'
|
||||
|| (!CloudNetworkLineFeature::enabled()
|
||||
&& !$placement['line_is_default']))) {
|
||||
$warnings[] = '当前资源池、线路或地区已不满足调度条件;保存的配置会保留,但不会接收新实例。';
|
||||
}
|
||||
return $warnings;
|
||||
}
|
||||
|
||||
private static function integer(array $body, string $key, int $minimum,
|
||||
int $maximum, string $label): int
|
||||
{
|
||||
if (!array_key_exists($key, $body)) {
|
||||
throw new CloudError('缺少必填字段:' . $key);
|
||||
}
|
||||
$value = filter_var($body[$key], FILTER_VALIDATE_INT);
|
||||
if ($value === false || $value < $minimum || $value > $maximum) {
|
||||
throw new CloudError($label . '必须为 ' . $minimum . ' 至 ' . $maximum . ' 的整数');
|
||||
}
|
||||
return (int) $value;
|
||||
}
|
||||
|
||||
private static function nullablePositiveId($value): ?int
|
||||
{
|
||||
if ($value === null || $value === '') {
|
||||
return null;
|
||||
}
|
||||
$id = filter_var($value, FILTER_VALIDATE_INT);
|
||||
if ($id === false || $id < 1) {
|
||||
throw new CloudError('资源池 ID 无效');
|
||||
}
|
||||
return (int) $id;
|
||||
}
|
||||
|
||||
private static function nullableInt($value): ?int
|
||||
{
|
||||
return $value === null ? null : (int) $value;
|
||||
}
|
||||
|
||||
private static function safeText(string $value, int $maximum): string
|
||||
{
|
||||
$value = preg_replace('/[\x00-\x1f\x7f]/u', '', $value) ?? '';
|
||||
return mb_substr(trim($value), 0, $maximum);
|
||||
}
|
||||
|
||||
private static function freshnessSeconds(): int
|
||||
{
|
||||
$value = filter_var(Config::get('cloud_capacity_fresh_seconds', 120),
|
||||
FILTER_VALIDATE_INT, ['options' => ['min_range' => 30, 'max_range' => 900]]);
|
||||
return $value === false ? 120 : (int) $value;
|
||||
}
|
||||
}
|
||||
@ -1,2 +1,2 @@
|
||||
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
|
||||
{assign var=venix_asset_version value='2026100307' scope='global'}
|
||||
{assign var=venix_asset_version value='2026100309' scope='global'}
|
||||
|
||||
@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$read = static function (string $path) use ($root): string {
|
||||
$contents = file_get_contents($root . '/' . $path);
|
||||
if (!is_string($contents)) {
|
||||
throw new RuntimeException('Unable to read ' . $path);
|
||||
}
|
||||
return $contents;
|
||||
};
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$service = $read('app/Services/Cloud/CloudAdminHostSchedulingService.php');
|
||||
$controller = $read('app/Controllers/CloudAdminController.php');
|
||||
$routes = $read('config/routes_cloud.php');
|
||||
$middleware = $read('app/Middleware/CloudApi.php');
|
||||
$template = $read('resources/views/venix/admin/hosts/index.tpl');
|
||||
$script = $read('public/cloud/admin.js');
|
||||
$assets = $read('resources/views/venix/layout_assets.tpl');
|
||||
|
||||
$assert(str_contains($routes, "'/admin/hosts/{id:[0-9]+}/scheduling'")
|
||||
&& str_contains($routes, "'/admin/hosts/{id:[0-9]+}/capacity-sync'"),
|
||||
'Host scheduling and capacity sync routes must be registered.');
|
||||
$assert(str_contains($middleware, '(?:scheduling|capacity-sync)')
|
||||
&& str_contains($controller, '$this->actor($request, $write)')
|
||||
&& str_contains($controller, '$this->actor($request, true)'),
|
||||
'Scheduling reads must allow administrators while writes stay super-admin only.');
|
||||
$assert(str_contains($controller, "'resource_pool_id', 'scheduler_state'")
|
||||
&& !str_contains(substr($controller,
|
||||
strpos($controller, 'public function hostScheduling'),
|
||||
strpos($controller, 'public function syncHostCapacity')
|
||||
- strpos($controller, 'public function hostScheduling')), 'public_ip'),
|
||||
'The scheduling allowlist must not accept manual public IP fields.');
|
||||
|
||||
$hostLock = strpos($service, "CloudHost::where('id', \$hostId)->lockForUpdate()");
|
||||
$policyLock = strpos($service, "CloudHostCapacityPolicy::where('host_id', \$hostId)");
|
||||
$assert($hostLock !== false && $policyLock !== false && $hostLock < $policyLock
|
||||
&& str_contains($service, '->lockForUpdate()->first();'),
|
||||
'Scheduling writes must lock host before capacity policy.');
|
||||
$assert(str_contains($service, "\$schedulerState === 'active'")
|
||||
&& str_contains($service, 'CloudNetworkLineFeature::enabled()')
|
||||
&& str_contains($service, "(string) \$pool->status !== 'active'")
|
||||
&& str_contains($service, "(string) \$region->status !== 'active'")
|
||||
&& str_contains($service, '$safety >= $configured'),
|
||||
'Active scheduling must validate the host, pool hierarchy and safety reserves.');
|
||||
$assert(str_contains($service, 'CloudHostInventorySyncService())->syncOne($hostId)')
|
||||
&& str_contains($service, '可以保存配置,但调度器会拒绝放置实例'),
|
||||
'Manual sync and non-blocking health/staleness warnings must remain explicit.');
|
||||
|
||||
$assert(str_contains($template, 'data-admin-host-scheduling-drawer')
|
||||
&& str_contains($template, 'id="host-capacity-sync"')
|
||||
&& str_contains($template, '{if $admin_can_manage|default:false}')
|
||||
&& str_contains($template, '公网 IP 仅由宿主机盘点维护'),
|
||||
'The host drawer must expose server-rendered write controls without IP editing.');
|
||||
$assert(str_contains($script, 'window.VenixDrawerMotion.openDrawerWithMotion')
|
||||
&& str_contains($script, 'window.VenixDrawerMotion.closeDrawerWithMotion')
|
||||
&& str_contains($script, '/capacity-sync')
|
||||
&& str_contains($script, '/scheduling'),
|
||||
'The host drawer must reuse shared motion and scheduling endpoints.');
|
||||
$assert(preg_match("/venix_asset_version value='([0-9]+)'/", $assets, $match) === 1
|
||||
&& (int) $match[1] >= 2026100308,
|
||||
'Shared asset version must be bumped for admin.js changes.');
|
||||
$assert(!file_exists($root . '/public/cloud/admin-host-scheduling.css'),
|
||||
'Host scheduling must not introduce a standalone CSS file.');
|
||||
|
||||
echo "Administrator host scheduling contract checks passed.\n";
|
||||
Loading…
Reference in New Issue