feat(system): add worker and VPS catalogs with guarded local removal
This commit is contained in:
@@ -444,7 +444,7 @@ export default function App() {
|
||||
workspace.openNavigation();
|
||||
if (rootId === "system") {
|
||||
workspace.openView(
|
||||
activeDefinition?.root === "system" ? activeDefinition.id : "modules",
|
||||
activeDefinition?.id === "vps" ? "vps" : "workers",
|
||||
);
|
||||
} else {
|
||||
workspace.closeView();
|
||||
@@ -666,7 +666,7 @@ export default function App() {
|
||||
connectionScenarioResetting: runtime.pendingAction === "mode",
|
||||
saveWorkspaceLayout,
|
||||
workspaceLayoutSaving: workspaceLayoutProfile.state === "saving",
|
||||
systemUtilityActions: computeContourSettings.utilityActions,
|
||||
systemUtilityActions: [...computeContourSettings.utilityActions, {label: "К списку воркеров", icon: "chevron-left", onClick: () => openNavigationView("workers")}],
|
||||
sessionOverview: { ...sessionOverview, available: Boolean(recordedReplay && replayPresented && !sourceSwitchBlocked) },
|
||||
});
|
||||
|
||||
@@ -738,8 +738,8 @@ export default function App() {
|
||||
navigation={currentRoot && activeRoot === "system" ? (
|
||||
<SystemNavigationPanel
|
||||
title={currentRoot.title}
|
||||
onAdd={computeContourSettings.openCreate}
|
||||
onNavigateRoot={() => openNavigationView("modules")}
|
||||
activeId={activeDefinition?.id ?? "workers"}
|
||||
onNavigate={openNavigationView}
|
||||
onClose={workspace.closeNavigation}
|
||||
/>
|
||||
) : currentRoot ? (
|
||||
@@ -844,6 +844,8 @@ export default function App() {
|
||||
<StatusBadge tone="neutral">Только наблюдение</StatusBadge>
|
||||
) : activeDefinition.kind === "contour-health" ? (
|
||||
<div ref={setWorkspaceHeaderToolsHost} />
|
||||
) : activeDefinition.kind === "workers" || activeDefinition.kind === "vps" ? (
|
||||
<div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} />
|
||||
) : activeDefinition.root === "system" ? (
|
||||
<SystemWorkspaceSelector
|
||||
value={activeDefinition.id}
|
||||
|
||||
@@ -2,10 +2,10 @@ import {Fragment,useEffect,useState} from 'react';
|
||||
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
|
||||
|
||||
type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]};
|
||||
export function InstallerCard({kind}:{kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'}){
|
||||
export function InstallerCard({kind,connectionInstruction}:{connectionInstruction?:string;kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'}){
|
||||
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
|
||||
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
|
||||
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((step,index)=><Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>)}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
|
||||
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((original,index)=>{const step=connectionInstruction&&index===item.instructions.length-1?connectionInstruction:original;return <Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>;})}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
|
||||
<Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button>
|
||||
</SettingsCard>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,Description,Icon,Select,SettingsCard,TextAreaField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {InstallerCard} from '../network/InstallerCard';
|
||||
import {serverRequest,type Server} from '../../core/system/servers';
|
||||
import {vpsRequest} from '../../core/fleet/vps';
|
||||
|
||||
export function ServerServiceSetup({server,onClose,onSaved}:{server:Server;onClose:()=>void;onSaved:()=>void}) {
|
||||
const [kind,setKind]=useState<'wireguard'|'arnavi'>('wireguard'),[document,setDocument]=useState(''),[filename,setFilename]=useState('');
|
||||
const [network,setNetwork]=useState(''),[interfaces,setInterfaces]=useState<{id:string;label:string}[]>([]);
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState('');const file=useRef<HTMLInputElement>(null);
|
||||
useEffect(()=>{let active=true;void vpsRequest<{items:{id:string;label:string}[]}>('/interfaces').then(r=>{if(active)setInterfaces(r.items);}).catch(()=>{});return()=>{active=false;};},[]);
|
||||
async function connect(){setBusy(true);setError('');try{
|
||||
await serverRequest(`/${server.id}/services`,'POST',{kind,document:document.trim(),expected_revision:server.revision,network_interface:network||null});
|
||||
setDocument('');onSaved();
|
||||
}catch(e){setError(e instanceof Error?e.message:'Не удалось подключить службу.');}finally{setBusy(false);}}
|
||||
return <><Window open title="Добавить службу" subtitle={`${server.name} · ${server.address}`} size="lg" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}}
|
||||
footer={<WindowFooterActions><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!document.trim()} onClick={()=>void connect()}>Подключить службу</Button></WindowFooterActions>}>
|
||||
<div className="system-catalog-form">
|
||||
<Select label="Служба" value={kind} disabled={busy} options={[{value:'wireguard',label:'WireGuard'},{value:'arnavi',label:'ARNavi'}]} onChange={value=>{setKind(value as typeof kind);setDocument('');setFilename('');setError('');}}/>
|
||||
<InstallerCard key={kind} connectionInstruction="Вернитесь в это окно и подключите установленную службу с выданным приглашением." kind={kind==='wireguard'?'vps-wireguard':'vps-arnavi'}/>
|
||||
<SettingsCard title="Подключение установленной службы" description="Запустите установщик на выбранном VPS. Затем передайте выданное им приглашение — Mission Core проверит сервер и сохранит подключение.">
|
||||
{kind==='wireguard'?<>
|
||||
<input ref={file} type="file" accept=".json,application/json" hidden onChange={event=>{const chosen=event.target.files?.[0];event.target.value='';if(!chosen)return;setDocument('');setFilename('');void (async()=>{if(chosen.size>16384)throw Error('Выберите файл приглашения WireGuard (до 16 КБ).');setDocument(await chosen.text());setFilename(chosen.name);})().catch(e=>setError(e.message));}}/>
|
||||
<Button icon={<Icon name="upload"/>} disabled={busy} onClick={()=>file.current?.click()}>Выбрать приглашение WireGuard</Button>
|
||||
{filename&&<Description>{filename}</Description>}
|
||||
<Description>Файл на VPS: /var/lib/ndc-wireguard-vps/mission-core-wireguard.json. Скопируйте его по защищённому соединению (например, SFTP). Приглашение действует 24 часа; новое выпускается командой connection того же установщика. Экспорт .conf из клиента WireGuard не подходит.</Description>
|
||||
</>:<TextAreaField label="Ключ подключения ARNavi" value={document} disabled={busy} rows={4} onChange={e=>setDocument(e.target.value)} hint="Ключ находится на VPS в /opt/nodedc-mission-vps/connect.key. Действует 24 часа и используется один раз."/>}
|
||||
</SettingsCard>
|
||||
{interfaces.length>0&&<Select label="Подключение к VPS" disabled={busy} value={network} options={[{value:'',label:'Через текущую сеть'},...interfaces.map(i=>({value:i.id,label:`Напрямую · ${i.label}`}))]} onChange={setNetwork}/>}
|
||||
</div>
|
||||
</Window><ToastStack items={error?[{id:'server-connect',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import {useState} from 'react';
|
||||
import {Button, Description, Icon, IconButton, LoadingRegion, SettingsCard, TextField, ToastStack, Window, WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {serverRequest,type Server,type ServerRemovalPlan} from '../../core/system/servers';
|
||||
|
||||
export function ServerSettings({server,onClose,onSaved,onRemoved}:{server?:Server;onClose:()=>void;onSaved:(server:Server)=>void;onRemoved?:()=>void}) {
|
||||
const [name,setName]=useState(server?.name??''),[address,setAddress]=useState(server?.address??'');
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
const [removing,setRemoving]=useState(false),[plan,setPlan]=useState<ServerRemovalPlan|null>(null);
|
||||
async function prepareRemoval(){if(!server)return;setRemoving(true);setPlan(null);setBusy(true);setError('');try{
|
||||
setPlan(await serverRequest<ServerRemovalPlan>(`/${server.id}/removal`,'POST',{expected_revision:server.revision}));
|
||||
}catch(e){setError(e instanceof Error?e.message:'Не удалось проверить подключения VPS.');}finally{setBusy(false);}}
|
||||
async function remove(){if(!server||!plan||plan.blocked.length)return;setBusy(true);setError('');try{
|
||||
await serverRequest(`/${server.id}`,'DELETE',{expected_revision:server.revision,confirmation:plan.confirmation});
|
||||
onRemoved?.();
|
||||
}catch(e){setPlan(null);setError(e instanceof Error?e.message:'Удаление не завершено. Повторите проверку.');}finally{setBusy(false);}}
|
||||
async function save(){setBusy(true);setError('');try{
|
||||
const item=await serverRequest<Server>(server?`/${server.id}`:'',server?'PUT':'POST',{name:name.trim(),address:address.trim(),...(server?{expected_revision:server.revision}:{})});
|
||||
onSaved(item);
|
||||
}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить VPS.');}finally{setBusy(false);}}
|
||||
return <><Window open title={removing?'Удалить VPS?':server?'Настройки VPS':'Добавить VPS'} subtitle={server?.name}
|
||||
size="md" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}}
|
||||
headerActionsPlacement="before-close" headerActions={server&&!removing&&<IconButton label="Удалить VPS" disabled={busy} onClick={()=>void prepareRemoval()}><Icon name="trash"/></IconButton>}
|
||||
footer={<WindowFooterActions>{removing?<><Button disabled={busy} onClick={()=>{setRemoving(false);setPlan(null);setError('');}}>Отменить</Button>{plan?<Button loading={busy} disabled={busy||!!plan.blocked.length} onClick={()=>void remove()}>Удалить</Button>:<Button loading={busy} disabled={busy} onClick={()=>void prepareRemoval()}>Повторить проверку</Button>}</>:<><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!name.trim()||!address.trim()} onClick={()=>void save()}>{server?'Сохранить':'Добавить VPS'}</Button></>}</WindowFooterActions>}>
|
||||
{removing?<LoadingRegion loading={busy&&!plan} label="Проверка подключений"><SettingsCard title={`Удалить «${server?.name}» из Mission Core?`} description="Это действие нельзя отменить.">
|
||||
<Description>Будут удалены карточка VPS, сохранённые подключения его служб и локальные туннели WireGuard. Для повторного подключения понадобятся новые приглашения.</Description>
|
||||
<Description>Сам VPS, установленные на нём службы и данные останутся на сервере.</Description>
|
||||
{plan&&<><Description>Подключения служб: {plan.services.join(', ')||'нет'}. Связанные подключения аппаратов: {plan.vehicle_connections}; воркеров: {plan.worker_connections}.</Description>{plan.blocked.map(message=><Description key={message}>{message}</Description>)}</>}
|
||||
</SettingsCard></LoadingRegion>:<div className="system-catalog-form">
|
||||
<TextField label="Название" placeholder="Например, Макхост · сеть парка" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
|
||||
<TextField label="Адрес сервера" hint={server?.services.length?'Адрес используется подключёнными службами.':'Публичный IP-адрес или DNS-имя, без протокола и порта.'} value={address} maxLength={253} disabled={busy||!!server?.services.length} onChange={e=>setAddress(e.target.value)}/>
|
||||
</div>}
|
||||
</Window><ToastStack items={error?[{id:'server-save',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
|
||||
}
|
||||
@@ -1,59 +1,13 @@
|
||||
import {
|
||||
AdminNavigationPanel,
|
||||
Icon,
|
||||
IconButton,
|
||||
} from "@nodedc/ui-react";
|
||||
import {AdminNavigationPanel, Icon} from "@nodedc/ui-react";
|
||||
import {workspacesForRoot} from "../../productModel";
|
||||
|
||||
import { useComputeContours } from "../../core/system/ComputeContourContext";
|
||||
|
||||
interface SystemNavigationPanelProps {
|
||||
title: string;
|
||||
onAdd: () => void;
|
||||
onNavigateRoot: () => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function SystemNavigationPanel({
|
||||
title,
|
||||
onAdd,
|
||||
onNavigateRoot,
|
||||
onClose,
|
||||
}: SystemNavigationPanelProps) {
|
||||
const { contours, selectedContour, selectContour } = useComputeContours();
|
||||
const contourCountLabel = contours.length === 1
|
||||
? "1 конфигурация"
|
||||
: `${contours.length} конфигураций`;
|
||||
|
||||
return (
|
||||
<AdminNavigationPanel
|
||||
eyebrow="MISSION CORE"
|
||||
title={title}
|
||||
closeLabel={`Закрыть раздел «${title}»`}
|
||||
navigationLabel="Вычислительные контуры"
|
||||
onClose={onClose}
|
||||
headerActions={(
|
||||
<IconButton label="Добавить вычислительный контур" onClick={onAdd}>
|
||||
<Icon name="plus" size={16} strokeWidth={1.6} />
|
||||
</IconButton>
|
||||
)}
|
||||
contexts={contours.map((contour) => ({
|
||||
id: contour.contour_id,
|
||||
label: contour.display_name,
|
||||
description: contour.expected_node_id,
|
||||
icon: <Icon name="apps" />,
|
||||
active: selectedContour?.contour_id === contour.contour_id,
|
||||
onSelect: () => { selectContour(contour.contour_id); onNavigateRoot(); },
|
||||
}))}
|
||||
items={[]}
|
||||
onItemChange={() => undefined}
|
||||
footer={(
|
||||
<>
|
||||
<span className="nodedc-admin-panel__nav-icon" aria-hidden="true">
|
||||
<Icon name="activity" />
|
||||
</span>
|
||||
<span>{contourCountLabel}</span>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
export function SystemNavigationPanel({title, activeId, onNavigate, onClose}: {
|
||||
title: string; activeId: string; onNavigate: (id: string) => void; onClose: () => void;
|
||||
}) {
|
||||
const categories = workspacesForRoot("system").filter(item => item.kind === "workers" || item.kind === "vps");
|
||||
return <AdminNavigationPanel eyebrow="MISSION CORE" title={title}
|
||||
closeLabel={`Закрыть раздел «${title}»`} navigationLabel="Система" onClose={onClose}
|
||||
contexts={categories.map(item => ({id: item.id, label: item.label, icon: <Icon name={item.icon}/>,
|
||||
active: item.id === (activeId === "vps" ? "vps" : "workers"),
|
||||
onSelect: () => onNavigate(item.id)}))} items={[]} onItemChange={() => undefined}/>;
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ export function useApplicationPanelActions({
|
||||
onClick: () => void saveWorkspaceLayout(),
|
||||
});
|
||||
}
|
||||
if (definition?.root === "system") actions.push(...systemUtilityActions);
|
||||
if (definition && ["compute-modules", "network-monitor"].includes(definition.kind)) actions.push(...systemUtilityActions);
|
||||
if (definition?.kind === "recordings" && sessionOverview) actions.push({
|
||||
label: sessionOverview.open ? "Закрыть информацию о записи" : "Информация о записи",
|
||||
icon: "info", pressed: sessionOverview.open, disabled: !sessionOverview.available,
|
||||
|
||||
@@ -42,7 +42,7 @@ const defaultQuickActions: Record<
|
||||
observation: ["cameras", "world-map"],
|
||||
missions: ["routes", null],
|
||||
data: ["recordings", "datasets"],
|
||||
system: ["modules", "integrations"],
|
||||
system: ["modules", "network"],
|
||||
polygon: ["observatory", "local-device"],
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import {useCallback, useEffect, useState} from 'react';
|
||||
import type {VPSHost} from '../fleet/vps';
|
||||
import {startSequentialPolling} from './sequentialPolling';
|
||||
|
||||
export type ServerService = {kind:'arnavi'|'wireguard';id:string;name:string;endpoint:string;state:string;last_seen:number|null;details:VPSHost|{id:string;name:string;endpoint:string;boards:number;last_verified:number|null;state:string}};
|
||||
export type Server = {id:string;name:string;address:string;revision:number;services:ServerService[]};
|
||||
export type ServerRemovalPlan = {confirmation:string;name:string;blocked:string[];services:string[];vehicle_connections:number;worker_connections:number};
|
||||
export async function serverRequest<T>(path='', method='GET', body?:unknown, signal?:AbortSignal):Promise<T> {
|
||||
const response = await fetch(`/api/v1/system/servers${path}`, {method, cache:'no-store', credentials:'same-origin',
|
||||
signal:AbortSignal.any([...(signal?[signal]:[]),AbortSignal.timeout(method === 'GET' ? 20000 : 240000)]),
|
||||
headers:body === undefined ? {} : {'Content-Type':'application/json'}, body:body === undefined ? undefined : JSON.stringify(body)});
|
||||
const value = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw Error(typeof value.detail === 'string' ? value.detail : 'Не удалось получить данные VPS.');
|
||||
return value as T;
|
||||
}
|
||||
export function useServers() {
|
||||
const [items,setItems]=useState<Server[]|null>(null),[error,setError]=useState(''),[generation,setGeneration]=useState(0);
|
||||
const refresh=useCallback(()=>setGeneration(n=>n+1),[]);
|
||||
useEffect(()=>{
|
||||
const controller=new AbortController();
|
||||
const stop=startSequentialPolling(async()=>{try{const value=await serverRequest<{items:Server[]}>('', 'GET', undefined, controller.signal);if(!controller.signal.aborted){setItems(value.items);setError('');}}catch(e){if(!controller.signal.aborted)setError(e instanceof Error?e.message:'Не удалось получить VPS.');}},5000);
|
||||
return()=>{stop();controller.abort();};
|
||||
},[generation]);
|
||||
return {items,error,refresh,generation};
|
||||
}
|
||||
export interface ServiceObservation {id:string;kind:ServerService['kind'];state:'online'|'unavailable';checked_at:number}
|
||||
export function useServerHealth(servers:Server[]|null,generation=0) {
|
||||
const [observations,setObservations]=useState<Record<string,ServiceObservation[]>>({});
|
||||
const keys=(servers??[]).map(s=>s.id).sort().join('|');
|
||||
useEffect(()=>{
|
||||
const controller=new AbortController();setObservations({});
|
||||
const stop=startSequentialPolling(async()=>{
|
||||
await Promise.all(keys.split('|').filter(Boolean).map(async id=>{
|
||||
let items:ServiceObservation[]=[];
|
||||
try{items=(await serverRequest<{items:ServiceObservation[]}>(`/${id}/health`,'GET',undefined,controller.signal)).items;}catch{/* Unknown is distinct from a successful observation. */}
|
||||
if(!controller.signal.aborted)setObservations(current=>({...current,[id]:items}));
|
||||
}));
|
||||
},15000);
|
||||
return()=>{stop();controller.abort();};
|
||||
},[keys,generation]);
|
||||
return observations;
|
||||
}
|
||||
export function serviceAvailability(service:ServerService, observations:ServiceObservation[]=[], now=Date.now()/1000) {
|
||||
const item=observations.find(s=>s.kind===service.kind&&s.id===service.id);
|
||||
if(!item||now-item.checked_at>40)return {tone:'neutral' as const,label:'Связь не проверена',online:false};
|
||||
return item.state==='online'?{tone:'success' as const,label:'На связи',online:true}:{tone:'neutral' as const,label:'Нет ответа',online:false};
|
||||
}
|
||||
export function serverAvailability(server:Server,observations:ServiceObservation[]=[]) {
|
||||
const states=server.services.map(s=>serviceAvailability(s,observations));
|
||||
if(!states.length)return {tone:'neutral' as const,label:'Нет подключённых служб'};
|
||||
if(states.every(s=>s.online))return {tone:'success' as const,label:'На связи'};
|
||||
if(states.some(s=>s.online))return {tone:'warning' as const,label:'Часть служб доступна'};
|
||||
return {tone:'neutral' as const,label:states.some(s=>s.label==='Нет ответа')?'Нет ответа от служб':'Связь не проверена'};
|
||||
}
|
||||
@@ -20,6 +20,8 @@ export type WorkspaceKind =
|
||||
| "catalog"
|
||||
| "contour-health"
|
||||
| "compute-modules"
|
||||
| "workers"
|
||||
| "vps"
|
||||
| "network-monitor"
|
||||
| "datasets"
|
||||
| "artifact-health"
|
||||
@@ -567,6 +569,16 @@ export const workspaces: WorkspaceDefinition[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "workers", root: "system", label: "Воркеры", title: "Воркеры",
|
||||
eyebrow: "СИСТЕМА / ВОРКЕРЫ", description: "Вычислительные узлы и их подключения.",
|
||||
icon: "apps", kind: "workers", groups: [],
|
||||
},
|
||||
{
|
||||
id: "vps", root: "system", label: "VPS", title: "VPS",
|
||||
eyebrow: "СИСТЕМА / VPS", description: "Серверы и установленные на них службы.",
|
||||
icon: "globe", kind: "vps", groups: [],
|
||||
},
|
||||
{
|
||||
id: "modules",
|
||||
root: "system",
|
||||
@@ -591,29 +603,7 @@ export const workspaces: WorkspaceDefinition[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "integrations",
|
||||
root: "system",
|
||||
label: "Интеграции",
|
||||
title: "Интеграции",
|
||||
eyebrow: "СИСТЕМА / ИНТЕГРАЦИИ",
|
||||
description: "Адаптеры данных и внешние контуры с явной границей ответственности.",
|
||||
icon: "network",
|
||||
kind: "catalog",
|
||||
groups: [
|
||||
{
|
||||
title: "Точки интеграции",
|
||||
description: "Внешние системы не определяют продуктовую навигацию.",
|
||||
capabilities: [
|
||||
active("Локальный API устройства", "Текущий контур управления FastAPI."),
|
||||
ready("Визуализатор Rerun", "Открытый веб-визуализатор встроен в пространственную рабочую поверхность."),
|
||||
contract("Мост ROS 2", "Стандартные PointCloud2, Pose, Odometry, TF и диагностика."),
|
||||
contract("Шлюз Zenoh", "Маршрутизация разрешённых потоков между бортом и сервером."),
|
||||
later("Сервисы парка", "Задачи, зарядки и координация нескольких аппаратов."),
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
{
|
||||
id: "network",
|
||||
root: "system",
|
||||
@@ -637,28 +627,7 @@ export const workspaces: WorkspaceDefinition[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "audit",
|
||||
root: "system",
|
||||
label: "Журнал и аудит",
|
||||
title: "Журнал и аудит",
|
||||
eyebrow: "СИСТЕМА / АУДИТ",
|
||||
description: "Технические события, действия оператора и воспроизводимость эксперимента.",
|
||||
icon: "clipboard",
|
||||
kind: "timeline",
|
||||
groups: [
|
||||
{
|
||||
title: "Доказательность",
|
||||
description: "Git хранит код, обезличенные метаданные и правила воспроизведения.",
|
||||
capabilities: [
|
||||
active("Первичное сохранение сырья", "Сырые сообщения сохраняются до декодирования предпросмотра."),
|
||||
active("Манифест сессии", "Версии, хэши и обезличенные сведения о прогоне."),
|
||||
contract("События аудита интерфейса", "Переходы, операции и подтверждения пользователя."),
|
||||
later("Центральный сервис аудита", "Поиск и корреляция событий нескольких аппаратов."),
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
];
|
||||
|
||||
export function rootById(id: RootId | null): RootDefinition | null {
|
||||
|
||||
@@ -27,6 +27,8 @@ import { ContourHealthWorkspace } from "./ContourHealthWorkspace";
|
||||
import { LaboratoryArchiveWorkspace } from "./laboratory/LaboratoryArchiveWorkspace";
|
||||
import { SimulationWorkspace } from "./simulation/SimulationWorkspace";
|
||||
import { ComputeModulesWorkspace } from "./system/ComputeModulesWorkspace";
|
||||
import { WorkersWorkspace } from "./system/WorkersWorkspace";
|
||||
import { ServersWorkspace } from "./system/ServersWorkspace";
|
||||
import { NetworkWorkspace } from "./system/NetworkWorkspace";
|
||||
import { WorldMapWorkspace } from "./map/WorldMapWorkspace";
|
||||
import { ObservatoryWorkspace } from "./observatory/ObservatoryWorkspace";
|
||||
@@ -441,6 +443,10 @@ export function WorkspaceRenderer(props: WorkspaceRendererProps) {
|
||||
state={props.state}
|
||||
/>
|
||||
);
|
||||
case "workers":
|
||||
return <WorkersWorkspace headerToolsHost={props.headerToolsHost} onView={() => props.navigation.openView("modules")} />;
|
||||
case "vps":
|
||||
return <ServersWorkspace headerToolsHost={props.headerToolsHost} />;
|
||||
case "compute-modules":
|
||||
return <ComputeModulesWorkspace />;
|
||||
case "network-monitor":
|
||||
|
||||
@@ -5,25 +5,27 @@ import type {SensorEnrollmentProps} from '../../../../../../packages/sensor-ui/s
|
||||
import {InstallerCard} from './InstallerCard';
|
||||
import type {Vehicle} from '../../../core/fleet/useFleet';
|
||||
|
||||
export function VPSHostSettings({host,hosts,vehicle,vehicles,onClose,onSaved,renderWindow}:{host?:VPSHost;hosts:VPSHost[];vehicle:Vehicle;vehicles:Vehicle[];onClose:()=>void;onSaved:()=>void;renderWindow?:SensorEnrollmentProps['renderWindow']}){
|
||||
const [existing,setExisting]=useState(''),[name,setName]=useState(host?.name??'VPS Host ARNavi'),[code,setCode]=useState(''),[selected,setSelected]=useState(host?.vehicle_ids??[vehicle.id]);
|
||||
export function VPSHostSettings({host,hosts,liveHost,connectionStatus,vehicle,vehicles,onClose,onSaved,renderWindow}:{host?:VPSHost;liveHost?:VPSHost;connectionStatus?:{online:boolean;label:string};hosts:VPSHost[];vehicle?:Vehicle;vehicles:Vehicle[];onClose:()=>void;onSaved:()=>void;renderWindow?:SensorEnrollmentProps['renderWindow']}){
|
||||
const [existing,setExisting]=useState(''),[name,setName]=useState(host?.name??'VPS Host ARNavi'),[code,setCode]=useState(''),[selected,setSelected]=useState(host?.vehicle_ids??(vehicle?[vehicle.id]:[]));
|
||||
const [advanced,setAdvanced]=useState(false),[replaces,setReplaces]=useState('');
|
||||
const [network,setNetwork]=useState(host?.network_interface??''),[interfaces,setInterfaces]=useState<{id:string;label:string}[]>([]);
|
||||
useEffect(()=>{let active=true;void vpsRequest<{items:{id:string;label:string}[]}>('/interfaces').then(v=>{if(active)setInterfaces(v.items);}).catch(()=>{});return()=>{active=false;};},[]);
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
const current=host??hosts.find(h=>h.id===existing);
|
||||
const observed=liveHost??current;
|
||||
const online=connectionStatus?.online??(observed?hostOnline(observed):false);
|
||||
async function save(){setBusy(true);setError('');try{if(current){await vpsRequest(`/${current.id}`,'PUT',{name:name.trim(),vehicle_ids:selected,network_interface:network||null,expected_revision:current.revision});}else{await vpsRequest('','POST',{code:code.trim(),name:name.trim(),vehicle_ids:selected,network_interface:network||null,replaces_id:replaces||null});}onSaved();}catch(e){setError(e instanceof Error?e.message:'Не удалось подключить VPS.');}finally{setBusy(false);}}
|
||||
const actions=<><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!name.trim()||(!current&&!code.trim())} onClick={()=>void save()}>{current?'Применить':'Подключить VPS'}</Button></>;
|
||||
const footer=<WindowFooterActions>{actions}</WindowFooterActions>;
|
||||
const content=<div className="fleet-form">
|
||||
{!host&&<Select label="VPS Host ARNavi" value={existing} options={[{value:'',label:'Подключить новый VPS'},...hosts.filter(h=>h.state==='paired').map(h=>({value:h.id,label:h.name}))]} disabled={busy} onChange={id=>{setExisting(id);const value=hosts.find(h=>h.id===id);setName(value?.name??'VPS Host ARNavi');setNetwork(value?.network_interface??'');setSelected(Array.from(new Set([...(value?.vehicle_ids??[]),vehicle.id])));}}/>}
|
||||
{!host&&<Select label="VPS Host ARNavi" value={existing} options={[{value:'',label:'Подключить новый VPS'},...hosts.filter(h=>h.state==='paired').map(h=>({value:h.id,label:h.name}))]} disabled={busy} onChange={id=>{setExisting(id);const value=hosts.find(h=>h.id===id);setName(value?.name??'VPS Host ARNavi');setNetwork(value?.network_interface??'');setSelected(Array.from(new Set([...(value?.vehicle_ids??[]),...(vehicle?[vehicle.id]:[])])));}}/>}
|
||||
{!current&&<InstallerCard kind="vps-arnavi"/>}
|
||||
<TextField label="Название" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
|
||||
{!current&&<TextAreaField label="Ключ подключения VPS" value={code} rows={5} disabled={busy} onChange={e=>setCode(e.target.value)} hint="После установки VPS Host ARNavi ключ находится в /opt/nodedc-mission-vps/connect.key. Он действует 24 часа и используется один раз."/>}
|
||||
{!current&&hosts.some(h=>h.state==='paired')&&<Select label="После переустановки" value={replaces} options={[{value:'',label:'Это новый VPS'},...hosts.filter(h=>h.state==='paired').map(h=>({value:h.id,label:`Заменить ${h.name}`}))]} onChange={setReplaces} disabled={busy}/>}
|
||||
{interfaces.length>0&&<><Button disabled={busy} onClick={()=>setAdvanced(v=>!v)}>{advanced?'Скрыть параметры подключения':'Параметры подключения при использовании VPN'}</Button>{advanced&&<SettingsCard title="Подключение с этого компьютера" description="Если VPN мешает доступу к VPS, выберите прямое подключение. Это влияет только на соединение Mission Core с этим сервером."><Select label="Способ подключения" value={network} options={[{value:'',label:'Обычное подключение (с учётом VPN)'},...interfaces.map(i=>({value:i.id,label:`Напрямую · ${i.label}`}))]} disabled={busy} onChange={setNetwork}/></SettingsCard>}</>}
|
||||
{current&&<SettingsCard title="Связь с VPS" description={current.endpoint}><StatusBadge tone={hostOnline(current)?'success':'neutral'}>{hostOnline(current)?'На связи':current.state==='pending'?'Подключение не завершено':'Нет связи'}</StatusBadge><dl className="fleet-facts"><div><dt>Версия</dt><dd>{current.status?.version??'Нет сведений'}</dd></div><div><dt>Последняя синхронизация</dt><dd>{current.last_sync_at?new Date(current.last_sync_at*1000).toLocaleString('ru-RU'):'Ещё не было'}</dd></div><div><dt>Приём ARNavi B2</dt><dd>{current.status?`${current.status.tracker.host}:${current.status.tracker.port}`:'Не подтверждён'}</dd></div><div><dt>Трекеры</dt><dd>{current.status?.devices??0}</dd></div></dl></SettingsCard>}
|
||||
{current&&<SettingsCard title="Связь с VPS" description={current.endpoint}><StatusBadge tone={online?'success':'neutral'}>{connectionStatus?.label??(online?'На связи':current.state==='pending'?'Подключение не завершено':'Нет свежих данных')}</StatusBadge><dl className="fleet-facts"><div><dt>Версия</dt><dd>{observed?.status?.version??'Нет сведений'}</dd></div><div><dt>Последняя синхронизация</dt><dd>{observed?.last_sync_at?new Date(observed.last_sync_at*1000).toLocaleString('ru-RU'):'Ещё не было'}</dd></div><div><dt>Приём ARNavi B2</dt><dd>{observed?.status?`${observed.status.tracker.host}:${observed.status.tracker.port}`:'Не подтверждён'}</dd></div><div><dt>Трекеры</dt><dd>{observed?.status?.devices??0}</dd></div></dl></SettingsCard>}
|
||||
<SettingsCard title="Обслуживаемые аппараты" description="Один VPS может обслуживать несколько аппаратов. Его настройки общие для всех привязок."><div className="fleet-form">{vehicles.map(v=><Switch key={v.id} label={v.name} checked={selected.includes(v.id)} disabled={busy} onChange={checked=>setSelected(ids=>checked?[...ids,v.id]:ids.filter(id=>id!==v.id))}/>)}</div></SettingsCard>
|
||||
</div>;
|
||||
return <>{renderWindow?renderWindow({content,actions,busy}):host?<FeatureSettingsWindow open title="Настройки VPS Host ARNavi" subtitle={host.name} identity={{title:'VPS Host ARNavi',subtitle:host.endpoint,avatarLabel:'VPS'}} sections={[{id:'host',label:'Сервер и аппараты'}]} activeSection="host" onSectionChange={()=>{}} onClose={()=>{if(!busy)onClose();}} footer={footer}>{content}</FeatureSettingsWindow>:<Window open title="Подключить VPS Host ARNavi" subtitle={vehicle.name} size="md" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}} footer={footer}>{content}</Window>}<ToastStack items={error?[{id:'vps-host-error',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
|
||||
return <>{renderWindow?renderWindow({content,actions,busy}):host?<FeatureSettingsWindow open title="Настройки VPS Host ARNavi" subtitle={host.name} identity={{title:'VPS Host ARNavi',subtitle:host.endpoint,avatarLabel:'VPS'}} sections={[{id:'host',label:'Сервер и аппараты'}]} activeSection="host" onSectionChange={()=>{}} onClose={()=>{if(!busy)onClose();}} footer={footer}>{content}</FeatureSettingsWindow>:<Window open title="Подключить VPS Host ARNavi" subtitle={vehicle?.name} size="md" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}} footer={footer}>{content}</Window>}<ToastStack items={error?[{id:'vps-host-error',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import {useState} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {Description,Icon,IconButton,LoadingRegion,ResourceList,ResourceRow,SettingsCard,StatusBadge,Window} from '@nodedc/ui-react';
|
||||
import {useServers,useServerHealth,serviceAvailability,serverAvailability,type ServiceObservation,type Server,type ServerService} from '../../core/system/servers';
|
||||
import {useFleet} from '../../core/fleet/useFleet';
|
||||
import type {VPSHost} from '../../core/fleet/vps';
|
||||
import {ServerSettings} from '../../components/system/ServerSettings';
|
||||
import {ServerServiceSetup} from '../../components/system/ServerServiceSetup';
|
||||
import {VPSHostSettings} from '../fleet/equipment/VPSHostSettings';
|
||||
import './system-catalog.css';
|
||||
|
||||
function Services({host,observations,onInspect}:{host:Server;observations?:ServiceObservation[];onInspect:(service:ServerService)=>void}) {
|
||||
return host.services.length?<ResourceList aria-label={`Службы: ${host.name}`}>{host.services.map(service=>{const state=serviceAvailability(service,observations);return <li key={`${service.kind}:${service.id}`}>
|
||||
<ResourceRow icon={<Icon name={service.kind==='wireguard'?'network':'activity'}/>} title={service.name} description={service.endpoint}
|
||||
metadata={state.label} statusPlacement="leading" status={<StatusBadge variant="indicator" tone={state.tone} aria-label={state.label} title={state.label}/>}
|
||||
actions={<IconButton label={`Настройки ${service.name}: ${host.name}`} onClick={()=>onInspect(service)}><Icon name="sliders"/></IconButton>}/>
|
||||
</li>;})}</ResourceList>:<SettingsCard title="Служб пока нет" description="Нажмите «+» у VPS, чтобы установить и подключить службу."/>;
|
||||
}
|
||||
|
||||
export function ServersWorkspace({headerToolsHost}:{headerToolsHost?:HTMLElement|null}) {
|
||||
const store=useServers();const fleet=useFleet();
|
||||
const [expanded,setExpanded]=useState<string[]>([]);
|
||||
const [editing,setEditing]=useState<Server|null|undefined>(),[addingService,setAddingService]=useState<Server|null>(null);
|
||||
const [inspecting,setInspecting]=useState<ServerService|null>(null);
|
||||
const health=useServerHealth(store.items,store.generation);
|
||||
const inspectedHost=store.items?.find(host=>host.services.some(s=>s.id===inspecting?.id&&s.kind===inspecting?.kind));
|
||||
const liveService=inspectedHost?.services.find(s=>s.id===inspecting?.id&&s.kind===inspecting?.kind);
|
||||
const liveState=inspecting?serviceAvailability(inspecting,inspectedHost&&!store.error?health[inspectedHost.id]:[]):null;
|
||||
const reload=()=>{store.refresh();setInspecting(null);};
|
||||
const actions=<>
|
||||
<IconButton label="Обновить список VPS" onClick={store.refresh}><Icon name="refresh"/></IconButton>
|
||||
<IconButton label="Добавить VPS" onClick={()=>setEditing(null)}><Icon name="plus"/></IconButton>
|
||||
</>;
|
||||
return <>
|
||||
{headerToolsHost?createPortal(actions,headerToolsHost):actions}
|
||||
<LoadingRegion loading={!store.items&&!store.error} label="Получение VPS">
|
||||
<ResourceList aria-label="VPS">{store.items?.map(host=>{const state=serverAvailability(host,store.error?[]:health[host.id]);return <li key={host.id}>
|
||||
<ResourceRow icon={<Icon name="globe"/>} title={host.name} description={host.address} metadata={`Служб: ${host.services.length}`}
|
||||
statusPlacement="leading" status={<StatusBadge variant="indicator" tone={state.tone} aria-label={state.label} title={state.label}/>}
|
||||
actions={<>
|
||||
<IconButton label={`Добавить службу: ${host.name}`} disabled={!!store.error} onClick={()=>setAddingService(host)}><Icon name="plus"/></IconButton>
|
||||
<IconButton label={`Настройки VPS: ${host.name}`} disabled={!!store.error} onClick={()=>setEditing(host)}><Icon name="sliders"/></IconButton>
|
||||
<IconButton label={`${expanded.includes(host.id)?'Свернуть':'Показать'} службы: ${host.name}`} aria-expanded={expanded.includes(host.id)} aria-controls={`services-${host.id}`} onClick={()=>setExpanded(ids=>ids.includes(host.id)?ids.filter(id=>id!==host.id):[...ids,host.id])}><Icon name={expanded.includes(host.id)?'chevron-up':'chevron-down'}/></IconButton>
|
||||
</>}/>
|
||||
{expanded.includes(host.id)&&<div className="system-catalog-services" id={`services-${host.id}`} role="region" aria-label={`Службы: ${host.name}`}><Services host={host} observations={store.error?[]:health[host.id]} onInspect={setInspecting}/></div>}
|
||||
</li>;})}</ResourceList>
|
||||
{store.items?.length===0&&!store.error&&<SettingsCard title="VPS пока нет" description="Добавьте сервер через «+», затем подключите нужные службы."/>}
|
||||
</LoadingRegion>
|
||||
{editing!==undefined&&<ServerSettings key={editing?.id??'new'} server={editing??undefined} onClose={()=>setEditing(undefined)} onRemoved={()=>{setEditing(undefined);store.refresh();}} onSaved={item=>{setEditing(undefined);setExpanded(ids=>[...new Set([...ids,item.id])]);store.refresh();}}/>}
|
||||
{addingService&&<ServerServiceSetup server={addingService} onClose={()=>setAddingService(null)} onSaved={()=>{setAddingService(null);store.refresh();}}/>}
|
||||
{inspecting?.kind==='arnavi'&&<VPSHostSettings host={inspecting.details as VPSHost} liveHost={liveService?.details as VPSHost|undefined} connectionStatus={liveState??undefined} hosts={[inspecting.details as VPSHost]} vehicles={fleet.items??[]} onClose={()=>setInspecting(null)} onSaved={reload}/>}
|
||||
{inspecting?.kind==='wireguard'&&<Window open title="WireGuard" subtitle={inspecting.endpoint} size="md" onClose={()=>setInspecting(null)}>
|
||||
<SettingsCard title={inspecting.details.name} description="Общая сеть доступна в настройках подключения устройств.">
|
||||
<StatusBadge tone={liveState?.tone??'neutral'}>{liveState?.label??'Связь не проверена'}</StatusBadge>
|
||||
<Description>Проверяется доступность службы. VPN для устройства выбирается в его настройках подключения.</Description>
|
||||
<Description>Подключено бортов: {'boards' in inspecting.details?inspecting.details.boards:0}</Description>
|
||||
</SettingsCard>
|
||||
</Window>}
|
||||
{store.error&&<SettingsCard title="Не удалось получить VPS" description={store.error}/>}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import {useState} from "react";
|
||||
import {createPortal} from "react-dom";
|
||||
import {Icon, IconButton, LoadingRegion, ResourceList, ResourceRow, SettingsCard, StatusBadge} from "@nodedc/ui-react";
|
||||
import {useComputeContours} from "../../core/system/ComputeContourContext";
|
||||
import {WorkerConnectionSettings} from "../../components/system/WorkerConnectionSettings";
|
||||
import {useWorkerTelemetry} from '../../core/system/useWorkerTelemetry';
|
||||
import {workerAvailable} from '../../core/system/contourHealth';
|
||||
|
||||
function WorkerStatus({id,generation}:{id:string;generation:number}) {
|
||||
const {telemetry}=useWorkerTelemetry(id,5000,true,generation,1);
|
||||
const online=workerAvailable(telemetry);
|
||||
const label=online?'В сети':'Нет свежих данных о связи';
|
||||
return <StatusBadge variant="indicator" tone={online?'success':'neutral'} aria-label={label} title={label}/>;
|
||||
}
|
||||
|
||||
export function WorkersWorkspace({headerToolsHost, onView}: {headerToolsHost?: HTMLElement | null; onView: () => void}) {
|
||||
const store = useComputeContours();
|
||||
const [editing, setEditing] = useState<string | null | undefined>();
|
||||
const actions = <><IconButton label="Обновить список воркеров" onClick={()=>{store.refresh();store.refreshTelemetry();}}><Icon name="refresh"/></IconButton>
|
||||
<IconButton label="Добавить воркер" onClick={() => setEditing(null)}><Icon name="plus"/></IconButton></>;
|
||||
return <>
|
||||
{headerToolsHost ? createPortal(actions, headerToolsHost) : actions}
|
||||
<LoadingRegion loading={store.loading && !store.contours.length} label="Получение воркеров">
|
||||
{!store.loading && !store.error && !store.contours.length && <SettingsCard title="Воркеров пока нет" description="Добавьте вычислительный узел через «+»."/>}
|
||||
<ResourceList aria-label="Воркеры">{store.contours.map(item => <li key={item.contour_id}>
|
||||
<ResourceRow icon={<Icon name="apps"/>} title={item.display_name} description={item.expected_node_id}
|
||||
statusPlacement="leading" status={<WorkerStatus id={item.contour_id} generation={store.telemetryRefreshGeneration}/>}
|
||||
actions={<>
|
||||
<IconButton label={`Настройки воркера: ${item.display_name}`} disabled={!!store.error} onClick={() => setEditing(item.contour_id)}><Icon name="sliders"/></IconButton>
|
||||
<IconButton label={`Посмотреть воркер: ${item.display_name}`} disabled={!!store.error} onClick={() => {store.selectContour(item.contour_id); onView();}}><Icon name="eye"/></IconButton>
|
||||
</>}/>
|
||||
</li>)}</ResourceList>
|
||||
</LoadingRegion>
|
||||
{editing !== undefined && <WorkerConnectionSettings open mode={editing === null ? "create" : "edit"}
|
||||
contour={store.contours.find(item => item.contour_id === editing) ?? null} onClose={() => setEditing(undefined)}
|
||||
onChanged={store.refresh} onUpdate={store.updateContour}/>}
|
||||
{store.error && <SettingsCard title="Не удалось получить воркеры" description={store.error}/>}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
.system-catalog-form {
|
||||
display: grid;
|
||||
gap: var(--nodedc-space-4);
|
||||
}
|
||||
.system-catalog-services {
|
||||
margin: var(--nodedc-space-3) 0 var(--nodedc-space-4) var(--nodedc-space-5);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import React from 'react';
|
||||
import {before,after,test} from 'node:test';
|
||||
import {createServer} from './support/vite-server.mjs';
|
||||
let server,Navigation,Workers,availability;
|
||||
before(async()=>{
|
||||
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true,hmr:false}});
|
||||
({SystemNavigationPanel:Navigation}=await server.ssrLoadModule('/src/components/system/SystemNavigationPanel.tsx'));
|
||||
({WorkersWorkspace:Workers}=await server.ssrLoadModule('/src/workspaces/system/WorkersWorkspace.tsx'));
|
||||
availability=await server.ssrLoadModule('/src/core/system/servers.ts');
|
||||
});
|
||||
after(async()=>{await server?.close();});
|
||||
function withHooks(hooks,fn){const internals=React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,previous=internals.H;internals.H=hooks;try{return fn();}finally{internals.H=previous;}}
|
||||
function find(tree,predicate){if(!tree)return null;if(Array.isArray(tree)){for(const item of tree){const r=find(item,predicate);if(r)return r;}return null;}if(typeof tree!=='object')return null;if(predicate(tree))return tree;return find(tree.props?.children,predicate)??find(tree.props?.actions,predicate);}
|
||||
|
||||
test('system category returns to catalog from worker detail and has no global add action',()=>{
|
||||
const selected=[];
|
||||
const tree=Navigation({title:'System',activeId:'network',onNavigate:id=>selected.push(id),onClose:()=>{}});
|
||||
assert.deepEqual(tree.props.contexts.map(x=>x.id),['workers','vps']);
|
||||
assert.equal(tree.props.contexts[0].active,true);
|
||||
assert.equal(tree.props.headerActions,undefined);
|
||||
tree.props.contexts[0].onSelect();tree.props.contexts[1].onSelect();
|
||||
assert.deepEqual(selected,['workers','vps']);
|
||||
});
|
||||
test('worker eye selects the requested worker before opening telemetry; settings does not navigate',()=>{
|
||||
const events=[],states=[];
|
||||
const store={contours:[{contour_id:'one',display_name:'First',expected_node_id:'node-a'},{contour_id:'two',display_name:'Second',expected_node_id:'node-b'}],selectContour:id=>events.push(id),refresh:()=>{},loading:false,error:null};
|
||||
const tree=withHooks({useContext:()=>store,useState:()=>[undefined,value=>states.push(value)]},()=>Workers({onView:()=>events.push('view')}));
|
||||
const eye=find(tree,x=>x.props?.label==='Посмотреть воркер: Second');
|
||||
eye.props.onClick();assert.deepEqual(events,['two','view']);
|
||||
const settings=find(tree,x=>x.props?.label==='Настройки воркера: First');
|
||||
settings.props.onClick();assert.deepEqual(states,['one']);assert.deepEqual(events,['two','view']);
|
||||
find(tree,x=>x.props?.label==='Добавить воркер').props.onClick();assert.equal(states.at(-1),null);
|
||||
});
|
||||
|
||||
|
||||
test('service readiness is not liveness; expired and wrong-service observations never show online',()=>{
|
||||
const service={kind:'wireguard',id:'one',state:'ready',last_seen:100};
|
||||
const now=Date.now()/1000;
|
||||
assert.equal(availability.serviceAvailability(service,[],now).online,false);
|
||||
assert.equal(availability.serviceAvailability(service,[{kind:'wireguard',id:'other',state:'online',checked_at:now}],now).online,false);
|
||||
const observed={kind:'wireguard',id:'one',state:'online',checked_at:now};
|
||||
assert.equal(availability.serviceAvailability(service,[observed],now).online,true);
|
||||
assert.equal(availability.serviceAvailability(service,[observed],now+41).online,false);
|
||||
const host={services:[service,{kind:'arnavi',id:'two'}]};
|
||||
assert.equal(availability.serverAvailability(host,[observed]).tone,'warning');
|
||||
assert.equal(availability.serverAvailability(host,[observed,{kind:'arnavi',id:'two',state:'online',checked_at:now}]).tone,'success');
|
||||
assert.equal(availability.serverAvailability(host,[]).tone,'neutral');
|
||||
});
|
||||
@@ -345,9 +345,25 @@ class Manager:
|
||||
raise ValueError("Invalid helper request")
|
||||
with self.lock:
|
||||
action = body.get("action")
|
||||
if action not in ("prepare", "status", "stage", "confirm", "apply", "disable", "rollback"):
|
||||
if action not in (
|
||||
"prepare", "status", "stage", "confirm", "apply", "disable", "rollback", "forget",
|
||||
):
|
||||
raise ValueError("Unknown action")
|
||||
identity = server_id(body.get("server_id"))
|
||||
if action == "forget":
|
||||
row = self.profiles.get(identity)
|
||||
if row is not None:
|
||||
if row.get("pending"):
|
||||
raise ValueError("A network change is pending")
|
||||
self.down(row)
|
||||
del self.profiles[identity]
|
||||
try:
|
||||
self.persist()
|
||||
except Exception:
|
||||
self.profiles[identity] = row
|
||||
raise
|
||||
self.restore_retry.pop(identity, None)
|
||||
return {"server_id": identity, "removed": True}
|
||||
row = self.prepare(identity)
|
||||
if action in ("stage", "apply"):
|
||||
config = body["config"]
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
# System inventory: Workers and VPS
|
||||
|
||||
Owner-approved composition, 2026-11-09.
|
||||
|
||||
## Product surface decision
|
||||
|
||||
The recurring operator job is to find a worker/server, configure its connections
|
||||
and inspect its actual services. System contains two categories: Workers and VPS.
|
||||
Both use the admitted Vehicles catalog composition: ResourceList/ResourceRow,
|
||||
header add and row settings. Worker rows retain eye/detail/back; VPS rows only
|
||||
expand services, with no duplicate eye view (owner revision at 23:38).
|
||||
Selecting a sidebar category
|
||||
returns to its catalog. The alternative device selector in the detail header was
|
||||
rejected by the owner in favor of a consistent catalog with Vehicles.
|
||||
|
||||
Worker detail retains Modules/Network and existing power/connection operations.
|
||||
VPS rows expand into services; + on a server opens a service setup window.
|
||||
No new shared control, root, generic deployment engine or executor installer.
|
||||
Design Guideline ResourceList, ResourceRow, Window, SettingsCard, Select,
|
||||
Description, IconButton, AdminNavigationPanel and ApplicationPanel are reused.
|
||||
States: initial loading, empty, fetch failure/retry, catalog, expanded services,
|
||||
detail/back, settings/save/error/stale revision, setup/import/pending/error/success.
|
||||
Catalog presence is not proof of network availability or completed installation.
|
||||
|
||||
## Data authority
|
||||
|
||||
`fleet/server_catalog.py` stores only operator metadata in
|
||||
`fleet.root/server-catalog.sqlite3`. It is durable configuration, not a cache.
|
||||
Writes are transactional and revision checked. Existing service registries remain
|
||||
the sole authorities for identity, certificates, tokens, participants, vehicle
|
||||
assignments and remote execution. Their public projections are grouped by the
|
||||
literal normalized endpoint hostname/IP, not by a DNS lookup. The grouping is
|
||||
presentation, not proof that service identities are interchangeable. Different
|
||||
DNS aliases are not merged. No live credentials or network routes are migrated.
|
||||
|
||||
Existing endpoints appear on first catalog read. Metadata edits persist stable
|
||||
server IDs; editing the address of a server with services is rejected. Adding a
|
||||
service verifies its invitation endpoint matches the selected server before
|
||||
calling the existing pinned-trust admission. Membership is derived from that
|
||||
registry, so a lost response cannot orphan an admitted service in a second store.
|
||||
An unavailable service store is an error, never an empty catalog.
|
||||
|
||||
Routes: `/api/v1/system/servers` GET/POST, `/{id}` PUT,
|
||||
`/{id}/services` POST. All use the existing local operator boundary.
|
||||
There is no raw SSH credential/command endpoint. Explicit local removal is described below; it never administers the remote VPS.
|
||||
|
||||
## Live availability
|
||||
|
||||
Rows use the same leading StatusBadge indicator as Vehicles. Worker availability
|
||||
uses its existing identity-checked telemetry, polling a single history sample.
|
||||
VPS and service indicators use `/{id}/health`: read-only GET `/v1/status` against
|
||||
already trusted endpoints, with the existing pinned certificate and identity
|
||||
validation. Four concurrent exchanges maximum, shared 15-second RAM observations,
|
||||
no persisted history or network mutation. Online never follows from stored
|
||||
`ready`/`paired` alone. Partial service availability is amber; no fresh answer is
|
||||
gray. Service observations expire in the UI; failures replace prior green state.
|
||||
|
||||
Catalog metadata/synchronization status refreshes every five seconds. Open ARNavi
|
||||
settings receive live observations separately from the captured editable draft
|
||||
and revision, so refresh neither ages a frozen status nor overwrites unsaved edits.
|
||||
WireGuard service availability does not claim this Mac is using that VPN tunnel.
|
||||
|
||||
## Installation boundary
|
||||
|
||||
The service window supplies the existing ARNavi or WireGuard installer and its
|
||||
version/OS/instructions. The operator runs it on the chosen VPS and returns the
|
||||
single-use ARNavi key or WireGuard invitation over a trusted transfer. Existing
|
||||
service registration owns secure exchange and profile persistence. A WireGuard
|
||||
profile is shared with the existing fleet/worker connection catalog immediately.
|
||||
No additional manual import into each device is needed.
|
||||
|
||||
This change does not remotely install packages, retrieve root-owned files using
|
||||
unprovisioned SSH credentials, or qualify a fresh VPS. Those require a separate
|
||||
trusted administration bootstrap; inventory registration alone grants none.
|
||||
WireGuard's existing peer protocol still admits Core/Node, not worker execution
|
||||
roles. This catalog does not claim to close that separate protocol gap.
|
||||
|
||||
## Ownership and verification
|
||||
|
||||
UI: `workspaces/system/WorkersWorkspace.tsx`, `ServersWorkspace.tsx`;
|
||||
forms: `components/system/ServerSettings.tsx`, `ServerServiceSetup.tsx`;
|
||||
read adapter: `core/system/servers.ts`; API: `web/server_catalog_api.py`.
|
||||
ARNavi service settings reuse `workspaces/fleet/equipment/VPSHostSettings.tsx`
|
||||
and preserve all existing vehicle assignments.
|
||||
|
||||
Acceptance evidence is recorded under `outputs/system-catalog-20261109`.
|
||||
|
||||
## Explicit removal — owner amendment, 2026-11-10
|
||||
|
||||
The VPS settings header provides trash between move and close. The same mounted
|
||||
Window changes to a confirmation context, with Cancel returning to the untouched
|
||||
settings draft. A server-side preflight lists the exact service owners and hashes
|
||||
stable identities, revisions and bindings. Delete rechecks that snapshot under
|
||||
owner locks; stale confirmations cannot delete changed connections.
|
||||
|
||||
Removal is local: forget the owned WireGuard tunnel, routes and helper key;
|
||||
remove service credentials, inactive device connection references and catalog
|
||||
metadata. The VPS machine and remote installations/peer records are not removed
|
||||
or revoked. ARNavi device records, source recordings and command audit history
|
||||
remain separate owners. Pending equipment commands or active/unknown device
|
||||
routes block deletion until the operator completes or switches them.
|
||||
|
||||
A failed cleanup retains a retryable server row. The UI reports success only after
|
||||
all local owners acknowledge; a retry processes remaining owners. The existing
|
||||
WireGuard helper installer may request macOS administrator authorization when it
|
||||
needs the updated forget operation. No helper update is silently performed during
|
||||
catalog browsing or deletion preflight. No production VPS was deleted during QA.
|
||||
@@ -0,0 +1,140 @@
|
||||
"""VPS inventory metadata. Service registries retain all trust and execution authority."""
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
import sqlite3
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
from uuid import NAMESPACE_URL, uuid5
|
||||
|
||||
Document = dict[str, Any]
|
||||
|
||||
|
||||
def address(value: str) -> str:
|
||||
value = value.strip().lower().rstrip(".")
|
||||
try:
|
||||
return str(ipaddress.ip_address(value))
|
||||
except ValueError:
|
||||
if (
|
||||
len(value) > 253
|
||||
or not re.fullmatch(
|
||||
r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+",
|
||||
value,
|
||||
)
|
||||
or all(c in "0123456789." for c in value)
|
||||
):
|
||||
raise ValueError("Укажите IP-адрес или DNS-имя VPS без протокола и порта.") from None
|
||||
return value
|
||||
|
||||
|
||||
def endpoint_address(endpoint: str) -> str:
|
||||
return address(urlsplit(endpoint).hostname or "")
|
||||
|
||||
|
||||
def identifier(host: str) -> str:
|
||||
return "server_" + uuid5(NAMESPACE_URL, "missioncore:vps:" + host).hex
|
||||
|
||||
|
||||
class ServerCatalog:
|
||||
"""Only labels/addresses persist here; service observations are projected on read.
|
||||
|
||||
Equal literal addresses group services for presentation, never merge their
|
||||
certificates/IDs. DNS aliases are not resolved or merged automatically.
|
||||
"""
|
||||
|
||||
def __init__(self, root: Path):
|
||||
self.path = root / "server-catalog.sqlite3"
|
||||
|
||||
@contextmanager
|
||||
def db(self) -> Iterator[sqlite3.Connection]:
|
||||
db = sqlite3.connect(self.path, timeout=10)
|
||||
try:
|
||||
db.execute("PRAGMA synchronous=FULL")
|
||||
db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS servers "
|
||||
"(id TEXT PRIMARY KEY, name TEXT NOT NULL, address TEXT UNIQUE NOT NULL, "
|
||||
"revision INTEGER NOT NULL)"
|
||||
)
|
||||
self.path.chmod(0o600)
|
||||
with db:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
def listing(self, services: list[Document]) -> list[Document]:
|
||||
with self.db() as db:
|
||||
rows = db.execute(
|
||||
"SELECT id,name,address,revision FROM servers ORDER BY rowid"
|
||||
).fetchall()
|
||||
hosts = {
|
||||
r[2]: dict(id=r[0], name=r[1], address=r[2], revision=r[3], services=[]) for r in rows
|
||||
}
|
||||
for service in services:
|
||||
host = endpoint_address(service["endpoint"])
|
||||
hosts.setdefault(
|
||||
host, dict(id=identifier(host), name=host, address=host, revision=1, services=[])
|
||||
)
|
||||
hosts[host]["services"].append(service)
|
||||
return list(hosts.values())
|
||||
|
||||
def find(self, key: str, services: list[Document]) -> Document:
|
||||
row = next((r for r in self.listing(services) if r["id"] == key), None)
|
||||
if row is None:
|
||||
raise ValueError("VPS не найден. Обновите список.")
|
||||
return row
|
||||
|
||||
def retain(self, row: Document) -> None:
|
||||
"""Keep a retryable catalog entry until all connection owners acknowledge removal."""
|
||||
with self.db() as db:
|
||||
db.execute("INSERT OR IGNORE INTO servers VALUES(?,?,?,?)",
|
||||
(row["id"], row["name"], row["address"], row["revision"]))
|
||||
|
||||
def remove(self, key: str) -> None:
|
||||
with self.db() as db:
|
||||
db.execute("DELETE FROM servers WHERE id=?", (key,))
|
||||
|
||||
def save(
|
||||
self,
|
||||
name: str,
|
||||
host: str,
|
||||
services: list[Document],
|
||||
key: str | None = None,
|
||||
revision: int | None = None,
|
||||
) -> Document:
|
||||
host = address(host)
|
||||
name = name.strip()
|
||||
if not name or len(name) > 80:
|
||||
raise ValueError("Укажите название VPS (до 80 символов).")
|
||||
current = self.find(key, services) if key else None
|
||||
if current and current["services"] and current["address"] != host:
|
||||
raise ValueError(
|
||||
"Адрес VPS связан с подключёнными службами. "
|
||||
"Смена адреса требует переподключения служб."
|
||||
)
|
||||
rows = self.listing(services)
|
||||
if any(r["address"] == host and r["id"] != key for r in rows):
|
||||
raise ValueError("Этот VPS уже есть в списке.")
|
||||
key = key or identifier(host)
|
||||
with self.db() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
saved = db.execute("SELECT revision FROM servers WHERE id=?", (key,)).fetchone()
|
||||
if current:
|
||||
if revision != (saved[0] if saved else current["revision"]):
|
||||
raise ValueError("Настройки VPS изменились. Откройте их повторно.")
|
||||
next_revision = int(current["revision"]) + 1
|
||||
else:
|
||||
if saved:
|
||||
raise ValueError("Этот VPS уже есть в списке.")
|
||||
next_revision = 1
|
||||
try:
|
||||
db.execute(
|
||||
"INSERT INTO servers VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET "
|
||||
"name=excluded.name,address=excluded.address,revision=excluded.revision",
|
||||
(key, name, host, next_revision),
|
||||
)
|
||||
except sqlite3.IntegrityError:
|
||||
raise ValueError("Этот VPS уже есть в списке.") from None
|
||||
return self.find(key, services)
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Explicit local VPS disconnection. Never administers the remote host or its peers."""
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from k1link.compute_connections.store import ConnectionStore, Registry, WorkerBinding
|
||||
from k1link.fleet import network_client
|
||||
from k1link.fleet.server_catalog import Document, ServerCatalog, endpoint_address
|
||||
|
||||
|
||||
class ServerRemoval:
|
||||
def __init__(self, fleet: Any, connections_root: Path):
|
||||
self.fleet = fleet
|
||||
self.hosts = fleet.vps_hosts
|
||||
self.networks = fleet.network_profiles
|
||||
self.connections = ConnectionStore(connections_root)
|
||||
self.catalog = ServerCatalog(fleet.root)
|
||||
|
||||
@contextmanager
|
||||
def locked(self) -> Iterator[None]:
|
||||
# Existing owners retain their locks. Profile imports and tunnel changes
|
||||
# cannot race retirement; fleet/connection revisions invalidate stale tabs.
|
||||
with (
|
||||
self.networks.import_lock,
|
||||
self.hosts.lock,
|
||||
self.networks.sync_lock,
|
||||
self.fleet.lock,
|
||||
self.networks.lock,
|
||||
self.connections.locked(),
|
||||
):
|
||||
yield
|
||||
|
||||
def snapshot(
|
||||
self, host: Document
|
||||
) -> tuple[Document, list[Document], list[Document], Registry, set[str], list[Document]]:
|
||||
arnavi = [
|
||||
r for r in self.hosts.rows() if endpoint_address(r["endpoint"]) == host["address"]
|
||||
]
|
||||
wg = [
|
||||
r
|
||||
for r in self.networks.profiles.values()
|
||||
if endpoint_address(r["endpoint"]) == host["address"]
|
||||
]
|
||||
ids = {r["server_id"] for r in wg}
|
||||
registry = self.connections.read()
|
||||
profiles = {
|
||||
p.id for p in registry.profiles if p.provider == "wireguard" and p.network_id in ids
|
||||
}
|
||||
vehicles = self.fleet.rows()
|
||||
blocked = []
|
||||
affected = []
|
||||
for row in vehicles:
|
||||
paths = set(row.get("network_paths", {})) & ids
|
||||
if paths:
|
||||
affected.append(row["id"])
|
||||
if row.get("network_active") in ids or (paths and not row.get("network_active")):
|
||||
blocked.append(
|
||||
f"Переключите подключение аппарата «{row.get('name') or row['id']}» "
|
||||
"на другую сеть."
|
||||
)
|
||||
for worker in registry.workers:
|
||||
if any(
|
||||
c.id == worker.active_connection_id and c.profile_id in profiles
|
||||
for c in worker.connections
|
||||
):
|
||||
blocked.append(
|
||||
f"Переключите подключение воркера «{worker.contour_id}» на другую сеть."
|
||||
)
|
||||
if any(t.is_alive() for t in self.networks.workers.values()):
|
||||
blocked.append("Дождитесь завершения переключения сетевых подключений.")
|
||||
if any(r.get("revocations") for r in wg):
|
||||
blocked.append("Дождитесь завершения отзыва сетевого доступа.")
|
||||
host_ids = {r["id"] for r in arnavi}
|
||||
with self.hosts.equipment.db() as db:
|
||||
pending = [
|
||||
json.loads(r[0])
|
||||
for r in db.execute(
|
||||
"SELECT body FROM command_journal "
|
||||
"WHERE state IN ('waiting','submitting','queued','dispatched')"
|
||||
)
|
||||
]
|
||||
probes = {r[0] for r in db.execute("SELECT host FROM command_result_probes")}
|
||||
outbox = {x for r in db.execute("SELECT host,target FROM network_outbox") for x in r}
|
||||
if any(r.get("host_id") in host_ids for r in pending) or (probes | outbox) & host_ids:
|
||||
blocked.append("Дождитесь завершения команд оборудования, отправленных через этот VPS.")
|
||||
signature = {
|
||||
"server": {k: host[k] for k in ("id", "name", "address", "revision")},
|
||||
"arnavi": [
|
||||
{k: r.get(k) for k in ("id", "revision", "endpoint", "fingerprint", "vehicle_ids")}
|
||||
for r in arnavi
|
||||
],
|
||||
"wg": [
|
||||
{
|
||||
k: r.get(k)
|
||||
for k in ("server_id", "endpoint", "fingerprint", "state", "revocations")
|
||||
}
|
||||
for r in wg
|
||||
],
|
||||
"vehicles": [
|
||||
{
|
||||
"id": r["id"],
|
||||
"active": r.get("network_active"),
|
||||
"paths": sorted(set(r.get("network_paths", {})) & ids),
|
||||
}
|
||||
for r in vehicles
|
||||
],
|
||||
"connections_revision": registry.revision,
|
||||
"blocked": blocked,
|
||||
}
|
||||
digest = hashlib.sha256(json.dumps(signature, sort_keys=True).encode()).hexdigest()
|
||||
plan = {
|
||||
"confirmation": digest,
|
||||
"name": host["name"],
|
||||
"blocked": blocked,
|
||||
"services": ["ARNavi"] * len(arnavi) + ["WireGuard"] * len(wg),
|
||||
"vehicle_connections": len(affected),
|
||||
"worker_connections": sum(
|
||||
c.profile_id in profiles for w in registry.workers for c in w.connections
|
||||
),
|
||||
}
|
||||
return plan, arnavi, wg, registry, profiles, vehicles
|
||||
|
||||
def preview(self, host: Document) -> Document:
|
||||
with self.locked():
|
||||
return self.snapshot(host)[0]
|
||||
|
||||
def remove(self, host: Document, confirmation: str) -> Document:
|
||||
with self.locked():
|
||||
plan, arnavi, wg, registry, profiles, vehicles = self.snapshot(host)
|
||||
if plan["confirmation"] != confirmation:
|
||||
raise ValueError(
|
||||
"Настройки или подключения изменились. Проверьте удаление ещё раз."
|
||||
)
|
||||
if plan["blocked"]:
|
||||
raise ValueError(plan["blocked"][0])
|
||||
self.catalog.retain(host)
|
||||
ids = {r["server_id"] for r in wg}
|
||||
# Do not erase the registry while an owned OS tunnel remains active.
|
||||
# The existing installer may request OS authorization on first use.
|
||||
if wg:
|
||||
network_client.ensure() # type: ignore[no-untyped-call] # existing OS helper
|
||||
for row in wg:
|
||||
result = network_client.request("forget", row["server_id"]) # type: ignore[no-untyped-call]
|
||||
if result.get("removed") is not True:
|
||||
raise ValueError(
|
||||
"Не удалось удалить локальный туннель. Повторите удаление VPS."
|
||||
)
|
||||
address = str(ipaddress.ip_network(row["subnet"])[2])
|
||||
listener = self.fleet.listeners.get(address)
|
||||
if listener is not None:
|
||||
listener.shutdown()
|
||||
listener.server_close()
|
||||
self.fleet.listeners.pop(address, None)
|
||||
if ids:
|
||||
workers = tuple(
|
||||
WorkerBinding.model_validate(
|
||||
{
|
||||
**w.model_dump(),
|
||||
"revision": w.revision + 1,
|
||||
"connections": [
|
||||
c for c in w.connections if c.profile_id not in profiles
|
||||
],
|
||||
}
|
||||
)
|
||||
for w in registry.workers
|
||||
)
|
||||
self.connections._write(
|
||||
Registry(
|
||||
revision=registry.revision + 1,
|
||||
profiles=tuple(p for p in registry.profiles if p.id not in profiles),
|
||||
workers=workers,
|
||||
)
|
||||
)
|
||||
for vehicle in vehicles:
|
||||
if set(vehicle.get("network_paths", {})) & ids:
|
||||
vehicle["network_paths"] = {
|
||||
k: v for k, v in vehicle["network_paths"].items() if k not in ids
|
||||
}
|
||||
self.fleet.save(vehicle)
|
||||
previous = copy.deepcopy(self.networks.profiles)
|
||||
for identity in ids:
|
||||
self.networks.profiles.pop(identity, None)
|
||||
try:
|
||||
self.networks.save()
|
||||
except Exception:
|
||||
self.networks.profiles = previous
|
||||
raise
|
||||
for identity in ids:
|
||||
self.networks.revoke_retry.pop(identity, None)
|
||||
# A failed stage retains the server row. Retrying repeats only owners
|
||||
# that remain; successful removal is never reported before all finish.
|
||||
with self.hosts.db() as db:
|
||||
db.execute("PRAGMA secure_delete=ON")
|
||||
for row in arnavi:
|
||||
instances = [
|
||||
r[0]
|
||||
for r in db.execute("SELECT instance FROM links WHERE host=?", (row["id"],))
|
||||
]
|
||||
for instance in instances:
|
||||
for table in ("positions", "outputs", "cellular", "b2_sim_identity"):
|
||||
db.execute(f"DELETE FROM {table} WHERE instance=?", (instance,))
|
||||
db.execute("DELETE FROM links WHERE host=?", (row["id"],))
|
||||
db.execute("DELETE FROM packets WHERE host=?", (row["id"],))
|
||||
db.execute("DELETE FROM hosts WHERE id=?", (row["id"],))
|
||||
self.catalog.remove(host["id"])
|
||||
return {"removed": True, "id": host["id"]}
|
||||
@@ -158,6 +158,7 @@ from k1link.web.simulation_world_provider_api import build_simulation_world_prov
|
||||
from k1link.web.system_telemetry_api import build_system_telemetry_router
|
||||
from k1link.web.viewer_diagnostics_api import build_viewer_diagnostics_router
|
||||
from k1link.web.vps_host_api import router as vps_host_router
|
||||
from k1link.web.server_catalog_api import router as server_catalog_router
|
||||
from k1link.web.vps_host_api import start as start_vps_hosts
|
||||
|
||||
REPOSITORY_ROOT = Path(__file__).resolve().parents[3]
|
||||
@@ -856,6 +857,8 @@ app.include_router(fleet_router)
|
||||
app.include_router(equipment_router)
|
||||
app.include_router(equipment_firmware_router)
|
||||
app.include_router(vps_host_router)
|
||||
app.state.system_connections_root = REPOSITORY_ROOT / ".runtime" / "system"
|
||||
app.include_router(server_catalog_router)
|
||||
app.include_router(installer_router)
|
||||
app.include_router(rover_router)
|
||||
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
"""Global VPS inventory; existing ARNavi/WireGuard authorities perform admission."""
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import http.client
|
||||
import sqlite3
|
||||
import threading
|
||||
from collections.abc import Callable
|
||||
from typing import Annotated, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from k1link.fleet.network_profiles import parse_file
|
||||
from k1link.fleet.registry import FleetRegistry
|
||||
from k1link.fleet.server_catalog import Document, ServerCatalog, endpoint_address
|
||||
from k1link.fleet.server_removal import ServerRemoval
|
||||
from k1link.fleet.vps_transport import invitation
|
||||
from k1link.web.fleet_api import local_operator
|
||||
from k1link.web.server_health import ServerHealth
|
||||
from k1link.web.vps_host_api import store as arnavi_store
|
||||
|
||||
router = APIRouter(prefix="/api/v1/system/servers", tags=["system-servers"])
|
||||
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
|
||||
# Serialize this catalog's edits and imports, including the remote admission.
|
||||
lock = threading.RLock()
|
||||
|
||||
|
||||
class Details(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
name: str = Field(min_length=1, max_length=80)
|
||||
address: str = Field(min_length=1, max_length=253)
|
||||
|
||||
|
||||
class Update(Details):
|
||||
expected_revision: int = Field(ge=1, strict=True)
|
||||
|
||||
|
||||
class ServiceImport(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
kind: Literal["arnavi", "wireguard"]
|
||||
document: str = Field(min_length=1, max_length=16384)
|
||||
network_interface: str | None = Field(default=None, max_length=20)
|
||||
expected_revision: int = Field(ge=1, strict=True)
|
||||
|
||||
|
||||
class RemovalPreview(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
expected_revision: int = Field(ge=1, strict=True)
|
||||
|
||||
|
||||
class Removal(RemovalPreview):
|
||||
confirmation: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
|
||||
|
||||
def services(fleet: FleetRegistry) -> list[Document]:
|
||||
# Do not silently show missing service stores as an empty inventory.
|
||||
result = []
|
||||
for h in arnavi_store(fleet).listing():
|
||||
result.append(
|
||||
dict(
|
||||
kind="arnavi",
|
||||
id=h["id"],
|
||||
endpoint=h["endpoint"],
|
||||
name="ARNavi",
|
||||
state=h["state"],
|
||||
last_seen=h["last_sync_at"],
|
||||
details=h,
|
||||
)
|
||||
)
|
||||
for p in fleet.network_profiles.listing(): # type: ignore[no-untyped-call] # existing network authority
|
||||
result.append(
|
||||
dict(
|
||||
kind="wireguard",
|
||||
id=p["id"],
|
||||
endpoint=p["endpoint"],
|
||||
name="WireGuard",
|
||||
state=p["state"],
|
||||
last_seen=p.get("last_verified"),
|
||||
details=p,
|
||||
)
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def perform(callback: Callable[[], Document]) -> Document:
|
||||
try:
|
||||
with lock:
|
||||
return callback()
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
except (OSError, sqlite3.Error, http.client.HTTPException):
|
||||
raise HTTPException(503, "Операция VPS не завершена. Повторите действие.") from None
|
||||
|
||||
|
||||
@router.get("")
|
||||
def listing(response: Response, fleet: Fleet) -> Document:
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return perform(lambda: {"items": ServerCatalog(fleet.root).listing(services(fleet))})
|
||||
|
||||
|
||||
@router.get("/{key}/health")
|
||||
async def health(key: str, request: Request, response: Response, fleet: Fleet) -> Document:
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
host = perform(lambda: ServerCatalog(fleet.root).find(key, services(fleet)))
|
||||
observer = getattr(request.app.state, "server_health", None)
|
||||
if observer is None:
|
||||
observer = request.app.state.server_health = ServerHealth()
|
||||
known = {(s["kind"], s["id"]) for s in host["services"]}
|
||||
rows = [("arnavi", r) for r in arnavi_store(fleet).rows() if ("arnavi", r["id"]) in known]
|
||||
with fleet.network_profiles.lock:
|
||||
rows += [
|
||||
("wireguard", copy.deepcopy(r))
|
||||
for r in fleet.network_profiles.profiles.values()
|
||||
if ("wireguard", r["server_id"]) in known
|
||||
]
|
||||
|
||||
async def inspect(kind: str, row: Document) -> Document:
|
||||
observed = await observer.observe(kind, row, fleet.network_profiles.verify_status)
|
||||
return {"kind": kind, "id": row.get("id", row.get("server_id")), **observed}
|
||||
|
||||
return {"items": await asyncio.gather(*(inspect(kind, row) for kind, row in rows))}
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create(body: Details, fleet: Fleet) -> Document:
|
||||
return perform(lambda: ServerCatalog(fleet.root).save(body.name, body.address, services(fleet)))
|
||||
|
||||
|
||||
def removal_target(key: str, revision: int, fleet: FleetRegistry) -> Document:
|
||||
host = ServerCatalog(fleet.root).find(key, services(fleet))
|
||||
if host["revision"] != revision:
|
||||
raise ValueError("Настройки VPS изменились. Откройте их повторно.")
|
||||
return host
|
||||
|
||||
|
||||
@router.post("/{key}/removal")
|
||||
def prepare_removal(key: str, body: RemovalPreview, request: Request, fleet: Fleet) -> Document:
|
||||
return perform(
|
||||
lambda: ServerRemoval(fleet, request.app.state.system_connections_root).preview(
|
||||
removal_target(key, body.expected_revision, fleet)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/{key}")
|
||||
def remove(key: str, body: Removal, request: Request, fleet: Fleet) -> Document:
|
||||
return perform(
|
||||
lambda: ServerRemoval(fleet, request.app.state.system_connections_root).remove(
|
||||
removal_target(key, body.expected_revision, fleet), body.confirmation
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.put("/{key}")
|
||||
def update(key: str, body: Update, fleet: Fleet) -> Document:
|
||||
return perform(
|
||||
lambda: ServerCatalog(fleet.root).save(
|
||||
body.name, body.address, services(fleet), key, body.expected_revision
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{key}/services")
|
||||
def connect_service(key: str, body: ServiceImport, fleet: Fleet) -> Document:
|
||||
def connect() -> Document:
|
||||
catalog = ServerCatalog(fleet.root)
|
||||
host = catalog.find(key, services(fleet))
|
||||
if host["revision"] != body.expected_revision:
|
||||
raise ValueError("Настройки VPS изменились. Откройте их повторно.")
|
||||
parsed = (
|
||||
parse_file(body.document) # type: ignore[no-untyped-call] # existing invitation validator
|
||||
if body.kind == "wireguard"
|
||||
else invitation(body.document.strip())
|
||||
)
|
||||
if endpoint_address(parsed["endpoint"]) != host["address"]:
|
||||
raise ValueError("Приглашение выдано другим VPS. Проверьте адрес выбранного сервера.")
|
||||
if body.kind == "wireguard":
|
||||
fleet.network_profiles.import_file( # type: ignore[no-untyped-call] # existing admission authority
|
||||
body.document, host["name"], body.network_interface
|
||||
)
|
||||
else:
|
||||
arnavi_store(fleet).pair(body.document, host["name"], [], body.network_interface)
|
||||
# Membership derives from the authoritative registries: no second commit
|
||||
# can orphan a successfully paired service, including after a lost response.
|
||||
return catalog.find(key, services(fleet))
|
||||
|
||||
return perform(connect)
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Read-only, bounded live observations of already trusted VPS services."""
|
||||
|
||||
import asyncio
|
||||
import http.client
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
|
||||
from k1link.fleet.server_catalog import Document
|
||||
from k1link.fleet.vps_transport import request
|
||||
|
||||
|
||||
def probe(kind: str, row: Document, verify: Callable[[Document, Document], Document]) -> Document:
|
||||
try:
|
||||
value = request(row, "GET", "/v1/status")
|
||||
if kind == "wireguard":
|
||||
verify(row, value)
|
||||
elif value.get("schema") != "missioncore.vps-host/v1" or value.get("host_id") != row["id"]:
|
||||
raise ValueError("Service identity mismatch")
|
||||
state = "online"
|
||||
except (OSError, ValueError, KeyError, TypeError, http.client.HTTPException):
|
||||
state = "unavailable"
|
||||
return {"state": state, "checked_at": time.time()}
|
||||
|
||||
|
||||
class ServerHealth:
|
||||
"""RAM-only observations; no enrollment, tunnel apply, or profile writes."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.slots = asyncio.Semaphore(4)
|
||||
self.cache: dict[tuple[str, ...], tuple[float, Document]] = {}
|
||||
self.pending: dict[tuple[str, ...], asyncio.Task[Document]] = {}
|
||||
|
||||
async def observe(
|
||||
self, kind: str, row: Document, verify: Callable[[Document, Document], Document]
|
||||
) -> Document:
|
||||
# Changes to the trusted binding must invalidate its prior observation.
|
||||
key = tuple(str(x) for x in (
|
||||
kind, row.get("id", row.get("server_id")), row["endpoint"],
|
||||
row.get("fingerprint"), row.get("token"), row.get("network_interface"),
|
||||
))
|
||||
now = time.monotonic()
|
||||
self.cache = {k: v for k, v in self.cache.items() if now - v[0] < 15}
|
||||
if key in self.cache:
|
||||
return self.cache[key][1]
|
||||
task = self.pending.get(key)
|
||||
if task is None:
|
||||
async def run() -> Document:
|
||||
try:
|
||||
async with self.slots:
|
||||
value = await asyncio.to_thread(probe, kind, row, verify)
|
||||
if len(self.cache) >= 1024:
|
||||
self.cache.pop(next(iter(self.cache)))
|
||||
self.cache[key] = (time.monotonic(), value)
|
||||
return value
|
||||
finally:
|
||||
self.pending.pop(key, None)
|
||||
task = asyncio.create_task(run())
|
||||
self.pending[key] = task
|
||||
return await asyncio.shield(task)
|
||||
@@ -0,0 +1,175 @@
|
||||
from threading import RLock
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from k1link.fleet.server_catalog import ServerCatalog, address
|
||||
from k1link.web import server_catalog_api as api
|
||||
from k1link.web.fleet_api import local_operator
|
||||
|
||||
|
||||
def service(kind="wireguard", host="203.0.113.10", key="wg-one"):
|
||||
return dict(kind=kind, id=key, endpoint=f"https://{host}:19444", name=kind, state="ready")
|
||||
|
||||
|
||||
def test_projection_keeps_service_identity_and_has_no_credentials(tmp_path):
|
||||
s = ServerCatalog(tmp_path)
|
||||
original = [service(), service("arnavi", key="arnavi-one"), service(host="203.0.113.20")]
|
||||
rows = s.listing(original)
|
||||
assert len(rows) == 2
|
||||
assert len(rows[0]["services"]) == 2
|
||||
assert rows[0]["services"] == original[:2]
|
||||
assert ServerCatalog(tmp_path).listing(original) == rows
|
||||
assert s.listing([]) == [] # discovery does not create orphan durable entries
|
||||
|
||||
|
||||
def test_metadata_persists_without_renaming_services_and_revision_is_enforced(tmp_path):
|
||||
s = ServerCatalog(tmp_path)
|
||||
services = [service()]
|
||||
row = s.listing(services)[0]
|
||||
changed = s.save("Primary", row["address"], services, row["id"], 1)
|
||||
assert changed["revision"] == 2
|
||||
assert changed["services"] == services
|
||||
assert ServerCatalog(tmp_path).find(row["id"], services)["name"] == "Primary"
|
||||
with pytest.raises(ValueError, match="изменились"):
|
||||
s.save("Stale", row["address"], services, row["id"], 1)
|
||||
with pytest.raises(ValueError, match="переподключения"):
|
||||
s.save("Moved", "203.0.113.99", services, row["id"], 2)
|
||||
with pytest.raises(ValueError, match="уже есть"):
|
||||
s.save("Duplicate", row["address"], services)
|
||||
|
||||
|
||||
def test_create_and_edit_empty_server_preserve_id(tmp_path):
|
||||
s = ServerCatalog(tmp_path)
|
||||
row = s.save("Test", "Server.Example.COM.", [])
|
||||
assert row["address"] == "server.example.com"
|
||||
assert row["services"] == []
|
||||
changed = s.save("Renamed", "new.example.com", [], row["id"], 1)
|
||||
assert changed["id"] == row["id"]
|
||||
assert s.listing([service(host="new.example.com")])[0]["services"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
[
|
||||
"https://server.example.com",
|
||||
"server.example.com:443",
|
||||
"user@host.com",
|
||||
"999.999.1.1",
|
||||
"",
|
||||
"host; rm -rf /",
|
||||
],
|
||||
)
|
||||
def test_invalid_address(value):
|
||||
with pytest.raises(ValueError):
|
||||
address(value)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(tmp_path):
|
||||
hosts = SimpleNamespace(listing=Mock(return_value=[]), pair=Mock())
|
||||
profiles = SimpleNamespace(listing=Mock(return_value=[]), import_file=Mock())
|
||||
fleet = SimpleNamespace(root=tmp_path, vps_hosts=hosts, network_profiles=profiles, lock=RLock())
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
app.dependency_overrides[local_operator] = lambda: fleet
|
||||
with TestClient(app) as c:
|
||||
yield c, fleet, app
|
||||
|
||||
|
||||
def test_api_new_and_stale_update(client):
|
||||
c, fleet, _ = client
|
||||
r = c.post("/api/v1/system/servers", json=dict(name="Test", address="test.example.com"))
|
||||
assert r.status_code == 200
|
||||
key = r.json()["id"]
|
||||
payload = dict(name="Edited", address="test.example.com", expected_revision=1)
|
||||
assert c.put(f"/api/v1/system/servers/{key}", json=payload).status_code == 200
|
||||
assert c.put(f"/api/v1/system/servers/{key}", json=payload).status_code == 409
|
||||
assert c.get("/api/v1/system/servers").json()["items"][0]["name"] == "Edited"
|
||||
fleet.vps_hosts.pair.assert_not_called()
|
||||
fleet.network_profiles.import_file.assert_not_called()
|
||||
|
||||
|
||||
def test_health_only_checks_the_selected_hosts_existing_bindings(client, monkeypatch):
|
||||
from k1link.web import server_health
|
||||
|
||||
c, fleet, _ = client
|
||||
wg = dict(
|
||||
id="wg-one", server_id="wg-one", name="WG",
|
||||
endpoint="https://one.example:19444", state="ready",
|
||||
)
|
||||
other = {**wg, "id": "wg-two", "server_id": "wg-two", "endpoint": "https://two.example:19444"}
|
||||
fleet.network_profiles.listing.return_value = [wg, other]
|
||||
fleet.network_profiles.lock = RLock()
|
||||
fleet.network_profiles.profiles = {"one": wg, "two": other}
|
||||
fleet.network_profiles.verify_status = Mock()
|
||||
fleet.vps_hosts.rows = Mock(return_value=[])
|
||||
probe = Mock(return_value={"state": "online", "checked_at": 100})
|
||||
monkeypatch.setattr(server_health, "probe", probe)
|
||||
key = next(
|
||||
x["id"] for x in c.get("/api/v1/system/servers").json()["items"]
|
||||
if x["address"] == "one.example"
|
||||
)
|
||||
result = c.get(f"/api/v1/system/servers/{key}/health")
|
||||
assert result.status_code == 200
|
||||
assert result.json()["items"] == [
|
||||
dict(id="wg-one", kind="wireguard", state="online", checked_at=100)
|
||||
]
|
||||
assert probe.call_args.args[1]["server_id"] == "wg-one"
|
||||
assert c.get("/api/v1/system/servers/unknown/health").status_code == 409
|
||||
fleet.network_profiles.import_file.assert_not_called()
|
||||
fleet.vps_hosts.pair.assert_not_called()
|
||||
|
||||
|
||||
def test_import_rejects_wrong_host_before_admission(client, monkeypatch):
|
||||
c, fleet, _ = client
|
||||
key = c.post(
|
||||
"/api/v1/system/servers", json=dict(name="Test", address="test.example.com")
|
||||
).json()["id"]
|
||||
monkeypatch.setattr(
|
||||
api, "parse_file", lambda _: dict(endpoint="https://other.example.com:19444")
|
||||
)
|
||||
assert (
|
||||
c.post(
|
||||
f"/api/v1/system/servers/{key}/services",
|
||||
json=dict(kind="wireguard", document="invitation", expected_revision=1),
|
||||
).status_code
|
||||
== 409
|
||||
)
|
||||
fleet.network_profiles.import_file.assert_not_called()
|
||||
|
||||
|
||||
def test_successful_admission_is_visible_without_second_persistence(client, monkeypatch):
|
||||
c, fleet, _ = client
|
||||
key = c.post(
|
||||
"/api/v1/system/servers", json=dict(name="Test", address="test.example.com")
|
||||
).json()["id"]
|
||||
monkeypatch.setattr(
|
||||
api, "parse_file", lambda _: dict(endpoint="https://test.example.com:19444")
|
||||
)
|
||||
row = dict(id="wg-one", name="Test", endpoint="https://test.example.com:19444", state="ready")
|
||||
fleet.network_profiles.import_file.side_effect = lambda *_: setattr(
|
||||
fleet.network_profiles.listing, "return_value", [row]
|
||||
)
|
||||
payload = dict(kind="wireguard", document="invitation", expected_revision=1)
|
||||
r = c.post(f"/api/v1/system/servers/{key}/services", json=payload)
|
||||
assert r.status_code == 200
|
||||
assert r.json()["services"][0]["id"] == "wg-one"
|
||||
assert c.get("/api/v1/system/servers").json()["items"][0]["services"][0]["id"] == "wg-one"
|
||||
|
||||
|
||||
def test_unavailable_service_store_does_not_look_empty(client):
|
||||
c, fleet, _ = client
|
||||
fleet.vps_hosts = None
|
||||
assert c.get("/api/v1/system/servers").status_code == 503
|
||||
|
||||
|
||||
def test_local_operator_required(client):
|
||||
c, _, app = client
|
||||
app.dependency_overrides.clear()
|
||||
assert c.post(
|
||||
"/api/v1/system/servers", json=dict(name="Test", address="test.example.com")
|
||||
).status_code in (401, 403, 503)
|
||||
@@ -0,0 +1,45 @@
|
||||
import asyncio
|
||||
from unittest.mock import Mock
|
||||
|
||||
from k1link.web import server_health as health
|
||||
|
||||
|
||||
def test_probe_is_read_only_and_rejects_wrong_identity(monkeypatch):
|
||||
request = Mock(return_value={"schema": "missioncore.vps-host/v1", "host_id": "other"})
|
||||
monkeypatch.setattr(health, "request", request)
|
||||
row = {"id": "ours"}
|
||||
assert health.probe("arnavi", row, Mock())["state"] == "unavailable"
|
||||
request.assert_called_once_with(row, "GET", "/v1/status")
|
||||
request.return_value["host_id"] = "ours"
|
||||
assert health.probe("arnavi", row, Mock())["state"] == "online"
|
||||
request.side_effect = TimeoutError()
|
||||
assert health.probe("arnavi", row, Mock())["state"] == "unavailable"
|
||||
|
||||
|
||||
def test_wireguard_requires_existing_identity_validator(monkeypatch):
|
||||
monkeypatch.setattr(health, "request", Mock(return_value={"schema": "wrong"}))
|
||||
verify = Mock(side_effect=ValueError("mismatch"))
|
||||
assert health.probe("wireguard", {}, verify)["state"] == "unavailable"
|
||||
verify.assert_called_once()
|
||||
|
||||
|
||||
def test_concurrent_checks_share_bounded_cache_and_binding_change_invalidates(monkeypatch):
|
||||
probe = Mock(return_value={"state": "online", "checked_at": 100})
|
||||
monkeypatch.setattr(health, "probe", probe)
|
||||
|
||||
async def scenario():
|
||||
service = health.ServerHealth()
|
||||
row = {"id": "one", "endpoint": "https://example:19443", "token": "old"}
|
||||
replies = await asyncio.gather(*(service.observe("arnavi", row, Mock()) for _ in range(10)))
|
||||
assert all(r["state"] == "online" for r in replies)
|
||||
assert probe.call_count == 1
|
||||
await service.observe("arnavi", row, Mock())
|
||||
assert probe.call_count == 1
|
||||
await service.observe("arnavi", {**row, "token": "changed"}, Mock())
|
||||
assert probe.call_count == 2
|
||||
service.cache = {k: (0, v) for k, (_, v) in service.cache.items()}
|
||||
probe.return_value = {"state": "unavailable", "checked_at": 101}
|
||||
assert (await service.observe("arnavi", row, Mock()))["state"] == "unavailable"
|
||||
assert not service.pending
|
||||
|
||||
asyncio.run(scenario())
|
||||
@@ -0,0 +1,287 @@
|
||||
import copy
|
||||
import json
|
||||
from threading import RLock
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.compute_connections.store import Connection, NetworkProfile, Registry, WorkerBinding
|
||||
from k1link.fleet.independent_equipment import EquipmentStore
|
||||
from k1link.fleet.network_profiles import NetworkProfiles
|
||||
from k1link.fleet.server_removal import ServerRemoval
|
||||
from k1link.fleet.vps_hosts import VPSHosts
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def setup(tmp_path, monkeypatch):
|
||||
from k1link.fleet import server_removal
|
||||
|
||||
fleet = SimpleNamespace(root=tmp_path, lock=RLock(), listeners={})
|
||||
fleet.network_profiles = NetworkProfiles(fleet)
|
||||
fleet.vps_hosts = VPSHosts(tmp_path, "core-test", EquipmentStore(tmp_path, {}))
|
||||
vehicles = []
|
||||
fleet.rows = lambda: copy.deepcopy(vehicles)
|
||||
fleet.save = lambda row: vehicles.__setitem__(
|
||||
next(i for i, v in enumerate(vehicles) if v["id"] == row["id"]), copy.deepcopy(row)
|
||||
)
|
||||
ensure, helper = Mock(), Mock(return_value={"removed": True})
|
||||
monkeypatch.setattr(server_removal.network_client, "ensure", ensure)
|
||||
monkeypatch.setattr(server_removal.network_client, "request", helper)
|
||||
manager = ServerRemoval(fleet, tmp_path / "system")
|
||||
host = manager.catalog.save("Chosen VPS", "one.example", [])
|
||||
return manager, host, vehicles, ensure, helper
|
||||
|
||||
|
||||
def seed(manager, vehicles):
|
||||
for name, address in [("one", "one.example"), ("two", "two.example")]:
|
||||
manager.networks.profiles[name] = dict(
|
||||
server_id=name,
|
||||
endpoint=f"https://{address}:19444",
|
||||
name=name,
|
||||
state="ready",
|
||||
subnet="10.203.1.0/24" if name == "one" else "10.203.2.0/24",
|
||||
token="private-" + name,
|
||||
)
|
||||
manager.hosts.save(
|
||||
dict(
|
||||
id=name,
|
||||
endpoint=f"https://{address}:19443",
|
||||
revision=1,
|
||||
fingerprint="fingerprint-" + name,
|
||||
token="arnavi-" + name,
|
||||
state="paired",
|
||||
vehicle_ids=["vehicle"],
|
||||
)
|
||||
)
|
||||
manager.networks.save()
|
||||
vehicles.append(
|
||||
dict(
|
||||
id="vehicle",
|
||||
name="Vehicle",
|
||||
network_active="tailscale",
|
||||
network_paths={"one": {"core": "10.203.1.2"}, "two": {"core": "10.203.2.2"}},
|
||||
)
|
||||
)
|
||||
worker = WorkerBinding(
|
||||
contour_id="worker",
|
||||
host_key_sha256="SHA256:" + "a" * 43,
|
||||
transport_id="transport",
|
||||
active_connection_id="path-two",
|
||||
connections=(
|
||||
Connection(
|
||||
id="path-one", profile_id="profile-one", endpoint="one.example", peer_id="peer"
|
||||
),
|
||||
Connection(
|
||||
id="path-two", profile_id="profile-two", endpoint="two.example", peer_id="peer"
|
||||
),
|
||||
),
|
||||
)
|
||||
profiles = tuple(
|
||||
NetworkProfile(id="profile-" + name, name=name, provider="wireguard", network_id=name)
|
||||
for name in ("one", "two")
|
||||
)
|
||||
with manager.connections.locked():
|
||||
manager.connections._write(Registry(profiles=profiles, workers=(worker,)))
|
||||
|
||||
|
||||
def test_empty_server_delete_and_stale_name(setup):
|
||||
manager, host, _, ensure, helper = setup
|
||||
first = manager.preview(host)
|
||||
changed = manager.catalog.save("Changed", host["address"], [], host["id"], 1)
|
||||
with pytest.raises(ValueError, match="изменились"):
|
||||
manager.remove(changed, first["confirmation"])
|
||||
manager.remove(changed, manager.preview(changed)["confirmation"])
|
||||
assert manager.catalog.listing([]) == []
|
||||
ensure.assert_not_called()
|
||||
helper.assert_not_called()
|
||||
|
||||
|
||||
def test_cascade_keeps_other_vps_devices_and_active_worker_connection(setup):
|
||||
manager, host, vehicles, ensure, helper = setup
|
||||
seed(manager, vehicles)
|
||||
unrelated = copy.deepcopy(manager.networks.profiles["two"])
|
||||
listener = Mock()
|
||||
manager.fleet.listeners["10.203.1.2"] = listener
|
||||
with manager.hosts.db() as db:
|
||||
db.execute("INSERT INTO packets VALUES('one',1,'dev-one',1,?)", (b"packet",))
|
||||
db.execute("INSERT INTO packets VALUES('two',1,'dev-two',1,?)", (b"keep",))
|
||||
db.execute("INSERT INTO links VALUES('dev-one','one',1)")
|
||||
db.execute("INSERT INTO positions VALUES('dev-one','{}')")
|
||||
plan = manager.preview(host)
|
||||
assert plan["blocked"] == []
|
||||
assert plan["services"] == ["ARNavi", "WireGuard"]
|
||||
assert plan["worker_connections"] == plan["vehicle_connections"] == 1
|
||||
assert manager.remove(host, plan["confirmation"])["removed"]
|
||||
helper.assert_called_once_with("forget", "one")
|
||||
ensure.assert_called_once()
|
||||
listener.shutdown.assert_called_once()
|
||||
listener.server_close.assert_called_once()
|
||||
assert manager.networks.profiles == {"two": unrelated}
|
||||
assert [r["id"] for r in manager.hosts.rows()] == ["two"]
|
||||
assert list(vehicles[0]["network_paths"]) == ["two"]
|
||||
registry = manager.connections.read()
|
||||
assert [p.id for p in registry.profiles] == ["profile-two"]
|
||||
worker = registry.workers[0]
|
||||
assert worker.active_connection_id == "path-two"
|
||||
assert [c.id for c in worker.connections] == ["path-two"]
|
||||
assert worker.revision == 1
|
||||
assert manager.catalog.listing([]) == []
|
||||
with manager.hosts.db() as db:
|
||||
assert db.execute("SELECT host FROM packets").fetchall() == [("two",)]
|
||||
assert db.execute("SELECT * FROM links").fetchall() == []
|
||||
assert db.execute("SELECT * FROM positions").fetchall() == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("consumer", ["worker", "board", "unknown-board", "command", "outbox"])
|
||||
def test_active_or_pending_consumers_block_before_any_mutation(setup, consumer):
|
||||
manager, host, vehicles, ensure, helper = setup
|
||||
seed(manager, vehicles)
|
||||
if consumer == "worker":
|
||||
manager.connections.select("worker", "path-one", expected_revision=0)
|
||||
if consumer == "board":
|
||||
vehicles[0]["network_active"] = "one"
|
||||
if consumer == "unknown-board":
|
||||
vehicles[0].pop("network_active")
|
||||
if consumer == "command":
|
||||
with manager.hosts.equipment.db() as db:
|
||||
db.execute(
|
||||
"INSERT INTO command_journal(id,instance,state,body) "
|
||||
"VALUES('cmd','dev','queued',?)",
|
||||
(json.dumps({"host_id": "one"}),),
|
||||
)
|
||||
if consumer == "outbox":
|
||||
with manager.hosts.equipment.db() as db:
|
||||
db.execute(
|
||||
"INSERT INTO network_outbox(id,instance,host,target,body) "
|
||||
"VALUES('cmd','dev','two','one','{}')"
|
||||
)
|
||||
before = manager.connections.path.read_bytes()
|
||||
plan = manager.preview(host)
|
||||
assert plan["blocked"]
|
||||
with pytest.raises(ValueError):
|
||||
manager.remove(host, plan["confirmation"])
|
||||
assert manager.connections.path.read_bytes() == before
|
||||
assert len(manager.hosts.rows()) == len(manager.networks.profiles) == 2
|
||||
ensure.assert_not_called()
|
||||
helper.assert_not_called()
|
||||
|
||||
|
||||
def test_new_service_invalidates_confirmation(setup):
|
||||
manager, host, vehicles, _, helper = setup
|
||||
old = manager.preview(host)
|
||||
seed(manager, vehicles)
|
||||
with pytest.raises(ValueError, match="изменились"):
|
||||
manager.remove(host, old["confirmation"])
|
||||
helper.assert_not_called()
|
||||
|
||||
|
||||
def test_helper_failure_preserves_connections_and_retryable_server(setup):
|
||||
manager, host, vehicles, _, helper = setup
|
||||
seed(manager, vehicles)
|
||||
helper.side_effect = OSError("helper unavailable")
|
||||
before = manager.connections.path.read_bytes()
|
||||
with pytest.raises(OSError):
|
||||
manager.remove(host, manager.preview(host)["confirmation"])
|
||||
assert manager.catalog.find(host["id"], [])["name"] == host["name"]
|
||||
assert manager.connections.path.read_bytes() == before
|
||||
assert len(manager.hosts.rows()) == len(manager.networks.profiles) == 2
|
||||
|
||||
|
||||
def test_interrupted_profile_write_is_retryable_and_never_reports_success(setup, monkeypatch):
|
||||
manager, host, vehicles, _, _ = setup
|
||||
seed(manager, vehicles)
|
||||
save = manager.networks.save
|
||||
monkeypatch.setattr(manager.networks, "save", Mock(side_effect=OSError("write failed")))
|
||||
with pytest.raises(OSError):
|
||||
manager.remove(host, manager.preview(host)["confirmation"])
|
||||
assert "one" in manager.networks.profiles
|
||||
assert len(manager.hosts.rows()) == 2
|
||||
assert manager.catalog.find(host["id"], [])
|
||||
monkeypatch.setattr(manager.networks, "save", save)
|
||||
assert manager.remove(host, manager.preview(host)["confirmation"])["removed"]
|
||||
assert "one" not in manager.networks.profiles
|
||||
assert [r["id"] for r in manager.hosts.rows()] == ["two"]
|
||||
|
||||
|
||||
def test_api_requires_fresh_confirmation_and_local_operator(setup):
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from k1link.web import server_catalog_api as api
|
||||
from k1link.web.fleet_api import local_operator
|
||||
|
||||
manager, host, _, ensure, helper = setup
|
||||
app = FastAPI()
|
||||
app.state.system_connections_root = manager.connections.path.parent
|
||||
app.include_router(api.router)
|
||||
app.dependency_overrides[local_operator] = lambda: manager.fleet
|
||||
path = "/api/v1/system/servers/" + host["id"]
|
||||
with TestClient(app) as client:
|
||||
assert client.request("DELETE", path, json={"expected_revision": 1}).status_code == 422
|
||||
plan = client.post(path + "/removal", json={"expected_revision": 1})
|
||||
assert plan.status_code == 200
|
||||
body = dict(expected_revision=1, confirmation=plan.json()["confirmation"])
|
||||
assert (
|
||||
client.request("DELETE", path, json={**body, "confirmation": "0" * 64}).status_code
|
||||
== 409
|
||||
)
|
||||
assert client.request("DELETE", path, json=body).status_code == 200
|
||||
assert client.get("/api/v1/system/servers").json()["items"] == []
|
||||
app.dependency_overrides.clear()
|
||||
assert client.request("DELETE", path, json=body).status_code in (401, 403, 503)
|
||||
ensure.assert_not_called()
|
||||
helper.assert_not_called()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def helper_manager(tmp_path):
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"removal_helper", Path(__file__).resolve().parents[1] / "apps/wireguard-client/helper.py"
|
||||
)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
manager = module.Manager(tmp_path)
|
||||
one, two = "wg_" + "1" * 32, "wg_" + "2" * 32
|
||||
row = dict(
|
||||
private_key="private", public_key="public", config=None, interface=None, pending=None
|
||||
)
|
||||
manager.profiles = {one: copy.deepcopy(row), two: copy.deepcopy(row)}
|
||||
manager.persist()
|
||||
return manager, one, two
|
||||
|
||||
|
||||
def test_helper_forgets_only_selected_profile_and_is_idempotent(helper_manager):
|
||||
manager, one, two = helper_manager
|
||||
manager.down = Mock()
|
||||
manager.prepare = Mock(side_effect=AssertionError("Must not create a profile"))
|
||||
assert manager.dispatch(dict(action="forget", server_id=one))["removed"]
|
||||
assert list(json.loads(manager.path.read_text())) == [two]
|
||||
assert manager.dispatch(dict(action="forget", server_id=one))["removed"]
|
||||
manager.down.assert_called_once()
|
||||
manager.prepare.assert_not_called()
|
||||
|
||||
|
||||
def test_helper_refuses_pending_or_foreign_tunnel_and_retains_profile(helper_manager):
|
||||
manager, one, two = helper_manager
|
||||
manager.down = Mock(side_effect=ValueError("Foreign interface"))
|
||||
manager.profiles[one]["pending"] = {"id": "operation"}
|
||||
with pytest.raises(ValueError, match="pending"):
|
||||
manager.dispatch(dict(action="forget", server_id=one))
|
||||
manager.down.assert_not_called()
|
||||
manager.profiles[one]["pending"] = None
|
||||
with pytest.raises(ValueError, match="Foreign"):
|
||||
manager.dispatch(dict(action="forget", server_id=one))
|
||||
assert set(manager.profiles) == {one, two}
|
||||
|
||||
|
||||
def test_helper_failed_persistence_retains_retryable_profile(helper_manager):
|
||||
manager, one, two = helper_manager
|
||||
manager.down = Mock()
|
||||
manager.persist = Mock(side_effect=OSError("full disk"))
|
||||
with pytest.raises(OSError):
|
||||
manager.dispatch(dict(action="forget", server_id=one))
|
||||
assert set(manager.profiles) == {one, two}
|
||||
Reference in New Issue
Block a user