feat: configure host placement policies

dev
admin 2 months ago
parent d6b6d390d5
commit 74cd779901

@ -3,6 +3,7 @@ namespace App\Controllers;
use App\Models\CloudHost;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudAdminHostSchedulingService;
use App\Services\Cloud\CloudDeploymentPageService;
use App\Services\Cloud\CloudEngineClient;
use App\Services\Cloud\CloudError;
@ -150,6 +151,37 @@ final class CloudAdminController
return $response->withJson((new CloudEngineClient())->host((int) $args['id'], 'POST', 'host/test', $actor, $body));
}
public function hostScheduling($request, $response, $args)
{
$write = $request->getMethod() !== 'GET';
$this->actor($request, $write);
$hostId = (int) $args['id'];
if (!$write) {
$result = CloudAdminHostSchedulingService::read($hostId);
} else {
$body = CloudInput::object($request);
CloudInput::only($body, [
'resource_pool_id', 'scheduler_state',
'configured_cpu_cores', 'configured_memory_mib',
'configured_disk_gib', 'safety_cpu_cores',
'safety_memory_mib', 'safety_disk_gib', 'max_instances',
]);
$result = CloudAdminHostSchedulingService::save($hostId, $body);
}
return $response->withJson($result)
->withHeader('Cache-Control', 'no-store');
}
public function syncHostCapacity($request, $response, $args)
{
$this->actor($request, true);
$body = CloudInput::object($request);
CloudInput::only($body, []);
return $response->withJson(CloudAdminHostSchedulingService::sync(
(int) $args['id']
))->withHeader('Cache-Control', 'no-store');
}
public function userIsoSettings($request, $response)
{
$write = $request->getMethod() !== 'GET';

@ -20,6 +20,7 @@ final class CloudApi
|| preg_match('#^/api/v1/admin/instances(?:/|$)#D', $path) === 1
|| preg_match('#^/api/v1/admin/operations(?:/|$)#D', $path) === 1
|| preg_match('#^/api/v1/admin/(?:resources|regions|network-lines|resource-pools|resource-reservations)(?:/|$)#D', $path) === 1
|| preg_match('#^/api/v1/admin/hosts/[0-9]+/(?:scheduling|capacity-sync)$#D', $path) === 1
|| preg_match('#^/api/v1/ssh-keys(?:/|$)#D', $path) === 1
|| preg_match('#^/api/v1/vms/[0-9]+/operations$#D', $path) === 1
|| $path === '/api/v1/announcements'

@ -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;
}
}

