diff --git a/web/app/Controllers/CloudAdminController.php b/web/app/Controllers/CloudAdminController.php index bf17717e..c1874823 100644 --- a/web/app/Controllers/CloudAdminController.php +++ b/web/app/Controllers/CloudAdminController.php @@ -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'; diff --git a/web/app/Middleware/CloudApi.php b/web/app/Middleware/CloudApi.php index db126dea..739ede39 100644 --- a/web/app/Middleware/CloudApi.php +++ b/web/app/Middleware/CloudApi.php @@ -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' diff --git a/web/app/Services/Cloud/CloudAdminHostSchedulingService.php b/web/app/Services/Cloud/CloudAdminHostSchedulingService.php new file mode 100644 index 00000000..dc032495 --- /dev/null +++ b/web/app/Services/Cloud/CloudAdminHostSchedulingService.php @@ -0,0 +1,307 @@ +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; + } +} diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php index 7ad553e4..b9ed4f7b 100644 --- a/web/config/routes_cloud.php +++ b/web/config/routes_cloud.php @@ -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'); diff --git a/web/public/cloud/admin.js b/web/public/cloud/admin.js index e48dce0b..e687c6b2 100644 --- a/web/public/cloud/admin.js +++ b/web/public/cloud/admin.js @@ -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); } diff --git a/web/resources/views/venix/admin/hosts/index.tpl b/web/resources/views/venix/admin/hosts/index.tpl index ff2f6a36..45f4ab53 100644 --- a/web/resources/views/venix/admin/hosts/index.tpl +++ b/web/resources/views/venix/admin/hosts/index.tpl @@ -144,5 +144,76 @@ + + +
+
+

Placement & Capacity

+

资源池与调度策略

+
+ +
+
+

请选择宿主机。

+ +
+ +
+
+ +
放置策略

排空会停止接收新实例;停用会完全退出自动调度。

+
+
+
+ + +
+
+
+ + +
+
+
+
+
+ +
可调度容量

填写允许调度器使用的上限;0 台最大实例数表示不单独限制。

+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
最近容量快照

健康异常或快照过期不会阻止保存,但调度器仍会拒绝该节点。

+
+
+
+
+
+ +
{include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index ef83b1fe..4b3ec6b0 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.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'} diff --git a/web/tests/AdminHostSchedulingContractTest.php b/web/tests/AdminHostSchedulingContractTest.php new file mode 100644 index 00000000..6c5ab3a5 --- /dev/null +++ b/web/tests/AdminHostSchedulingContractTest.php @@ -0,0 +1,70 @@ +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"; diff --git a/web/tests/DrawerMotionAssetsTest.php b/web/tests/DrawerMotionAssetsTest.php index 57e834f4..4765d7a8 100644 --- a/web/tests/DrawerMotionAssetsTest.php +++ b/web/tests/DrawerMotionAssetsTest.php @@ -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')