feat(system): add worker and VPS catalogs with guarded local removal
This commit is contained in:
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user