@ -50,6 +50,10 @@ $app->group('/api/v1', function () {
$this->map(['GET', 'POST'], '/ssh-keys', 'App\Controllers\CloudApiController:sshKeys');
$this->delete('/ssh-keys/{id:[0-9]+}', 'App\Controllers\CloudApiController:deleteKey');
$this->post('/admin/hosts/scan', 'App\Controllers\CloudAdminController:scan');
$this->map(['GET', 'PUT'], '/admin/hosts/{id:[0-9]+}/scheduling',
'App\Controllers\CloudAdminController:hostScheduling');
$this->post('/admin/hosts/{id:[0-9]+}/capacity-sync',
'App\Controllers\CloudAdminController:syncHostCapacity');
$this->get('/admin/instances', 'App\Controllers\CloudAdminInstanceController:index');
$this->get('/admin/instances/{id:[0-9]+}', 'App\Controllers\CloudAdminInstanceController:detail');
$this->get('/admin/instances/{id:[0-9]+}/network-options', 'App\Controllers\CloudAdminInstanceController:networkOptions');

@ -1,6 +1,6 @@
const root = document.querySelector('[data-cloud-admin]');
const byId = id => document.getElementById(id);
const state = { csrf: window.ADMIN_CSRF_TOKEN || '', hosts: [], selectedHost: '', scanned: null, scanTarget: '', busy: false, epoch: 0 };
const state = { csrf: window.ADMIN_CSRF_TOKEN || '', hosts: [], selectedHost: '', scanned: null, scanTarget: '', busy: false, epoch: 0, schedulingBusy: false, schedulingOpener: null, schedulingScroll: null };
// Permission state is rendered by the server on the page. API endpoints keep
// the authoritative authorization check; this only controls the UI affordances.
const canManage = root?.dataset.canManage === '1';
@ -81,7 +81,66 @@ function fillHost(host) {
}
function renderHosts() {
const list = byId('host-list'); list.replaceChildren(); if (!state.hosts.length) list.append(element('p', 'text-muted', '暂无宿主机。'));
for (const host of state.hosts) { const button = element('button', 'btn btn-light cloud-admin-host'); button.type = 'button'; button.append(element('strong', '', host.name || `宿主机 ${host.id}`), element('div', 'text-muted', `${host.region || '地区未设置'} · #${host.id} · ${host.enabled ? '启用' : '停用'}`)); button.addEventListener('click', async () => { if (state.busy) return; try { fillHost(profile(await api(`/api/v1/admin/hosts/${encodeURIComponent(host.id)}`))); notice('已读取配置。若需保存,请重新扫描并核对主机指纹。'); } catch (error) { notice(error.message, true); } }); list.append(button); }
for (const host of state.hosts) { const row = element('div', 'd-grid gap-2'); const button = element('button', 'btn btn-light cloud-admin-host'); button.type = 'button'; button.append(element('strong', '', host.name || `宿主机 ${host.id}`), element('div', 'text-muted', `${host.region || '地区未设置'} · #${host.id} · ${host.enabled ? '连接启用' : '连接停用'} · ${schedulerLabel(host.scheduler_state)}`)); button.addEventListener('click', async () => { if (state.busy) return; try { fillHost(profile(await api(`/api/v1/admin/hosts/${encodeURIComponent(host.id)}`))); notice('已读取配置。若需保存,请重新扫描并核对主机指纹。'); } catch (error) { notice(error.message, true); } }); const scheduling = element('button', 'btn btn-outline-primary btn-sm', '资源池与调度策略'); scheduling.type = 'button'; scheduling.addEventListener('click', () => openHostScheduling(host.id, scheduling)); row.append(button, scheduling); list.append(row); }
}
function schedulerLabel(value) { return ({ active: '调度启用', draining: '正在排空', disabled: '调度停用' })[value] || '调度未配置'; }
function hostSchedulingNotice(message, error = false) { const box = byId('host-scheduling-status'); box.textContent = message; box.className = `alert ${error ? 'alert-danger' : 'alert-info'}`; }
function formatTimestamp(value) { const timestamp = Number(value || 0); return timestamp > 0 ? new Date(timestamp * 1000).toLocaleString() : '尚未记录'; }
function formatBytes(value) { const bytes = Number(value || 0); return bytes > 0 ? `${(bytes / 1024 ** 3).toFixed(1)} GiB` : '0 GiB'; }
function setSchedulingWarnings(warnings) {
const box = byId('host-scheduling-warnings'); box.replaceChildren(); const entries = Array.isArray(warnings) ? warnings.filter(Boolean) : [];
box.hidden = entries.length === 0; if (!entries.length) return;
const list = element('ul', 'mb-0'); for (const warning of entries) list.append(element('li', '', warning)); box.append(list);
}
function renderCapacitySnapshot(snapshot) {
const list = byId('host-capacity-snapshot'); list.replaceChildren();
const rows = snapshot ? [
['同步状态', snapshot.stale ? '需重新同步' : '数据新鲜'],
['观测时间', formatTimestamp(snapshot.observed_at)],
['CPU', `${snapshot.cpu_allocated_cores} / ${snapshot.cpu_total_cores} 核已分配,${snapshot.cpu_available_cores} 核可用`],
['内存', `${snapshot.memory_allocated_mib} / ${snapshot.memory_total_mib} MiB 已分配,${snapshot.memory_available_mib} MiB 可用`],
['磁盘', `${formatBytes(snapshot.storage_allocated_bytes)} / ${formatBytes(snapshot.storage_total_bytes)} 已分配,${formatBytes(snapshot.storage_available_bytes)} 可用`],
['实例', `${snapshot.instance_total_count} 台,共 ${snapshot.instance_running_count} 台运行`],
['公网 IP', snapshot.public_ip_configured ? `${snapshot.public_ip_available_count} 可用 / ${snapshot.public_ip_total_count} 总数` : '宿主机未配置公网地址池'],
] : [['容量快照', '尚未同步']];
for (const [label, value] of rows) list.append(element('dt', '', label), element('dd', '', value));
}
function renderHostScheduling(payload) {
const host = payload?.host || {}; const policy = payload?.policy || {}; const pools = Array.isArray(payload?.pools) ? payload.pools : [];
byId('host-scheduling-title').textContent = `${host.name || `宿主机 #${host.id}`} · 资源池与调度策略`;
byId('host-scheduling-host-id').value = host.id || '';
const select = byId('host-resource-pool'); select.replaceChildren(); const empty = element('option', '', '不加入资源池'); empty.value = ''; select.append(empty);
for (const pool of pools) { const option = element('option', '', `${pool.region_name} / ${pool.line_name} / ${pool.name}${pool.status === 'active' && pool.line_status === 'active' && pool.region_status === 'active' ? '' : '(不可调度)'}`); option.value = String(pool.id); option.selected = Number(host.resource_pool_id) === Number(pool.id); select.append(option); }
byId('host-scheduler-state').value = ['active', 'draining', 'disabled'].includes(host.scheduler_state) ? host.scheduler_state : 'disabled';
const fields = { 'host-capacity-cpu': policy.configured_cpu_cores, 'host-capacity-memory': policy.configured_memory_mib, 'host-capacity-disk': policy.configured_disk_gib, 'host-safety-cpu': policy.safety_cpu_cores, 'host-safety-memory': policy.safety_memory_mib, 'host-safety-disk': policy.safety_disk_gib, 'host-max-instances': policy.max_instances };
for (const [id, value] of Object.entries(fields)) byId(id).value = Number(value || 0);
byId('host-resource-pool-help').textContent = payload?.network_lines_enabled ? '线路功能已开启,可选择任意启用线路下的资源池。' : '线路功能关闭,只允许启用地区的默认线路参与调度。';
setSchedulingWarnings(payload?.warnings); renderCapacitySnapshot(payload?.snapshot);
hostSchedulingNotice(`连接:${host.enabled ? '启用' : '停用'} · 健康:${host.health_state || 'unknown'} · ${schedulerLabel(host.scheduler_state)}`);
}
function lockSchedulingScroll() { state.schedulingScroll = { x: window.scrollX, y: window.scrollY }; document.body.style.setProperty('--admin-instance-scroll-top', `${-state.schedulingScroll.y}px`); document.documentElement.classList.add('admin-instance-detail-open'); }
function finishSchedulingClose() { document.documentElement.classList.remove('admin-instance-detail-open'); document.body.style.removeProperty('--admin-instance-scroll-top'); if (state.schedulingScroll) { window.scrollTo({ left: state.schedulingScroll.x, top: state.schedulingScroll.y, behavior: 'instant' }); state.schedulingScroll = null; } if (state.schedulingOpener?.isConnected) state.schedulingOpener.focus({ preventScroll: true }); state.schedulingOpener = null; }
function closeHostScheduling() { const dialog = byId('host-scheduling-drawer'); if (!dialog?.open) return; void window.VenixDrawerMotion.closeDrawerWithMotion(dialog).then(closed => { if (closed) finishSchedulingClose(); }); }
async function openHostScheduling(hostId, opener) {
if (state.schedulingBusy) return; state.schedulingBusy = true; const dialog = byId('host-scheduling-drawer'); state.schedulingOpener = opener; hostSchedulingNotice('正在读取资源池和容量配置…'); setSchedulingWarnings([]); renderCapacitySnapshot(null);
if (!dialog.open) { lockSchedulingScroll(); window.VenixDrawerMotion.openDrawerWithMotion(dialog); }
try { renderHostScheduling(await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/scheduling`)); }
catch (error) { hostSchedulingNotice(error.message, true); }
finally { state.schedulingBusy = false; }
}
function schedulingBody() { return { resource_pool_id: byId('host-resource-pool').value ? Number(byId('host-resource-pool').value) : null, scheduler_state: byId('host-scheduler-state').value, configured_cpu_cores: Number(byId('host-capacity-cpu').value), configured_memory_mib: Number(byId('host-capacity-memory').value), configured_disk_gib: Number(byId('host-capacity-disk').value), safety_cpu_cores: Number(byId('host-safety-cpu').value), safety_memory_mib: Number(byId('host-safety-memory').value), safety_disk_gib: Number(byId('host-safety-disk').value), max_instances: Number(byId('host-max-instances').value) }; }
async function saveHostScheduling(event) {
event.preventDefault(); if (!canManage || state.schedulingBusy) return; const hostId = byId('host-scheduling-host-id').value; if (!hostId) return;
state.schedulingBusy = true; const button = byId('host-scheduling-save'); if (button) button.disabled = true; hostSchedulingNotice('正在保存调度配置…');
try { const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/scheduling`, { method: 'PUT', body: schedulingBody() }); renderHostScheduling(payload); const host = state.hosts.find(item => Number(item.id) === Number(hostId)); if (host) { host.resource_pool_id = payload.host.resource_pool_id; host.scheduler_state = payload.host.scheduler_state; renderHosts(); } hostSchedulingNotice('调度配置已保存。健康异常或过期快照仍会被调度器拒绝。'); }
catch (error) { hostSchedulingNotice(error.message, true); }
finally { state.schedulingBusy = false; if (button) button.disabled = false; }
}
async function syncHostCapacity() {
if (!canManage || state.schedulingBusy) return; const hostId = byId('host-scheduling-host-id').value; if (!hostId) return; state.schedulingBusy = true; const button = byId('host-capacity-sync'); if (button) button.disabled = true; hostSchedulingNotice('正在从宿主机同步容量与公网 IP 汇总…');
try { const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/capacity-sync`, { method: 'POST', body: {} }); renderHostScheduling(payload.scheduling); const failed = Number(payload?.sync?.succeeded || 0) < 1; hostSchedulingNotice(failed ? '同步未成功,已保留上一份容量并显示告警;请检查宿主机连接与后台盘点身份。' : '容量快照已同步。', failed); }
catch (error) { hostSchedulingNotice(error.message, true); }
finally { state.schedulingBusy = false; if (button) button.disabled = false; }
}
async function scanHost() {
if (state.busy) return; const host = byId('host-address').value.trim(); const port = Number(byId('host-port').value); if (!host || port < 1 || port > 65535) return notice('请输入正确的 SSH 地址和端口。', true);
@ -223,7 +282,7 @@ async function uploadRescue(event) {
async function initialize() {
if (!root) return;
try { const session = await api('/api/v1/session'); state.csrf = session.csrf_token || state.csrf; if (!session.admin) throw new Error('需要管理员权限。'); if (!state.csrf) throw new Error('会话令牌缺失,请重新登录。');
if (root.dataset.cloudAdmin === 'hosts') { await Promise.all([loadHosts(), loadUserIsoSettings()]); renderHosts(); fillHost(null); byId('host-new').addEventListener('click', () => fillHost(null)); byId('host-scan').addEventListener('click', scanHost); byId('host-form').addEventListener('submit', saveHost); byId('user-iso-settings-form').addEventListener('submit', saveUserIsoSettings); for (const id of ['host-address', 'host-port']) byId(id).addEventListener('input', resetScan); if (!canManage) { byId('host-form').querySelectorAll('input,textarea,button').forEach(input => { input.disabled = true; }); byId('user-iso-settings-form').querySelectorAll('input,button').forEach(input => { input.disabled = true; }); } notice(canManage ? '请选择宿主机编辑,或添加新的宿主机。' : '当前管理员仅可查看配置。'); }
if (root.dataset.cloudAdmin === 'hosts') { await Promise.all([loadHosts(), loadUserIsoSettings()]); renderHosts(); fillHost(null); byId('host-new').addEventListener('click', () => fillHost(null)); byId('host-scan').addEventListener('click', scanHost); byId('host-form').addEventListener('submit', saveHost); byId('user-iso-settings-form').addEventListener('submit', saveUserIsoSettings); byId('host-scheduling-form').addEventListener('submit', saveHostScheduling); byId('host-scheduling-close').addEventListener('click', closeHostScheduling); byId('host-capacity-sync')?.addEventListener('click', syncHostCapacity); const schedulingDrawer = byId('host-scheduling-drawer'); schedulingDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostScheduling(); }); schedulingDrawer.addEventListener('click', event => { if (event.target === schedulingDrawer) closeHostScheduling(); }); for (const id of ['host-address', 'host-port']) byId(id).addEventListener('input', resetScan); if (!canManage) { byId('host-form').querySelectorAll('input,textarea,button').forEach(input => { input.disabled = true; }); byId('user-iso-settings-form').querySelectorAll('input,button').forEach(input => { input.disabled = true; }); } notice(canManage ? '请选择宿主机编辑,或添加新的宿主机。' : '当前管理员仅可查看配置。'); }
else if (root.dataset.cloudAdmin === 'templates') { byId('template-import')?.addEventListener('submit', importTemplate); byId('template-upload')?.addEventListener('submit', uploadCloudTemplate); await loadCatalog(); }
else if (root.dataset.cloudAdmin === 'rescue') { await loadHosts(); const select = byId('catalog-host'); select.replaceChildren(); for (const host of state.hosts) { const option = element('option', '', `${host.name} · ${host.region || '地区未设置'}`); option.value = String(host.id); select.append(option); } select.addEventListener('change', loadCatalog); byId('rescue-upload')?.addEventListener('submit', uploadRescue); await loadCatalog(); }
} catch (error) { notice(error.message, true); }

@ -144,5 +144,76 @@
</form>
</div>
</section>
<dialog id="host-scheduling-drawer" data-admin-instance-drawer data-admin-host-scheduling-drawer aria-labelledby="host-scheduling-title">
<header class="admin-instance-drawer-header">
<div>
<p class="admin-eyebrow mb-1">Placement &amp; Capacity</p>
<h2 id="host-scheduling-title">资源池与调度策略</h2>
</div>
<button id="host-scheduling-close" class="btn btn-light" type="button" aria-label="关闭资源池与调度策略">
<i class="mdi mdi-close"></i>
</button>
</header>
<div class="admin-instance-drawer-body">
<p id="host-scheduling-status" class="alert alert-info" role="status" aria-live="polite">请选择宿主机。</p>
<div id="host-scheduling-warnings" class="alert alert-warning" hidden></div>
<form id="host-scheduling-form">
<input id="host-scheduling-host-id" type="hidden">
<div class="cloud-admin-form-section">
<div class="cloud-admin-section-title">
<span><i class="mdi mdi-server-network"></i></span>
<div><h6>放置策略</h6><p>排空会停止接收新实例;停用会完全退出自动调度。</p></div>
</div>
<div class="cloud-admin-form-grid">
<div class="cloud-admin-full">
<label for="host-resource-pool" class="form-label">资源池</label>
<select id="host-resource-pool" class="form-select" {if !$admin_can_manage|default:false}disabled{/if}></select>
<div id="host-resource-pool-help" class="form-text"></div>
</div>
<div class="cloud-admin-full">
<label for="host-scheduler-state" class="form-label">调度状态</label>
<select id="host-scheduler-state" class="form-select" {if !$admin_can_manage|default:false}disabled{/if}>
<option value="active">启用调度</option>
<option value="draining">排空(不接收新实例)</option>
<option value="disabled">停用调度</option>
</select>
</div>
</div>
</div>
<div class="cloud-admin-form-section">
<div class="cloud-admin-section-title">
<span><i class="mdi mdi-gauge"></i></span>
<div><h6>可调度容量</h6><p>填写允许调度器使用的上限;0 台最大实例数表示不单独限制。</p></div>
</div>
<div class="cloud-admin-form-grid">
<div><label for="host-capacity-cpu" class="form-label">配置 CPU(核)</label><input id="host-capacity-cpu" class="form-control" type="number" min="0" max="65535" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div><label for="host-safety-cpu" class="form-label">CPU 安全预留(核)</label><input id="host-safety-cpu" class="form-control" type="number" min="0" max="65535" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div><label for="host-capacity-memory" class="form-label">配置内存(MiB)</label><input id="host-capacity-memory" class="form-control" type="number" min="0" max="2147483647" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div><label for="host-safety-memory" class="form-label">内存安全预留(MiB)</label><input id="host-safety-memory" class="form-control" type="number" min="0" max="2147483647" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div><label for="host-capacity-disk" class="form-label">配置磁盘(GiB)</label><input id="host-capacity-disk" class="form-control" type="number" min="0" max="2147483647" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div><label for="host-safety-disk" class="form-label">磁盘安全预留(GiB)</label><input id="host-safety-disk" class="form-control" type="number" min="0" max="2147483647" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div class="cloud-admin-full"><label for="host-max-instances" class="form-label">最大实例数</label><input id="host-max-instances" class="form-control" type="number" min="0" max="2147483647" required {if !$admin_can_manage|default:false}disabled{/if}></div>
</div>
</div>
<div class="cloud-admin-form-section">
<div class="cloud-admin-section-title">
<span><i class="mdi mdi-database-sync-outline"></i></span>
<div><h6>最近容量快照</h6><p>健康异常或快照过期不会阻止保存,但调度器仍会拒绝该节点。</p></div>
</div>
<dl id="host-capacity-snapshot" class="admin-instance-details"></dl>
</div>
</form>
</div>
<footer class="admin-instance-drawer-footer">
<span class="text-muted">公网 IP 仅由宿主机盘点维护,此处不提供手工编辑。</span>
<div class="d-flex gap-2">
{if $admin_can_manage|default:false}
<button id="host-capacity-sync" class="btn btn-outline-primary" type="button"><i class="mdi mdi-sync me-1"></i>手动同步</button>
<button id="host-scheduling-save" class="btn btn-primary" type="submit" form="host-scheduling-form"><i class="mdi mdi-content-save-outline me-1"></i>保存调度配置</button>
{/if}
</div>
</footer>
</dialog>
<script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>
{include file='admin/static_footer.tpl'}

@ -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";

@ -21,7 +21,7 @@ $assert(str_contains($motion, 'window.VenixDrawerMotion = Object.freeze')
&& str_contains($motion, "prefers-reduced-motion: reduce"),
'The shared drawer motion controller must coordinate entry, exit and reduced motion.');
foreach (['account-drawer.js', 'announcements.js', 'admin-instances.js', 'admin-operations.js', 'admin-billing.js', 'admin-resources.js'] as $script) {
foreach (['account-drawer.js', 'announcements.js', 'admin.js', 'admin-instances.js', 'admin-operations.js', 'admin-billing.js', 'admin-resources.js'] as $script) {
$source = $read($root . '/public/cloud/' . $script);
$assert(str_contains($source, 'window.VenixDrawerMotion')
&& str_contains($source, 'openDrawerWithMotion')

Loading…
Cancel
Save