Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5a46594ec9 |
No files matched your search
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
import { useEffect, useState, type ReactNode } from "react"
|
import { useEffect, useState, type ReactNode } from "react"
|
||||||
import type { IxBondBundle, IxBondCandidate, IxBondCatalog, IxBondEdit, IxBondMode, IxSavedBond, IxSegment } from "@mmapp/contracts/internet-exchange"
|
import type { IxBondBundle, IxBondCandidate, IxBondCatalog, IxBondEdit, IxBondMode, IxSavedBond, IxSegment } from "@mmapp/contracts/internet-exchange"
|
||||||
import { Frame, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
|
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { Checkbox } from "@/components/ui/checkbox"
|
import { Checkbox } from "@/components/ui/checkbox"
|
||||||
import { Input } from "@/components/ui/input"
|
import { Input } from "@/components/ui/input"
|
||||||
@@ -29,7 +28,7 @@ const modeLabel = (mode: IxBondMode) => modes.find(item => item.value === mode)?
|
|||||||
export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly, download, live, children }: {
|
export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly, download, live, children }: {
|
||||||
segmentId: string; segments: IxSegment[]; backendUrl: string; nodes: IxNode[]; readOnly: boolean; live: boolean
|
segmentId: string; segments: IxSegment[]; backendUrl: string; nodes: IxNode[]; readOnly: boolean; live: boolean
|
||||||
download: (filename: string, text: string) => void
|
download: (filename: string, text: string) => void
|
||||||
children: (action: IxRowBondAction, catalog: IxBondCatalog) => ReactNode
|
children: (action: IxRowBondAction, catalog: IxBondCatalog, groups: (clientId: string) => ReactNode, unassigned: ReactNode) => ReactNode
|
||||||
}) {
|
}) {
|
||||||
const [catalog, setCatalog] = useState<IxBondCatalog>({ groups: [], candidates: [] })
|
const [catalog, setCatalog] = useState<IxBondCatalog>({ groups: [], candidates: [] })
|
||||||
const [reload, setReload] = useState(0)
|
const [reload, setReload] = useState(0)
|
||||||
@@ -93,29 +92,7 @@ export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly
|
|||||||
const needsConfirmation = selected.length > 1 && selected.some(c => !c.clientId && !previous?.members.some(m => memberKey(m) === memberKey(c)))
|
const needsConfirmation = selected.length > 1 && selected.some(c => !c.clientId && !previous?.members.some(m => memberKey(m) === memberKey(c)))
|
||||||
const selectionKey = selected.map(memberKey).sort().join(",")
|
const selectionKey = selected.map(memberKey).sort().join(",")
|
||||||
const issue = error && <p role="alert" className="text-sm text-destructive">{error}</p>
|
const issue = error && <p role="alert" className="text-sm text-destructive">{error}</p>
|
||||||
const rows = children(binding => {
|
const renderGroups = (clientId: string) => ownedGroups.filter(g => g.clientId === clientId).map(g => <div key={g.id} className="grid gap-1.5">
|
||||||
const k = memberKey({ ...binding, segmentId })
|
|
||||||
const current = ownedGroups.find(g => g.members.some(m => memberKey(m) === k))
|
|
||||||
const candidate = available.get(k)
|
|
||||||
if (current) return { label: "Открыть группу «" + current.name + "»", open: () => open(current) }
|
|
||||||
if (candidate?.destinations.length) return { label: "Создать группу с этим туннелем", open: () => open(undefined, candidate) }
|
|
||||||
const site = segments.find(s => s.id === segmentId)?.configuration.sites.find(s => s.serverId === binding.serverId)
|
|
||||||
const saved = site?.interfaces.find(b => b.name === binding.interfaceName)
|
|
||||||
if (saved && saved.kind !== "uplink" && !saved.peerServerId && !saved.linux && !saved.provisionWireguard && !saved.provisionGre &&
|
|
||||||
!saved.provisionTransit && !site?.neighbors.some(p => p.binding === saved.name)) {
|
|
||||||
return { label: "Создать группу с этим туннелем", open: () => { open(); setInitialInterface(binding); setImporting(true) } }
|
|
||||||
}
|
|
||||||
}, catalog)
|
|
||||||
if (!live) return <>{rows}</>
|
|
||||||
return <>{rows}<Frame spacing="sm">
|
|
||||||
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
|
|
||||||
<FrameTitle>Группы туннелей VPS</FrameTitle>
|
|
||||||
{!readOnly && <Button size="sm" variant="outline" onClick={() => open()}>Создать группу</Button>}
|
|
||||||
</FrameHeader>
|
|
||||||
<FramePanel className="grid gap-3">
|
|
||||||
{!draft && issue}
|
|
||||||
{!ownedGroups.length && <p className="text-sm text-muted-foreground">Туннели этого сегмента используются отдельно.</p>}
|
|
||||||
{ownedGroups.map(g => <div key={g.id} className="grid gap-1.5">
|
|
||||||
<span className="font-medium">{g.name} · {modeLabel(g.mode)}</span>
|
<span className="font-medium">{g.name} · {modeLabel(g.mode)}</span>
|
||||||
<ol className="grid gap-1 text-sm">{g.members.map((m, i) => {
|
<ol className="grid gap-1 text-sm">{g.members.map((m, i) => {
|
||||||
const c = available.get(memberKey(m))
|
const c = available.get(memberKey(m))
|
||||||
@@ -131,9 +108,23 @@ export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly
|
|||||||
download("ix-bond-" + g.id + ".json", JSON.stringify(bundle, null, 2))
|
download("ix-bond-" + g.id + ".json", JSON.stringify(bundle, null, 2))
|
||||||
})}>Скачать для ix-client</Button>
|
})}>Скачать для ix-client</Button>
|
||||||
</div>}
|
</div>}
|
||||||
</div>)}
|
</div>)
|
||||||
{!!ownedGroups.length && <p className="text-sm text-muted-foreground">Импортируйте JSON в ix-client на VPS и сверьте выбранные локальные интерфейсы. Активный путь показывает TUI клиента.</p>}
|
const rows = children(binding => {
|
||||||
</FramePanel>
|
const k = memberKey({ ...binding, segmentId })
|
||||||
|
const current = ownedGroups.find(g => g.members.some(m => memberKey(m) === k))
|
||||||
|
const candidate = available.get(k)
|
||||||
|
if (current) return { label: "Открыть группу «" + current.name + "»", open: () => open(current) }
|
||||||
|
if (candidate?.destinations.length) return { label: "Создать группу с этим туннелем", open: () => open(undefined, candidate) }
|
||||||
|
const site = segments.find(s => s.id === segmentId)?.configuration.sites.find(s => s.serverId === binding.serverId)
|
||||||
|
const saved = site?.interfaces.find(b => b.name === binding.interfaceName)
|
||||||
|
if (saved && saved.kind !== "uplink" && !saved.peerServerId && !saved.linux && !saved.provisionWireguard && !saved.provisionGre &&
|
||||||
|
!saved.provisionTransit && !site?.neighbors.some(p => p.binding === saved.name)) {
|
||||||
|
return { label: "Создать группу с этим туннелем", open: () => { open(); setInitialInterface(binding); setImporting(true) } }
|
||||||
|
}
|
||||||
|
}, catalog, renderGroups, live && !readOnly &&
|
||||||
|
<Button size="sm" variant="outline" onClick={() => open()}>Создать группу вручную</Button>)
|
||||||
|
if (!live) return <>{rows}</>
|
||||||
|
return <>{rows}{!draft && issue}
|
||||||
<Sheet open={!!draft} onOpenChange={value => !value && !busy && setDraft(null)}>
|
<Sheet open={!!draft} onOpenChange={value => !value && !busy && setDraft(null)}>
|
||||||
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-xl">
|
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-xl">
|
||||||
<SheetHeader><SheetTitle>Группа туннелей VPS</SheetTitle>
|
<SheetHeader><SheetTitle>Группа туннелей VPS</SheetTitle>
|
||||||
@@ -204,5 +195,5 @@ export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly
|
|||||||
</form>}
|
</form>}
|
||||||
</SheetContent>
|
</SheetContent>
|
||||||
</Sheet>
|
</Sheet>
|
||||||
</Frame></>
|
</>
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useMemo, useState } from "react"
|
import { useMemo, useState, type ReactNode } from "react"
|
||||||
import { type ColumnDef, useTable } from "@tanstack/react-table"
|
import { type ColumnDef, useTable } from "@tanstack/react-table"
|
||||||
import { EllipsisIcon, PencilIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
|
import { EllipsisIcon, PencilIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
|
||||||
import type { IxBondCatalog, IxLinuxBinding, IxLinuxClientRequest, IxSegment, IxSite } from "@mmapp/contracts/internet-exchange"
|
import type { IxBondCatalog, IxLinuxBinding, IxLinuxClientRequest, IxSegment, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||||
@@ -17,6 +17,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
|
|||||||
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
|
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
|
||||||
import { Textarea } from "@/components/ui/textarea"
|
import { Textarea } from "@/components/ui/textarea"
|
||||||
import { isIpv4String } from "@/lib/gre-endpoint-resolve"
|
import { isIpv4String } from "@/lib/gre-endpoint-resolve"
|
||||||
|
import { formatBytes } from "@/lib/fmt-rate"
|
||||||
import { publicEndpoint, transitName } from "./ix-exits"
|
import { publicEndpoint, transitName } from "./ix-exits"
|
||||||
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
|
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
|
||||||
import type { IxRowBondAction } from "./ix-client-bonds"
|
import type { IxRowBondAction } from "./ix-client-bonds"
|
||||||
@@ -230,12 +231,21 @@ function ClientForm({ segment, edit, setAddProtocol, nodes, backendUrl, catalog,
|
|||||||
</form>
|
</form>
|
||||||
}
|
}
|
||||||
|
|
||||||
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, inspect, bondAction, catalog }: {
|
function TunnelTable({ data, columns, busy }: {
|
||||||
|
data: IxLinuxBinding[]; columns: ColumnDef<DataGridFeatures, IxLinuxBinding>[]; busy: boolean
|
||||||
|
}) {
|
||||||
|
const table = useTable({ features: dataGridFeatures, manualPagination: true, data, columns,
|
||||||
|
getRowId: row => row.serverId + ":" + row.interfaceName })
|
||||||
|
return <DataGridShell table={table} recordCount={data.length} isLoading={busy && !data.length} loadingMode="skeleton" emptyMessage="В сегменте пока нет Linux-клиентов" />
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, inspect, bondAction, catalog, renderGroups, manualGroup }: {
|
||||||
segment: IxSegment; nodes: IxNode[]; backendUrl: string; applied: IxLinuxBinding[]; readOnly: boolean; busy: boolean; error?: string
|
segment: IxSegment; nodes: IxNode[]; backendUrl: string; applied: IxLinuxBinding[]; readOnly: boolean; busy: boolean; error?: string
|
||||||
save: (input: IxLinuxClientRequest) => Promise<boolean>; refresh: () => void
|
save: (input: IxLinuxClientRequest) => Promise<boolean>; refresh: () => void
|
||||||
view: (binding: IxLinuxBinding, transportOnly?: boolean) => void; revoke: (binding: IxLinuxBinding) => void
|
view: (binding: IxLinuxBinding, transportOnly?: boolean) => void; revoke: (binding: IxLinuxBinding) => void
|
||||||
inspect: (binding: IxLinuxBinding) => void
|
inspect: (binding: IxLinuxBinding) => void
|
||||||
bondAction: IxRowBondAction; catalog: IxBondCatalog
|
bondAction: IxRowBondAction; catalog: IxBondCatalog
|
||||||
|
renderGroups: (clientId: string) => ReactNode; manualGroup: ReactNode
|
||||||
}) {
|
}) {
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
const [edit, setEdit] = useState<ClientSelection | null>(null)
|
const [edit, setEdit] = useState<ClientSelection | null>(null)
|
||||||
@@ -247,10 +257,27 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
|
|||||||
}] : []))
|
}] : []))
|
||||||
return [...saved, ...applied.filter(binding => !saved.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName))]
|
return [...saved, ...applied.filter(binding => !saved.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName))]
|
||||||
}, [segment, applied])
|
}, [segment, applied])
|
||||||
|
const clients = new Map<string, { name: string; tunnels: IxLinuxBinding[]; hasGroups: boolean }>()
|
||||||
|
const relevantGroups = catalog.groups.filter(group => group.members.some(member => member.segmentId === segment.id))
|
||||||
|
const tunnelKey = (binding: Pick<IxLinuxBinding, "serverId" | "interfaceName">) => binding.serverId + ":" + binding.interfaceName
|
||||||
|
const affiliations = new Map(relevantGroups.flatMap(group => group.members.filter(member => member.segmentId === segment.id)
|
||||||
|
.map(member => [tunnelKey(member), group.clientId] as const)))
|
||||||
|
for (const row of rows) {
|
||||||
|
const key = affiliations.get(tunnelKey(row)) ?? row.policy?.clientId ?? tunnelKey(row)
|
||||||
|
const client = clients.get(key) ?? { name: row.name ?? row.interfaceName, tunnels: [], hasGroups: false }
|
||||||
|
if (row.name && !client.tunnels.some(tunnel => tunnel.name)) client.name = row.name
|
||||||
|
client.tunnels.push(row)
|
||||||
|
clients.set(key, client)
|
||||||
|
}
|
||||||
|
for (const group of relevantGroups) {
|
||||||
|
const client = clients.get(group.clientId) ?? { name: group.name, tunnels: [], hasGroups: false }
|
||||||
|
client.hasGroups = true
|
||||||
|
clients.set(group.clientId, client)
|
||||||
|
}
|
||||||
const columns = useMemo<ColumnDef<DataGridFeatures, IxLinuxBinding>[]>(() => [
|
const columns = useMemo<ColumnDef<DataGridFeatures, IxLinuxBinding>[]>(() => [
|
||||||
{ id: "name", header: "Клиент", size: 170, cell: ({ row }) => <div className="grid gap-0.5">
|
{ id: "name", header: "Интерфейс", size: 195, cell: ({ row }) => <div className="grid gap-0.5">
|
||||||
<span className="font-medium">{row.original.name ?? row.original.interfaceName}</span>
|
<span className="break-all font-medium">{row.original.interfaceName}</span>
|
||||||
<span className="text-xs text-muted-foreground">{nodeLabel(nodes, row.original.serverId)} · {row.original.interfaceName}</span>
|
<span className="text-xs text-muted-foreground">{nodeLabel(nodes, row.original.serverId)}</span>
|
||||||
</div> },
|
</div> },
|
||||||
{ id: "transport", header: "Туннель", size: 105, cell: ({ row }) => row.original.kind === "wireguard" ? "WireGuard" : "GRE/IPsec" },
|
{ id: "transport", header: "Туннель", size: 105, cell: ({ row }) => row.original.kind === "wireguard" ? "WireGuard" : "GRE/IPsec" },
|
||||||
{ id: "egress", header: "Выход трафика", size: 205, cell: ({ row }) => {
|
{ id: "egress", header: "Выход трафика", size: 205, cell: ({ row }) => {
|
||||||
@@ -274,11 +301,15 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
|
|||||||
if (!site?.interfaces.some(item => item.name === binding.interfaceName)) return <Badge variant="warning-light">Ожидает отзыва</Badge>
|
if (!site?.interfaces.some(item => item.name === binding.interfaceName)) return <Badge variant="warning-light">Ожидает отзыва</Badge>
|
||||||
if (!live || JSON.stringify(binding.policy) !== JSON.stringify(live.policy)) return <Badge variant="warning-light">Ожидает сохранения</Badge>
|
if (!live || JSON.stringify(binding.policy) !== JSON.stringify(live.policy)) return <Badge variant="warning-light">Ожидает сохранения</Badge>
|
||||||
if (!binding.enabled) return <Badge variant="secondary">Приостановлен</Badge>
|
if (!binding.enabled) return <Badge variant="secondary">Приостановлен</Badge>
|
||||||
return binding.connection?.state === "connected" ? <div className="grid gap-1">
|
const { state, rx, tx } = binding.connection ?? {}
|
||||||
<Badge variant="success-light" className="w-fit">Подключён</Badge>
|
return <div className="grid gap-1">
|
||||||
{binding.connection.rx !== undefined && <span className="text-xs text-muted-foreground">RX {binding.connection.rx} · TX {binding.connection.tx}</span>}
|
<Badge className="w-fit" variant={state === "connected" ? "success-light" : "secondary"}>
|
||||||
|
{state === "connected" ? "Подключён" : state === "waiting" ? "Ожидает туннель" : "Нет данных"}
|
||||||
|
</Badge>
|
||||||
|
{(rx !== undefined || tx !== undefined) && <span className="text-xs text-muted-foreground" title="Счётчики на узле IX">
|
||||||
|
RX {rx !== undefined ? formatBytes(Number(rx)) : "—"} · TX {tx !== undefined ? formatBytes(Number(tx)) : "—"}
|
||||||
|
</span>}
|
||||||
</div>
|
</div>
|
||||||
: <Badge variant="secondary">{binding.connection?.state === "waiting" ? "Ожидает туннель" : "Нет данных"}</Badge>
|
|
||||||
} },
|
} },
|
||||||
{ id: "actions", header: "Действия", size: 140, cell: ({ row }) => {
|
{ id: "actions", header: "Действия", size: 140, cell: ({ row }) => {
|
||||||
const binding = row.original
|
const binding = row.original
|
||||||
@@ -292,7 +323,8 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
|
|||||||
(paired ? binding.kind === "wireguard" ? " · WireGuard" : " · GRE/IPsec" : "")}
|
(paired ? binding.kind === "wireguard" ? " · WireGuard" : " · GRE/IPsec" : "")}
|
||||||
onClick={() => view(live)}>Конфиг Linux</Button>}
|
onClick={() => view(live)}>Конфиг Linux</Button>}
|
||||||
{(bond || binding.policy && (live || !readOnly && saved?.linux)) && <DropdownMenu>
|
{(bond || binding.policy && (live || !readOnly && saved?.linux)) && <DropdownMenu>
|
||||||
<DropdownMenuTrigger render={<Button type="button" size="icon-sm" variant="ghost" disabled={busy} aria-label={"Действия клиента " + (binding.name ?? binding.interfaceName)} />}>
|
<DropdownMenuTrigger render={<Button type="button" size="icon-sm" variant="ghost" disabled={busy} aria-label={"Действия клиента " +
|
||||||
|
(binding.name ?? binding.interfaceName) + (paired ? " · " + binding.interfaceName : "")} />}>
|
||||||
<EllipsisIcon aria-hidden />
|
<EllipsisIcon aria-hidden />
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
@@ -308,19 +340,25 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
|
|||||||
</div>
|
</div>
|
||||||
} },
|
} },
|
||||||
], [nodes, applied, segment, readOnly, busy, view, revoke, inspect, bondAction, catalog.candidates])
|
], [nodes, applied, segment, readOnly, busy, view, revoke, inspect, bondAction, catalog.candidates])
|
||||||
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns,
|
|
||||||
getRowId: row => row.serverId + ":" + row.interfaceName })
|
|
||||||
return <Frame spacing="sm" className="min-w-0">
|
return <Frame spacing="sm" className="min-w-0">
|
||||||
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
|
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
|
||||||
<FrameTitle>Linux-клиенты</FrameTitle>
|
<FrameTitle>Linux-клиенты</FrameTitle>
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
<Button type="button" size="icon-sm" variant="outline" aria-label="Обновить клиентов" disabled={busy || !segment.appliedRevision} onClick={refresh}><RefreshCwIcon /></Button>
|
<Button type="button" size="icon-sm" variant="outline" aria-label="Обновить клиентов" disabled={busy || !segment.appliedRevision} onClick={refresh}><RefreshCwIcon /></Button>
|
||||||
{!readOnly && <Button type="button" size="sm" disabled={busy} onClick={() => { setEdit(null); setOpen(true) }}><PlusIcon />Подключить Linux</Button>}
|
{!readOnly && <Button type="button" size="sm" disabled={busy} onClick={() => { setEdit(null); setOpen(true) }}><PlusIcon />Подключить Linux</Button>}
|
||||||
|
{manualGroup}
|
||||||
</div>
|
</div>
|
||||||
</FrameHeader>
|
</FrameHeader>
|
||||||
<FramePanel className="min-w-0 p-0">
|
{clients.size ? [...clients].map(([key, client]) => <FramePanel key={key} className="grid min-w-0 gap-3 p-0">
|
||||||
<DataGridShell table={table} recordCount={rows.length} isLoading={busy && !rows.length} loadingMode="skeleton" emptyMessage="В сегменте пока нет Linux-клиентов" />
|
<section aria-label={"Клиент " + client.name} className="grid min-w-0 gap-3">
|
||||||
</FramePanel>
|
<h3 className="px-4 pt-3 text-sm font-semibold">{client.name}</h3>
|
||||||
|
{!!client.tunnels.length && <TunnelTable data={client.tunnels} columns={columns} busy={busy} />}
|
||||||
|
{client.hasGroups && <div className="grid gap-3 px-4 pb-4">
|
||||||
|
<h4 className="text-sm font-medium">Группы туннелей</h4>
|
||||||
|
{renderGroups(key)}
|
||||||
|
</div>}
|
||||||
|
</section>
|
||||||
|
</FramePanel>) : <FramePanel className="min-w-0 p-0"><TunnelTable data={rows} columns={columns} busy={busy} /></FramePanel>}
|
||||||
<Sheet open={open} onOpenChange={value => !busy && setOpen(value)}>
|
<Sheet open={open} onOpenChange={value => !busy && setOpen(value)}>
|
||||||
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-lg" showCloseButton={!busy}>
|
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-lg" showCloseButton={!busy}>
|
||||||
<SheetHeader><SheetTitle>{edit?.chooseTransport ? "Добавить туннель" : edit?.addProtocol ? "Добавить другой протокол" : edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
|
<SheetHeader><SheetTitle>{edit?.chooseTransport ? "Добавить туннель" : edit?.addProtocol ? "Добавить другой протокол" : edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
|
||||||
|
|||||||
@@ -469,7 +469,8 @@ export default function IxPage() {
|
|||||||
<TabsContent value="linux" className="grid min-w-0 gap-3">
|
<TabsContent value="linux" className="grid min-w-0 gap-3">
|
||||||
{selected ? <IxClientBonds key={selected.id + ":" + selected.appliedRevision} segmentId={selected.id} segments={segments}
|
{selected ? <IxClientBonds key={selected.id + ":" + selected.appliedRevision} segmentId={selected.id} segments={segments}
|
||||||
backendUrl={backendUrl} nodes={peers} readOnly={!write || busy || dirty} live={live} download={download}>
|
backendUrl={backendUrl} nodes={peers} readOnly={!write || busy || dirty} live={live} download={download}>
|
||||||
{(bondAction, catalog) => <IxLinuxClients segment={selected} nodes={peers} backendUrl={backendUrl} bondAction={bondAction} catalog={catalog}
|
{(bondAction, catalog, renderGroups, manualGroup) => <IxLinuxClients segment={selected} nodes={peers} backendUrl={backendUrl}
|
||||||
|
bondAction={bondAction} catalog={catalog} renderGroups={renderGroups} manualGroup={manualGroup}
|
||||||
applied={linuxBindings} busy={busy} error={error} readOnly={!live || !write || dirty}
|
applied={linuxBindings} busy={busy} error={error} readOnly={!live || !write || dirty}
|
||||||
save={input => perform(() => stageClient(input))} revoke={binding => void perform(() => stageClient(binding))}
|
save={input => perform(() => stageClient(input))} revoke={binding => void perform(() => stageClient(binding))}
|
||||||
refresh={() => void perform(loadLinuxBindings)} view={(binding, transportOnly) => void perform(() => exportLinux(binding, transportOnly))}
|
refresh={() => void perform(loadLinuxBindings)} view={(binding, transportOnly) => void perform(() => exportLinux(binding, transportOnly))}
|
||||||
|
|||||||
@@ -41,6 +41,16 @@ const serveRouter = (rows: RouterRows): RequestListener => async (request, respo
|
|||||||
const path = new URL(request.url!, "http://127.0.0.1").pathname.replace(/^\/rest/, "")
|
const path = new URL(request.url!, "http://127.0.0.1").pathname.replace(/^\/rest/, "")
|
||||||
let result: unknown
|
let result: unknown
|
||||||
if (request.method === "GET") result = rows[path] ?? []
|
if (request.method === "GET") result = rows[path] ?? []
|
||||||
|
else if (request.method === "POST" && path === "/interface/print") {
|
||||||
|
let raw = ""
|
||||||
|
for await (const chunk of request) raw += chunk
|
||||||
|
const body = JSON.parse(raw)
|
||||||
|
assert.equal(body.stats, "")
|
||||||
|
result = (rows["/interface"] ?? []).map(row => {
|
||||||
|
const gre = rows["/interface/gre"]?.some(item => item.name === row.name)
|
||||||
|
return { name: row.name, "rx-byte": gre ? "1536" : "9000", "tx-byte": gre ? "2048" : "8000" }
|
||||||
|
})
|
||||||
|
}
|
||||||
else if (request.method === "PUT") {
|
else if (request.method === "PUT") {
|
||||||
if (writes === failPutAt) throw Error("Synthetic RouterOS apply failure")
|
if (writes === failPutAt) throw Error("Synthetic RouterOS apply failure")
|
||||||
let raw = ""
|
let raw = ""
|
||||||
@@ -312,6 +322,8 @@ try {
|
|||||||
const clientInput = { serverId: Number(server.id), name: "linux-auto", kind: "wireguard", hubEndpoint: "192.0.2.20",
|
const clientInput = { serverId: Number(server.id), name: "linux-auto", kind: "wireguard", hubEndpoint: "192.0.2.20",
|
||||||
peerEndpoint: "192.0.2.40", exit: "local-wan", prefixes: [], destinations: ["203.0.113.0/24"], enabled: true }
|
peerEndpoint: "192.0.2.40", exit: "local-wan", prefixes: [], destinations: ["203.0.113.0/24"], enabled: true }
|
||||||
const staged = await post(managedPath + "/linux", { ...clientInput, revision: managed.revision }, 200)
|
const staged = await post(managedPath + "/linux", { ...clientInput, revision: managed.revision }, 200)
|
||||||
|
assert.match(staged.interfaceName, /^il-wg-[a-z0-9-]+-[0-9a-f]{12}$/)
|
||||||
|
assert.ok(staged.segment.configuration.sites[0].interfaces[0].linux.clientId)
|
||||||
const clientKey = { serverId: clientInput.serverId, interfaceName: staged.interfaceName }
|
const clientKey = { serverId: clientInput.serverId, interfaceName: staged.interfaceName }
|
||||||
await post(managedPath + "/linux/credential", clientKey, 409)
|
await post(managedPath + "/linux/credential", clientKey, 409)
|
||||||
await post(managedPath + "/linux/credential", clientKey, 403, reader)
|
await post(managedPath + "/linux/credential", clientKey, 403, reader)
|
||||||
@@ -379,6 +391,7 @@ try {
|
|||||||
const paired = await post(managedPath + "/linux", { ...companionInput, revision: resumed.segment.revision }, 200)
|
const paired = await post(managedPath + "/linux", { ...companionInput, revision: resumed.segment.revision }, 200)
|
||||||
const bindings = paired.segment.configuration.sites[0].interfaces
|
const bindings = paired.segment.configuration.sites[0].interfaces
|
||||||
const [wireguard, greBinding] = bindings
|
const [wireguard, greBinding] = bindings
|
||||||
|
assert.match(greBinding.name, /^il-gre-[a-z0-9-]+-[0-9a-f]{12}$/)
|
||||||
assert.ok(wireguard.linux.clientId)
|
assert.ok(wireguard.linux.clientId)
|
||||||
const original = resumed.segment.configuration.sites[0].interfaces[0]
|
const original = resumed.segment.configuration.sites[0].interfaces[0]
|
||||||
assert.deepEqual(wireguard, { ...original, linux: { ...original.linux, clientId: wireguard.linux.clientId } })
|
assert.deepEqual(wireguard, { ...original, linux: { ...original.linux, clientId: wireguard.linux.clientId } })
|
||||||
@@ -393,6 +406,11 @@ try {
|
|||||||
const pairPlan = await post(managedPath + "/plan", { revision: paired.segment.revision }, 200)
|
const pairPlan = await post(managedPath + "/plan", { revision: paired.segment.revision }, 200)
|
||||||
assert(!pairPlan.changes.some(change => change.path.startsWith("/interface/wireguard")))
|
assert(!pairPlan.changes.some(change => change.path.startsWith("/interface/wireguard")))
|
||||||
const pairedApplied = await post(managedPath + "/apply", { revision: paired.segment.revision, digest: pairPlan.digest }, 200)
|
const pairedApplied = await post(managedPath + "/apply", { revision: paired.segment.revision, digest: pairPlan.digest }, 200)
|
||||||
|
const countersResponse = await fetch(origin + "/api/ix/segments" + managedPath + "/linux", { headers: { authorization: "Bearer " + reader } })
|
||||||
|
assert.equal(countersResponse.status, 200)
|
||||||
|
const observedGre = (await countersResponse.json()).items.find(item => item.interfaceName === greBinding.name)
|
||||||
|
assert.equal(observedGre.connection.rx, "1536")
|
||||||
|
assert.equal(observedGre.connection.tx, "2048")
|
||||||
const pairVrf = rows["/ip/vrf"].find(row => row.interfaces?.includes(wireguard.name))!
|
const pairVrf = rows["/ip/vrf"].find(row => row.interfaces?.includes(wireguard.name))!
|
||||||
assert(pairVrf.interfaces.split(",").includes(greBinding.name))
|
assert(pairVrf.interfaces.split(",").includes(greBinding.name))
|
||||||
const greCredential = await post(managedPath + "/linux/credential",
|
const greCredential = await post(managedPath + "/linux/credential",
|
||||||
|
|||||||
@@ -167,6 +167,10 @@ function verifyEgressMembers(device: NativeDevice, id: string, objects: IxRouter
|
|||||||
|
|
||||||
async function readRows(client: IpCore, path: string, props: readonly string[]) {
|
async function readRows(client: IpCore, path: string, props: readonly string[]) {
|
||||||
const raw = await client.get<unknown>(path + "?" + new URLSearchParams({ ".proplist": [...new Set(props)].join(",") }))
|
const raw = await client.get<unknown>(path + "?" + new URLSearchParams({ ".proplist": [...new Set(props)].join(",") }))
|
||||||
|
return nativeRows(raw, props)
|
||||||
|
}
|
||||||
|
|
||||||
|
function nativeRows(raw: unknown, props: readonly string[]) {
|
||||||
if (!Array.isArray(raw) || raw.length > 10000 || raw.some(value => !value || typeof value !== "object" || Array.isArray(value))) {
|
if (!Array.isArray(raw) || raw.length > 10000 || raw.some(value => !value || typeof value !== "object" || Array.isArray(value))) {
|
||||||
throw new IxConflict("Не удалось прочитать полный каталог RouterOS")
|
throw new IxConflict("Не удалось прочитать полный каталог RouterOS")
|
||||||
}
|
}
|
||||||
@@ -280,8 +284,8 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
|
|||||||
}) : undefined
|
}) : undefined
|
||||||
const result = second ?? first
|
const result = second ?? first
|
||||||
const currentId = site?.interfaces.find(binding => binding.name === input.interfaceName)?.linux?.clientId
|
const currentId = site?.interfaces.find(binding => binding.name === input.interfaceName)?.linux?.clientId
|
||||||
const clientId = existingId ?? input.vpsClientId ?? currentId ?? (companion || second ? randomUUID() : undefined)
|
const clientId = existingId ?? input.vpsClientId ?? currentId ??
|
||||||
if (!clientId) return result
|
(input.interfaceName ? await ixBondClientId(segment.id, input.serverId, input.interfaceName) : undefined) ?? randomUUID()
|
||||||
const siblings = new Set([first.interfaceName, second?.interfaceName, companion ? companion.name : undefined])
|
const siblings = new Set([first.interfaceName, second?.interfaceName, companion ? companion.name : undefined])
|
||||||
return { interfaceName: first.interfaceName, configuration: {
|
return { interfaceName: first.interfaceName, configuration: {
|
||||||
...result.configuration,
|
...result.configuration,
|
||||||
@@ -332,7 +336,9 @@ async function configureIxLinuxTunnel(segment: IxSegment, input: IxLinuxClientRe
|
|||||||
}
|
}
|
||||||
let listenPort = 51820
|
let listenPort = 51820
|
||||||
while (ports.has(listenPort) && listenPort <= 65535) listenPort++
|
while (ports.has(listenPort) && listenPort <= 65535) listenPort++
|
||||||
const name = previous?.name ?? "il-" + randomUUID().replace(/-/g, "").slice(0, 12)
|
const slug = input.name.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 24).replace(/-$/, "")
|
||||||
|
const transport = input.kind === "wireguard" ? "wg" : "gre"
|
||||||
|
const name = previous?.name ?? ["il", transport, slug || "vps", randomUUID().replace(/-/g, "").slice(0, 12)].join("-")
|
||||||
const family = isIP(peerAddress)
|
const family = isIP(peerAddress)
|
||||||
const localExit = "ix-wan" + family
|
const localExit = "ix-wan" + family
|
||||||
const groups = [...site.groups]
|
const groups = [...site.groups]
|
||||||
@@ -808,23 +814,30 @@ export async function listIxLinuxClients(segment: IxSegment) {
|
|||||||
const observedAt = new Date().toISOString()
|
const observedAt = new Date().toISOString()
|
||||||
try {
|
try {
|
||||||
const client = await requiredIxNode(site.serverId)
|
const client = await requiredIxNode(site.serverId)
|
||||||
const [peers, ipsec] = await Promise.all([
|
const hasGre = bindings.some(binding => binding.linux?.enabled && binding.provisionGre)
|
||||||
|
const counterFields = ["name", "rx-byte", "tx-byte"]
|
||||||
|
const [peers, ipsec, stats] = await Promise.all([
|
||||||
bindings.some(binding => binding.linux && binding.provisionWireguard) ? readRows(client, "/interface/wireguard/peers",
|
bindings.some(binding => binding.linux && binding.provisionWireguard) ? readRows(client, "/interface/wireguard/peers",
|
||||||
["interface", "public-key", "last-handshake", "rx", "tx"]) : [],
|
["interface", "public-key", "last-handshake", "rx", "tx"]).catch(() => null) : [],
|
||||||
bindings.some(binding => binding.linux && binding.provisionGre) ? readRows(client, "/ip/ipsec/active-peers", ["remote-address", "state"]) : [],
|
hasGre ? readRows(client, "/ip/ipsec/active-peers", ["remote-address", "state"]).catch(() => null) : [],
|
||||||
|
hasGre ? client.post<unknown>("/interface/print", { stats: "", ".proplist": counterFields })
|
||||||
|
.then(raw => nativeRows(raw, counterFields)).catch(() => []) : [],
|
||||||
])
|
])
|
||||||
for (const [index, binding] of bindings.entries()) {
|
for (const [index, binding] of bindings.entries()) {
|
||||||
if (!binding.linux?.enabled) continue
|
if (!binding.linux?.enabled) continue
|
||||||
const peer = peers.find(row => row.interface === binding.name && row["public-key"] === binding.provisionWireguard?.peerPublicKey)
|
const peer = peers?.find(row => row.interface === binding.name && row["public-key"] === binding.provisionWireguard?.peerPublicKey)
|
||||||
const handshake = peer?.["last-handshake"]?.trim()
|
const handshake = peer?.["last-handshake"]?.trim()
|
||||||
const age = handshake && /^\d+:\d{2}:\d{2}$/.test(handshake)
|
const age = handshake && /^\d+:\d{2}:\d{2}$/.test(handshake)
|
||||||
? handshake.split(":").reduce((total, part) => total * 60 + Number(part), 0)
|
? handshake.split(":").reduce((total, part) => total * 60 + Number(part), 0)
|
||||||
: handshake && /^(?:(\d+)m)?(?:(\d+)s)?$/.exec(handshake)
|
: handshake && /^(?:(\d+)m)?(?:(\d+)s)?$/.exec(handshake)
|
||||||
const fresh = typeof age === "number" ? age < 180 :
|
const fresh = typeof age === "number" ? age < 180 :
|
||||||
Array.isArray(age) && Number(age[1] ?? 0) * 60 + Number(age[2] ?? 0) < 180
|
Array.isArray(age) && Number(age[1] ?? 0) * 60 + Number(age[2] ?? 0) < 180
|
||||||
const established = binding.provisionGre && ipsec.some(row => row.state === "established" &&
|
const established = binding.provisionGre && ipsec?.some(row => row.state === "established" &&
|
||||||
(row["remote-address"] === binding.endpoint || row["remote-address"]?.startsWith(binding.endpoint + ":")))
|
(row["remote-address"] === binding.endpoint || row["remote-address"]?.startsWith(binding.endpoint + ":")))
|
||||||
items[index].connection = { observedAt, state: fresh || established ? "connected" : "waiting", ...(peer && { rx: peer.rx, tx: peer.tx }) }
|
const iface = binding.provisionGre && stats.find(row => row.name === binding.name)
|
||||||
|
const state = fresh || established ? "connected" : (binding.provisionGre ? ipsec : peers) === null ? "unknown" : "waiting"
|
||||||
|
items[index].connection = { observedAt, state,
|
||||||
|
rx: peer?.rx ?? (iface ? iface["rx-byte"] : undefined), tx: peer?.tx ?? (iface ? iface["tx-byte"] : undefined) }
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
for (const item of items) if (item.enabled) item.connection = { observedAt, state: "unknown" }
|
for (const item of items) if (item.enabled) item.connection = { observedAt, state: "unknown" }
|
||||||
|
|||||||
@@ -66,6 +66,8 @@
|
|||||||
|
|
||||||
### Несколько туннелей на одном VPS
|
### Несколько туннелей на одном VPS
|
||||||
|
|
||||||
|
Карточка Linux-клиента объединяет его туннели и группы резервирования. Для нового интерфейса RouterOS имя включает протокол, имя клиента и уникальный суффикс, например `il-gre-tg-a1b2c3d4e5f6`. Существующие подключения сохраняют свои имена. RX и TX в строке GRE/IPsec показывают накопленные байты интерфейса на CHR.
|
||||||
|
|
||||||
1. В **Linux-клиенты** откройте меню действующего подключения и выберите **Создать группу с этим туннелем**. Интерфейс уже будет первым в списке. Для участника существующей группы это же меню открывает её редактор. Ключи VPS и CHR при создании группы сохраняются. Для нового транспорта откройте меню клиента и скачайте **Конфиг для группы ix-client**.
|
1. В **Linux-клиенты** откройте меню действующего подключения и выберите **Создать группу с этим туннелем**. Интерфейс уже будет первым в списке. Для участника существующей группы это же меню открывает её редактор. Ключи VPS и CHR при создании группы сохраняются. Для нового транспорта откройте меню клиента и скачайте **Конфиг для группы ix-client**.
|
||||||
2. Добавьте второе подключение одного VPS. Старые управляемые подключения без идентификатора VPS можно выбрать вместе, подтвердив их принадлежность одному серверу. Для исправления прежней привязки свободного подключения откройте **Доступ и выход → Привязка к VPS**, выберите VPS и сохраните ревизию. У всех участников должны различаться внутренние IP-адреса VPS и IX и совпадать семейство адресов и сети назначения. В режиме резервирования первым поставьте основной, затем резервы в порядке предпочтения. В параллельном режиме задайте равное распределение или веса. В прямые исключения внесите сети, к которым VPS должен обращаться через WAN.
|
2. Добавьте второе подключение одного VPS. Старые управляемые подключения без идентификатора VPS можно выбрать вместе, подтвердив их принадлежность одному серверу. Для исправления прежней привязки свободного подключения откройте **Доступ и выход → Привязка к VPS**, выберите VPS и сохраните ревизию. У всех участников должны различаться внутренние IP-адреса VPS и IX и совпадать семейство адресов и сети назначения. В режиме резервирования первым поставьте основной, затем резервы в порядке предпочтения. В параллельном режиме задайте равное распределение или веса. В прямые исключения внесите сети, к которым VPS должен обращаться через WAN.
|
||||||
3. Нажмите **Скачать для ix-client** и импортируйте JSON группы через **B → I**. Если имя интерфейса на VPS отличается от имени в JSON, ix-client сопоставит существующий транспорт по адресам и параметрам пира. Проверьте найденное локальное имя и соответствие туннеля в предварительном просмотре **F2**. Нажмите **Enter** для применения и **Y** для подтверждения. Без подтверждения через 60 секунд восстановится предыдущая конфигурация. Одиночные интерфейсы можно продолжать использовать отдельно.
|
3. Нажмите **Скачать для ix-client** и импортируйте JSON группы через **B → I**. Если имя интерфейса на VPS отличается от имени в JSON, ix-client сопоставит существующий транспорт по адресам и параметрам пира. Проверьте найденное локальное имя и соответствие туннеля в предварительном просмотре **F2**. Нажмите **Enter** для применения и **Y** для подтверждения. Без подтверждения через 60 секунд восстановится предыдущая конфигурация. Одиночные интерфейсы можно продолжать использовать отдельно.
|
||||||
|
|||||||
@@ -65,8 +65,9 @@ test("IX: сборка группы VPS из двух площадок с вес
|
|||||||
await expect(editor.getByRole("button", { name: "Сохранить" })).toBeDisabled()
|
await expect(editor.getByRole("button", { name: "Сохранить" })).toBeDisabled()
|
||||||
await editor.getByRole("checkbox", { name: "Подтверждаю, что выбранные интерфейсы настроены на одном VPS" }).check()
|
await editor.getByRole("checkbox", { name: "Подтверждаю, что выбранные интерфейсы настроены на одном VPS" }).check()
|
||||||
await editor.getByRole("button", { name: "Сохранить" }).click()
|
await editor.getByRole("button", { name: "Сохранить" }).click()
|
||||||
await expect(page.getByText("vps-01 · Параллельно, по весам")).toBeVisible()
|
const clientCard = page.getByRole("region", { name: "Клиент wg-vps", exact: true })
|
||||||
await expect(page.getByRole("button", { name: "Скачать для ix-client" })).toBeVisible()
|
await expect(clientCard.getByText("vps-01 · Параллельно, по весам")).toBeVisible()
|
||||||
|
await expect(clientCard.getByRole("button", { name: "Скачать для ix-client" })).toBeVisible()
|
||||||
await page.getByRole("button", { name: "Действия клиента wg-vps" }).click()
|
await page.getByRole("button", { name: "Действия клиента wg-vps" }).click()
|
||||||
await page.getByRole("menuitem", { name: "Открыть группу «vps-01»" }).click()
|
await page.getByRole("menuitem", { name: "Открыть группу «vps-01»" }).click()
|
||||||
await expect(editor.getByLabel("Имя группы")).toHaveValue("vps-01")
|
await expect(editor.getByLabel("Имя группы")).toHaveValue("vps-01")
|
||||||
@@ -372,6 +373,7 @@ for (const mode of ["WAN IX", "два протокола", "новый ExitNode"
|
|||||||
if (path === `/api/ix/segments/${id}/linux`) {
|
if (path === `/api/ix/segments/${id}/linux`) {
|
||||||
return json({ revision: segment.appliedRevision, items: segment.appliedRevision >= 3 && client ? [
|
return json({ revision: segment.appliedRevision, items: segment.appliedRevision >= 3 && client ? [
|
||||||
client, ...(both || segment.appliedRevision === 5 ? [{ name: "vps-01", kind: "gre-ipsec", serverId: 1, interfaceName: "il-gre",
|
client, ...(both || segment.appliedRevision === 5 ? [{ name: "vps-01", kind: "gre-ipsec", serverId: 1, interfaceName: "il-gre",
|
||||||
|
connection: { observedAt, state: "connected", rx: "1536", tx: "2048" },
|
||||||
policy: segment.configuration.sites[0].interfaces[1].linux }] : []),
|
policy: segment.configuration.sites[0].interfaces[1].linux }] : []),
|
||||||
] : [] })
|
] : [] })
|
||||||
}
|
}
|
||||||
@@ -418,6 +420,9 @@ for (const mode of ["WAN IX", "два протокола", "новый ExitNode"
|
|||||||
expect(await readFile((await file.path())!, "utf8")).toBe(configFile)
|
expect(await readFile((await file.path())!, "utf8")).toBe(configFile)
|
||||||
await expect(page.getByText("TEST_PRIVATE_KEY")).toHaveCount(0)
|
await expect(page.getByText("TEST_PRIVATE_KEY")).toHaveCount(0)
|
||||||
if (both) {
|
if (both) {
|
||||||
|
const card = page.getByRole("region", { name: "Клиент vps-01", exact: true })
|
||||||
|
await expect(card.getByRole("row").filter({ hasText: "il-vps" })).toHaveCount(1)
|
||||||
|
await expect(card.getByRole("row").filter({ hasText: "il-gre" })).toContainText("RX 1.5 КБ · TX 2.0 КБ")
|
||||||
await page.getByRole("button", { name: "Получить конфиг vps-01 · GRE/IPsec", exact: true }).click()
|
await page.getByRole("button", { name: "Получить конфиг vps-01 · GRE/IPsec", exact: true }).click()
|
||||||
await expect(page.getByText(/sudo sh .\/vps-gre-setup\.sh/)).toBeVisible()
|
await expect(page.getByText(/sudo sh .\/vps-gre-setup\.sh/)).toBeVisible()
|
||||||
await expect(page.getByText("TEST_PSK")).toHaveCount(0)
|
await expect(page.getByText("TEST_PSK")).toHaveCount(0)
|
||||||
|
|||||||
Reference in new issue
Block a user