Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af82497f20 | ||
|
|
ca65969728 | ||
|
|
ee6fd675ac | ||
|
|
5a46594ec9 | ||
|
|
31f75a8eed | ||
|
|
2a759ae5e5 | ||
|
|
fad89c7059 | ||
|
|
350ae34862 | ||
|
|
676be13251 | ||
|
|
ca1bc1ab38 |
No files matched your search
@@ -0,0 +1,199 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, type ReactNode } from "react"
|
||||
import type { IxBondBundle, IxBondCandidate, IxBondCatalog, IxBondEdit, IxBondMode, IxSavedBond, IxSegment } from "@mmapp/contracts/internet-exchange"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { Field, FieldLabel } from "@/components/ui/field"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
import { nodeLabel, type IxNode } from "./ix-view"
|
||||
import { IxExistingTransport } from "./ix-existing-transport"
|
||||
|
||||
const modes = [
|
||||
{ value: "failover", label: "Основной и резервные" },
|
||||
{ value: "equal", label: "Параллельно, поровну" },
|
||||
{ value: "weighted", label: "Параллельно, по весам" },
|
||||
] as const
|
||||
type Member = IxBondEdit["members"][number]
|
||||
type Ref = Pick<Member, "segmentId" | "interfaceName" | "serverId">
|
||||
export type IxRowBondAction = (binding: Pick<Ref, "interfaceName" | "serverId">) => { label: string; open: () => void } | undefined
|
||||
const memberKey = (m: Pick<Member, "segmentId" | "interfaceName" | "serverId">) => [m.segmentId, m.serverId, m.interfaceName].join("/")
|
||||
const memberRef = ({ segmentId, serverId, appliedRevision, interfaceName }: IxBondCandidate): Member => ({ segmentId, serverId, appliedRevision, interfaceName, weight: 1 })
|
||||
const modeLabel = (mode: IxBondMode) => modes.find(item => item.value === mode)?.label
|
||||
|
||||
export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly, download, live, children }: {
|
||||
segmentId: string; segments: IxSegment[]; backendUrl: string; nodes: IxNode[]; readOnly: boolean; live: boolean
|
||||
download: (filename: string, text: string) => void
|
||||
children: (action: IxRowBondAction, catalog: IxBondCatalog, groups: (clientId: string) => ReactNode, unassigned: ReactNode) => ReactNode
|
||||
}) {
|
||||
const [catalog, setCatalog] = useState<IxBondCatalog>({ groups: [], candidates: [] })
|
||||
const [reload, setReload] = useState(0)
|
||||
const [draft, setDraft] = useState<IxBondEdit | null>(null)
|
||||
const [direct, setDirect] = useState("")
|
||||
const [error, setError] = useState("")
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [remove, setRemove] = useState(false)
|
||||
const [confirmedMembers, setConfirmedMembers] = useState("")
|
||||
const [importing, setImporting] = useState(false)
|
||||
const [initialInterface, setInitialInterface] = useState<Pick<Ref, "serverId" | "interfaceName">>()
|
||||
useEffect(() => {
|
||||
if (!live) return
|
||||
const ctl = new AbortController()
|
||||
void requestJson<IxBondCatalog>(backendUrl, "/api/ix/linux-bonds", { signal: ctl.signal })
|
||||
.then(result => { if (!ctl.signal.aborted) setCatalog(result) })
|
||||
.catch(e => { if (!ctl.signal.aborted) setError(e.message) })
|
||||
return () => ctl.abort()
|
||||
}, [backendUrl, segmentId, reload, live])
|
||||
const available = new Map(catalog.candidates.map(c => [memberKey(c), c]))
|
||||
for (const m of [...catalog.groups.flatMap(g => g.members), ...(draft?.members ?? [])]) {
|
||||
if (!m.existing) continue
|
||||
const segment = segments.find(s => s.id === m.segmentId)
|
||||
available.set(memberKey(m), { ...m, ...m.existing, name: m.existing.linuxInterface, segmentName: segment?.configuration.name ?? m.segmentId,
|
||||
appliedRevision: segment?.appliedRevision ?? m.appliedRevision, destinations: [...new Set(m.existing.destinations)].sort() })
|
||||
}
|
||||
const label = (c: IxBondCandidate) => [c.name, c.segmentName, nodeLabel(nodes, c.serverId), c.kind === "wireguard" ? "WG" : "GRE/IPsec", c.endpoint, c.interfaceName].join(" · ")
|
||||
function open(group?: IxSavedBond, first?: IxBondCandidate) {
|
||||
setError("")
|
||||
setRemove(false)
|
||||
setConfirmedMembers("")
|
||||
setImporting(false)
|
||||
setInitialInterface(undefined)
|
||||
setDirect(group?.directCidrs.join("\n") ?? "")
|
||||
setDraft(group ? {
|
||||
id: group.id, revision: group.revision, name: group.name, mode: group.mode, directCidrs: group.directCidrs,
|
||||
members: group.members.map(m => ({ ...m, appliedRevision: available.get(memberKey(m))?.appliedRevision ?? m.appliedRevision })),
|
||||
} : { revision: 0, name: first?.name ?? "", mode: "failover", members: first ? [memberRef(first)] : [], directCidrs: [] })
|
||||
}
|
||||
async function perform(action: () => Promise<void>) {
|
||||
if (busy || readOnly) return
|
||||
setBusy(true)
|
||||
setError("")
|
||||
try { await action() } catch (e) { setError(e instanceof Error ? e.message : "Ошибка операции с группой") }
|
||||
finally { setBusy(false) }
|
||||
}
|
||||
const patch = (fields: Partial<IxBondEdit>) => setDraft(old => old && { ...old, ...fields })
|
||||
const ownedGroups = catalog.groups.filter(g => g.members.some(m => m.segmentId === segmentId))
|
||||
const previous = catalog.groups.find(g => g.id === draft?.id)
|
||||
const owner = previous?.ownerSegmentId ?? segmentId
|
||||
const root = "/api/ix/segments/" + owner + "/linux-bonds"
|
||||
const occupied = new Set(catalog.groups.filter(g => g.id !== draft?.id).flatMap(g => g.members.map(memberKey)))
|
||||
const selected = (draft?.members ?? []).flatMap(m => available.get(memberKey(m)) ?? [])
|
||||
const identity = previous?.clientId ?? selected.find(m => m.clientId)?.clientId
|
||||
const first = selected[0]
|
||||
const choices = catalog.candidates.filter(c => c.destinations.length && !occupied.has(memberKey(c)) && (!identity || !c.clientId || c.clientId === identity) &&
|
||||
(!first || c.address.includes(":") === first.address.includes(":") && JSON.stringify(c.destinations) === JSON.stringify(first.destinations) &&
|
||||
!selected.some(m => [m.address, m.probe].some(ip => ip === c.address || ip === c.probe))) &&
|
||||
!draft?.members.some(m => memberKey(m) === memberKey(c)))
|
||||
.map(c => ({ value: memberKey(c), label: label(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 issue = error && <p role="alert" className="text-sm text-destructive">{error}</p>
|
||||
const renderGroups = (clientId: string) => ownedGroups.filter(g => g.clientId === clientId).map(g => <div key={g.id} className="grid gap-1.5">
|
||||
<span className="font-medium">{g.name} · {modeLabel(g.mode)}</span>
|
||||
<ol className="grid gap-1 text-sm">{g.members.map((m, i) => {
|
||||
const c = available.get(memberKey(m))
|
||||
const role = g.mode === "failover" ? (i ? "Резерв " + i : "Основной") : "Вес " + (g.mode === "weighted" ? m.weight : 1)
|
||||
return <li key={memberKey(m)}>{role} · {c ? label(c) : m.interfaceName + " · недоступен"}
|
||||
{c && c.appliedRevision !== m.appliedRevision ? " · изменена ревизия" : ""}</li>
|
||||
})}</ol>
|
||||
{!readOnly && <div className="flex flex-wrap gap-2">
|
||||
<Button size="sm" variant="outline" disabled={busy} onClick={() => open(g)}>Изменить</Button>
|
||||
<Button size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
|
||||
const bundle = await requestJson<IxBondBundle>(backendUrl, "/api/ix/segments/" + g.ownerSegmentId + "/linux-bonds/" + g.id + "/export",
|
||||
{ method: "POST", body: JSON.stringify({ revision: g.revision }) })
|
||||
download("ix-bond-" + g.id + ".json", JSON.stringify(bundle, null, 2))
|
||||
})}>Скачать для ix-client</Button>
|
||||
</div>}
|
||||
</div>)
|
||||
const rows = children(binding => {
|
||||
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)}>
|
||||
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-xl">
|
||||
<SheetHeader><SheetTitle>Группа туннелей VPS</SheetTitle>
|
||||
<SheetDescription>Выберите применённые подключения одного VPS. В режиме резервирования первый туннель в списке основной.</SheetDescription>
|
||||
</SheetHeader>
|
||||
{draft && <form className="flex min-h-0 flex-1 flex-col" onSubmit={e => {
|
||||
e.preventDefault()
|
||||
if (importing || needsConfirmation && confirmedMembers !== selectionKey) return
|
||||
void perform(async () => {
|
||||
await requestJson(backendUrl, root, { method: "POST", body: JSON.stringify({ ...draft,
|
||||
directCidrs: direct.split(/[\s,]+/).filter(Boolean) }) })
|
||||
setDraft(null); setReload(n => n + 1)
|
||||
})
|
||||
}}>
|
||||
<div className="grid min-h-0 gap-4 overflow-y-auto px-4">
|
||||
{issue}
|
||||
<Field><FieldLabel htmlFor="ix-bond-name">Имя группы</FieldLabel><Input id="ix-bond-name" value={draft.name} required maxLength={80} onChange={e => patch({ name: e.target.value })} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-bond-mode">Режим</FieldLabel>
|
||||
<Select value={draft.mode} items={[...modes]} onValueChange={v => v && patch({ mode: v })}>
|
||||
<SelectTrigger id="ix-bond-mode"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{modes.map(m => <SelectItem key={m.value} value={m.value}>{m.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>
|
||||
{draft.members.map((m, index) => {
|
||||
const candidate = available.get(memberKey(m))
|
||||
return <div key={memberKey(m)} className="grid gap-2 rounded-md border p-2 text-sm">
|
||||
<span>{index + 1}. {candidate ? label(candidate) : m.interfaceName + " · недоступен"}</span>
|
||||
{draft.mode === "weighted" && <Field><FieldLabel htmlFor={"ix-bond-weight-" + index}>Вес</FieldLabel>
|
||||
<Input id={"ix-bond-weight-" + index} type="number" min={1} max={100} required value={m.weight}
|
||||
onChange={e => patch({ members: draft.members.map((item, n) => n === index ? { ...item, weight: Number(e.target.value) } : item) })} /></Field>}
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" variant="outline" type="button" disabled={!index} onClick={() => {
|
||||
const members = [...draft.members]; members.splice(index - 1, 0, ...members.splice(index, 1)); patch({ members })
|
||||
}}>Выше</Button>
|
||||
<Button size="sm" variant="outline" type="button" onClick={() => patch({ members: draft.members.filter((_, i) => i !== index) })}>Исключить</Button>
|
||||
</div>
|
||||
</div>
|
||||
})}
|
||||
<Field><FieldLabel htmlFor="ix-bond-member">Добавить туннель этого VPS</FieldLabel>
|
||||
<Select<string> key={draft.members.length} value={null} items={choices} disabled={!choices.length || draft.members.length >= 16} onValueChange={v => {
|
||||
const c = v && available.get(v)
|
||||
if (c) patch({ members: [...draft.members, memberRef(c)] })
|
||||
}}>
|
||||
<SelectTrigger id="ix-bond-member"><SelectValue placeholder="Выберите интерфейс" /></SelectTrigger>
|
||||
<SelectContent alignItemWithTrigger={false}>{choices.map(c => <SelectItem key={c.value} value={c.value}>{c.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>
|
||||
{!choices.length && draft.members.length < 2 && <p className="text-sm text-muted-foreground">Для второго туннеля нужны другой внутренний адрес, то же семейство и одинаковые назначения. Проверьте привязку к VPS и применение подключения на его площадке.</p>}
|
||||
{importing ? <IxExistingTransport backendUrl={backendUrl} segments={segments} segmentId={segmentId} nodes={nodes} initial={initialInterface}
|
||||
members={[...draft.members, ...catalog.groups.filter(g => g.id !== draft.id).flatMap(g => g.members)]} destinations={first?.destinations ?? []}
|
||||
cancel={() => setImporting(false)} add={m => { patch({ members: [...draft.members, m] }); setImporting(false) }} />
|
||||
: <Button type="button" variant="outline" disabled={draft.members.length >= 16} onClick={() => { setInitialInterface(undefined); setImporting(true) }}>Добавить из интерфейсов RouterOS</Button>}
|
||||
{needsConfirmation && <Field orientation="horizontal"><Checkbox id="ix-bond-same-vps" checked={confirmedMembers === selectionKey}
|
||||
onCheckedChange={checked => setConfirmedMembers(checked ? selectionKey : "")} />
|
||||
<FieldLabel htmlFor="ix-bond-same-vps">Подтверждаю, что выбранные интерфейсы настроены на одном VPS</FieldLabel></Field>}
|
||||
<Field><FieldLabel htmlFor="ix-bond-direct">Прямой выход для сетей (CIDR)</FieldLabel>
|
||||
<Textarea id="ix-bond-direct" rows={3} value={direct} onChange={e => setDirect(e.target.value)} /></Field>
|
||||
</div>
|
||||
<SheetFooter>
|
||||
<Button type="submit" disabled={busy || readOnly || importing || draft.members.length < 2 || needsConfirmation && confirmedMembers !== selectionKey}>Сохранить</Button>
|
||||
{draft.id && <Button type="button" variant="outline" disabled={busy || readOnly} onClick={() => {
|
||||
if (!remove) { setRemove(true); return }
|
||||
void perform(async () => {
|
||||
await requestJson(backendUrl, root + "/" + draft.id, { method: "DELETE", body: JSON.stringify({ revision: draft.revision }) })
|
||||
setDraft(null); setReload(n => n + 1)
|
||||
})
|
||||
}}>{remove ? "Подтвердить удаление группы" : "Удалить группу"}</Button>}
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={() => setDraft(null)}>Отмена</Button>
|
||||
</SheetFooter>
|
||||
</form>}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</>
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { ixExistingTransportSchema, type IxBondEdit, type IxSegment } from "@mmapp/contracts/internet-exchange"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
|
||||
|
||||
type Member = IxBondEdit["members"][number]
|
||||
|
||||
export function IxExistingTransport({ backendUrl, segmentId, segments, nodes, members, destinations, initial, add, cancel }: {
|
||||
backendUrl: string; segmentId: string; segments: IxSegment[]; nodes: IxNode[]; members: Member[]; destinations: string[]
|
||||
add: (ref: Member) => void; cancel: () => void
|
||||
initial?: Pick<Member, "serverId" | "interfaceName">
|
||||
}) {
|
||||
const sites = segments.filter(s => s.appliedRevision).flatMap(segment => segment.configuration.sites.map(site => ({
|
||||
value: segment.id + "/" + site.serverId, label: segment.configuration.name + " · " + nodeLabel(nodes, site.serverId), segment, site,
|
||||
})))
|
||||
const [selection, setSelection] = useState(sites.find(s => s.segment.id === segmentId && (!initial || s.site.serverId === initial.serverId))?.value ?? "")
|
||||
const site = sites.find(s => s.value === selection)
|
||||
const inventory = useIxNodeInventory(backendUrl, site?.site.serverId ?? 0, site?.segment.id)
|
||||
const [iface, setIface] = useState(initial?.interfaceName ?? "")
|
||||
const [linuxInterface, setLinuxInterface] = useState("")
|
||||
const [probe, setProbe] = useState("")
|
||||
const [address, setAddress] = useState("")
|
||||
const [endpoint, setEndpoint] = useState("")
|
||||
const [peer, setPeer] = useState("")
|
||||
const [routes, setRoutes] = useState(destinations.join("\n"))
|
||||
const interfaces = (inventory.inventory?.interfaces ?? []).filter(i => /^(wg|wireguard|gre|gre-tunnel)$/.test(i.type) && !i.disabled && i.addresses.length &&
|
||||
!site?.site.interfaces.some(b => b.name === i.name && (b.linux || b.provisionWireguard || b.provisionGre || b.provisionTransit || b.peerServerId)) &&
|
||||
!site?.site.neighbors.some(p => p.binding === i.name) && !members.some(m => m.serverId === site?.site.serverId && m.interfaceName === i.name))
|
||||
const active = interfaces.find(i => i.name === iface)
|
||||
const wg = active?.type === "wg" || active?.type === "wireguard"
|
||||
const probes = active?.addresses.map(a => a.split("/")[0]) ?? []
|
||||
const selectedProbe = probes.includes(probe) ? probe : probes[0] ?? ""
|
||||
const input = ixExistingTransportSchema.safeParse({ ...(wg ? { kind: "wireguard", clientPublicKey: peer.trim() } : { kind: "gre-ipsec", remoteEndpoint: peer.trim() }),
|
||||
linuxInterface: linuxInterface.trim(), probe: selectedProbe, address: address.trim(), endpoint: endpoint.trim(), destinations: routes.trim().split(/[\s,]+/) })
|
||||
return <div className="grid gap-3 rounded-md border p-3">
|
||||
<Field><FieldLabel htmlFor="ix-adopt-site">Площадка и узел IX</FieldLabel>
|
||||
<Select value={selection} items={sites} onValueChange={v => { setSelection(v ?? ""); setIface(""); setProbe(""); setPeer(""); setEndpoint("") }}>
|
||||
<SelectTrigger id="ix-adopt-site"><SelectValue /></SelectTrigger><SelectContent>{sites.map(s => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>
|
||||
<Field><FieldLabel htmlFor="ix-adopt-interface">Интерфейс RouterOS</FieldLabel>
|
||||
<Select value={iface || null} items={interfaces.map(i => ({ value: i.name, label: i.name }))} onValueChange={v => {
|
||||
setIface(v ?? ""); setProbe(interfaces.find(i => i.name === v)?.addresses[0]?.split("/")[0] ?? ""); setPeer("")
|
||||
}}><SelectTrigger id="ix-adopt-interface"><SelectValue placeholder="Выберите WG или GRE" /></SelectTrigger>
|
||||
<SelectContent>{interfaces.map(i => <SelectItem value={i.name} key={i.name}>{i.name}</SelectItem>)}</SelectContent></Select>
|
||||
<FieldDescription>{inventory.error ?? (inventory.loading ? "Читаем интерфейсы узла…" : "Доступны включённые интерфейсы с внутренним IP. Настройки RouterOS сохраняются.")}</FieldDescription></Field>
|
||||
{active && <>
|
||||
<Field><FieldLabel htmlFor="ix-adopt-linux">Имя интерфейса на VPS</FieldLabel><Input id="ix-adopt-linux" value={linuxInterface} onChange={e => setLinuxInterface(e.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-adopt-probe">Адрес IX внутри туннеля</FieldLabel>
|
||||
<Select value={selectedProbe} items={probes.map(value => ({ value, label: value }))} onValueChange={v => setProbe(v ?? "")}>
|
||||
<SelectTrigger id="ix-adopt-probe"><SelectValue /></SelectTrigger><SelectContent>{probes.map(v => <SelectItem key={v} value={v}>{v}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>
|
||||
<Field><FieldLabel htmlFor="ix-adopt-address">Адрес VPS внутри туннеля</FieldLabel><Input id="ix-adopt-address" value={address} onChange={e => setAddress(e.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-adopt-endpoint">Внешний адрес IX</FieldLabel><Input id="ix-adopt-endpoint" value={endpoint} onChange={e => setEndpoint(e.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-adopt-peer">{wg ? "Публичный ключ WireGuard VPS" : "Внешний IPv4 VPS"}</FieldLabel><Input id="ix-adopt-peer" value={peer} onChange={e => setPeer(e.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-adopt-routes">Назначения через туннель (CIDR)</FieldLabel><Textarea id="ix-adopt-routes" rows={2} value={routes} onChange={e => setRoutes(e.target.value)} /></Field>
|
||||
</>}
|
||||
<div className="flex gap-2"><Button type="button" variant="outline" size="sm" disabled={!site || !active || !input.success} onClick={() => {
|
||||
if (input.success && site?.segment.appliedRevision && active) add({ segmentId: site.segment.id, serverId: site.site.serverId,
|
||||
appliedRevision: site.segment.appliedRevision, interfaceName: active.name, existing: input.data, weight: 1 })
|
||||
}}>Включить в список</Button><Button type="button" size="sm" variant="ghost" onClick={cancel}>Отмена выбора</Button></div>
|
||||
</div>
|
||||
}
|
||||
@@ -1,28 +1,33 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo, useState } from "react"
|
||||
import { useMemo, useState, type ReactNode } from "react"
|
||||
import { type ColumnDef, useTable } from "@tanstack/react-table"
|
||||
import { EllipsisIcon, PencilIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
|
||||
import type { IxLinuxBinding, IxLinuxClientRequest, IxSegment, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import type { IxBondCatalog, IxLinuxBinding, IxLinuxClientRequest, IxSegment, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
|
||||
import { Frame, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ButtonGroup } from "@/components/ui/button-group"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
|
||||
import { Field, FieldDescription, FieldLabel, FieldTitle } from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { isIpv4String } from "@/lib/gre-endpoint-resolve"
|
||||
import { formatBytes } from "@/lib/fmt-rate"
|
||||
import { publicEndpoint, transitName } from "./ix-exits"
|
||||
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
|
||||
import type { IxRowBondAction } from "./ix-client-bonds"
|
||||
|
||||
type Binding = IxSite["interfaces"][number]
|
||||
type ClientSelection = { site: IxSite; binding: Binding; addProtocol?: boolean; chooseTransport?: boolean }
|
||||
type FormState = {
|
||||
serverId: number
|
||||
name: string
|
||||
kind: IxLinuxClientRequest["kind"]
|
||||
kind: IxLinuxClientRequest["kind"] | "both"
|
||||
hub: string
|
||||
peer: string
|
||||
key: string
|
||||
@@ -32,9 +37,20 @@ type FormState = {
|
||||
destinations: string
|
||||
exit: string
|
||||
enabled: boolean
|
||||
transitLocal: string
|
||||
transitRemote: string
|
||||
}
|
||||
|
||||
const lines = (value: string) => value.split(/[,\n]/).map(line => line.trim()).filter(Boolean)
|
||||
const protocols = [
|
||||
{ kind: "wireguard", label: "WireGuard" },
|
||||
{ kind: "gre-ipsec", label: "GRE/IPsec" },
|
||||
] as const
|
||||
|
||||
function hasCompanion(site: IxSite, binding: Binding) {
|
||||
const clientId = binding.linux?.clientId
|
||||
return !!clientId && site.interfaces.some(item => item.kind !== binding.kind && item.linux?.clientId === clientId)
|
||||
}
|
||||
|
||||
function groupLabel(group: IxSite["groups"][number], site: IxSite, nodes: IxNode[]) {
|
||||
const target = site.interfaces.find(binding => binding.name === group.primary.interface)?.peerServerId
|
||||
@@ -42,36 +58,62 @@ function groupLabel(group: IxSite["groups"][number], site: IxSite, nodes: IxNode
|
||||
return [label, group.backup && "с резервом"].filter(Boolean).join(" · ")
|
||||
}
|
||||
|
||||
function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
|
||||
segment: IxSegment; edit: { site: IxSite; binding: Binding } | null; nodes: IxNode[]; backendUrl: string
|
||||
function ClientForm({ segment, edit, setAddProtocol, nodes, backendUrl, catalog, busy, save, cancel }: {
|
||||
segment: IxSegment; edit: ClientSelection | null; nodes: IxNode[]; backendUrl: string
|
||||
catalog: IxBondCatalog
|
||||
setAddProtocol: (add: boolean) => void
|
||||
busy: boolean; save: (input: IxLinuxClientRequest) => Promise<void>; cancel: () => void
|
||||
}) {
|
||||
const binding = edit?.binding
|
||||
const [form, setForm] = useState<FormState>(() => ({
|
||||
serverId: edit?.site.serverId ?? segment.configuration.sites[0].serverId,
|
||||
name: binding?.linux?.name ?? "", kind: binding?.kind === "gre-ipsec" ? "gre-ipsec" : "wireguard",
|
||||
hub: binding?.localEndpoint ?? binding?.provisionWireguard?.hubEndpoint ?? "",
|
||||
peer: binding?.linux?.peerEndpoint ?? binding?.endpoint ?? "",
|
||||
key: binding?.provisionWireguard?.credentialId ? "" : binding?.provisionWireguard?.peerPublicKey ?? "",
|
||||
localAddress: (binding?.provisionWireguard ?? binding?.provisionGre)?.localAddress ?? "",
|
||||
peerAddress: (binding?.provisionWireguard ?? binding?.provisionGre)?.peerAddress ?? "",
|
||||
prefixes: binding?.prefixes.join("\n") ?? "", destinations: binding?.linux?.destinations.join("\n") ?? "",
|
||||
exit: binding?.linux?.exit ?? "isolated", enabled: binding?.linux?.enabled ?? true,
|
||||
}))
|
||||
const existing = edit?.binding
|
||||
const companion = edit?.addProtocol ? existing : undefined
|
||||
const binding = companion ? undefined : existing
|
||||
const paired = !!edit && hasCompanion(edit.site, edit.binding)
|
||||
const initialForm = (addProtocol: boolean): FormState => {
|
||||
const current = addProtocol ? undefined : existing
|
||||
const tunnel = current?.provisionWireguard ?? current?.provisionGre
|
||||
return {
|
||||
serverId: edit?.site.serverId ?? segment.configuration.sites[0].serverId,
|
||||
name: existing?.linux?.name ?? "",
|
||||
kind: addProtocol ? (existing?.kind === "wireguard" ? "gre-ipsec" : "wireguard")
|
||||
: current?.kind === "gre-ipsec" ? "gre-ipsec" : "wireguard",
|
||||
hub: existing?.localEndpoint ?? existing?.provisionWireguard?.hubEndpoint ?? "",
|
||||
peer: existing?.linux?.peerEndpoint ?? existing?.endpoint ?? "",
|
||||
key: current?.provisionWireguard?.credentialId ? "" : current?.provisionWireguard?.peerPublicKey ?? "",
|
||||
localAddress: tunnel?.localAddress ?? "", peerAddress: tunnel?.peerAddress ?? "",
|
||||
prefixes: current?.prefixes.join("\n") ?? "", destinations: current?.linux?.destinations.join("\n") ?? "",
|
||||
exit: current?.linux?.exit ?? "isolated", enabled: current?.linux?.enabled ?? true,
|
||||
transitLocal: "", transitRemote: "",
|
||||
}
|
||||
}
|
||||
const [currentForm, setCurrentForm] = useState(() => initialForm(false))
|
||||
const [companionForm, setCompanionForm] = useState(() => initialForm(true))
|
||||
const form = companion ? companionForm : currentForm
|
||||
const setForm = companion ? setCompanionForm : setCurrentForm
|
||||
const wireguard = form.kind !== "gre-ipsec"
|
||||
const gre = form.kind !== "wireguard"
|
||||
const [rotate, setRotate] = useState(false)
|
||||
const [vpsId, setVpsId] = useState("")
|
||||
const currentGroup = edit && catalog.groups.find(g => g.members.some(m => m.segmentId === segment.id &&
|
||||
m.serverId === edit.site.serverId && m.interfaceName === edit.binding.name))
|
||||
const currentVps = currentGroup?.clientId ?? existing?.linux?.clientId
|
||||
const knownVps = useMemo(() => {
|
||||
const labels = new Map<string, string>()
|
||||
for (const c of catalog.candidates) if (c.clientId) labels.set(c.clientId, c.name + " · " + c.segmentName)
|
||||
for (const group of catalog.groups) labels.set(group.clientId, group.name)
|
||||
if (currentVps && !labels.has(currentVps)) labels.set(currentVps, existing?.linux?.name ?? "Текущий VPS")
|
||||
return [...labels].map(([value, label]) => ({ value, label: label + " · " + value.slice(0, 8) }))
|
||||
}, [catalog, currentVps, existing])
|
||||
const origin = useIxNodeInventory(backendUrl, form.serverId, segment.id)
|
||||
const [transitLocal, setTransitLocal] = useState("")
|
||||
const [transitRemote, setTransitRemote] = useState("")
|
||||
const site = segment.configuration.sites.find(site => site.serverId === form.serverId)
|
||||
const suggested = publicEndpoint(origin.inventory)
|
||||
const hub = form.hub.trim() || suggested
|
||||
const targetId = form.exit.startsWith("remote:") ? Number(form.exit.slice(7)) : 0
|
||||
const target = useIxNodeInventory(backendUrl, targetId, segment.id)
|
||||
const localEndpoint = transitLocal.trim() || suggested || (form.hub.includes(":") ? "" : form.hub.trim())
|
||||
const remoteEndpoint = transitRemote.trim() || publicEndpoint(target.inventory)
|
||||
const family = form.peerAddress.includes(":") ? 6 : 4
|
||||
const localEndpoint = form.transitLocal.trim() || suggested || (form.hub.includes(":") ? "" : form.hub.trim())
|
||||
const remoteEndpoint = form.transitRemote.trim() || publicEndpoint(target.inventory)
|
||||
const family = form.kind !== "both" && form.peerAddress.includes(":") ? 6 : 4
|
||||
const patch = (fields: Partial<FormState>) => setForm(value => ({ ...value, ...fields }))
|
||||
const nodeChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) }))
|
||||
const transports = [{ value: "wireguard", label: "WireGuard" }, { value: "gre-ipsec", label: "GRE/IPsec (IKEv2)" }]
|
||||
const groups = site?.groups.filter(group => group.onFailure === "block" && group.gateway.includes(":") === (family === 6)) ?? []
|
||||
const local = groups.find(group => group.id === "ix-wan" + family && group.primary.viaMain)
|
||||
const targets = nodes.filter(node => node.enabled && node.id !== form.serverId && ["ix-node", "exit-node"].includes(node.type ?? ""))
|
||||
@@ -82,7 +124,7 @@ function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
|
||||
...targets.filter(node => !groups.some(group => site?.interfaces.some(link => link.name === group.primary.interface && link.peerServerId === node.id)))
|
||||
.map(node => ({ value: "remote:" + node.id, label: "Через " + node.name + (node.type === "exit-node" ? " · ExitNode" : " · IX") })),
|
||||
]
|
||||
const valid = !!form.name.trim() && !!(form.hub || suggested) && (form.kind === "wireguard" || !!form.peer) &&
|
||||
const valid = !!form.name.trim() && !!hub && (!gre || isIpv4String(form.peer.trim()) && isIpv4String(hub)) &&
|
||||
(!targetId || !!localEndpoint && !!remoteEndpoint) && exits.some(exit => exit.value === form.exit)
|
||||
const destinationsField = <Field><FieldLabel htmlFor="ix-linux-destinations">Разрешённые сети IX</FieldLabel>
|
||||
<Textarea id="ix-linux-destinations" rows={2} value={form.destinations} placeholder="По одному CIDR на строку" onChange={event => patch({ destinations: event.target.value })} />
|
||||
@@ -92,36 +134,58 @@ function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
|
||||
if (!valid || busy) return
|
||||
void save({
|
||||
revision: segment.revision, serverId: form.serverId, interfaceName: binding?.name, name: form.name,
|
||||
kind: form.kind, hubEndpoint: form.hub.trim() || suggested, peerEndpoint: form.peer.trim() || undefined,
|
||||
peerPublicKey: form.kind === "wireguard" ? form.key.trim() || undefined : undefined,
|
||||
localAddress: form.localAddress.trim() || undefined, peerAddress: form.peerAddress.trim() || undefined,
|
||||
vpsClientId: !companion && vpsId && vpsId !== currentVps ? vpsId : undefined,
|
||||
kind: wireguard ? "wireguard" : "gre-ipsec", additionalGre: form.kind === "both" || undefined, companionOf: companion?.name,
|
||||
hubEndpoint: hub, peerEndpoint: form.peer.trim() || undefined,
|
||||
peerPublicKey: wireguard ? form.key.trim() || undefined : undefined,
|
||||
localAddress: form.kind === "both" ? undefined : form.localAddress.trim() || undefined,
|
||||
peerAddress: form.kind === "both" ? undefined : form.peerAddress.trim() || undefined,
|
||||
prefixes: lines(form.prefixes), destinations: lines(form.destinations), exit: form.exit === "isolated" || targetId ? undefined : form.exit,
|
||||
transit: targetId ? { targetServerId: targetId, name: transitName(segment, form.serverId, targetId, family), family,
|
||||
localEndpoint, remoteEndpoint } : undefined,
|
||||
enabled: form.enabled, rotate,
|
||||
enabled: form.enabled, rotate: !!binding && rotate,
|
||||
})
|
||||
}}>
|
||||
<div className="grid min-h-0 gap-4 overflow-y-auto px-4 pb-4">
|
||||
<Field><FieldLabel htmlFor="ix-linux-name">Имя клиента</FieldLabel>
|
||||
<Input id="ix-linux-name" value={form.name} placeholder="vps-01" required onChange={event => patch({ name: event.target.value })} /></Field>
|
||||
<Input id="ix-linux-name" value={form.name} placeholder="vps-01" readOnly={!!companion} required onChange={event => patch({ name: event.target.value })} /></Field>
|
||||
{!companion && !!knownVps.length && <Field><FieldLabel htmlFor="ix-linux-vps">Привязка к VPS</FieldLabel>
|
||||
<Select value={vpsId || currentVps || "separate"} disabled={!!currentGroup} items={[{ value: "separate", label: "Отдельное подключение" }, ...knownVps]}
|
||||
onValueChange={v => setVpsId(v && v !== "separate" ? v : "")}>
|
||||
<SelectTrigger id="ix-linux-vps"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{!currentVps && <SelectItem value="separate">Отдельное подключение</SelectItem>}
|
||||
{knownVps.map(v => <SelectItem key={v.value} value={v.value}>{v.label}</SelectItem>)}</SelectContent>
|
||||
</Select>{currentGroup && <FieldDescription>Привязка задана группой «{currentGroup.name}».</FieldDescription>}</Field>}
|
||||
{nodeChoices.length > 1 && <Field><FieldLabel htmlFor="ix-linux-node">Узел IX</FieldLabel>
|
||||
<Select value={String(form.serverId)} items={nodeChoices} disabled={!!edit}
|
||||
onValueChange={value => value && patch({ serverId: Number(value), hub: "", exit: "isolated" })}>
|
||||
<SelectTrigger id="ix-linux-node" className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{nodeChoices.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>}
|
||||
<Field><FieldLabel htmlFor="ix-linux-transport">Туннель</FieldLabel>
|
||||
<Select value={form.kind} items={transports} disabled={!!edit}
|
||||
onValueChange={value => (value === "wireguard" || value === "gre-ipsec") && patch({ kind: value })}>
|
||||
<SelectTrigger id="ix-linux-transport" className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{transports.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>
|
||||
<Field>
|
||||
<FieldTitle id="ix-linux-transport">Протоколы подключения</FieldTitle>
|
||||
<ButtonGroup aria-labelledby="ix-linux-transport" className="max-w-full">
|
||||
{protocols.map(({ kind, label }) => {
|
||||
const choosing = !!companion && edit?.chooseTransport
|
||||
const selected = choosing ? form.kind === kind : paired || !!companion || form.kind === "both" || form.kind === kind
|
||||
return <Button key={kind} type="button" size="sm" variant={selected ? "secondary" : "outline"} aria-pressed={selected}
|
||||
disabled={busy || (choosing ? form.kind === kind : existing ? paired || existing.kind === kind : form.kind === kind)}
|
||||
onClick={() => choosing ? patch({ kind }) : existing ? setAddProtocol(!companion)
|
||||
: patch({ kind: form.kind === "both" ? (kind === "wireguard" ? "gre-ipsec" : "wireguard") : "both" })}>{label}</Button>
|
||||
})}
|
||||
</ButtonGroup>
|
||||
{form.kind === "both" ? <FieldDescription>Оба туннеля получат свои адреса в одной VRF сегмента.</FieldDescription>
|
||||
: companion ? <FieldDescription>Настройки ниже относятся к новому туннелю в той же VRF.</FieldDescription>
|
||||
: paired ? <FieldDescription>Оба протокола настроены. Здесь редактируется {binding?.kind === "gre-ipsec" ? "GRE/IPsec" : "WireGuard"}.</FieldDescription>
|
||||
: edit ? <FieldDescription>Выберите второй протокол, чтобы добавить туннель в ту же VRF.</FieldDescription>
|
||||
: <FieldDescription>Можно отметить оба протокола.</FieldDescription>}
|
||||
</Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-peer">Внешний адрес Linux</FieldLabel>
|
||||
<Input id="ix-linux-peer" value={form.peer} placeholder="123.123.123.123" required={form.kind === "gre-ipsec"} onChange={event => patch({ peer: event.target.value })} />
|
||||
<FieldDescription>{form.kind === "gre-ipsec" ? "Фиксированный IPv4 на стороне VPS для GRE/IPsec." : form.exit === "isolated"
|
||||
<Input id="ix-linux-peer" value={form.peer} placeholder="123.123.123.123" required={gre} onChange={event => patch({ peer: event.target.value })} />
|
||||
<FieldDescription>{gre ? "Фиксированный IPv4 на VPS для GRE/IPsec. Ответы на SSH по этому адресу пойдут напрямую." : form.exit === "isolated"
|
||||
? "Для WireGuard это поле необязательно." : "Укажите публичный IP VPS, чтобы сохранить доступ по SSH при выходе через IX."}</FieldDescription></Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-exit">Выход трафика</FieldLabel>
|
||||
<Select value={form.exit} items={exits} onValueChange={value => { if (value) { patch({ exit: value }); setTransitLocal(""); setTransitRemote("") } }}>
|
||||
<Select value={form.exit} items={exits} onValueChange={value => { if (value) patch({ exit: value, transitLocal: "", transitRemote: "" }) }}>
|
||||
<SelectTrigger id="ix-linux-exit" className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{exits.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
@@ -129,52 +193,62 @@ function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
|
||||
</Field>
|
||||
{!!targetId && !publicEndpoint(target.inventory) && (target.loading ? <p role="status" className="text-sm text-muted-foreground">Читаем WAN выходного узла…</p> :
|
||||
<Field><FieldLabel htmlFor="ix-transit-target">IPv4 выходного узла</FieldLabel>
|
||||
<Input id="ix-transit-target" value={transitRemote} onChange={event => setTransitRemote(event.target.value)} />
|
||||
<Input id="ix-transit-target" value={form.transitRemote} onChange={event => patch({ transitRemote: event.target.value })} />
|
||||
<FieldDescription>Укажите адрес интерфейса CHR для межузлового туннеля.</FieldDescription></Field>)}
|
||||
{!!targetId && !suggested && !origin.loading && <Field><FieldLabel htmlFor="ix-transit-source">IPv4 узла IX для транзита</FieldLabel>
|
||||
<Input id="ix-transit-source" value={localEndpoint} onChange={event => setTransitLocal(event.target.value)} /></Field>}
|
||||
<Input id="ix-transit-source" value={localEndpoint} onChange={event => patch({ transitLocal: event.target.value })} /></Field>}
|
||||
{form.exit === "isolated" && destinationsField}
|
||||
<details className="grid gap-3" key={form.serverId + ":" + origin.loading}
|
||||
open={!origin.loading && !suggested && !binding?.provisionWireguard?.hubEndpoint && !binding?.localEndpoint}>
|
||||
<details className="grid gap-3" key={form.serverId + ":" + origin.loading + ":" + gre}
|
||||
open={!origin.loading && (!hub || gre && !isIpv4String(hub)) || undefined}>
|
||||
<summary className="cursor-pointer text-sm font-medium">Параметры туннеля</summary>
|
||||
<div className="mt-3 grid gap-3">
|
||||
<Field><FieldLabel htmlFor="ix-linux-hub">Внешний адрес IX</FieldLabel>
|
||||
<Input id="ix-linux-hub" value={form.hub || suggested} onChange={event => patch({ hub: event.target.value })} />
|
||||
<FieldDescription>{origin.loading ? "Читаем адрес WAN с CHR…" : suggested ? "Адрес WAN для подключения VPS." : "Введите адрес IX, доступный с VPS."}</FieldDescription>
|
||||
</Field>
|
||||
{form.kind === "wireguard" && <Field><FieldLabel htmlFor="ix-linux-key">Публичный ключ Linux</FieldLabel>
|
||||
{wireguard && <Field><FieldLabel htmlFor="ix-linux-key">Публичный ключ Linux</FieldLabel>
|
||||
<Input id="ix-linux-key" value={form.key} placeholder="Создать автоматически" onChange={event => patch({ key: event.target.value })} />
|
||||
<FieldDescription>Укажите ключ только для своей пары WireGuard.</FieldDescription></Field>}
|
||||
{form.exit !== "isolated" && destinationsField}
|
||||
<Field><FieldLabel htmlFor="ix-linux-tunnel-local">Адрес IX в туннеле (CIDR)</FieldLabel>
|
||||
{form.kind !== "both" && <><Field><FieldLabel htmlFor="ix-linux-tunnel-local">Адрес IX в туннеле (CIDR)</FieldLabel>
|
||||
<Input id="ix-linux-tunnel-local" value={form.localAddress} placeholder="Автоматический IPv4" onChange={event => patch({ localAddress: event.target.value })} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-tunnel-peer">Адрес Linux в туннеле</FieldLabel>
|
||||
<Input id="ix-linux-tunnel-peer" value={form.peerAddress} placeholder="Автоматический IPv4" onChange={event => patch({ peerAddress: event.target.value })} /></Field>
|
||||
<Input id="ix-linux-tunnel-peer" value={form.peerAddress} placeholder="Автоматический IPv4" onChange={event => patch({ peerAddress: event.target.value })} /></Field></>}
|
||||
<Field><FieldLabel htmlFor="ix-linux-prefixes">Сети за Linux</FieldLabel>
|
||||
<Textarea id="ix-linux-prefixes" rows={2} value={form.prefixes} onChange={event => patch({ prefixes: event.target.value })} /></Field>
|
||||
</div>
|
||||
</details>
|
||||
{edit && <div className="flex flex-wrap gap-2">
|
||||
{binding && <div className="flex flex-wrap gap-2">
|
||||
<Button type="button" size="sm" variant={form.enabled ? "outline" : "secondary"} aria-pressed={!form.enabled}
|
||||
onClick={() => patch({ enabled: !form.enabled })}>{form.enabled ? "Приостановить доступ" : "Возобновить доступ"}</Button>
|
||||
{form.kind === "gre-ipsec" && <Button type="button" size="sm" variant={rotate ? "secondary" : "outline"}
|
||||
aria-pressed={rotate} onClick={() => setRotate(!rotate)}>Выпустить новый PSK</Button>}
|
||||
</div>}
|
||||
</div>
|
||||
<SheetFooter>{form.kind === "wireguard" && !form.key && <p className="text-sm text-muted-foreground">После подтверждения можно скачать готовый файл WireGuard для Linux.</p>}
|
||||
<Button type="submit" disabled={!valid || busy}>Сохранить</Button>
|
||||
<SheetFooter>{(gre || !form.key) && <p className="text-sm text-muted-foreground">После подтверждения файлы подключения будут доступны в таблице.</p>}
|
||||
<Button type="submit" disabled={!valid || busy}>{companion ? "Добавить туннель" : "Сохранить"}</Button>
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button></SheetFooter>
|
||||
</form>
|
||||
}
|
||||
|
||||
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, inspect }: {
|
||||
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
|
||||
save: (input: IxLinuxClientRequest) => Promise<boolean>; refresh: () => void
|
||||
view: (binding: IxLinuxBinding) => void; revoke: (binding: IxLinuxBinding) => void
|
||||
view: (binding: IxLinuxBinding, transportOnly?: boolean) => void; revoke: (binding: IxLinuxBinding) => void
|
||||
inspect: (binding: IxLinuxBinding) => void
|
||||
bondAction: IxRowBondAction; catalog: IxBondCatalog
|
||||
renderGroups: (clientId: string) => ReactNode; manualGroup: ReactNode
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [edit, setEdit] = useState<{ site: IxSite; binding: Binding } | null>(null)
|
||||
const [edit, setEdit] = useState<ClientSelection | null>(null)
|
||||
const rows = useMemo(() => {
|
||||
const saved = segment.configuration.sites.flatMap(site => site.interfaces.flatMap(binding => binding.linux ? [{
|
||||
serverId: site.serverId, interfaceName: binding.name, kind: binding.kind as IxLinuxBinding["kind"],
|
||||
@@ -183,9 +257,26 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
|
||||
}] : []))
|
||||
return [...saved, ...applied.filter(binding => !saved.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName))]
|
||||
}, [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>[]>(() => [
|
||||
{ id: "name", header: "Клиент", size: 170, cell: ({ row }) => <div className="grid gap-0.5">
|
||||
<span className="font-medium">{row.original.name ?? row.original.interfaceName}</span>
|
||||
{ id: "name", header: "Интерфейс", size: 195, cell: ({ row }) => <div className="grid gap-0.5">
|
||||
<span className="break-all font-medium">{row.original.interfaceName}</span>
|
||||
<span className="text-xs text-muted-foreground">{nodeLabel(nodes, row.original.serverId)}</span>
|
||||
</div> },
|
||||
{ id: "transport", header: "Туннель", size: 105, cell: ({ row }) => row.original.kind === "wireguard" ? "WireGuard" : "GRE/IPsec" },
|
||||
@@ -202,58 +293,80 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
|
||||
} },
|
||||
{ id: "state", header: "Состояние", size: 160, cell: ({ row }) => {
|
||||
const binding = row.original
|
||||
if (!binding.policy) return <Badge variant="secondary">Прежняя настройка</Badge>
|
||||
if (!binding.policy) return <div className="grid gap-1"><Badge className="w-fit" variant="secondary">Прежняя настройка</Badge>
|
||||
{!catalog.candidates.some(c => c.segmentId === segment.id && c.serverId === binding.serverId && c.interfaceName === binding.interfaceName) &&
|
||||
<span className="text-xs text-muted-foreground">Параметры ручного туннеля проверяются при добавлении из RouterOS.</span>}</div>
|
||||
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName)
|
||||
const site = segment.configuration.sites.find(item => item.serverId === binding.serverId)
|
||||
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 (!binding.enabled) return <Badge variant="secondary">Приостановлен</Badge>
|
||||
return binding.connection?.state === "connected" ? <div className="grid gap-1">
|
||||
<Badge variant="success-light" className="w-fit">Подключён</Badge>
|
||||
{binding.connection.rx !== undefined && <span className="text-xs text-muted-foreground">RX {binding.connection.rx} · TX {binding.connection.tx}</span>}
|
||||
const { state, rx, tx } = binding.connection ?? {}
|
||||
return <div className="grid gap-1">
|
||||
<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>
|
||||
: <Badge variant="secondary">{binding.connection?.state === "waiting" ? "Ожидает туннель" : "Нет данных"}</Badge>
|
||||
} },
|
||||
{ id: "actions", header: "Действия", size: 140, cell: ({ row }) => {
|
||||
const binding = row.original
|
||||
const site = segment.configuration.sites.find(site => site.serverId === binding.serverId)
|
||||
const saved = site?.interfaces.find(candidate => candidate.name === binding.interfaceName)
|
||||
const paired = !!site && !!saved && hasCompanion(site, saved)
|
||||
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName && item.enabled !== false)
|
||||
const bond = !readOnly && bondAction(binding)
|
||||
return <div className="flex flex-wrap gap-1">
|
||||
{live && <Button size="sm" variant="outline" disabled={busy} aria-label={"Получить конфиг " + (binding.name ?? binding.interfaceName)}
|
||||
{live && <Button size="sm" variant="outline" disabled={busy} aria-label={"Получить конфиг " + (binding.name ?? binding.interfaceName) +
|
||||
(paired ? binding.kind === "wireguard" ? " · WireGuard" : " · GRE/IPsec" : "")}
|
||||
onClick={() => view(live)}>Конфиг Linux</Button>}
|
||||
{binding.policy && (live || !readOnly && saved?.linux) && <DropdownMenu>
|
||||
<DropdownMenuTrigger render={<Button type="button" size="icon-sm" variant="ghost" disabled={busy} aria-label={"Действия клиента " + binding.name} />}>
|
||||
{(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) + (paired ? " · " + binding.interfaceName : "")} />}>
|
||||
<EllipsisIcon aria-hidden />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{live && <DropdownMenuItem onClick={() => inspect(live)}>Проверить путь</DropdownMenuItem>}
|
||||
{bond && <DropdownMenuItem onClick={bond.open}>{bond.label}</DropdownMenuItem>}
|
||||
{live && (binding.policy || catalog.candidates.some(c => c.segmentId === segment.id && c.serverId === live.serverId && c.interfaceName === live.interfaceName)) &&
|
||||
<DropdownMenuItem onClick={() => view(live, true)}>Конфиг для группы ix-client</DropdownMenuItem>}
|
||||
{live?.policy && <DropdownMenuItem onClick={() => inspect(live)}>Проверить путь</DropdownMenuItem>}
|
||||
{!readOnly && site && saved?.linux && <DropdownMenuItem
|
||||
onClick={() => { setEdit({ site, binding: saved, addProtocol: true, chooseTransport: true }); setOpen(true) }}>Добавить туннель</DropdownMenuItem>}
|
||||
{!readOnly && saved?.linux && <DropdownMenuItem variant="destructive" onClick={() => revoke(binding)}>Отозвать доступ…</DropdownMenuItem>}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>}
|
||||
</div>
|
||||
} },
|
||||
], [nodes, applied, segment.configuration.sites, readOnly, busy, view, revoke, inspect])
|
||||
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns,
|
||||
getRowId: row => row.serverId + ":" + row.interfaceName })
|
||||
], [nodes, applied, segment, readOnly, busy, view, revoke, inspect, bondAction, catalog.candidates])
|
||||
return <Frame spacing="sm" className="min-w-0">
|
||||
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
|
||||
<FrameTitle>Linux-клиенты</FrameTitle>
|
||||
<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>
|
||||
{!readOnly && <Button type="button" size="sm" disabled={busy} onClick={() => { setEdit(null); setOpen(true) }}><PlusIcon />Подключить Linux</Button>}
|
||||
{manualGroup}
|
||||
</div>
|
||||
</FrameHeader>
|
||||
<FramePanel className="min-w-0 p-0">
|
||||
<DataGridShell table={table} recordCount={rows.length} isLoading={busy && !rows.length} loadingMode="skeleton" emptyMessage="В сегменте пока нет Linux-клиентов" />
|
||||
</FramePanel>
|
||||
{clients.size ? [...clients].map(([key, client]) => <FramePanel key={key} className="grid min-w-0 gap-3 p-0">
|
||||
<section aria-label={"Клиент " + client.name} className="grid min-w-0 gap-3">
|
||||
<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)}>
|
||||
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-lg" showCloseButton={!busy}>
|
||||
<SheetHeader><SheetTitle>{edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
|
||||
<SheetHeader><SheetTitle>{edit?.chooseTransport ? "Добавить туннель" : edit?.addProtocol ? "Добавить другой протокол" : edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
|
||||
<SheetDescription>Укажите VPS и выберите, куда направлять его трафик.</SheetDescription>
|
||||
{error && <p className="text-sm text-destructive" role="alert">{error}</p>}
|
||||
</SheetHeader>
|
||||
{open && <ClientForm segment={segment} edit={edit} nodes={nodes} backendUrl={backendUrl} busy={busy}
|
||||
{open && <ClientForm segment={segment} edit={edit} nodes={nodes} backendUrl={backendUrl} catalog={catalog} busy={busy}
|
||||
setAddProtocol={addProtocol => setEdit(selection => selection && { ...selection, addProtocol })}
|
||||
save={async input => { if (await save(input)) setOpen(false) }} cancel={() => setOpen(false)} />}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
+24
-13
@@ -23,6 +23,7 @@ import { requestJson } from "@/shared/api/http-client"
|
||||
import { ConfigurationFields, newSite, nodeLabel, RouteGrid, SegmentGrid, SegmentStatus, type IxNode } from "./ix-view"
|
||||
import { IxLinuxClients } from "./ix-linux-clients"
|
||||
import { IxExits } from "./ix-exits"
|
||||
import { IxClientBonds } from "./ix-client-bonds"
|
||||
|
||||
type Tab = "configuration" | "routes" | "linux"
|
||||
|
||||
@@ -74,7 +75,7 @@ export default function IxPage() {
|
||||
const [activeNode, setActiveNode] = useState(ALL_SERVERS_ID)
|
||||
const [observations, setObservations] = useState<IxSiteObservation[] | null>(null)
|
||||
const [linuxBindings, setLinuxBindings] = useState<IxLinuxBinding[]>([])
|
||||
const [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding) | null>(null)
|
||||
const [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding & { transportOnly: boolean }) | null>(null)
|
||||
const [linuxPath, setLinuxPath] = useState<(IxLinuxPath & Pick<IxLinuxBinding, "name" | "interfaceName">) | null>(null)
|
||||
const [review, setReview] = useState("")
|
||||
const [reviewError, setReviewError] = useState("")
|
||||
@@ -261,22 +262,23 @@ export default function IxPage() {
|
||||
setLinuxBindings(items)
|
||||
}
|
||||
|
||||
async function exportLinux(binding: IxLinuxBinding) {
|
||||
async function exportLinux(binding: IxLinuxBinding, transportOnly = false) {
|
||||
if (!selected) return
|
||||
setLinux(null)
|
||||
const query = new URLSearchParams({ serverId: String(binding.serverId), interfaceName: binding.interfaceName })
|
||||
if (transportOnly) query.set("transportOnly", "true")
|
||||
if (binding.managedWireguard && write) {
|
||||
const access = await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`,
|
||||
post({ serverId: binding.serverId, interfaceName: binding.interfaceName }))
|
||||
post({ serverId: binding.serverId, interfaceName: binding.interfaceName, ...(transportOnly && { transportOnly }) }))
|
||||
download(access.filename, access.template)
|
||||
setNotice("Конфигурация WireGuard скачана")
|
||||
return
|
||||
}
|
||||
const access = binding.policy && binding.kind === "gre-ipsec" && write
|
||||
? await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`,
|
||||
post({ serverId: binding.serverId, interfaceName: binding.interfaceName }))
|
||||
post({ serverId: binding.serverId, interfaceName: binding.interfaceName, ...(transportOnly && { transportOnly }) }))
|
||||
: await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux?${query}`)
|
||||
setLinux({ ...binding, ...access })
|
||||
setLinux({ ...binding, ...access, transportOnly })
|
||||
}
|
||||
|
||||
async function inspectLinux(binding: IxLinuxBinding) {
|
||||
@@ -465,12 +467,16 @@ export default function IxPage() {
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="linux" className="grid min-w-0 gap-3">
|
||||
{selected ? <IxLinuxClients key={selected.id} segment={selected} nodes={peers} backendUrl={backendUrl}
|
||||
{selected ? <IxClientBonds key={selected.id + ":" + selected.appliedRevision} segmentId={selected.id} segments={segments}
|
||||
backendUrl={backendUrl} nodes={peers} readOnly={!write || busy || dirty} live={live} download={download}>
|
||||
{(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}
|
||||
save={input => perform(() => stageClient(input))} revoke={binding => void perform(() => stageClient(binding))}
|
||||
refresh={() => void perform(loadLinuxBindings)} view={binding => void perform(() => exportLinux(binding))}
|
||||
inspect={binding => void perform(() => inspectLinux(binding))} />
|
||||
: <EmptyState title="Сохраните сегмент" description="После сохранения можно подключать клиентов." />}
|
||||
refresh={() => void perform(loadLinuxBindings)} view={(binding, transportOnly) => void perform(() => exportLinux(binding, transportOnly))}
|
||||
inspect={binding => void perform(() => inspectLinux(binding))} />}
|
||||
</IxClientBonds>
|
||||
: <EmptyState title="Сохраните сегмент" description="После сохранения можно подключать клиентов." />}
|
||||
{linuxPath && <Frame spacing="sm">
|
||||
<FrameHeader>
|
||||
<FrameTitle>Маршруты клиента · {linuxPath.name ?? linuxPath.interfaceName}</FrameTitle>
|
||||
@@ -489,19 +495,24 @@ export default function IxPage() {
|
||||
<FrameDescription>Ревизия {linux.revision} · {nodeLabel(nodes, linux.serverId)}</FrameDescription>
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid min-w-0 gap-3">
|
||||
<p className="text-sm text-muted-foreground">{linux.kind === "wireguard"
|
||||
<p className="text-sm text-muted-foreground">{linux.transportOnly
|
||||
? "Подготовьте туннель на VPS с указанным именем интерфейса. Маршруты назначит ix-client после включения группы."
|
||||
: linux.kind === "wireguard"
|
||||
? linux.managedWireguard ? "Готовый файл с ключом доступен пользователю с правом управления сетью."
|
||||
: "Подставьте приватный ключ Linux. После установки проверьте, куда направляются трафик и соединение управления."
|
||||
: linux.policy && write ? "Подключите файл к strongSwan. Храните конфиг с PSK с правами доступа только для root."
|
||||
: linux.policy && write ? "Скачайте оба файла в одну папку на VPS. Скрипт установит профиль strongSwan и поднимет GRE. SSH по внешнему IPv4 VPS останется прямым."
|
||||
: "Для подключения нужен индивидуальный PSK, выданный оператором."}</p>
|
||||
{(!linux.policy || linux.kind === "wireguard") && <pre className="max-h-64 min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.template}</pre>}
|
||||
<Button type="button" variant="outline" size="sm" className="w-fit" onClick={() => download(linux.filename, linux.template)}>
|
||||
Скачать {linux.managedWireguard ? "шаблон" : linux.filename}
|
||||
</Button>
|
||||
{linux.setup && <>
|
||||
<pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.setup}</pre>
|
||||
{linux.policy && write ? <pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{
|
||||
"sudo apt install charon-systemd strongswan-swanctl\nsudo systemctl start strongswan\nsudo sh ./" +
|
||||
linux.filename.replace(/\.conf$/, "-setup.sh")
|
||||
}</pre> : <pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.setup}</pre>}
|
||||
<Button type="button" variant="outline" size="sm" className="w-fit"
|
||||
onClick={() => download(linux.filename.replace(/\.conf$/, "-setup.sh"), "#!/bin/sh\nset -eu\n" + linux.setup + "\n")}>Скачать команды настройки</Button>
|
||||
onClick={() => download(linux.filename.replace(/\.conf$/, "-setup.sh"), "#!/bin/sh\nset -eu\n" + linux.setup + "\n")}>Скачать скрипт GRE</Button>
|
||||
</>}
|
||||
{linux.bgp && <p className="wrap-anywhere text-sm text-muted-foreground">
|
||||
BGP · ASN Linux {linux.bgp.localAs} · ASN IX {linux.bgp.remoteAs} · сосед {linux.bgp.neighbor}
|
||||
|
||||
+71
-137
@@ -70,7 +70,8 @@ import {
|
||||
type MatchedNetflowHop,
|
||||
} from "@/lib/map-netflow-hops"
|
||||
import { useMapGreTraffic } from "@/hooks/use-map-gre-traffic"
|
||||
import type { FlowMapCountryServiceGroup, FlowMapHop, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import { formatBytes } from "@/lib/fmt-rate"
|
||||
import type { FlowMapCountryServiceGroup, FlowMapInterfaceTraffic, FlowMapHop, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
|
||||
import { CountryFlagSvg } from "@/components/network-map/country-flag-svg"
|
||||
import { Button } from "@/components/ui/button"
|
||||
@@ -355,85 +356,6 @@ function serviceSharePct(share: number): string {
|
||||
return `${Math.round(share * 100)}%`
|
||||
}
|
||||
|
||||
function exitNodeIdsFromGre(greEdges: GreMapEdge[]): string[] {
|
||||
const ids = new Set<string>()
|
||||
for (const g of greEdges) {
|
||||
if (g.fromServer.type === "exit-node") ids.add(g.fromServer.id)
|
||||
if (g.toServer.type === "exit-node") ids.add(g.toServer.id)
|
||||
}
|
||||
return [...ids]
|
||||
}
|
||||
|
||||
function remapServiceEdgeFromId(
|
||||
fromId: string,
|
||||
servers: Server[],
|
||||
greEdges: GreMapEdge[],
|
||||
soleEnId: string | null,
|
||||
): string | null {
|
||||
const srv = servers.find((s) => s.id === fromId)
|
||||
if (srv?.type === "exit-node") return fromId
|
||||
for (const g of greEdges) {
|
||||
if (g.fromServer.id === fromId && g.toServer.type === "exit-node") return g.toServer.id
|
||||
if (g.toServer.id === fromId && g.fromServer.type === "exit-node") return g.fromServer.id
|
||||
}
|
||||
return soleEnId
|
||||
}
|
||||
|
||||
/** API-рёбра на EN; если hop нет — синтез от единственного EN на карте (GRE / каталог). */
|
||||
function drawableServiceEdges(
|
||||
services: FlowMapService[],
|
||||
edges: FlowMapServiceEdge[],
|
||||
servers: Server[],
|
||||
greEdges: GreMapEdge[],
|
||||
nodePosById: Record<string, { x: number; y: number }>,
|
||||
): FlowMapServiceEdge[] {
|
||||
const keep = new Set(services.map((s) => s.id))
|
||||
const greEn = exitNodeIdsFromGre(greEdges)
|
||||
const catalogEn = servers.filter((s) => s.type === "exit-node").map((s) => s.id)
|
||||
const enPool = greEn.length > 0 ? greEn : catalogEn
|
||||
const soleEnId = enPool.length === 1 ? enPool[0]! : null
|
||||
const merged = new Map<string, FlowMapServiceEdge>()
|
||||
|
||||
function bump(e: FlowMapServiceEdge) {
|
||||
const key = `${e.fromId}|${e.toId}`
|
||||
const prev = merged.get(key)
|
||||
if (!prev) {
|
||||
merged.set(key, { ...e })
|
||||
return
|
||||
}
|
||||
merged.set(key, {
|
||||
...prev,
|
||||
bytes: prev.bytes + e.bytes,
|
||||
bps: prev.bps + e.bps,
|
||||
bpsFwd: prev.bpsFwd + e.bpsFwd,
|
||||
bpsRev: prev.bpsRev + e.bpsRev,
|
||||
})
|
||||
}
|
||||
|
||||
for (const e of edges) {
|
||||
if (!keep.has(e.toId)) continue
|
||||
const fromId = remapServiceEdgeFromId(e.fromId, servers, greEdges, soleEnId)
|
||||
if (!fromId || !nodePosById[fromId]) continue
|
||||
bump({ ...e, fromId })
|
||||
}
|
||||
|
||||
const covered = new Set([...merged.values()].map((e) => e.toId))
|
||||
if (soleEnId && nodePosById[soleEnId]) {
|
||||
for (const svc of services) {
|
||||
if (covered.has(svc.id)) continue
|
||||
bump({
|
||||
fromId: soleEnId,
|
||||
toId: svc.id,
|
||||
bytes: svc.bytes,
|
||||
bps: svc.bps,
|
||||
bpsFwd: svc.bps,
|
||||
bpsRev: 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
return [...merged.values()]
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function pingColor(ms: number | null) {
|
||||
@@ -596,26 +518,33 @@ function GreEdgeMetricBadge({
|
||||
)
|
||||
}
|
||||
|
||||
// The badge shows download first. Destination edges are oriented from exit to service.
|
||||
function destinationRate(edge: FlowMapServiceEdge): MatchedNetflowHop {
|
||||
return { bytes: edge.bytes, bps: edge.bps, bpsFwd: edge.bpsRev, bpsRev: edge.bpsFwd }
|
||||
}
|
||||
|
||||
/** Живой поток NetFlow (не ёмкость канала / не BT). */
|
||||
function NetflowRateBadge({
|
||||
mx,
|
||||
my,
|
||||
hop,
|
||||
liveInterface,
|
||||
sourceLabel,
|
||||
emptyLabel,
|
||||
onOpen,
|
||||
}: {
|
||||
mx: number
|
||||
my: number
|
||||
hop: Pick<MatchedNetflowHop, "bps" | "bpsFwd" | "bpsRev">
|
||||
liveInterface?: string
|
||||
hop?: Pick<MatchedNetflowHop, "bps" | "bpsFwd" | "bpsRev">
|
||||
sourceLabel?: string
|
||||
emptyLabel?: string
|
||||
onOpen?: (e: React.SyntheticEvent<SVGElement>) => void
|
||||
}) {
|
||||
const showDir = !!liveInterface || hop.bpsFwd > 0 && hop.bpsRev > 0
|
||||
const bw = showDir ? 86 : 72
|
||||
const bh = liveInterface ? 41 : showDir ? 32 : 20
|
||||
const showDir = hop && (!!sourceLabel || hop.bpsFwd > 0 && hop.bpsRev > 0)
|
||||
const bw = sourceLabel ? 105 : showDir ? 86 : 72
|
||||
const bh = sourceLabel ? 41 : showDir ? 32 : 20
|
||||
return (
|
||||
<g
|
||||
role={onOpen?"button":undefined} aria-label={onOpen ? liveInterface ? "Текущий трафик GRE " + liveInterface : "Поток NetFlow между узлами" : undefined} tabIndex={onOpen?0:undefined} className="network-map-focusable"
|
||||
role={onOpen?"button":undefined} aria-label={onOpen ? "Поток NetFlow между узлами" : undefined} tabIndex={onOpen?0:undefined} className="network-map-focusable"
|
||||
onKeyDown={e=>{if(onOpen&&(e.key==="Enter"||e.key===" ")){e.preventDefault();e.stopPropagation();onOpen(e)}}}
|
||||
transform={`translate(${mx},${my})`}
|
||||
style={{ cursor: onOpen ? "pointer" : "default" }}
|
||||
@@ -623,7 +552,7 @@ function NetflowRateBadge({
|
||||
onClick={(e) => { e.stopPropagation(); onOpen?.(e) }}
|
||||
>
|
||||
<title>
|
||||
{liveInterface ? "Текущий RX/TX интерфейса " + liveInterface : "Поток NetFlow между узлами за интервал карты, без overlay/mesh."}
|
||||
{sourceLabel ? sourceLabel + " · RX/TX интерфейса" : "Средняя скорость по сохранённым потокам NetFlow за завершённые минуты."}
|
||||
</title>
|
||||
<rect className="network-map-focus-ring" x={-bw / 2 - 4} y={-bh / 2 - 4} width={bw + 8} height={bh + 8} rx="9" fill="none" stroke="var(--ring)" strokeWidth="2" />
|
||||
<rect
|
||||
@@ -636,15 +565,15 @@ function NetflowRateBadge({
|
||||
stroke="var(--status-online)"
|
||||
strokeWidth="1.15"
|
||||
/>
|
||||
<text textAnchor="middle" y={liveInterface ? "-8" : showDir ? "-4" : "4"} fontFamily="ui-monospace,monospace">
|
||||
<tspan fill="var(--status-online-fg)" fontSize="8" fontWeight="700">{formatNetflowRate(hop)}</tspan>
|
||||
<text textAnchor="middle" y={sourceLabel ? "-8" : showDir ? "-4" : "4"} fontFamily="ui-monospace,monospace">
|
||||
<tspan fill="var(--status-online-fg)" fontSize="8" fontWeight="700">{hop ? formatNetflowRate(hop) : emptyLabel}</tspan>
|
||||
</text>
|
||||
{showDir && (
|
||||
<text textAnchor="middle" y={liveInterface ? "4" : "10"} fontFamily="ui-monospace,monospace">
|
||||
<text textAnchor="middle" y={sourceLabel ? "4" : "10"} fontFamily="ui-monospace,monospace">
|
||||
<tspan fill="var(--status-online)" fontSize="6.5" fontWeight="600">{formatNetflowDir(hop)}</tspan>
|
||||
</text>
|
||||
)}
|
||||
{liveInterface && <text textAnchor="middle" y="14" fill="var(--muted-foreground)" fontSize="6.5">Live GRE</text>}
|
||||
{sourceLabel && <text textAnchor="middle" y="14" fill="var(--muted-foreground)" fontSize="6.5">{sourceLabel}</text>}
|
||||
</g>
|
||||
)
|
||||
}
|
||||
@@ -1173,6 +1102,7 @@ function NetworkMapContent() {
|
||||
}, [apiFetch, useLiveData, hasIxNodes])
|
||||
const [speedProbes, setSpeedProbes] = useState<GreSpeedProbeSnapshot[]>([])
|
||||
const [mapHops, setMapHops] = useState<FlowMapHop[]>([])
|
||||
const [interfaceTraffic, setInterfaceTraffic] = useState<FlowMapInterfaceTraffic[]>()
|
||||
const [mapServices, setMapServices] = useState<FlowMapService[]>([])
|
||||
const [mapServiceEdges, setMapServiceEdges] = useState<FlowMapServiceEdge[]>([])
|
||||
const [mapServicePaths, setMapServicePaths] = useState<FlowMapServicePath[]>([])
|
||||
@@ -1283,6 +1213,7 @@ function NetworkMapContent() {
|
||||
setSpeedProbes([])
|
||||
setGreResolvedIpv4ByHost({})
|
||||
setMapHops([])
|
||||
setInterfaceTraffic(undefined)
|
||||
setMapServices(MOCK_MAP_SERVICES)
|
||||
setMapServiceEdges(MOCK_MAP_SERVICE_EDGES)
|
||||
setMapServicePaths(MOCK_MAP_SERVICE_PATHS)
|
||||
@@ -1401,6 +1332,7 @@ function NetworkMapContent() {
|
||||
const setSearch=(value:string)=>updateUrl({q:value||null},true)
|
||||
const [showPingBadges, setShowPingBadges] = useState(true)
|
||||
const [showNetflow, setShowNetflow] = useState(true)
|
||||
const missingNetflow = !showNetflow ? "Слой выключен" : flowReadAt && !flowError ? "Нет записей" : "Нет данных"
|
||||
const [showServices, setShowServices] = useState(true)
|
||||
const reducedMotion=usePrefersReducedMotion()
|
||||
const [showAnimDots, setShowAnimDots] = useState(true)
|
||||
@@ -1412,6 +1344,7 @@ function NetworkMapContent() {
|
||||
if (!useLiveData) {
|
||||
queueMicrotask(() => {
|
||||
setMapHops([])
|
||||
setInterfaceTraffic(undefined)
|
||||
setMapServices(MOCK_MAP_SERVICES)
|
||||
setMapServiceEdges(MOCK_MAP_SERVICE_EDGES)
|
||||
setMapServicePaths(MOCK_MAP_SERVICE_PATHS)
|
||||
@@ -1441,6 +1374,7 @@ function NetworkMapContent() {
|
||||
if (cancelled||request!==epoch) return
|
||||
const res=networkMapFlowSchema.parse(raw)
|
||||
setMapHops(res.hops)
|
||||
setInterfaceTraffic(res.interfaceTraffic)
|
||||
setMapServices(res.services)
|
||||
setMapServiceEdges(res.serviceEdges)
|
||||
setMapServicePaths(res.servicePaths)
|
||||
@@ -1638,23 +1572,19 @@ function NetworkMapContent() {
|
||||
const m = new Map<string, GreNetflowHop>()
|
||||
if (!showNetflow) return m
|
||||
for (const e of greEdges) {
|
||||
const hop = matchNetflowForGreEdge(e, mapHops)
|
||||
if (hop && hopHasRate(hop)) m.set(greEdgeKey(e), hop)
|
||||
const hop = matchNetflowForGreEdge(e, mapHops, interfaceTraffic, mapWindowSec)
|
||||
if (hop) m.set(greEdgeKey(e), hop)
|
||||
}
|
||||
return m
|
||||
}, [greEdges, mapHops, showNetflow])
|
||||
}, [greEdges, mapHops, interfaceTraffic, mapWindowSec, showNetflow])
|
||||
|
||||
const greTrafficTargets = useMemo(() => {
|
||||
if (!useLiveData || !showNetflow || (!flowReadAt && !flowError)) return []
|
||||
return greEdges.flatMap(edge => {
|
||||
const edgeId = greEdgeKey(edge)
|
||||
const owner = edge.fromServer.id === edge.tunnel.serverId ? edge.fromServer : edge.toServer
|
||||
return edge.tunnel.enabled && edge.tunnel.status !== "down" && owner.status !== "offline" &&
|
||||
edge.tunnel.name && !netflowByGreKey.get(edgeId)?.exactInterface
|
||||
? [{ edgeId, serverId: owner.id, iface: edge.tunnel.name }]
|
||||
: []
|
||||
})
|
||||
}, [useLiveData, showNetflow, flowReadAt, flowError, greEdges, netflowByGreKey])
|
||||
if (!useLiveData || !selectedGreEdge) return []
|
||||
const { tunnel, fromServer, toServer } = selectedGreEdge
|
||||
const owner = tunnel.serverId === fromServer.id ? fromServer : toServer
|
||||
return tunnel.enabled && tunnel.status !== "down" && owner.status !== "offline" && tunnel.name
|
||||
? [{ edgeId: greEdgeKey(selectedGreEdge), serverId: owner.id, iface: tunnel.name }] : []
|
||||
}, [useLiveData, selectedGreEdge])
|
||||
const getGreLiveRate = useMapGreTraffic(backendUrl, greTrafficTargets)
|
||||
|
||||
const netflowByWanKey = useMemo(() => {
|
||||
@@ -1679,9 +1609,14 @@ function NetworkMapContent() {
|
||||
|
||||
const visibleMapServices = showServices ? destNodes : []
|
||||
const visibleServiceEdges = showServices
|
||||
? drawableServiceEdges(visibleMapServices, destEdges, mapServers, greEdges, nodePosById)
|
||||
? destEdges.filter(edge => nodePosById[edge.fromId] && visibleMapServices.some(service => service.id === edge.toId))
|
||||
: []
|
||||
|
||||
const selectedExitEdges = destEdges.filter(edge => edge.toId === liveSelectedService?.id)
|
||||
const unassignedBytes = liveSelectedService
|
||||
? liveSelectedService.bytes - selectedExitEdges.reduce((sum, edge) => sum + edge.bytes, 0)
|
||||
: 0
|
||||
|
||||
const nodes = mapServers
|
||||
.map((s) => ({ ...s, ...nodePosById[s.id]! }))
|
||||
// Визуальный приоритет: HR поверх JH, JH поверх EN.
|
||||
@@ -2290,7 +2225,7 @@ function NetworkMapContent() {
|
||||
|
||||
{/* ── Canvas ── */}
|
||||
<div ref={canvasRef} className={cn("flex-1 min-h-0 min-w-0 relative overflow-hidden bg-background select-none", (selected || selectedGreEdge || selectedService) && "hidden lg:block")}>
|
||||
<NetworkMapLegend />
|
||||
<NetworkMapLegend compact={Boolean(selected || selectedGreEdge || selectedService || (nodes.length && !nodes.some(isVisible)))} />
|
||||
{ixLinks.length > 0 && <button type="button" aria-pressed={showIx} onClick={() => setShowIx(value => !value)}
|
||||
className="absolute right-3 top-3 z-20 rounded-md border bg-popover px-3 py-2 text-xs font-medium">
|
||||
Связи IX
|
||||
@@ -2353,8 +2288,7 @@ function NetworkMapContent() {
|
||||
tBadge,
|
||||
normalPx,
|
||||
)
|
||||
const liveRate = getGreLiveRate(edgeId)
|
||||
const flowHop = liveRate ?? netflowByGreKey.get(edgeId)
|
||||
const flowHop = netflowByGreKey.get(edgeId)
|
||||
const flowPos = edgeBadgePosition(
|
||||
e.from.x,
|
||||
e.from.y,
|
||||
@@ -2419,12 +2353,13 @@ function NetworkMapContent() {
|
||||
outerSummary={greOuterSummaryLine(e.tunnel, fromN, toN, greResolvedMap)}
|
||||
/>
|
||||
)}
|
||||
{showNetflow && flowHop && (
|
||||
{showNetflow && (
|
||||
<NetflowRateBadge
|
||||
mx={flowPos.mx}
|
||||
my={flowPos.my}
|
||||
hop={flowHop}
|
||||
liveInterface={liveRate ? e.tunnel.name : undefined}
|
||||
hop={flowHop?.inWindow ? flowHop : undefined}
|
||||
emptyLabel={missingNetflow}
|
||||
sourceLabel={`NetFlow · ${mapWindowSec / 60} мин${flowHop?.source === "retained" ? " · выборка" : ""}`}
|
||||
onOpen={openGreDetail}
|
||||
/>
|
||||
)}
|
||||
@@ -2632,12 +2567,7 @@ function NetworkMapContent() {
|
||||
const from = nodeById[edge.fromId] ?? nodePosById[edge.fromId]
|
||||
const to = servicePosById[edge.toId]
|
||||
if (!from || !to) return null
|
||||
const hop: MatchedNetflowHop = {
|
||||
bytes: edge.bytes,
|
||||
bps: edge.bps,
|
||||
bpsFwd: edge.bpsFwd,
|
||||
bpsRev: edge.bpsRev,
|
||||
}
|
||||
const hop = destinationRate(edge)
|
||||
const fromR = "type" in from && from.type
|
||||
? TYPE_STYLE[from.type].r
|
||||
: TYPE_STYLE["exit-node"].r
|
||||
@@ -2717,12 +2647,7 @@ function NetworkMapContent() {
|
||||
const from = servicePosById[edge.fromId]
|
||||
const to = nestedPosById[edge.toId]
|
||||
if (!from || !to) return null
|
||||
const hop: MatchedNetflowHop = {
|
||||
bytes: edge.bytes,
|
||||
bps: edge.bps,
|
||||
bpsFwd: edge.bpsFwd,
|
||||
bpsRev: edge.bpsRev,
|
||||
}
|
||||
const hop = destinationRate(edge)
|
||||
const clipped = clipSegmentCircleToRect(
|
||||
from.x,
|
||||
from.y,
|
||||
@@ -2904,7 +2829,7 @@ function NetworkMapContent() {
|
||||
const tunnelOwner = edge.fromServer.id === t.serverId ? edge.fromServer : edge.toServer
|
||||
const selectedEdgeId = greEdgeKey(edge)
|
||||
const liveRate = getGreLiveRate(selectedEdgeId)
|
||||
const greFlow = liveRate ?? netflowByGreKey.get(selectedEdgeId)
|
||||
const greFlow = netflowByGreKey.get(selectedEdgeId)
|
||||
const localWanName = ifaceNameForGreOuterIp(edge.fromServer, t.localAddress, greResolvedMap)
|
||||
const remoteWanName = ifaceNameForGreOuterIp(edge.toServer, t.remoteAddress, greResolvedMap)
|
||||
const baseProbe = greTunnelProbe(t,!useLiveData)
|
||||
@@ -2968,19 +2893,23 @@ function NetworkMapContent() {
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">{liveRate ? "Текущий RX/TX GRE" : "Поток (NetFlow)"}</span>
|
||||
<span className="text-xs font-mono font-semibold text-emerald-400">
|
||||
{greFlow ? liveRate || greFlow.bpsFwd > 0 && greFlow.bpsRev > 0
|
||||
? formatNetflowDir(greFlow)
|
||||
: formatNetflowRate(greFlow) : "—"}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">NetFlow · {mapWindowSec / 60} мин{greFlow?.source === "retained" ? " · выборка" : ""}</span>
|
||||
<span className="text-xs font-mono">{greFlow?.inWindow ? formatNetflowDir(greFlow) : missingNetflow}</span>
|
||||
</div>
|
||||
{greFlow?.inWindow && greFlow.packets !== undefined && <p className="text-xs text-muted-foreground">
|
||||
За интервал · {formatBytes(greFlow.bytes)} · {greFlow.packets.toLocaleString("ru-RU")} пак.
|
||||
</p>}
|
||||
{greFlow?.lastBucketAt && <p className="text-xs text-muted-foreground">Последняя минута с данными · {new Date(greFlow.lastBucketAt).toLocaleString("ru-RU")}</p>}
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">Live GRE · RX/TX сейчас</span>
|
||||
<span className="text-xs font-mono">{liveRate ? formatNetflowDir(liveRate) : "Нет замера"}</span>
|
||||
</div>
|
||||
<p className="text-[10px] text-muted-foreground pt-2 leading-snug">
|
||||
{merged.hasSpeedMonitor
|
||||
? "Ping и/или TX/RX — с последнего прогона speed-пробы; проба сопоставляется с этим GRE по WAN и интерфейсам. "
|
||||
: useLiveData?"Измерения GRE неизвестны: нет подходящей пробы. ":"Измерения демонстрационные. "}
|
||||
{spGr?"Проба "+spGr.id+" · время Ping: "+(spGr.lastPingAt?new Date(spGr.lastPingAt).toLocaleString("ru-RU"):"неизвестно")+" · время TX/RX неизвестно. ":""}
|
||||
{liveRate ? "Текущий трафик по счётчикам интерфейса RouterOS." : `Поток по данным NetFlow за ${mapWindowSec / 60} мин, без overlay/mesh.`}
|
||||
Скорости RX/TX указаны со стороны {tunnelOwner.name}.{greFlow?.peerObservation ? " NetFlow получен с противоположного конца туннеля." : ""}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -3199,7 +3128,7 @@ function NetworkMapContent() {
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">Скорость</span>
|
||||
<span className="text-xs text-muted-foreground">Скорость по сохранённым потокам</span>
|
||||
<span className="text-xs font-mono font-medium [overflow-wrap:anywhere] text-right">
|
||||
{formatNetflowRate({
|
||||
bytes: liveSelectedService.bytes,
|
||||
@@ -3236,7 +3165,13 @@ function NetworkMapContent() {
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2">Выход</p>
|
||||
<div className="flex flex-col gap-3">
|
||||
{visibleServiceEdges.filter((e) => e.toId === liveSelectedService.id).map((e) => {
|
||||
{unassignedBytes > 0 && (
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
<span>Выход не определён</span>
|
||||
<span className="font-mono">{formatNetflowRate({ bps: liveSelectedService.bps * unassignedBytes / liveSelectedService.bytes })}</span>
|
||||
</div>
|
||||
)}
|
||||
{selectedExitEdges.map((e) => {
|
||||
const src = mapServers.find((s) => s.id === e.fromId)
|
||||
const enPaths = destPaths
|
||||
.filter((p) => p.serviceId === liveSelectedService.id && p.enId === e.fromId)
|
||||
@@ -3434,8 +3369,7 @@ function NetworkMapContent() {
|
||||
fromServer && toServer ? speedProbeByTunnelId.get(tunnelPanelKey) : undefined
|
||||
const merged = mergeGreMetricsWithSpeedProbe(spGre, baseProbe)
|
||||
const pc = pingColor(merged.pingMs)
|
||||
const liveRate = getGreLiveRate(tunnelPanelKey)
|
||||
const greFlow = liveRate ?? netflowByGreKey.get(tunnelPanelKey)
|
||||
const greFlow = showNetflow ? matchNetflowForGreEdge({tunnel: t}, mapHops, interfaceTraffic, mapWindowSec) : undefined
|
||||
const showMetrics =
|
||||
merged.pingMs != null ||
|
||||
(merged.dlMbps != null && merged.ulMbps != null) ||
|
||||
@@ -3481,7 +3415,7 @@ function NetworkMapContent() {
|
||||
)}
|
||||
{greFlow && (
|
||||
<span className="text-[9px] ml-1.5 text-emerald-400">
|
||||
{formatNetflowRate(greFlow)}{liveRate ? " · Live GRE" : ""}
|
||||
NetFlow · {mapWindowSec / 60} мин · {greFlow.inWindow ? formatNetflowRate(greFlow) : "Нет записей"}{greFlow.source === "retained" ? " · выборка" : ""}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
|
||||
@@ -464,6 +464,13 @@
|
||||
],
|
||||
"reason": "Общий listRevisions с REST: только метаданные, максимум 50 записей; серверная область и права проверяются до SQL, payload ревизии не выдаётся."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/linux-bonds",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Каталог для формы выбора туннелей одного VPS в WebUI. Оператор сопоставляет подключения разных площадок со своими локальными интерфейсами."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/nodes",
|
||||
@@ -1618,6 +1625,27 @@
|
||||
"operations": [],
|
||||
"reason": "Локальный предпросмотр объектов из компилятора. План MCP дополнительно фиксирует состояние площадок и требует подтверждения."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/linux-bonds",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "WebUI сохраняет выбранные оператором интерфейсы и порядок путей для последующего импорта и подтверждения в локальном ix-client."
|
||||
},
|
||||
{
|
||||
"method": "DELETE",
|
||||
"path": "/api/ix/segments/:id/linux-bonds/:bondId",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Оператор удаляет сохранённое описание группы из WebUI. Снятие политики на самом VPS подтверждается отдельно в ix-client."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/linux-bonds/:bondId/export",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Оператор скачивает JSON группы из WebUI и локально сопоставляет его с интерфейсами VPS в ix-client."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/plan",
|
||||
|
||||
@@ -60,6 +60,7 @@
|
||||
"test:ipsec": "tsx src/services/ipsec-config.test.ts && tsx src/services/ipsec-state.test.ts && tsx src/routes/ipsec-history.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-operation.test.ts && tsx src/routes/ipsec-mutation.test.ts && tsx src/routes/ipsec-nat.test.ts && tsx src/routes/ipsec-group.test.ts && tsx src/services/ipsec-peer-delete.test.ts && tsx src/modules/mcp/ipsec-peer-delete-actions.test.ts && tsx src/services/ipsec-user-delete.test.ts && tsx src/modules/mcp/ipsec-user-delete-actions.test.ts && tsx src/services/ipsec-certificate-delete.test.ts && tsx src/modules/mcp/ipsec-certificate-delete-actions.test.ts && tsx src/services/ipsec-peer-update.test.ts && tsx src/modules/mcp/ipsec-peer-update-actions.test.ts && tsx src/services/ipsec-user-update-model.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/services/ipsec-server-delete-model.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/ipsec-user-create-model.test.ts",
|
||||
"test:live-maps": "tsx src/services/gre-revision-restore.test.ts && tsx src/services/gre-native-mutation.test.ts && tsx src/services/gre-mutation.test.ts && tsx src/services/filter-rules-observed.test.ts && tsx src/services/firewall-revision-restore.test.ts && tsx src/services/firewall-address-write.test.ts && tsx src/services/firewall-rule-write.test.ts && tsx src/services/gre-observed-read.test.ts && tsx src/services/network-observed-read.test.ts && tsx src/services/firewall-rule-move.test.ts && tsx src/services/ospf-state-read.test.ts && tsx src/modules/mcp/readiness-http.test.ts && tsx src/services/probe-interface-model.test.ts && tsx src/services/wan-runtime-model.test.ts && tsx src/services/gre-keepalive.test.ts && tsx src/services/gre-read.test.ts && tsx src/services/ospf-route-parse.test.ts && tsx src/services/vxlan-live.test.ts && tsx src/routes/vxlan.test.ts && tsx src/services/containers-live.test.ts && tsx src/services/firewall-poll.test.ts && tsx src/services/gre-catalog-poll.test.ts && tsx src/routes/filters-gre-catalog.test.ts && tsx src/routes/bgp-catalog.test.ts && tsx src/services/bgp-catalog-parse.test.ts && tsx src/routes/ospf-catalog.test.ts && tsx src/services/ospf-observed-values.test.ts && tsx src/routes/ospf-legacy.test.ts",
|
||||
"test": "node scripts/test.mjs",
|
||||
"test:ix": "tsx --test src/services/internet-exchange-plan.test.ts src/services/internet-exchange-execution.test.ts src/services/internet-exchange-bonds.test.ts src/services/ix-bond-transport.test.ts",
|
||||
"test:evolution": "tsx src/services/evobgp-catalog.test.ts && tsx src/services/evobgp-client.test.ts && tsx src/routes/evobgp-catalog.test.ts && tsx src/routes/evobgp-settings.test.ts && tsx src/plugins/auth.evolution-settings.test.ts",
|
||||
"test:netflow-purge": "tsx src/db/operation-lock.test.ts && tsx src/services/traffic-flow-purge-execution.test.ts && tsx src/services/flow-purge-partitions.test.ts && tsx --test src/services/traffic-flow-worker-lifecycle.test.ts && tsx src/routes/traffic-flow-purge.test.ts",
|
||||
"test:netflow-settings": "tsx src/services/traffic-flow-host-file-builders.test.ts && tsx src/services/traffic-flow-key-execution.test.ts && tsx src/routes/traffic-flow-settings.test.ts && tsx src/plugins/auth.netflow-settings.test.ts && tsx src/services/traffic-flow-agent-install.test.ts && tsx src/services/traffic-flow-agent-client.test.ts && tsx src/services/traffic-flow-operation-queue.test.ts && tsx src/routes/traffic-flow-host.test.ts && tsx src/services/traffic-flow-settings-execution.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/traffic-flow-lifecycle-fence.test.ts && tsx src/services/traffic-flow-settings-store.test.ts && tsx src/services/traffic-flow-settings-service.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts",
|
||||
@@ -68,7 +69,7 @@
|
||||
"test:containers": "tsx src/services/containers-live.test.ts && tsx src/services/containers-state.test.ts && tsx src/services/container-removal.test.ts && tsx src/routes/containers-state.test.ts",
|
||||
"test:certificates": "tsx src/services/certificate-installation.test.ts && tsx src/services/certificate-renew-collector.test.ts && tsx src/services/certificate-issue-execution.test.ts && tsx src/services/certificate-issue-request.test.ts && tsx src/routes/certificates-issue.test.ts && tsx src/services/certificate-issue-dto.test.ts && tsx src/services/certificate-parse.test.ts && tsx src/services/certificates-state.test.ts && tsx src/routes/certificates-state.test.ts && tsx src/services/acme-settings-test.test.ts && tsx src/services/acme-settings-update-model.test.ts && tsx src/modules/mcp/acme-settings-actions.test.ts",
|
||||
"test:system-database": "tsx src/services/bounded-database-dump.test.ts && tsx src/services/database-dump-connection.test.ts && tsx src/services/system-database-partition-restore.test.ts && tsx src/services/system-database-cache.test.ts && tsx src/services/database-background-work.test.ts && tsx src/services/database-request-gate.test.ts && tsx --test src/services/detached-database-admission.test.ts && tsx src/services/traffic-flow-worker-shutdown.test.ts && tsx src/services/system-database-restore-execution.test.ts && tsx src/services/system-database-operation.test.ts && tsx src/services/system-database-schema-readiness.test.ts && tsx --test src/routes/mcp-oauth-database-admission.test.ts && tsx src/routes/system-database.test.ts && tsx src/plugins/auth.system-database.test.ts && tsx src/services/database-control-archive-boundary.test.ts && tsx src/db/database-schema-control-model.test.ts && tsx src/db/database-schema-control.test.ts && tsx src/db/controlled-migrations.test.ts && tsx src/db/controlled-schema-verification.test.ts && tsx --test src/db/migration-data-inventory.test.ts && tsx --test src/services/database-maintenance-startup.test.ts && tsx --test src/services/database-restore-audit.test.ts && tsx --test src/services/database-maintenance-resolution.test.ts && tsx --test scripts/database-maintenance-resolution.test.mts && tsx src/db/database-runtime-schema.test.ts",
|
||||
"test:all": "npm run test:logs && npm run test:probes && npm run test:exec && npm run test:alert-engine && npm run test:alerts-telegram && npm run test:auth && npm run test:wireguard && npm run test:ipsec && npm run test:traffic-rate && npm run test:traffic-flow && npm run test:users && npm run test:pg && npm run test:sidebar-counts && npm run test:backups && npm run test:scheduler && npm run test:live-maps && npm run test:ospf-optimizer && npm run test:recursive-routes && npm run test:config-sync && npm run test:ros-file && npm run test:containers && npm run test:certificates && npm run test:netflow-settings && npm run test:netflow-purge && npm run test:evolution && npm run test:system-database && npm run test:server-privacy && npm run test:mcp:module-completion && npm run test:mcp:loopback-agent && npm run test:server-probe-management && npm run test:server-poll-management && npm run test:mcp:routing-authority && npm run test:mcp:native-readers && npm run test:mcp:chr-acquisition && npm run test:mcp:shared-context && npm run test:mcp:telemetry-configuration",
|
||||
"test:all": "npm run test:ix && npm run test:logs && npm run test:probes && npm run test:exec && npm run test:alert-engine && npm run test:alerts-telegram && npm run test:auth && npm run test:wireguard && npm run test:ipsec && npm run test:traffic-rate && npm run test:traffic-flow && npm run test:users && npm run test:pg && npm run test:sidebar-counts && npm run test:backups && npm run test:scheduler && npm run test:live-maps && npm run test:ospf-optimizer && npm run test:recursive-routes && npm run test:config-sync && npm run test:ros-file && npm run test:containers && npm run test:certificates && npm run test:netflow-settings && npm run test:netflow-purge && npm run test:evolution && npm run test:system-database && npm run test:server-privacy && npm run test:mcp:module-completion && npm run test:mcp:loopback-agent && npm run test:server-probe-management && npm run test:server-poll-management && npm run test:mcp:routing-authority && npm run test:mcp:native-readers && npm run test:mcp:chr-acquisition && npm run test:mcp:shared-context && npm run test:mcp:telemetry-configuration",
|
||||
"test:server-privacy": "tsx ../packages/contracts/src/servers.test.ts && tsx src/routes/server-secrets-sql.test.ts && tsx --test src/services/server-connection-test.test.ts",
|
||||
"test:mcp:flow-rebuild:pg": "node scripts/test-mcp-postgres.mjs --flow-rebuild-mcp",
|
||||
"test:mcp:flow-host-keys:pg": "node scripts/test-mcp-postgres.mjs --flow-host-keys",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { createPrivateKey, createPublicKey, randomBytes, randomUUID } from "node:crypto"
|
||||
import { mkdtemp } from "node:fs/promises"
|
||||
import { createServer } from "node:http"
|
||||
import { mkdtemp, writeFile } from "node:fs/promises"
|
||||
import { createServer, type RequestListener } from "node:http"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { setTimeout as delay } from "node:timers/promises"
|
||||
@@ -23,7 +23,8 @@ Object.assign(process.env, {
|
||||
})
|
||||
await pg.initialise()
|
||||
await pg.start()
|
||||
const rows: Record<string, Record<string, string>[]> = {
|
||||
type RouterRows = Record<string, Record<string, string>[]>
|
||||
const rows: RouterRows = {
|
||||
"/ip/vrf": [{ ".id": "*1", name: "main", interfaces: "all", builtin: "true" }],
|
||||
"/interface": [{ ".id": "*A0", name: "gre-client", type: "gre", comment: "IX:ix-web-fixture" }],
|
||||
"/interface/gre": [{ ".id": "*A0", name: "gre-client", "local-address": "192.0.2.20", "remote-address": "192.0.2.21", "allow-fast-path": "false" }],
|
||||
@@ -34,26 +35,47 @@ let writes = 0
|
||||
let deletes = 0
|
||||
let failPutAt = -1
|
||||
let failDeleteAt = -1
|
||||
const router = createServer(async (request, response) => {
|
||||
const fixtureHubPublicKey = Buffer.alloc(32, 11).toString("base64")
|
||||
const serveRouter = (rows: RouterRows): RequestListener => async (request, response) => {
|
||||
try {
|
||||
const path = new URL(request.url!, "http://127.0.0.1").pathname.replace(/^\/rest/, "")
|
||||
let result: unknown
|
||||
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") {
|
||||
if (writes === failPutAt) throw Error("Synthetic RouterOS apply failure")
|
||||
let raw = ""
|
||||
for await (const chunk of request) raw += chunk
|
||||
const { "place-before": place, ...fields } = JSON.parse(raw)
|
||||
const row = { ...fields, ...(path === "/interface/wireguard" && { "public-key": "B".repeat(43) + "=" }),
|
||||
const row = { ...fields, ...(path === "/interface/wireguard" && { "public-key": fixtureHubPublicKey }),
|
||||
".id": "*" + (++writes + 1).toString(16).toUpperCase() }
|
||||
const list = rows[path] ??= []
|
||||
const index = list.findIndex(entry => entry[".id"] === place)
|
||||
list.splice(index < 0 ? list.length : index, 0, row)
|
||||
if (path === "/ip/vrf" || path === "/interface/wireguard" || path === "/interface/bridge") {
|
||||
if (["/ip/vrf", "/interface/wireguard", "/interface/bridge", "/interface/gre"].includes(path)) {
|
||||
rows["/interface"].push({ ".id": row[".id"], name: row.name,
|
||||
type: path === "/interface/wireguard" ? "wg" : path.split("/").at(-1)!, comment: row.comment })
|
||||
}
|
||||
result = row
|
||||
} else if (request.method === "PATCH") {
|
||||
const parent = path.slice(0, path.lastIndexOf("/"))
|
||||
const id = decodeURIComponent(path.slice(path.lastIndexOf("/") + 1))
|
||||
const row = rows[parent]?.find(entry => entry[".id"] === id)
|
||||
assert(row)
|
||||
let raw = ""
|
||||
for await (const chunk of request) raw += chunk
|
||||
Object.assign(row, JSON.parse(raw))
|
||||
writes++
|
||||
result = row
|
||||
} else if (request.method === "DELETE") {
|
||||
if (deletes === failDeleteAt) throw Error("Synthetic RouterOS deletion failure")
|
||||
const parent = path.slice(0, path.lastIndexOf("/"))
|
||||
@@ -73,7 +95,16 @@ const router = createServer(async (request, response) => {
|
||||
response.statusCode = 500
|
||||
response.end(JSON.stringify({ error: String(error) }))
|
||||
}
|
||||
})
|
||||
}
|
||||
const router = createServer(serveRouter(rows))
|
||||
const backupRows: RouterRows = {
|
||||
"/ip/vrf": [{ ".id": "*1", name: "main", interfaces: "all", builtin: "true" }],
|
||||
"/interface": [{ ".id": "*2", name: "ether1", type: "ether", running: "true" }],
|
||||
"/ip/address": [{ ".id": "*3", interface: "ether1", address: "198.51.100.20/24" }],
|
||||
"/ip/route": [{ ".id": "*4", "routing-table": "main", "dst-address": "0.0.0.0/0",
|
||||
gateway: "198.51.100.1%ether1", "immediate-gw": "198.51.100.1%ether1", active: "true" }],
|
||||
}
|
||||
const backupRouter = createServer(serveRouter(backupRows))
|
||||
const { initDatabase } = await import("../../src/db/bootstrap.js")
|
||||
const { pool } = await import("../../src/db/index.js")
|
||||
let app: Awaited<ReturnType<typeof import("../../src/index.js").buildApp>> | undefined
|
||||
@@ -281,9 +312,18 @@ try {
|
||||
{ serverId: Number(server.id), autonomousSystem: 64512, routerId: "192.0.2.6" },
|
||||
] } }, 200)).segment
|
||||
const managedPath = "/" + managed.id
|
||||
rows["/interface"].push({ ".id": "*FA", name: "ether1", type: "ether", running: "true" })
|
||||
;(rows["/ip/address"] ??= []).push(
|
||||
{ ".id": "*FB", interface: "ether1", address: "192.0.2.20/24" },
|
||||
{ ".id": "*FC", interface: "ether1", address: "192.0.2.30/24" },
|
||||
)
|
||||
;(rows["/ip/route"] ??= []).push({ ".id": "*FD", "routing-table": "main", "dst-address": "0.0.0.0/0",
|
||||
gateway: "192.0.2.1%ether1", "immediate-gw": "192.0.2.1%ether1", active: "true" })
|
||||
const clientInput = { serverId: Number(server.id), name: "linux-auto", kind: "wireguard", hubEndpoint: "192.0.2.20",
|
||||
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)
|
||||
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 }
|
||||
await post(managedPath + "/linux/credential", clientKey, 409)
|
||||
await post(managedPath + "/linux/credential", clientKey, 403, reader)
|
||||
@@ -341,23 +381,91 @@ try {
|
||||
assert.equal(inactive.status, 409)
|
||||
delete appliedPeer.disabled
|
||||
|
||||
const companionInput = { ...clientInput, kind: "gre-ipsec", companionOf: clientKey.interfaceName }
|
||||
const canceled = await post(managedPath + "/linux", { ...companionInput, revision: credential.revision }, 200)
|
||||
const canceledKey = { serverId: clientKey.serverId, interfaceName: canceled.interfaceName }
|
||||
const reverted = await post(managedPath + "/linux/revoke", { ...canceledKey, revision: canceled.segment.revision }, 200)
|
||||
const noChanges = await post(managedPath + "/plan", { revision: reverted.segment.revision }, 200)
|
||||
assert.deepEqual(noChanges.changes, [])
|
||||
const resumed = await post(managedPath + "/apply", { revision: reverted.segment.revision, digest: noChanges.digest }, 200)
|
||||
const paired = await post(managedPath + "/linux", { ...companionInput, revision: resumed.segment.revision }, 200)
|
||||
const bindings = paired.segment.configuration.sites[0].interfaces
|
||||
const [wireguard, greBinding] = bindings
|
||||
assert.match(greBinding.name, /^il-gre-[a-z0-9-]+-[0-9a-f]{12}$/)
|
||||
assert.ok(wireguard.linux.clientId)
|
||||
const original = resumed.segment.configuration.sites[0].interfaces[0]
|
||||
assert.deepEqual(wireguard, { ...original, linux: { ...original.linux, clientId: wireguard.linux.clientId } })
|
||||
assert.equal(wireguard.linux.clientId, greBinding.linux.clientId)
|
||||
assert.notEqual(wireguard.provisionWireguard.peerAddress, greBinding.provisionGre.peerAddress)
|
||||
const foreignRoute = { ".id": "*FE", "routing-table": "main", "dst-address": "198.51.100.0/24",
|
||||
gateway: "10.254.0.2%" + clientKey.interfaceName }
|
||||
rows["/ip/route"].push(foreignRoute)
|
||||
const blockedForeign = await post(managedPath + "/plan", { revision: paired.segment.revision }, 409)
|
||||
assert.match(blockedForeign.error, /другой маршрутизацией/)
|
||||
assert.equal(rows["/ip/route"].pop(), foreignRoute)
|
||||
const pairPlan = await post(managedPath + "/plan", { revision: paired.segment.revision }, 200)
|
||||
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 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))!
|
||||
assert(pairVrf.interfaces.split(",").includes(greBinding.name))
|
||||
const greCredential = await post(managedPath + "/linux/credential",
|
||||
{ serverId: clientKey.serverId, interfaceName: paired.interfaceName }, 200)
|
||||
assert.match(greCredential.template, /secret = "[a-f0-9]{64}"/)
|
||||
assert.match(greCredential.setup, /install -m 0600 "\$conf" \/etc\/swanctl\/conf\.d\//)
|
||||
assert.match(greCredential.setup, /ip -4 rule add pref \d+ from 192\.0\.2\.40\/32 lookup main/)
|
||||
assert.match(greCredential.setup, /ip -4 route replace default dev ixg\w+ src \S+ table \d+/)
|
||||
assert(greCredential.setup.indexOf(" lookup main\n") < greCredential.setup.indexOf("swanctl --initiate"))
|
||||
assert.equal((await post(managedPath + "/linux/credential", clientKey, 200)).template, credential.template)
|
||||
|
||||
const bondPath = managedPath + "/linux-bonds"
|
||||
const bondInput = { revision: 0, name: "mixed", mode: "weighted", directCidrs: ["192.0.2.0/24"],
|
||||
members: [wireguard, greBinding].map((binding, i) => ({ segmentId: managed.id, serverId: clientKey.serverId,
|
||||
interfaceName: binding.name, weight: i ? 1 : 3, appliedRevision: pairedApplied.segment.revision })) }
|
||||
await post(bondPath, bondInput, 403, reader)
|
||||
const bond = await post(bondPath, bondInput, 200)
|
||||
assert.equal(bond.clientId, wireguard.linux.clientId)
|
||||
await post(bondPath, bondInput, 409)
|
||||
const bundlePath = bondPath + "/" + bond.id + "/export"
|
||||
const bundle = await post(bundlePath, { revision: 1 }, 200)
|
||||
assert.deepEqual(bundle.members.map(member => [member.kind, member.weight]), [["wireguard", 3], ["gre-ipsec", 1]])
|
||||
assert.equal(bundle.members[0].peerPublicKey, fixtureHubPublicKey)
|
||||
assert.deepEqual(bundle.destinations, ["0.0.0.0/0"])
|
||||
assert(!JSON.stringify(bundle).includes(privateKey))
|
||||
if (process.env.IX_BOND_TEST_EXPORT) {
|
||||
await writeFile(process.env.IX_BOND_TEST_EXPORT, JSON.stringify(bundle, null, 2) + "\n", { flag: "wx" })
|
||||
}
|
||||
await post(bundlePath, { revision: 1 }, 403, reader)
|
||||
await post(managedPath + "/removal-plan", { revision: pairedApplied.segment.revision }, 409)
|
||||
|
||||
const { rows: [exit] } = await pool.query(`INSERT INTO servers
|
||||
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
|
||||
VALUES('owned-exit','127.0.0.1',$1,true,'exit-node','synthetic','synthetic',false,true) RETURNING id`, [port])
|
||||
rows["/interface"].push({ ".id": "*FA", name: "ether1", type: "ether", running: "true" })
|
||||
rows["/ip/address"].push(
|
||||
{ ".id": "*FB", interface: "ether1", address: "192.0.2.20/24" },
|
||||
{ ".id": "*FC", interface: "ether1", address: "192.0.2.30/24" },
|
||||
)
|
||||
rows["/ip/route"].push({ ".id": "*FD", "routing-table": "main", "dst-address": "0.0.0.0/0", "immediate-gw": "192.0.2.1%ether1", active: "true" })
|
||||
const transit = { targetServerId: Number(exit.id), localEndpoint: "192.0.2.20", remoteEndpoint: "192.0.2.30", family: 4, name: "remote-exit" }
|
||||
const remoteClient = { ...clientInput, name: "linux-remote", revision: credential.revision, transit }
|
||||
const appliedRevision = pairedApplied.segment.revision
|
||||
const remoteClient = { ...clientInput, name: "linux-remote", revision: appliedRevision, exit: undefined, transit }
|
||||
const beforeStage = writes
|
||||
await post(managedPath + "/linux", { ...remoteClient, localAddress: "10.254.21.1/30" }, 400)
|
||||
const stagedRemote = await post(managedPath + "/linux", remoteClient, 200)
|
||||
assert(!Object.hasOwn(stagedRemote.segment.configuration, "linuxBonds"))
|
||||
assert.deepEqual(await post(bundlePath, { revision: 1 }, 200), bundle)
|
||||
const racing = await Promise.all(["equal", "failover"].map(mode => fetch(origin + "/api/ix/segments" + bondPath, {
|
||||
method: "POST", headers: { authorization: "Bearer " + writer, "content-type": "application/json" },
|
||||
body: JSON.stringify({ ...bondInput, id: bond.id, revision: 1, mode }),
|
||||
})))
|
||||
assert.deepEqual(racing.map(r => r.status).sort(), [200, 409])
|
||||
const revised = await racing.find(r => r.ok)!.json()
|
||||
assert.equal(revised.revision, 2)
|
||||
await post(bundlePath, { revision: 1 }, 409)
|
||||
await post(bondPath + "/" + bond.id, { revision: 2 }, 204, writer, "DELETE")
|
||||
await post(bundlePath, { revision: 2 }, 409)
|
||||
assert.equal(writes, beforeStage)
|
||||
assert.equal(stagedRemote.segment.revision, credential.revision + 1)
|
||||
assert.equal(stagedRemote.segment.appliedRevision, credential.revision)
|
||||
assert.equal(stagedRemote.segment.revision, appliedRevision + 1)
|
||||
assert.equal(stagedRemote.segment.appliedRevision, appliedRevision)
|
||||
const remoteSite = stagedRemote.segment.configuration.sites[0]
|
||||
assert.equal(remoteSite.interfaces.find(row => row.name === stagedRemote.interfaceName).linux.exit, transit.name)
|
||||
const transitBinding = remoteSite.interfaces.find(row => row.name === remoteSite.groups.find(group => group.id === transit.name).primary.interface)
|
||||
@@ -369,15 +477,91 @@ try {
|
||||
change.path === "/ip/firewall/nat" && change.fields["out-interface"] === "ether1"))
|
||||
assert(remotePlan.changes.some(change => change.serverId === Number(server.id) && change.path === "/interface/wireguard"))
|
||||
assert.equal(writes, beforeStage)
|
||||
const both = await post(managedPath + "/linux", { ...clientInput, name: "both", peerEndpoint: "192.0.2.41",
|
||||
revision: stagedRemote.segment.revision, additionalGre: true }, 200)
|
||||
const added = both.segment.configuration.sites[0].interfaces.filter(binding => binding.linux?.name === "both")
|
||||
assert.deepEqual(added.map(binding => binding.kind), ["wireguard", "gre-ipsec"])
|
||||
assert.ok(added[0].linux.clientId)
|
||||
assert.equal(added[0].linux.clientId, added[1].linux.clientId)
|
||||
|
||||
await new Promise<void>(resolve => backupRouter.listen(0, "127.0.0.1", resolve))
|
||||
const { rows: [secondIx] } = await pool.query(`INSERT INTO servers
|
||||
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
|
||||
VALUES('owned-bond-peer','127.0.0.1',$1,true,'ix-node','synthetic','synthetic',false,true) RETURNING id`,
|
||||
[(backupRouter.address() as { port: number }).port])
|
||||
const secondSegment = (await post("", { revision: 0, configuration: { name: "ix-web-bond-peer", sites: [
|
||||
{ serverId: Number(secondIx.id), autonomousSystem: 64513, routerId: "192.0.2.8" },
|
||||
] } }, 200)).segment
|
||||
const secondPath = "/" + secondSegment.id
|
||||
const secondInput = { ...clientInput, hubEndpoint: "198.51.100.20", serverId: Number(secondIx.id), revision: secondSegment.revision }
|
||||
await post(secondPath + "/linux", { ...secondInput, vpsClientId: randomUUID() }, 409)
|
||||
const existingPair = await post(secondPath + "/linux", { ...secondInput, additionalGre: true }, 200)
|
||||
const initialPairPlan = await post(secondPath + "/plan", { revision: existingPair.segment.revision }, 200)
|
||||
const appliedPair = (await post(secondPath + "/apply", { revision: existingPair.segment.revision, digest: initialPairPlan.digest }, 200)).segment
|
||||
const [oldWg, oldGre] = appliedPair.configuration.sites[0].interfaces
|
||||
assert.notEqual(oldWg.linux.clientId, bond.clientId)
|
||||
const changeIdentity = { ...secondInput, interfaceName: oldWg.name, vpsClientId: bond.clientId, revision: appliedPair.revision }
|
||||
const secondWg = await post(secondPath + "/linux", changeIdentity, 200)
|
||||
const newTunnel = secondWg.segment.configuration.sites[0].interfaces[0]
|
||||
assert.deepEqual(newTunnel, { ...oldWg, linux: { ...oldWg.linux, clientId: bond.clientId } })
|
||||
assert.deepEqual(secondWg.segment.configuration.sites[0].interfaces[1], oldGre)
|
||||
assert.notEqual(newTunnel.provisionWireguard.peerAddress, wireguard.provisionWireguard.peerAddress)
|
||||
const secondaryPlan = await post(secondPath + "/plan", { revision: secondWg.segment.revision }, 200)
|
||||
assert.deepEqual(secondaryPlan.changes, [])
|
||||
const secondaryApplied = (await post(secondPath + "/apply", { revision: secondWg.segment.revision, digest: secondaryPlan.digest }, 200)).segment
|
||||
const cross = await post(bondPath, { ...bondInput, members: [bondInput.members[0], {
|
||||
segmentId: secondSegment.id, appliedRevision: secondaryApplied.revision, serverId: secondInput.serverId, interfaceName: secondWg.interfaceName, weight: 1,
|
||||
}] }, 200)
|
||||
await post(secondPath + "/removal-plan", { revision: secondaryApplied.revision }, 409)
|
||||
const groupedChange = await post(secondPath + "/linux", { ...changeIdentity, vpsClientId: oldGre.linux.clientId, revision: secondaryApplied.revision }, 409)
|
||||
assert.match(groupedChange.error, /исключите подключение/)
|
||||
const crossBundle = await post(bondPath + "/" + cross.id + "/export", { revision: 1 }, 200)
|
||||
assert.equal(crossBundle.members[1].address, newTunnel.provisionWireguard.peerAddress)
|
||||
await post(bondPath + "/" + cross.id, { revision: 1 }, 204, writer, "DELETE")
|
||||
const ownPublicKey = Buffer.alloc(32, 29).toString("base64")
|
||||
const manualVrf = backupRows["/ip/vrf"]
|
||||
const manualGrePolicy = { "src-address": "198.51.100.20/32", "dst-address": "192.0.2.22/32", protocol: "gre", action: "encrypt", level: "require", tunnel: "false" }
|
||||
backupRows["/interface/wireguard"].push({ name: "pre-wg", "public-key": fixtureHubPublicKey })
|
||||
backupRows["/interface/wireguard/peers"].push({ interface: "pre-wg", "public-key": ownPublicKey, "allowed-address": "10.7.0.2/32" })
|
||||
backupRows["/interface/gre"].push({ name: "pre-gre", "local-address": "198.51.100.20", "remote-address": "192.0.2.22", "allow-fast-path": "false" })
|
||||
backupRows["/ip/ipsec/policy"].push(manualGrePolicy)
|
||||
backupRows["/ip/address"].push({ interface: "pre-wg", address: "10.7.0.1/30" }, { interface: "pre-gre", address: "10.8.0.1/30" })
|
||||
const refs = ["pre-wg", "pre-gre"].map((interfaceName, i) => ({ interfaceName, segmentId: secondSegment.id, serverId: secondInput.serverId,
|
||||
appliedRevision: secondaryApplied.revision, weight: 1, existing: { linuxInterface: i ? "gre-manual" : "wg0", address: "10." + (7 + i) + ".0.2",
|
||||
probe: "10." + (7 + i) + ".0.1", endpoint: "198.51.100.20", destinations: ["10.250.0.0/24"],
|
||||
...(i ? { kind: "gre-ipsec", remoteEndpoint: "192.0.2.22" } : { kind: "wireguard", clientPublicKey: ownPublicKey }) } }))
|
||||
const manualPath = secondPath + "/linux-bonds"
|
||||
const manualInput = { ...bondInput, name: "existing", members: refs }
|
||||
const beforeManual = JSON.stringify(backupRows)
|
||||
const writesBeforeManual = writes
|
||||
await post(manualPath, manualInput, 403, reader)
|
||||
await post(manualPath, { ...manualInput, members: [{ ...refs[0], existing: { ...refs[0].existing, clientPublicKey: fixtureHubPublicKey } }, refs[1]] }, 409)
|
||||
manualVrf.unshift({ name: "another-vrf", interfaces: "pre-wg" })
|
||||
await post(manualPath, manualInput, 409)
|
||||
manualVrf.shift()
|
||||
const manual = await post(manualPath, manualInput, 200)
|
||||
const manualExport = manualPath + "/" + manual.id + "/export"
|
||||
const result = await post(manualExport, { revision: 1 }, 200)
|
||||
assert.deepEqual(result.members.map(p => p.interfaceName), ["wg0", "gre-manual"])
|
||||
assert.equal(result.members[0].peerPublicKey, fixtureHubPublicKey)
|
||||
manualGrePolicy.level = "use"
|
||||
await post(manualExport, { revision: 1 }, 409)
|
||||
manualGrePolicy.level = "require"
|
||||
await post(manualPath + "/" + manual.id, { revision: 1 }, 204, writer, "DELETE")
|
||||
assert.equal(writes, writesBeforeManual)
|
||||
assert.equal(JSON.stringify(backupRows), beforeManual)
|
||||
await post(secondPath + "/removal-plan", { revision: secondaryApplied.revision }, 200)
|
||||
|
||||
console.log(JSON.stringify({ appliedRevisions: [2, 4], writes, audit: audit.n, mcpConnections: connections.n,
|
||||
unauthenticated: 401, readOnly: 403, ownerMismatch: 409, drift: 409, replay: 409, protected: 409, linuxClients: clients.items.length,
|
||||
deletedDraft: true, removedNativeObjects: deletes, revisionsRetained: archive.revisions,
|
||||
mcpRemovalVerified: true, managedWireguardVerified: true, clientWithTransitStagedAtomically: true }))
|
||||
mcpRemovalVerified: true, managedWireguardVerified: true, clientWithTransitStagedAtomically: true, bothProtocolsInOneVrf: true,
|
||||
mixedBondExport: true, crossSegmentBond: true, concurrentBondEdits: true, existingRouterOsTunnels: true }))
|
||||
} finally {
|
||||
await mcp?.close()
|
||||
await app?.close()
|
||||
await new Promise<void>(resolve => router.close(() => resolve()))
|
||||
if (backupRouter.listening) await new Promise<void>(resolve => backupRouter.close(() => resolve()))
|
||||
await pool.end()
|
||||
await pg.stop()
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ import internetPathRoutes from "./routes/internet-path.js"
|
||||
import evobgpRoutes from "./routes/evobgp.js"
|
||||
import { createStorageProbeRoutes } from "./routes/probe-storage-handler.js"
|
||||
import schedulerRoutes from "./routes/scheduler.js"
|
||||
import { ConfigurationBusyError } from "./services/config-mutation-lock.js"
|
||||
import sidebarCountsRoutes from "./routes/sidebar-counts.js"
|
||||
import alertsRoutes from "./routes/alerts.js"
|
||||
import backupsRoutes from "./routes/backups.js"
|
||||
@@ -105,6 +106,7 @@ export async function buildApp(opts?: {
|
||||
return reply.status(status).send({ error: "Внутренняя ошибка сервера" })
|
||||
}
|
||||
const message = error instanceof Error ? error.message : "Ошибка запроса"
|
||||
if (error instanceof ConfigurationBusyError) return reply.code(409).send({ error: message, code: error.code })
|
||||
return reply.status(status).send({ error: message })
|
||||
})
|
||||
|
||||
|
||||
@@ -9,6 +9,10 @@ assert.equal(new Set(coverage.routes.map(routeKey)).size, coverage.routes.length
|
||||
assert.deepEqual(coverage.routes.map(routeKey).sort(), actual.map(routeKey).sort(), "REST routes changed: update mcp-coverage.json with a typed tool, human-only reason, or explicit pending adapter")
|
||||
const implemented = new Set(listActions().map(action => action.operation.id))
|
||||
const ixInterfaceRoutes = new Set([
|
||||
"GET /api/ix/linux-bonds",
|
||||
"POST /api/ix/segments/:id/linux-bonds",
|
||||
"DELETE /api/ix/segments/:id/linux-bonds/:bondId",
|
||||
"POST /api/ix/segments/:id/linux-bonds/:bondId/export",
|
||||
"GET /api/ix/nodes",
|
||||
"GET /api/ix/segments/:id/linux",
|
||||
"GET /api/ix/topology",
|
||||
|
||||
@@ -10,6 +10,8 @@ const leases = createPool(limit, true)
|
||||
leases.on("error", () => console.error("MCP database request lease lost on idle connection"))
|
||||
const apiLeases = createPool(limit, true)
|
||||
apiLeases.on("error", () => console.error("REST database request lease lost on idle connection"))
|
||||
const writeReserve = createPool(2, true)
|
||||
writeReserve.on("error", () => console.error("REST write database lease lost on idle connection"))
|
||||
const detachedApiLeases = createPool(2, true)
|
||||
detachedApiLeases.on("error", () => console.error("Detached REST database lease lost on idle connection"))
|
||||
const context = new AsyncLocalStorage<{ accepting: boolean; children: Set<Promise<unknown>>; signal: AbortSignal }>()
|
||||
@@ -28,19 +30,24 @@ export function withActiveDatabaseRequest<T>(run: (signal: AbortSignal) => Promi
|
||||
return child
|
||||
}
|
||||
|
||||
export function withMcpDatabaseRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, true) }
|
||||
export function withDatabaseApiRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, false) }
|
||||
export function withMcpDatabaseRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, leases) }
|
||||
export function withDatabaseApiRequest<T>(run: () => Promise<T>, mutation = false): Promise<T> {
|
||||
// A burst of slow GETs must leave room for a configuration change to reach its lock.
|
||||
const saturated = apiLeases.totalCount >= limit && apiLeases.idleCount === 0
|
||||
return withDatabaseRequest(run, mutation && saturated ? writeReserve : apiLeases)
|
||||
}
|
||||
export function checkDatabaseApiStartup(): Promise<void> {
|
||||
return withDatabaseRequest(async () => {}, false, false, true)
|
||||
return withDatabaseRequest(async () => {}, apiLeases, true)
|
||||
}
|
||||
|
||||
async function withDatabaseRequest<T>(run: () => Promise<T>, mcp: boolean, detached = false, starting = false): Promise<T> {
|
||||
async function withDatabaseRequest<T>(run: () => Promise<T>, pool: typeof apiLeases, starting = false): Promise<T> {
|
||||
const nested = withActiveDatabaseRequest(run)
|
||||
if (nested) return nested
|
||||
const mcp = pool === leases
|
||||
if (mcp && active >= limit) throw new McpError("RATE_LIMITED", "Лимит одновременно выполняемых запросов MCP", 429)
|
||||
if (mcp) active++
|
||||
try {
|
||||
const client = await (detached ? detachedApiLeases : mcp ? leases : apiLeases).connect()
|
||||
const client = await pool.connect()
|
||||
let destroy = true, acquired = false
|
||||
const lifetime = new AbortController()
|
||||
const disconnected = () => lifetime.abort(new McpError("PROTOCOL_STORAGE_BUSY", "Соединение с допуском MCP потеряно", 503))
|
||||
@@ -90,5 +97,5 @@ export function withMcpRunnerDatabaseRequest<T>(run: () => Promise<T>): Promise<
|
||||
|
||||
/** Detached jobs keep their own lease through terminal persistence after the HTTP response. */
|
||||
export function withDetachedDatabaseApiRequest<T>(run: () => Promise<T>): Promise<T> {
|
||||
return context.exit(() => sharedDatabaseGate.request(() => withDatabaseRequest(run, false, true)))
|
||||
return context.exit(() => sharedDatabaseGate.request(() => withDatabaseRequest(run, detachedApiLeases)))
|
||||
}
|
||||
@@ -49,7 +49,7 @@ export function registerFlowMapActions(register: typeof add) {
|
||||
await authorize()
|
||||
const output = { serverId: server.id, userId: input.userId ?? null, interface: input.interface ?? null, map: projected, pages, sourceWindow,
|
||||
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false, listenerBound,
|
||||
source: "retained flow_buckets plus pending; same REST map engine with scoped topology",
|
||||
source: "closed minutes for all rates; retained flows for services, exit exporter or observed GRE peer/next hop for paths; interfaceTraffic includes private routed traffic before top-N",
|
||||
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,
|
||||
referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false,
|
||||
rowSumIsNetworkTotal: false, historicalOwnershipVerified: false,
|
||||
|
||||
@@ -94,6 +94,7 @@ test("actual collector initial settings failures release resource/ping/group bus
|
||||
const modules:Record<string,unknown>={"../db/index.js":{db,dbAll:async()=>[]},"../db/schema.js":tables,"drizzle-orm":Object.fromEntries(["and","asc","eq","gte","lte","inArray","max","sql"].map(name=>[name,()=>null])),
|
||||
"./config-mutation-policy.js":{executeGuardedApplicationWrite:()=>assert.fail("no config mutation")},"./monitoring-server-catalog.js":{listEnabledMonitoringServers:async()=>[]},"./mikrotik.js":{MikrotikClient:class{}},"../types/scheduler-run-snapshot.js":{SCHEDULER_RUN_SNAPSHOT_VERSION:1},"../constants/ping-probe.js":{PING_PROBE_WARN_RTT_MS:100},"./ros-metric-parse.js":{},"./ping-probe-replacement.js":{},"./partition-write-transaction.js":{withPartitionWrite:()=>assert.fail("no targets"),isPartitionWriteOutcomeUnknown:()=>false,PartitionWriteError:class extends Error{}}}
|
||||
const exports:Record<string,(...args:unknown[])=>Record<string,unknown>|Promise<Record<string,unknown>>>={}
|
||||
modules["./config-mutation-lock.js"] = { withApplicationCollectorLock: (collect: () => Promise<unknown>) => collect() }
|
||||
const code=ts.transpileModule(await readFile(new URL("../../services/uptime-collector.ts",import.meta.url),"utf8"),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText
|
||||
runInNewContext(code,{exports,require:(name:string)=>{assert(name in modules,name);return modules[name]},Date,performance,console,Set,Map,Promise,Number,String,Math,Object,JSON,Error})
|
||||
for(const method of ["collectResourceSamplesOnce","collectPingProbesOnce","collectPingForProbeIds"]){
|
||||
|
||||
@@ -23,7 +23,7 @@ export function installDatabaseRequestGate(app: FastifyInstance, admit = withDat
|
||||
const run = async () => withConfigurationActor(request.authUser?.id ?? "system", async () => await original.call(this, request, reply))
|
||||
// The service owns exclusivity, including calls that do not originate in HTTP.
|
||||
if (operation) return run()
|
||||
if (!stream) return gate.request(() => admit(run))
|
||||
if (!stream) return gate.request(() => admit(run, !["GET", "HEAD", "OPTIONS"].includes(request.method)))
|
||||
const state = { cancelled: false, abort: undefined as (() => void) | undefined }
|
||||
streams.set(request, state)
|
||||
try {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { coalesceCatalogReads, observationIsCurrent, readCatalogWithObservedCache, withCatalogWriteLock } from "../services/routing-catalog-observation.js"
|
||||
import { and, asc, eq, inArray } from "drizzle-orm"
|
||||
import { z } from "zod"
|
||||
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
|
||||
@@ -8,7 +9,6 @@ import { pollGreCatalog } from "../services/gre-catalog-poll.js"
|
||||
import { parseKeepalive } from "../services/gre-live.js"
|
||||
import { parseDbServerId } from "../utils/server-id.js"
|
||||
import { observeBgpFilterRules } from "../services/filter-rules-observed.js"
|
||||
import { withApplicationMutationLock, withConfigMutationLock } from "../services/config-mutation-lock.js"
|
||||
import { appendEvent } from "../modules/events/service/events-service.js"
|
||||
import { managedComment, hasManagedCommentPrefix } from "../managed-markers.js"
|
||||
import { compileManagedFilterRules, filterRuleBranches, filterRuleDescriptions, filterRuleToken, validatedFilterRules } from "../services/filter-rules-write-model.js"
|
||||
@@ -282,6 +282,8 @@ export async function fetchServerFilters(server: ServerRow) {
|
||||
}
|
||||
}
|
||||
|
||||
const readWebFilters = coalesceCatalogReads(fetchServerFilters)
|
||||
|
||||
async function toApiRulesets(serverRows: ServerRow[]) {
|
||||
const dbRules = serverRows.length ? await db.select().from(filterRules).where(inArray(filterRules.serverId, serverRows.map(server => server.id))).orderBy(asc(filterRules.serverId), asc(filterRules.sortOrder), asc(filterRules.id)) : []
|
||||
return serverRows.map(s => ({
|
||||
@@ -381,20 +383,26 @@ export async function readFilterRulesCatalog(selected: ServerRow[], options: { s
|
||||
const rulesets = await toApiRulesets(selected)
|
||||
return rulesets.map(ruleset => ({ ...ruleset, greTunnels: [] as LiveGreTunnel[], nativeRules: null as ReturnType<typeof observeBgpFilterRules> | null, live: false, stale: false, source: "cache" as const, error: null as string | null }))
|
||||
}
|
||||
const readSelected = () => Promise.all(selected.map(async server => {
|
||||
return Promise.all(selected.map(async server => {
|
||||
try {
|
||||
const remote = await fetchServerFilters(server)
|
||||
if (options.persistObserved) {
|
||||
const read = async (fresh: boolean) => {
|
||||
const remote = await (fresh || !options.persistObserved ? fetchServerFilters : readWebFilters)(server)
|
||||
if (!options.persistObserved) return { remote, rules: remote.rules, current: true }
|
||||
const rules = await cacheRulesetsForServer(server.id)
|
||||
const current = await observationIsCurrent(server.id, "filters", canonicalFilterRules(remote.rules), canonicalFilterRules(rules))
|
||||
return { remote, rules, current }
|
||||
}
|
||||
const { remote, rules } = await readCatalogWithObservedCache(server, read, async ({ remote }) => {
|
||||
await replaceDbRules(server.id, remote.rules)
|
||||
await appendRevisionIfChanged({ serverId: server.id, section: "filters", source: "observed", payload: canonicalFilterRules(remote.rules) })
|
||||
}
|
||||
return { serverId: String(server.id), rules: options.persistObserved ? await cacheRulesetsForServer(server.id) : remote.rules, greTunnels: remote.tunnels, nativeRules: remote.nativeRules, live: true, stale: false, source: "device" as const, error: null as string | null }
|
||||
} catch {
|
||||
return { remote, rules: await cacheRulesetsForServer(server.id), current: true }
|
||||
})
|
||||
return { serverId: String(server.id), rules, greTunnels: remote.tunnels, nativeRules: remote.nativeRules, live: true, stale: false, source: "device" as const, error: null as string | null }
|
||||
} catch (error) {
|
||||
if (error instanceof McpError && error.statusCode === 409) throw error
|
||||
return { serverId: String(server.id), rules: await cacheRulesetsForServer(server.id), greTunnels: [] as LiveGreTunnel[], nativeRules: null, live: false, stale: true, source: "cache" as const, error: server.enabled ? "Не подтверждено чтение фильтров выбранного сервера" : "Сервер выключен. Опрос фильтров недоступен." }
|
||||
}
|
||||
}))
|
||||
return options.persistObserved
|
||||
? withApplicationMutationLock(() => withConfigMutationLock(selected.map(server => server.id), readSelected)) : readSelected()
|
||||
}
|
||||
|
||||
export async function applyFiltersToServer(
|
||||
@@ -406,7 +414,7 @@ export async function applyFiltersToServer(
|
||||
if (!server.enabled) throw new McpError("DEVICE_UNAVAILABLE", "Сервер выключен; изменение фильтров запрещено", 409)
|
||||
if (options.managedRuleComment !== undefined && !hasManagedCommentPrefix(options.managedRuleComment)) throw new McpError("PROTECTED_OBJECT", "Сохранённый comment фильтра не принадлежит приложению", 409)
|
||||
rules = validatedFilterRules(rules)
|
||||
return executeGuardedApplicationWrite({ kind: "filters", id: "managed-bgp-in" }, [server.id], () => withConfigMutationLock([server.id], async () => {
|
||||
return withCatalogWriteLock(server, "filters", () => executeGuardedApplicationWrite({ kind: "filters", id: "managed-bgp-in" }, [server.id], async () => {
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const interfaces = rules.some(rule => rule.action !== "blackhole" && rule.gatewayTunnelId && !rule.gatewayTunnelId.startsWith("rec:")) ? nativeBgpRows(await client.get("/interface/gre")) : []
|
||||
const ruleBody = await toRouterRuleBody(server.id, rules, interfaces)
|
||||
@@ -442,7 +450,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
const server = enabledServers.find(s => s.id === sid)
|
||||
if (!server) return reply.status(404).send({ error: "Server not found" })
|
||||
try {
|
||||
const remote = await fetchServerFilters(server)
|
||||
const remote = await readWebFilters(server)
|
||||
return reply.send({ tunnels: remote.tunnels })
|
||||
} catch (error) {
|
||||
app.log.warn({ serverId: sid, err: String(error) }, "filters GRE catalog unavailable")
|
||||
@@ -450,7 +458,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
}
|
||||
}
|
||||
|
||||
return reply.send(await pollGreCatalog(enabledServers, fetchServerFilters))
|
||||
return reply.send(await pollGreCatalog(enabledServers, readWebFilters))
|
||||
})
|
||||
|
||||
/** Без serverId — cache для дашборда. С serverId — live с CHR, cache fallback. */
|
||||
@@ -523,6 +531,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
rules: cached,
|
||||
})
|
||||
} catch (err) {
|
||||
if (err instanceof McpError && err.statusCode === 409) throw err
|
||||
app.log.error({ serverId, err: String(err) }, "filters apply failed")
|
||||
await appendEvent({
|
||||
level: "critical",
|
||||
@@ -588,6 +597,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
})
|
||||
return reply.send({ ok: true, rules: cached, pushedRules: result.pushed })
|
||||
} catch (err) {
|
||||
if (err instanceof McpError) throw err
|
||||
app.log.error({ serverId: server.id, err: String(err) }, "filters restore failed")
|
||||
return reply.status(500).send({ error: String(err) })
|
||||
}
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import { randomUUID } from "node:crypto"
|
||||
import type { FastifyPluginAsync } from "fastify"
|
||||
import { z } from "zod"
|
||||
import { ixChangeSchema, ixLinuxClientRequest, ixTransitRequest, type IxWebPlan } from "@mmapp/contracts/internet-exchange"
|
||||
import { ixBondEditSchema, ixChangeSchema, ixLinuxClientRequest, ixTransitRequest, type IxWebPlan } from "@mmapp/contracts/internet-exchange"
|
||||
import { fingerprint, McpError } from "../modules/mcp/security.js"
|
||||
import { audit } from "../modules/mcp/store.js"
|
||||
import { pool } from "../db/index.js"
|
||||
import { captureVerifiedRestRequest, inspectVerifiedRestRequest, RestRequestProvenanceError } from "../plugins/auth.js"
|
||||
import { withApplicationMutationLock } from "../services/config-mutation-lock.js"
|
||||
import { withApplicationCollectorLock, withApplicationMutationLock } from "../services/config-mutation-lock.js"
|
||||
import { withConfigurationActor } from "../services/config-mutation-policy.js"
|
||||
import { applyIxChange, assignIxRouterIds, configureIxLinuxClient, configureIxTransit, listIxLinuxClients, observeIxLinuxPath, observeIxSegment, prepareIxChange, prepareIxRemoval, readIxLinuxClient, readIxNodeInventory, removeIxSegment } from "../services/internet-exchange-execution.js"
|
||||
import { compileIxConfiguration, IxConflict } from "../services/internet-exchange-plan.js"
|
||||
import { assertIxRevision, listIxSegments, readIxSegment, writeIxRevision } from "../services/internet-exchange-store.js"
|
||||
import { changeIxBond, exportIxBond, inspectIxBondImports, ixBondCatalog } from "../services/internet-exchange-bonds.js"
|
||||
|
||||
const paging = z.object({
|
||||
limit: z.coerce.number().int().min(1).max(100).default(25),
|
||||
@@ -52,7 +53,7 @@ const ixRoutes: FastifyPluginAsync = async app => {
|
||||
app.setErrorHandler((error, request, reply) => {
|
||||
if (error instanceof z.ZodError) return reply.code(400).send({ error: "Некорректные параметры IX", details: error.issues })
|
||||
if (error instanceof IxConflict) return reply.code(error.statusCode).send({ error: error.message })
|
||||
if (error instanceof McpError) return reply.code(error.statusCode).send({ error: error.message })
|
||||
if (error instanceof McpError) return reply.code(error.statusCode).send({ error: error.message, code: error.code })
|
||||
if (error instanceof RestRequestProvenanceError) return reply.code(403).send({ error: "Нет действующего права изменения IX" })
|
||||
request.log.error({ error: error instanceof Error ? error.name : "unknown" }, "IX request failed")
|
||||
const errorMessage = request.method === "DELETE" ? "Удаление сегмента IX не подтверждено. Обновите данные и проверьте план."
|
||||
@@ -65,6 +66,34 @@ const ixRoutes: FastifyPluginAsync = async app => {
|
||||
const input = paging.parse(request.query)
|
||||
return { items: await listIxSegments(input.limit, input.offset) }
|
||||
})
|
||||
app.get("/ix/linux-bonds", async () => ixBondCatalog())
|
||||
app.post("/ix/segments/:id/linux-bonds", async request => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const edit = ixBondEditSchema.parse(request.body)
|
||||
await inspectIxBondImports(id, edit)
|
||||
return withApplicationMutationLock(() => changeIxBond(id, edit, request.authUser?.id ?? "local-operator"), { waitMs: 5000 })
|
||||
})
|
||||
app.delete("/ix/segments/:id/linux-bonds/:bondId", async (request, reply) => {
|
||||
const { id, bondId } = segmentParams.extend({ bondId: z.uuid() }).parse(request.params)
|
||||
const { revision } = planRequest.parse(request.body)
|
||||
await withApplicationMutationLock(() => changeIxBond(id, { id: bondId, revision }, request.authUser?.id ?? "local-operator"), { waitMs: 5000 })
|
||||
return reply.code(204).send()
|
||||
})
|
||||
app.post("/ix/segments/:id/linux-bonds/:bondId/export", async (request, reply) => {
|
||||
const { id, bondId } = segmentParams.extend({ bondId: z.uuid() }).parse(request.params)
|
||||
const { revision } = planRequest.parse(request.body)
|
||||
const scope = { deadlineAt: Date.now() + 90_000 }
|
||||
const token = await captureVerifiedRestRequest(request, scope)
|
||||
const authorize = () => inspectVerifiedRestRequest(token, scope, "mm:network:write")
|
||||
const { ownerId } = await authorize()
|
||||
return withApplicationCollectorLock(async () => {
|
||||
const bundle = await exportIxBond(id, bondId, revision, authorize)
|
||||
await audit(pool, ownerId, "ix.bond.exported", null, { segmentId: id, bondId, revision })
|
||||
await authorize()
|
||||
reply.header("Cache-Control", "no-store")
|
||||
return bundle
|
||||
})
|
||||
})
|
||||
app.get("/ix/nodes", async () => {
|
||||
const [nodes, peers] = await Promise.all([
|
||||
pool.query("SELECT id,name,site,country,enabled FROM servers WHERE type='ix-node' ORDER BY name,id LIMIT 500"),
|
||||
@@ -96,12 +125,12 @@ const ixRoutes: FastifyPluginAsync = async app => {
|
||||
app.get("/ix/segments/:id/linux", async request => {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params)
|
||||
const query = z.union([
|
||||
z.object({ serverId: z.coerce.number().positive().int().safe(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) }).strict(),
|
||||
z.object({ serverId: z.coerce.number().positive().int().safe(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/), transportOnly: z.literal("true").optional() }).strict(),
|
||||
z.object({}).strict(),
|
||||
]).parse(request.query)
|
||||
const segment = await readIxSegment(id)
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
return "serverId" in query ? readIxLinuxClient(segment, query.serverId, query.interfaceName) : listIxLinuxClients(segment)
|
||||
return "serverId" in query ? readIxLinuxClient(segment, query.serverId, query.interfaceName, false, query.transportOnly === "true") : listIxLinuxClients(segment)
|
||||
})
|
||||
app.post("/ix/segments/:id/linux", async request => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
@@ -129,13 +158,13 @@ const ixRoutes: FastifyPluginAsync = async app => {
|
||||
})
|
||||
app.post("/ix/segments/:id/linux/credential", async (request, reply) => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { serverId, interfaceName } = clientKey.parse(request.body)
|
||||
const { serverId, interfaceName, transportOnly } = clientKey.extend({ transportOnly: z.boolean().optional() }).parse(request.body)
|
||||
const scope = { deadlineAt: Date.now() + 60_000 }
|
||||
const token = await captureVerifiedRestRequest(request, scope)
|
||||
const { ownerId } = await inspectVerifiedRestRequest(token, scope, "mm:network:write")
|
||||
const segment = await readIxSegment(id)
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
const access = await readIxLinuxClient(segment, serverId, interfaceName, true)
|
||||
const access = await readIxLinuxClient(segment, serverId, interfaceName, true, transportOnly)
|
||||
await inspectVerifiedRestRequest(token, scope, "mm:network:write")
|
||||
await audit(pool, ownerId, "ix.linux.credential_exported", null, { segmentId: id, serverId, interfaceName, revision: access.revision })
|
||||
reply.header("Cache-Control", "no-store")
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { coalesceCatalogReads, observationIsCurrent, readCatalogWithObservedCache, withCatalogWriteLock } from "../services/routing-catalog-observation.js"
|
||||
import { recursiveApplyBodySchema, recursiveTargetSchema, recursiveInputRowsSchema } from '../services/recursive-route-validation.js'
|
||||
import { parseRecursiveCatalog, parseRecursiveGatewayCatalog, readRecursiveEffectiveProperties, type RecursiveObservedProperty } from "../services/recursive-route-catalog.js"
|
||||
import { executeRecursiveApply, RecursiveApplyError } from "../services/recursive-apply.js"
|
||||
import { storeRecursiveRoutes } from "../services/recursive-route-store.js"
|
||||
import { planRecursiveIdentities } from "../services/recursive-route-identity.js"
|
||||
import { withApplicationMutationLock, withConfigMutationLock } from "../services/config-mutation-lock.js"
|
||||
import { McpError } from "../modules/mcp/security.js"
|
||||
import { asc, eq } from "drizzle-orm"
|
||||
import { z } from "zod"
|
||||
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
|
||||
@@ -100,7 +101,7 @@ export async function applyRecursiveToServer(
|
||||
source: ConfigRevisionSource,
|
||||
validateExisting?: (rows: ReturnType<typeof parseRecursiveCatalog>) => void | Promise<void>,
|
||||
): Promise<{ pushed: number; deleted: number }> {
|
||||
return withApplicationMutationLock(() => withConfigMutationLock([server.id], async () => {
|
||||
return withCatalogWriteLock(server, "recursive-routes", async () => {
|
||||
await storeRecursiveRoutes(server.id, routes, source, true)
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
return executeRecursiveApply(client, routes.map(toRouterPayload), async () => {
|
||||
@@ -116,7 +117,7 @@ export async function applyRecursiveToServer(
|
||||
await validateExisting?.(parseRecursiveCatalog(observed))
|
||||
return observed
|
||||
}, () => readRecursiveNativeRowsForServer(server))
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
const RevisionIdParamSchema = z.object({ id: z.string().min(1) })
|
||||
@@ -158,16 +159,32 @@ const recursiveDefaults: RecursiveRouteDependencies = {
|
||||
|
||||
/** Strict observation shared by both transports. REST can persist metadata;
|
||||
* observers opt out. An unavailable source always fails this catalog read. */
|
||||
export async function readRecursiveCatalogForServer(server: ServerRow, deps: Pick<RecursiveRouteDependencies, "readRaw" | "readProperty" | "getRoutes" | "saveObserved"> = recursiveDefaults, options: { persistObserved?: boolean } = {}) {
|
||||
const read = async () => {
|
||||
type RecursiveReadDependencies = Pick<RecursiveRouteDependencies, "readRaw" | "readProperty" | "getRoutes" | "saveObserved">
|
||||
|
||||
const readWebRecursiveRows = coalesceCatalogReads(readRecursiveNativeRowsForServer)
|
||||
|
||||
async function observeRecursiveRoutes(server: ServerRow, deps: RecursiveReadDependencies, persist: boolean) {
|
||||
const read = async (fresh: boolean) => {
|
||||
if (!server.enabled) throw new Error("Устройство отключено: каталог маршрутов недоступен")
|
||||
const observed = await readRecursiveEffectiveProperties(await deps.readRaw(server), (id, property) => deps.readProperty(server, id, property))
|
||||
const routes = mergeCachedCountry(parseRecursiveCatalog(observed), await deps.getRoutes(server.id))
|
||||
if (options.persistObserved !== false) await deps.saveObserved(server.id, routes)
|
||||
return { serverId: server.id, routes, live: true, stale: false }
|
||||
const observed = !fresh && persist && deps === recursiveDefaults ? await readWebRecursiveRows(server)
|
||||
: await readRecursiveEffectiveProperties(await deps.readRaw(server), (id, property) => deps.readProperty(server, id, property))
|
||||
const cached = await deps.getRoutes(server.id)
|
||||
const routes = mergeCachedCountry(parseRecursiveCatalog(observed), cached)
|
||||
const current = !persist || deps === recursiveDefaults && await observationIsCurrent(server.id, "recursive-routes", canonicalRecursiveRoutes(routes), canonicalRecursiveRoutes(cached))
|
||||
return { routes, cached, current }
|
||||
}
|
||||
return deps === recursiveDefaults && options.persistObserved !== false
|
||||
? withApplicationMutationLock(() => withConfigMutationLock([server.id], read)) : read()
|
||||
const save = async (snapshot: Awaited<ReturnType<typeof read>>) => {
|
||||
await deps.saveObserved(server.id, snapshot.routes)
|
||||
return { ...snapshot, cached: await deps.getRoutes(server.id), current: true }
|
||||
}
|
||||
if (deps === recursiveDefaults) return readCatalogWithObservedCache(server, read, save)
|
||||
const snapshot = await read(true)
|
||||
return snapshot.current ? snapshot : save(snapshot)
|
||||
}
|
||||
|
||||
export async function readRecursiveCatalogForServer(server: ServerRow, deps: RecursiveReadDependencies = recursiveDefaults, options: { persistObserved?: boolean } = {}) {
|
||||
const { routes } = await observeRecursiveRoutes(server, deps, options.persistObserved !== false)
|
||||
return { serverId: server.id, routes, live: true, stale: false }
|
||||
}
|
||||
|
||||
export async function readRecursiveNativeRowsForServer(server: ServerRow) {
|
||||
@@ -187,22 +204,18 @@ export async function readRecursiveGatewaysForServer(server: ServerRow, deps: Pi
|
||||
|
||||
/** Legacy application read, including its explicit stale fallback. MCP observers
|
||||
* share the source/parser while leaving cache and revision history untouched. */
|
||||
export async function readRecursiveRoutesForServer(server: ServerRow, deps: Pick<RecursiveRouteDependencies, "readRaw" | "readProperty" | "getRoutes" | "saveObserved"> = recursiveDefaults, options: { persistObserved?: boolean } = {}) {
|
||||
export async function readRecursiveRoutesForServer(server: ServerRow, deps: RecursiveReadDependencies = recursiveDefaults, options: { persistObserved?: boolean } = {}) {
|
||||
if (!server.enabled) throw new Error("Устройство отключено: опрос маршрутов недоступен")
|
||||
const read = async () => {
|
||||
const cached = await deps.getRoutes(server.id)
|
||||
try {
|
||||
const result = await readRecursiveCatalogForServer(server, deps, options)
|
||||
const routes = options.persistObserved === false
|
||||
? planRecursiveIdentities(cached, result.routes, new Set(), "observed").rows.map((row, index) => ({ ...row, id: row.id || result.routes[index].id }))
|
||||
: await deps.getRoutes(server.id)
|
||||
return { ...result, routes }
|
||||
} catch {
|
||||
return { serverId: server.id, routes: cached, live: false, stale: true, error: "Не удалось подтвердить живой каталог; возвращена сохранённая конфигурация" }
|
||||
}
|
||||
try {
|
||||
const observed = await observeRecursiveRoutes(server, deps, options.persistObserved !== false)
|
||||
const routes = options.persistObserved === false
|
||||
? planRecursiveIdentities(observed.cached, observed.routes, new Set(), "observed").rows.map((row, index) => ({ ...row, id: row.id || observed.routes[index].id }))
|
||||
: observed.cached
|
||||
return { serverId: server.id, routes, live: true, stale: false }
|
||||
} catch (error) {
|
||||
if (error instanceof McpError && (error.code === "CONFIGURATION_BUSY" || error.code === "STATE_CONFLICT")) throw error
|
||||
return { serverId: server.id, routes: await deps.getRoutes(server.id), live: false, stale: true, error: "Не удалось подтвердить живой каталог; возвращена сохранённая конфигурация" }
|
||||
}
|
||||
return deps === recursiveDefaults && options.persistObserved !== false
|
||||
? withApplicationMutationLock(() => withConfigMutationLock([server.id], read)) : read()
|
||||
}
|
||||
|
||||
export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependencies> = {}): FastifyPluginAsyncZod {
|
||||
@@ -218,6 +231,7 @@ export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependenc
|
||||
try {
|
||||
return reply.send(await readRecursiveCatalogForServer(server, deps))
|
||||
} catch (error) {
|
||||
if (error instanceof McpError) throw error
|
||||
return reply.status(503).send({ error: error instanceof Error ? error.message : "Не удалось прочитать каталог маршрутов" })
|
||||
}
|
||||
})
|
||||
@@ -276,6 +290,7 @@ export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependenc
|
||||
return reply.send({ ok: true, serverId, routes: stored, pushedRoutes: result.pushed })
|
||||
} catch (err) {
|
||||
const receipt = recursiveFailureReceipt(err, result)
|
||||
if (!receipt && err instanceof McpError) throw err
|
||||
return reply.status(receipt ? 502 : 500).send({ error: String(err), serverId, ...receipt })
|
||||
}
|
||||
})
|
||||
@@ -313,6 +328,7 @@ export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependenc
|
||||
return reply.send({ ok: true, serverId: server.id, routes: stored, pushedRoutes: result.pushed })
|
||||
} catch (err) {
|
||||
const receipt = recursiveFailureReceipt(err, result)
|
||||
if (!receipt && err instanceof McpError) throw err
|
||||
return reply.status(receipt ? 502 : 500).send({ error: String(err), serverId: server.id, ...receipt })
|
||||
}
|
||||
})
|
||||
|
||||
@@ -5,6 +5,7 @@ import { createSchedulerRoutes } from "./scheduler.js"
|
||||
import type { SchedulerRunReceipt } from "../services/scheduler-recorded-run.js"
|
||||
import { pauseSchedulerJobsAndWait, resumeSchedulerJobs } from "../services/scheduler-running.js"
|
||||
import { runSchedulerJobNow } from "../services/scheduler.js"
|
||||
import { ConfigurationBusyError } from "../services/config-mutation-lock.js"
|
||||
const receipt: SchedulerRunReceipt = { status: "ok", error: null, result: { v: 1, job: "backups", sampledAt: "2026-10-01T00:00:00Z", due: true, created: 1, failures: 0, pruned: 0 } }
|
||||
async function setup(patch: Partial<Parameters<typeof createSchedulerRoutes>[0]> = {}) {
|
||||
const app = Fastify(); let calls = 0
|
||||
@@ -39,3 +40,13 @@ test("collector or journal rejection remains explicit without a fabricated recei
|
||||
const { app } = await setup({ run: async () => { throw Error("journal not confirmed; retry may repeat operations") } })
|
||||
try { const response = await app.inject({ method: "POST", url: "/scheduler/jobs/backups/run-now" }); assert.equal(response.statusCode, 500); assert.match(response.json().error, /retry may repeat/); assert.equal(response.json().result, undefined) } finally { await app.close() }
|
||||
})
|
||||
|
||||
test("configuration contention is distinguishable from an already running job", async () => {
|
||||
const busy = new ConfigurationBusyError("server")
|
||||
const { app } = await setup({ run: async () => { throw busy } })
|
||||
try {
|
||||
const response = await app.inject({ method: "POST", url: "/scheduler/jobs/uptime_ping/run-now" })
|
||||
assert.equal(response.statusCode, 409)
|
||||
assert.deepEqual(response.json(), { code: "CONFIGURATION_BUSY", error: busy.message })
|
||||
} finally { await app.close() }
|
||||
})
|
||||
@@ -51,11 +51,11 @@ return async (app) => {
|
||||
return reply.send({ ok: result.status === "ok", result, status, ...(statusError ? { statusError } : {}) })
|
||||
} catch (e) {
|
||||
const statusCode = (e as Error & { statusCode?: number }).statusCode
|
||||
if (statusCode === 409) {
|
||||
const paused = (e as Error & { code?: string }).code === "SCHEDULER_PAUSED"
|
||||
return reply.status(409).send({ error: paused ? "Планировщик приостановлен для операции с базой" : "Задача уже выполняется" })
|
||||
}
|
||||
const msg = e instanceof Error ? e.message : String(e)
|
||||
if (statusCode === 409) {
|
||||
const code = (e as Error & { code?: string }).code
|
||||
return reply.status(409).send({ error: msg, ...(code ? { code } : {}) })
|
||||
}
|
||||
return reply.status(500).send({ error: msg })
|
||||
}
|
||||
})
|
||||
|
||||
@@ -14,10 +14,10 @@ const held = new AsyncLocalStorage<ServerLockCompletion>()
|
||||
const applicationLease = new AsyncLocalStorage<LockCompletion>()
|
||||
const collectorLease = new AsyncLocalStorage<LockCompletion>()
|
||||
const applicationLockKey = "hashtextextended('mm-config:application',0)"
|
||||
/** Another mutation holds the global configuration lock, or collectors hold it shared while they read routers.
|
||||
* Same message and 409 as before; the code lets MCP report it instead of a generic device failure. */
|
||||
export class ConfigurationBusyError extends McpError {
|
||||
constructor() { super("CONFIGURATION_BUSY", "Глобальная конфигурация изменяется другой операцией", 409) }
|
||||
constructor(scope: "application" | "server" = "application") {
|
||||
super("CONFIGURATION_BUSY", scope === "server" ? "Конфигурация сервера временно занята другой операцией" : "Глобальная конфигурация временно занята другой операцией", 409)
|
||||
}
|
||||
}
|
||||
|
||||
export async function acquireApplicationMutationTransactionLock(client: Pick<PoolClient, "query">): Promise<void> {
|
||||
@@ -90,7 +90,7 @@ export async function withApplicationCollectorLock<T>(work: () => Promise<T>): P
|
||||
let acquired = false, unsafe = false
|
||||
try {
|
||||
acquired = (await client.query(`SELECT pg_try_advisory_lock_shared(${applicationLockKey}) AS acquired`)).rows[0].acquired
|
||||
if (!acquired) throw Object.assign(new Error("Глобальная конфигурация изменяется другой операцией"), { statusCode: 409 })
|
||||
if (!acquired) throw new ConfigurationBusyError()
|
||||
return await collectorLease.run(context, work)
|
||||
} finally {
|
||||
context.active = false
|
||||
@@ -159,7 +159,7 @@ async function runConfigMutationLock<T>(serverIds: number[], work: () => Promise
|
||||
}
|
||||
for (const id of requested) {
|
||||
const { rows: [row] } = await client.query<{ acquired: boolean }>("SELECT pg_try_advisory_lock(hashtextextended($1,0)) AS acquired", ["mm-config:" + id])
|
||||
if (!row.acquired) throw Object.assign(new Error("Конфигурация сервера изменяется другой операцией"), { statusCode: 409 })
|
||||
if (!row.acquired) throw new ConfigurationBusyError("server")
|
||||
acquired.push(id)
|
||||
signal.throwIfAborted()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import type { IxBondCandidate, IxBondEdit, IxSavedBond } from "@mmapp/contracts/internet-exchange"
|
||||
import { ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
|
||||
import { bondCandidates, resolveBondMembers } from "./internet-exchange-bonds.js"
|
||||
|
||||
const owner = "a213a2c7-53cd-4325-8e43-e2d953cd761b"
|
||||
const other = "5c1364bd-6147-46ea-b726-273a7e933302"
|
||||
const client = "5a7fa65a-f94f-475a-96cd-a2ece0ed77ce"
|
||||
const primary: IxBondCandidate = { segmentId: owner, appliedRevision: 3, serverId: 5, segmentName: "eu",
|
||||
interfaceName: "wg-vps", name: "alpha", kind: "wireguard", probe: "10.255.0.1", address: "10.255.0.2", endpoint: "192.0.2.1", destinations: ["0.0.0.0/0"] }
|
||||
const backup: IxBondCandidate = { ...primary, segmentId: other, segmentName: "asia", clientId: client,
|
||||
serverId: 6, kind: "gre-ipsec", interfaceName: "gre-vps", probe: "10.255.0.5", address: "10.255.0.6" }
|
||||
const edit: IxBondEdit = { name: "vps", mode: "weighted", directCidrs: [], revision: 0,
|
||||
members: [primary, backup].map(({ segmentId, appliedRevision, serverId, interfaceName }, i) =>
|
||||
({ segmentId, appliedRevision, serverId, interfaceName, weight: i ? 1 : 3 })) }
|
||||
|
||||
test("cross-segment members retain order, declared VPS identity and revision", () => {
|
||||
const { members, clientId } = resolveBondMembers(edit, [backup, primary], [], owner)
|
||||
assert.deepEqual(members, [primary, backup])
|
||||
assert.equal(clientId, client)
|
||||
const saved: IxSavedBond = { ...edit, id: other, ownerSegmentId: owner, revision: 1, clientId }
|
||||
assert.throws(() => resolveBondMembers(edit, [primary, backup], [saved], owner), /уже входит/)
|
||||
assert.equal(resolveBondMembers(saved, [primary, backup], [saved], owner, saved).clientId, client)
|
||||
})
|
||||
|
||||
test("reject stale, revoked, foreign-client and conflicting routing paths", () => {
|
||||
const invalid: Array<[IxBondCandidate, RegExp]> = [
|
||||
[{ ...backup, appliedRevision: 4 }, /изменилось/],
|
||||
[{ ...backup, destinations: ["198.51.100.0/24"] }, /назначения/],
|
||||
[{ ...backup, address: primary.probe }, /внутренние адреса/],
|
||||
]
|
||||
for (const [candidate, reason] of invalid) {
|
||||
assert.throws(() => resolveBondMembers(edit, [primary, candidate], [], owner), reason)
|
||||
}
|
||||
assert.throws(() => resolveBondMembers(edit, [primary], [], owner), /недоступно/)
|
||||
assert.throws(() => resolveBondMembers(edit, [{ ...primary, clientId: owner }, backup], [], owner), /разными VPS/)
|
||||
assert.throws(() => resolveBondMembers(edit, [primary, backup], [], client), /текущего сегмента/)
|
||||
})
|
||||
|
||||
test("existing static WireGuard exports keep their applied prefixes; external GRE and BGP remain independent", () => {
|
||||
const config = ixSegmentConfigurationSchema.parse({ name: "legacy", sites: [{ serverId: 5, autonomousSystem: 64512,
|
||||
routerId: "192.0.2.1", interfaces: [
|
||||
{ kind: "wireguard", name: "wg-static", provisionWireguard: { listenPort: 31820, hubEndpoint: primary.endpoint,
|
||||
localAddress: primary.probe + "/30", peerAddress: primary.address, peerPublicKey: Buffer.alloc(32, 3).toString("base64") } },
|
||||
{ kind: "gre-ipsec", name: "gre-manual", localEndpoint: primary.endpoint, endpoint: "198.51.100.8", prefixes: ["10.7.0.0/24"] },
|
||||
] }] })
|
||||
const [candidate] = bondCandidates(owner, 7, config)
|
||||
assert.deepEqual(bondCandidates(owner, 7, config).map(c => c.interfaceName), ["wg-static"])
|
||||
assert.deepEqual(candidate.destinations, ["10.7.0.0/24"])
|
||||
assert.equal(candidate.clientId, undefined)
|
||||
config.sites[0].neighbors.push({ id: "bgp", binding: "wg-static", type: "member", remoteAs: 64513,
|
||||
address: primary.address, localAddress: primary.probe, prefixes: [], exportPrefixes: [], rules: [], limit: 10 })
|
||||
assert.deepEqual(bondCandidates(owner, 7, config), [])
|
||||
})
|
||||
@@ -0,0 +1,176 @@
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { isIP } from "node:net"
|
||||
import type { PoolClient } from "pg"
|
||||
import {
|
||||
ixBondBundleSchema, ixSavedBondSchema, ixSegmentConfigurationSchema, type IxBondCandidate,
|
||||
type IxBondEdit, type IxSavedBond, type IxConfiguration, type IxBondBundle,
|
||||
} from "@mmapp/contracts/internet-exchange"
|
||||
import { pool } from "../db/index.js"
|
||||
import { audit } from "../modules/mcp/store.js"
|
||||
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
||||
import { ixLegacyWireguardRoutes, ixLinuxBindingKind, ixLinuxInterfaceName } from "./internet-exchange-client.js"
|
||||
import { readIxLinuxClient, verifyIxExistingTransport } from "./internet-exchange-execution.js"
|
||||
import { IxConflict } from "./internet-exchange-plan.js"
|
||||
import { ixReservedTunnelBindings, readIxSegment } from "./internet-exchange-store.js"
|
||||
import { admitPartitionWriter } from "./partition-write-transaction.js"
|
||||
|
||||
type Query = Pick<PoolClient, "query">
|
||||
type MemberRef = IxBondEdit["members"][number]
|
||||
const visible = "(s.configuration->>'deleted') IS DISTINCT FROM 'true'"
|
||||
const key = (m: Pick<MemberRef, "segmentId" | "serverId" | "interfaceName">) => [m.segmentId, m.serverId, m.interfaceName].join("/")
|
||||
|
||||
export function bondCandidates(segmentId: string, appliedRevision: number, config: IxConfiguration): IxBondCandidate[] {
|
||||
return config.sites.flatMap(site => site.interfaces.flatMap(binding => {
|
||||
const kind = ixLinuxBindingKind(binding)
|
||||
const linux = binding.linux
|
||||
const tunnel = binding.provisionWireguard ?? binding.provisionGre
|
||||
if (!kind || linux?.enabled === false || !tunnel || binding.peerServerId) return []
|
||||
if (!linux && (kind !== "wireguard" || site.neighbors.some(peer => peer.binding === binding.name))) return []
|
||||
const family = isIP(tunnel.peerAddress)
|
||||
const routes = linux ? linux.destinations : ixLegacyWireguardRoutes(config, binding)
|
||||
const destinations = linux?.exit ? [family === 6 ? "::/0" : "0.0.0.0/0"]
|
||||
: [...new Set(routes.map(canonicalBgpPolicyPrefix))].sort()
|
||||
if (!linux && (!destinations.length || destinations.length > 64 || destinations.some(cidr => isIP(cidr.split("/")[0]) !== family))) return []
|
||||
return [{
|
||||
segmentId, appliedRevision, segmentName: config.name, serverId: site.serverId, interfaceName: binding.name,
|
||||
name: linux?.name ?? binding.name, clientId: linux?.clientId, kind, address: tunnel.peerAddress, probe: tunnel.localAddress.split("/")[0],
|
||||
endpoint: (binding.provisionWireguard?.hubEndpoint ?? binding.localEndpoint)!,
|
||||
destinations,
|
||||
}]
|
||||
}))
|
||||
}
|
||||
|
||||
async function candidates(sql: Query, ids?: string[], refs: MemberRef[] = []) {
|
||||
const { rows } = await sql.query(`SELECT s.id,s.applied_revision,r.configuration FROM ix_segments s
|
||||
JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
|
||||
WHERE ${visible} AND ($1::uuid[] IS NULL OR s.id=ANY($1)) ORDER BY s.name,s.id`, [ids ?? null])
|
||||
return rows.flatMap(row => {
|
||||
const config = ixSegmentConfigurationSchema.parse(row.configuration)
|
||||
const result = bondCandidates(row.id, row.applied_revision, config)
|
||||
for (const ref of refs) {
|
||||
const path = ref.existing
|
||||
if (!path || ref.segmentId !== row.id) continue
|
||||
const site = config.sites.find(s => s.serverId === ref.serverId)
|
||||
const binding = site?.interfaces.find(b => b.name === ref.interfaceName)
|
||||
if (!site || binding && (binding.peerServerId || binding.provisionTransit || binding.provisionWireguard || binding.provisionGre || binding.linux ||
|
||||
binding.kind !== path.kind) || result.some(c => key(c) === key(ref)) || site.neighbors.some(p => p.binding === ref.interfaceName)) {
|
||||
throw new IxConflict("Интерфейс занят клиентом, BGP либо принадлежит другому узлу: " + ref.interfaceName)
|
||||
}
|
||||
result.push({ ...ref, ...path, segmentName: config.name, appliedRevision: row.applied_revision, name: path.linuxInterface,
|
||||
destinations: [...new Set(path.destinations.map(canonicalBgpPolicyPrefix))].sort() })
|
||||
}
|
||||
return result
|
||||
})
|
||||
}
|
||||
|
||||
export async function inspectIxBondImports(ownerId: string, edit: IxBondEdit) {
|
||||
if (!edit.members.some(m => m.existing)) return
|
||||
const [available, groups] = await Promise.all([candidates(pool, [...new Set(edit.members.map(m => m.segmentId))], edit.members), savedGroups(pool)])
|
||||
resolveBondMembers(edit, available, groups, ownerId, groups.find(g => g.id === edit.id && g.ownerSegmentId === ownerId))
|
||||
for (const m of edit.members) if (m.existing) await verifyIxExistingTransport(m.segmentId, m.serverId, m.interfaceName, m.existing)
|
||||
}
|
||||
|
||||
async function savedGroups(sql: Query, ownerId?: string): Promise<IxSavedBond[]> {
|
||||
const { rows } = await sql.query(`SELECT item FROM ix_segments s
|
||||
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') item
|
||||
WHERE ${visible} AND ($1::uuid IS NULL OR s.id=$1) ORDER BY s.id`, [ownerId ?? null])
|
||||
return rows.map(row => ixSavedBondSchema.parse(row.item))
|
||||
}
|
||||
|
||||
export async function ixBondCatalog() {
|
||||
const [groups, available] = await Promise.all([savedGroups(pool), candidates(pool)])
|
||||
return { groups, candidates: available }
|
||||
}
|
||||
|
||||
export function resolveBondMembers(edit: IxBondEdit, available: IxBondCandidate[], groups: IxSavedBond[], ownerId: string, previous?: IxSavedBond) {
|
||||
const routerInterface = (m: MemberRef) => m.serverId + "/" + m.interfaceName
|
||||
const occupied = new Set(groups.filter(g => g.id !== previous?.id).flatMap(g => g.members.map(routerInterface)))
|
||||
const owned = new Map(available.map(m => [key(m), m]))
|
||||
const addresses = new Set<string>()
|
||||
const linuxNames = new Set<string>()
|
||||
const members = edit.members.map(member => {
|
||||
const label = member.interfaceName
|
||||
const found = owned.get(key(member))
|
||||
if (!found || found.appliedRevision !== member.appliedRevision) throw new IxConflict("Подключение изменилось или недоступно: " + label)
|
||||
if (occupied.has(routerInterface(member))) throw new IxConflict("Интерфейс уже входит в группу: " + label)
|
||||
occupied.add(routerInterface(member))
|
||||
const linuxName = found.existing?.linuxInterface ?? ixLinuxInterfaceName(found.kind === "wireguard" ? "ixw" : "ixg", found.serverId, { name: found.interfaceName })
|
||||
if (linuxNames.has(linuxName)) throw new IxConflict("Имя интерфейса на VPS повторяется: " + linuxName)
|
||||
linuxNames.add(linuxName)
|
||||
for (const address of [found.address, found.probe]) {
|
||||
const host = canonicalBgpPolicyPrefix(address + (isIP(address) === 6 ? "/128" : "/32"))
|
||||
if (addresses.has(host)) throw new IxConflict("Назначьте разные внутренние адреса участникам группы: " + address)
|
||||
addresses.add(host)
|
||||
}
|
||||
return found
|
||||
})
|
||||
const first = members[0]
|
||||
if (!members.some(m => m.segmentId === ownerId)) throw new IxConflict("Выберите подключение из текущего сегмента")
|
||||
if (!first?.destinations.length || members.some(m => isIP(m.address) !== isIP(first.address) ||
|
||||
JSON.stringify(m.destinations) !== JSON.stringify(first.destinations))) {
|
||||
throw new IxConflict("Участникам нужны одинаковые непустые назначения и одно семейство адресов")
|
||||
}
|
||||
const identities = new Set(members.flatMap(m => m.clientId ? [m.clientId] : []))
|
||||
if (previous) identities.add(previous.clientId)
|
||||
if (identities.size > 1) throw new IxConflict("Выбранные подключения зарегистрированы за разными VPS")
|
||||
return { members, clientId: [...identities][0] ?? randomUUID() }
|
||||
}
|
||||
|
||||
export async function changeIxBond(ownerId: string, edit: IxBondEdit | { id: string; revision: number }, actor: string) {
|
||||
const sql = await pool.connect()
|
||||
try {
|
||||
await sql.query("BEGIN")
|
||||
await admitPartitionWriter(sql)
|
||||
// A member can belong to only one group, including groups owned by another segment.
|
||||
await sql.query("SELECT pg_advisory_xact_lock(hashtextextended('ix-linux-bonds',0))")
|
||||
if (!await readIxSegment(ownerId, sql)) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
const groups = await savedGroups(sql)
|
||||
const previous = groups.find(group => group.ownerSegmentId === ownerId && group.id === edit.id)
|
||||
if (edit.id && !previous) throw new IxConflict("Группа не найдена", 404)
|
||||
if ((previous?.revision ?? 0) !== edit.revision) throw new IxConflict("Группа изменилась. Обновите данные")
|
||||
let next: IxSavedBond | null = null
|
||||
if ("members" in edit) {
|
||||
const available = await candidates(sql, [...new Set(edit.members.map(m => m.segmentId))], edit.members)
|
||||
const { clientId } = resolveBondMembers(edit, available, groups, ownerId, previous)
|
||||
for (const m of edit.members) if (m.existing && (await ixReservedTunnelBindings(m.serverId, m.segmentId, sql)).some(b => b.name === m.interfaceName)) {
|
||||
throw new IxConflict("Интерфейс уже закреплён за другим сегментом: " + m.interfaceName)
|
||||
}
|
||||
next = ixSavedBondSchema.parse({ ...edit, id: previous?.id ?? randomUUID(), ownerSegmentId: ownerId, clientId,
|
||||
revision: edit.revision + 1, directCidrs: [...new Set(edit.directCidrs.map(canonicalBgpPolicyPrefix))] })
|
||||
}
|
||||
const owned = groups.filter(group => group.ownerSegmentId === ownerId && group.id !== edit.id)
|
||||
if (next) owned.push(next)
|
||||
const result = await sql.query(`UPDATE ix_segments s SET configuration=jsonb_set(configuration,'{linuxBonds}',$2::jsonb)
|
||||
WHERE s.id=$1 AND ${visible}`, [ownerId, JSON.stringify(owned)])
|
||||
if (result.rowCount !== 1) throw new IxConflict("Сегмент IX недоступен")
|
||||
await audit(sql, actor, next ? "ix.bond.saved" : "ix.bond.removed", null, { ownerId, id: next?.id ?? edit.id, revision: next?.revision ?? edit.revision })
|
||||
await sql.query("COMMIT")
|
||||
return next
|
||||
} catch (error) {
|
||||
await sql.query("ROLLBACK").catch(() => {})
|
||||
throw error
|
||||
} finally { sql.release() }
|
||||
}
|
||||
|
||||
export async function exportIxBond(ownerId: string, id: string, revision: number, authorize: () => Promise<unknown>): Promise<IxBondBundle> {
|
||||
const group = (await savedGroups(pool, ownerId)).find(g => g.id === id)
|
||||
if (!group || group.revision !== revision) throw new IxConflict("Группа отсутствует или её ревизия изменилась")
|
||||
const segments = [...new Set(group.members.map(m => m.segmentId))]
|
||||
const { members } = resolveBondMembers(group, await candidates(pool, segments, group.members), [], ownerId, group)
|
||||
const result = []
|
||||
for (const [index, m] of members.entries()) {
|
||||
await authorize()
|
||||
const segment = await readIxSegment(m.segmentId)
|
||||
if (!segment || segment.appliedRevision !== m.appliedRevision) throw new IxConflict("Изменилась площадка " + m.segmentName)
|
||||
const access = m.existing ? { filename: m.existing.linuxInterface,
|
||||
hubPublicKey: await verifyIxExistingTransport(m.segmentId, m.serverId, m.interfaceName, m.existing) }
|
||||
: await readIxLinuxClient(segment, m.serverId, m.interfaceName)
|
||||
result.push({ kind: m.kind, interfaceName: m.existing ? m.existing.linuxInterface : access.filename.replace(/\.conf$/, ""), address: m.address, probe: m.probe,
|
||||
endpoint: m.endpoint, weight: group.mode === "weighted" ? group.members[index].weight : 1,
|
||||
...(m.kind === "wireguard" && { peerPublicKey: access.hubPublicKey }) })
|
||||
}
|
||||
const bundle = ixBondBundleSchema.parse({ version: 1, id, revision, name: group.name, clientId: group.clientId, mode: group.mode,
|
||||
destinations: members[0].destinations, directCidrs: group.directCidrs, members: result })
|
||||
await authorize()
|
||||
return bundle
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createHash } from "node:crypto"
|
||||
import { isIP } from "node:net"
|
||||
import type { IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import type { IxConfiguration, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
||||
import { IxConflict } from "./internet-exchange-plan.js"
|
||||
|
||||
@@ -12,11 +12,16 @@ export function ixLinuxBindingKind(binding: Binding) {
|
||||
return null
|
||||
}
|
||||
|
||||
export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, binding: Binding) {
|
||||
export function ixLegacyWireguardRoutes(configuration: IxConfiguration, binding: Binding) {
|
||||
return configuration.sites.flatMap(site => site.interfaces
|
||||
.filter(connection => connection !== binding && connection.kind !== "uplink").flatMap(connection => connection.prefixes))
|
||||
}
|
||||
|
||||
export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, binding: Pick<Binding, "name">) {
|
||||
return prefix + createHash("sha256").update(JSON.stringify([serverId, binding.name])).digest("hex").slice(0, 12)
|
||||
}
|
||||
|
||||
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[], privateKey = "<локальный_приватный_ключ>") {
|
||||
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[], privateKey = "<локальный_приватный_ключ>", transportOnly = false) {
|
||||
const config = binding.provisionWireguard
|
||||
if (binding.kind !== "wireguard" || !config?.hubEndpoint || !/^[A-Za-z0-9+/]{43}=$/.test(hubPublicKey)) {
|
||||
throw new IxConflict("Для Linux нужны публичный ключ узла и заданный внешний адрес IX")
|
||||
@@ -29,8 +34,8 @@ export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string
|
||||
"[Interface]",
|
||||
"Address = " + address(config.peerAddress),
|
||||
"PrivateKey = " + privateKey,
|
||||
binding.linux ? "Table = auto" : "Table = off",
|
||||
...(binding.linux?.exit && binding.linux.peerEndpoint && isIP(binding.linux.peerEndpoint) === family ? [
|
||||
binding.linux && !transportOnly ? "Table = auto" : "Table = off",
|
||||
...(!transportOnly && binding.linux?.exit && binding.linux.peerEndpoint && isIP(binding.linux.peerEndpoint) === family ? [
|
||||
"PostUp = ip -" + family + " rule add pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main",
|
||||
"PreDown = ip -" + family + " rule del pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main",
|
||||
] : []),
|
||||
@@ -44,7 +49,7 @@ export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string
|
||||
].join("\n")
|
||||
}
|
||||
|
||||
export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: { address: string; localAddress: string }, credential?: string) {
|
||||
export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: { address: string; localAddress: string }, credential?: string, transportOnly = false) {
|
||||
const hub = binding.localEndpoint
|
||||
const client = binding.endpoint
|
||||
if (binding.kind !== "gre-ipsec" || !hub || !client || isIP(hub) !== 4 || isIP(client) !== 4 || hub === client) {
|
||||
@@ -55,13 +60,47 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
|
||||
const tunnel = binding.provisionGre
|
||||
const family = tunnel ? isIP(tunnel.peerAddress) : 4
|
||||
const protocol = "ip -" + family
|
||||
const local = tunnel?.localAddress.split("/")[0]
|
||||
const table = 30000 + parseInt(id.slice(-4), 16)
|
||||
const management = 10000 + parseInt(id.slice(-3), 16)
|
||||
const management = 12000 + 2 * parseInt(id.slice(-3), 16)
|
||||
const managementRules = [
|
||||
["ip -4", "to " + hub + "/32 lookup main"],
|
||||
["ip -4", "from " + client + "/32 lookup main"],
|
||||
...(family === 6 && binding.linux?.exit ? [["ip -6", "ipproto tcp sport 22 lookup main"]] : []),
|
||||
]
|
||||
const greParameters = id + " mode gre local " + client + " remote " + hub
|
||||
const common = [
|
||||
"swanctl --load-all",
|
||||
"swanctl --initiate --child " + id + " --timeout 20",
|
||||
"ip tunnel add " + greParameters,
|
||||
]
|
||||
const addressCommand = tunnel && "ip address add " + tunnel.peerAddress + (family === 4 ? "/32" : "/128") + " dev " + id
|
||||
const transportSetup = transportOnly && tunnel && [
|
||||
'conf="$(dirname -- "$0")/' + id + '.conf"',
|
||||
'unit=/etc/systemd/system/ix-gre-' + id + '.service',
|
||||
'profile=/etc/swanctl/conf.d/' + id + '.conf',
|
||||
'if [ ! -r "$conf" ]; then echo "Положите ' + id + '.conf рядом со скриптом."; exit 1; fi',
|
||||
'candidate=$(mktemp)',
|
||||
'trap \'rm -f "$candidate"\' EXIT',
|
||||
'cat >"$candidate" <<\'IX_GRE_UNIT\'',
|
||||
"[Unit]", "Description=IX Client GRE/IPsec " + id, "Wants=network-online.target", "After=network-online.target strongswan.service",
|
||||
"Requires=strongswan.service", "[Service]", "Type=oneshot", "RemainAfterExit=yes",
|
||||
"ExecStartPre=/usr/sbin/swanctl --load-all",
|
||||
"ExecStart=/bin/sh -ec '/usr/sbin/ip tunnel add " + greParameters + '; trap "/usr/sbin/ip link del dev ' + id +
|
||||
'" EXIT; /usr/sbin/' + addressCommand + "; /usr/sbin/ip link set " + id + " up; trap - EXIT'",
|
||||
"ExecStop=/usr/sbin/ip link del dev " + id,
|
||||
"[Install]", "WantedBy=multi-user.target", "IX_GRE_UNIT",
|
||||
'if [ -e "$unit" ] && ! cmp -s "$candidate" "$unit"; then echo "Служба уже принадлежит другой конфигурации."; exit 1; fi',
|
||||
'if [ -e "$profile" ] && ! cmp -s "$conf" "$profile"; then echo "Профиль strongSwan отличается от существующего."; exit 1; fi',
|
||||
'if [ ! -e "$unit" ] && ip link show dev ' + id + ' >/dev/null 2>&1; then echo "Интерфейс уже существует."; exit 1; fi',
|
||||
'install -d -m 0700 /etc/swanctl/conf.d',
|
||||
'if [ ! -e "$profile" ]; then install -m 0600 "$conf" "$profile"; fi',
|
||||
'install -m 0644 "$candidate" "$unit"',
|
||||
"systemctl daemon-reload", "systemctl enable --now ix-gre-" + id + ".service",
|
||||
].join("\n")
|
||||
return {
|
||||
filename: id + ".conf",
|
||||
template: [
|
||||
"# Сверьте предложения и идентификаторы IKE с профилем узла IX.",
|
||||
...(tunnel ? [] : ["# Сверьте предложения и идентификаторы IKE с профилем узла IX."]),
|
||||
"connections {",
|
||||
" " + id + " {",
|
||||
" version = 2",
|
||||
@@ -97,28 +136,36 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
setup: [
|
||||
"swanctl --load-all",
|
||||
"swanctl --initiate --child " + id,
|
||||
"# Создайте GRE после успешного установления IPsec.",
|
||||
"ip tunnel add " + id + " mode gre local " + client + " remote " + hub,
|
||||
tunnel ? "ip address add " + tunnel.peerAddress + (family === 4 ? "/32" : "/128") + " dev " + id :
|
||||
bgp ? "ip address add " + bgp.address + hostMask + " dev " + id : "# Назначьте согласованный адрес Linux внутри туннеля.",
|
||||
setup: transportSetup || (tunnel ? [
|
||||
'conf="$(dirname -- "$0")/' + id + '.conf"',
|
||||
'if [ ! -r "$conf" ]; then echo "Положите файл ' + id + '.conf рядом со скриптом" >&2; exit 1; fi',
|
||||
'if ip link show dev ' + id + ' >/dev/null 2>&1; then echo "GRE уже поднят" >&2; exit 1; fi',
|
||||
'install -d -m 0700 /etc/swanctl/conf.d',
|
||||
'install -m 0600 "$conf" /etc/swanctl/conf.d/' + id + '.conf',
|
||||
"cleanup() {",
|
||||
" " + protocol + " rule del pref " + (management + 1) + " lookup " + table + " 2>/dev/null || :",
|
||||
" ip link del dev " + id + " 2>/dev/null || :",
|
||||
...managementRules.map(([ip, selector]) => " " + ip + " rule del pref " + management + " " + selector + " 2>/dev/null || :"),
|
||||
" swanctl --terminate --ike " + id + " --timeout 5 >/dev/null 2>&1 || :",
|
||||
"}",
|
||||
"trap cleanup 0",
|
||||
...managementRules.map(([ip, selector]) => ip + " rule add pref " + management + " " + selector),
|
||||
...common,
|
||||
addressCommand!,
|
||||
"ip link set " + id + " up",
|
||||
...[...new Set([
|
||||
tunnel.localAddress.split("/")[0] + (family === 4 ? "/32" : "/128"),
|
||||
...(binding.linux?.destinations ?? []).map(canonicalBgpPolicyPrefix),
|
||||
...(bgp && isIP(bgp.localAddress) === family ? [bgp.localAddress + hostMask] : []),
|
||||
...(binding.linux?.exit ? ["default"] : []),
|
||||
])].map(prefix => protocol + " route replace " + prefix + " dev " + id + " src " + tunnel.peerAddress + " table " + table),
|
||||
protocol + " rule add pref " + (management + 1) + " lookup " + table,
|
||||
"trap - 0",
|
||||
] : [
|
||||
...common,
|
||||
bgp ? "ip address add " + bgp.address + hostMask + " dev " + id : "# Назначьте согласованный адрес Linux внутри туннеля.",
|
||||
"ip link set " + id + " up",
|
||||
...(tunnel ? [
|
||||
protocol + " route replace " + local + (family === 4 ? "/32" : "/128") + " dev " + id + " src " + tunnel.peerAddress,
|
||||
...(binding.linux?.destinations ?? []).map(prefix => protocol + " route replace " + prefix + " dev " + id + " src " + tunnel.peerAddress),
|
||||
...(binding.linux?.exit ? [
|
||||
protocol + " route replace default dev " + id + " src " + tunnel.peerAddress + " table " + table,
|
||||
...(family === 4 ? [
|
||||
"ip -4 rule add pref " + management + " to " + hub + "/32 lookup main",
|
||||
"ip -4 rule add pref " + management + " from " + client + "/32 lookup main",
|
||||
] : []),
|
||||
protocol + " rule add pref " + (management + 1) + " lookup " + table,
|
||||
"# Удаление политик: " + protocol + " rule del pref " + (management + 1) + " lookup " + table,
|
||||
] : []),
|
||||
] : []),
|
||||
...(bgp ? ["ip route add " + bgp.localAddress + hostMask + " dev " + id + " src " + bgp.address] : []),
|
||||
].join("\n"),
|
||||
]).join("\n"),
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,10 @@ import { getServerRowById, type ServerRow } from "../modules/servers/repository/
|
||||
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
|
||||
import { assertVerifiedConfigurationAccess } from "./config-mutation-policy.js"
|
||||
import { compileIxConfiguration, inIxNetwork, IxConflict, ixClientRoutingTable, ixDeviceIds, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
|
||||
import { archiveIxSegment, assertIxName, assertIxRevision, assertIxRouterIds, assertIxSites, ixReservedRouterIds, ixReservedTunnelBindings, nextIxRouterId, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js"
|
||||
import { archiveIxSegment, assertIxBondClientAssignments, assertIxName, assertIxRevision, assertIxRouterIds, assertIxSites, assertIxSegmentWithoutBonds, ixBondClientId, ixKnownVpsClient, ixReservedLinuxPoolBlocks, ixReservedRouterIds, ixReservedTunnelBindings, nextIxRouterId, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js"
|
||||
import { MikrotikClient } from "./mikrotik.js"
|
||||
import { ixGreClientTemplate, ixLinuxBindingKind, ixLinuxInterfaceName, ixWireguardClientTemplate } from "./internet-exchange-client.js"
|
||||
import { ixGreClientTemplate, ixLegacyWireguardRoutes, ixLinuxBindingKind, ixLinuxInterfaceName, ixWireguardClientTemplate } from "./internet-exchange-client.js"
|
||||
import { ixWireguardPublicKey, type IxExistingTransport } from "@mmapp/contracts/internet-exchange"
|
||||
|
||||
type NativeRow = Record<string, string>
|
||||
type IpCore = Pick<MikrotikClient, "get" | "put" | "patch" | "delete">
|
||||
@@ -166,6 +167,10 @@ function verifyEgressMembers(device: NativeDevice, id: string, objects: IxRouter
|
||||
|
||||
async function readRows(client: IpCore, path: string, props: readonly string[]) {
|
||||
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))) {
|
||||
throw new IxConflict("Не удалось прочитать полный каталог RouterOS")
|
||||
}
|
||||
@@ -260,6 +265,39 @@ export async function assignIxRouterIds(id: string, configuration: IxConfigurati
|
||||
}
|
||||
|
||||
export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxClientRequest) {
|
||||
if (input.vpsClientId && !await ixKnownVpsClient(input.vpsClientId)) throw new IxConflict("VPS больше не зарегистрирован в применённой конфигурации IX")
|
||||
if (input.additionalGre && (isIP(input.peerEndpoint ?? "") !== 4 || isIP(input.hubEndpoint) !== 4)) {
|
||||
throw new IxConflict("Для подключения по обоим протоколам укажите два внешних IPv4-адреса", 400)
|
||||
}
|
||||
const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId)
|
||||
const companion = input.companionOf && site?.interfaces.find(binding => binding.name === input.companionOf && binding.linux)
|
||||
if (input.companionOf && !companion) throw new IxConflict("Исходное подключение Linux не найдено", 404)
|
||||
if (input.interfaceName && input.vpsClientId) {
|
||||
const groupVps = await ixBondClientId(segment.id, input.serverId, input.interfaceName)
|
||||
if (groupVps && groupVps !== input.vpsClientId) throw new IxConflict("Сначала исключите подключение из действующей группы VPS")
|
||||
}
|
||||
const existingId = companion ? companion.linux?.clientId ?? await ixBondClientId(segment.id, input.serverId, companion.name) : undefined
|
||||
const name = companion ? companion.linux!.name : input.name
|
||||
const first = await configureIxLinuxTunnel(segment, { ...input, name })
|
||||
const second = input.additionalGre ? await configureIxLinuxTunnel({ ...segment, configuration: first.configuration }, {
|
||||
...input, kind: "gre-ipsec", localAddress: undefined, peerAddress: undefined, peerPublicKey: undefined, prefixes: [],
|
||||
}) : undefined
|
||||
const result = second ?? first
|
||||
const currentId = site?.interfaces.find(binding => binding.name === input.interfaceName)?.linux?.clientId
|
||||
const clientId = existingId ?? input.vpsClientId ?? currentId ??
|
||||
(input.interfaceName ? await ixBondClientId(segment.id, input.serverId, input.interfaceName) : undefined) ?? randomUUID()
|
||||
const siblings = new Set([first.interfaceName, second?.interfaceName, companion ? companion.name : undefined])
|
||||
return { interfaceName: first.interfaceName, configuration: {
|
||||
...result.configuration,
|
||||
sites: result.configuration.sites.map(site => site.serverId !== input.serverId ? site : {
|
||||
...site, interfaces: site.interfaces.map(binding =>
|
||||
binding.linux && (siblings.has(binding.name) || !input.vpsClientId && binding.linux.clientId === clientId)
|
||||
? { ...binding, linux: { ...binding.linux, name, clientId } } : binding),
|
||||
}),
|
||||
} }
|
||||
}
|
||||
|
||||
async function configureIxLinuxTunnel(segment: IxSegment, input: IxLinuxClientRequest) {
|
||||
const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId)
|
||||
if (!site) throw new IxConflict("Узел не входит в сегмент IX", 404)
|
||||
const previous = site.interfaces.find(binding => binding.name === input.interfaceName && binding.linux)
|
||||
@@ -272,11 +310,13 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
|
||||
let localAddress = input.localAddress ?? currentTunnel?.localAddress
|
||||
let peerAddress = input.peerAddress ?? currentTunnel?.peerAddress
|
||||
if (!localAddress && !peerAddress) {
|
||||
const occupiedBlocks = await ixReservedLinuxPoolBlocks()
|
||||
const used = inventory.interfaces.flatMap(item => item.addresses).concat(reserved
|
||||
.concat(segment.configuration.sites.flatMap(candidate => candidate.interfaces))
|
||||
.flatMap(binding => [binding.provisionWireguard?.localAddress, binding.provisionGre?.localAddress,
|
||||
binding.provisionTransit?.localAddress, ...binding.prefixes].filter(value => value !== undefined)))
|
||||
for (let index = 0; index < 65536; index += 4) {
|
||||
if (occupiedBlocks.has(index)) continue
|
||||
const base = "10.254." + (index >> 8) + "."
|
||||
const next = base + ((index & 255) + 1) + "/30"
|
||||
if (used.some(network => inIxNetwork(network, next) || inIxNetwork(next, network))) continue
|
||||
@@ -296,7 +336,9 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
|
||||
}
|
||||
let listenPort = 51820
|
||||
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 localExit = "ix-wan" + family
|
||||
const groups = [...site.groups]
|
||||
@@ -313,7 +355,7 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
|
||||
}
|
||||
const binding: IxSite["interfaces"][number] = {
|
||||
name, kind: input.kind, prefixes: input.prefixes,
|
||||
linux: { name: input.name, enabled: input.enabled, destinations: input.destinations, peerEndpoint: input.peerEndpoint,
|
||||
linux: { name: input.name, clientId: previous?.linux?.clientId, enabled: input.enabled, destinations: input.destinations, peerEndpoint: input.peerEndpoint,
|
||||
exit: input.exit === "local-wan" ? localExit : input.exit },
|
||||
}
|
||||
if (input.kind === "wireguard") {
|
||||
@@ -329,6 +371,10 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
|
||||
localAddress, peerAddress, hubEndpoint: input.hubEndpoint }
|
||||
} else {
|
||||
if (isIP(input.peerEndpoint ?? "") !== 4 || isIP(input.hubEndpoint) !== 4) throw new IxConflict("Укажите два внешних IPv4 для GRE/IPsec", 400)
|
||||
if (site.interfaces.some(item => item !== previous && item.kind === "gre-ipsec" &&
|
||||
item.localEndpoint === input.hubEndpoint && item.endpoint === input.peerEndpoint)) {
|
||||
throw new IxConflict("Эта пара внешних адресов уже используется для GRE/IPsec")
|
||||
}
|
||||
binding.endpoint = input.peerEndpoint
|
||||
binding.localEndpoint = input.hubEndpoint
|
||||
binding.provisionGre = { localAddress, peerAddress,
|
||||
@@ -440,12 +486,78 @@ function verifyGreBinding(binding: IxSite["interfaces"][number], interfaces: Nat
|
||||
return gre
|
||||
}
|
||||
|
||||
function validateBindings(configuration: IxConfiguration, id: string, devices: NativeDevice[]) {
|
||||
/** Inspect operator-owned transports without running the provisioning or VRF planner. */
|
||||
export async function verifyIxExistingTransport(segmentId: string, serverId: number, name: string, path: IxExistingTransport) {
|
||||
const client = await requiredIxNode(serverId)
|
||||
const addrPath = (address: string) => isIP(address) === 4 ? "/ip/address" : "/ipv6/address"
|
||||
const readAddresses = (ip: string) => readRows(client, addrPath(ip), ["address", "network", "interface", "vrf", "disabled", "invalid"])
|
||||
const [addresses, vrfs, reserved] = await Promise.all([readAddresses(path.probe), readRows(client, "/ip/vrf", ["name", "interfaces", "disabled"]), ixReservedTunnelBindings(serverId, segmentId)])
|
||||
if (reserved.some(b => b.name === name)) throw new IxConflict("Интерфейс уже закреплён за другим сегментом: " + name)
|
||||
const sameIP = (a: string | undefined, b: string) => !!a && isIP(a) === isIP(b) &&
|
||||
inIxNetwork(b + (isIP(b) === 4 ? "/32" : "/128"), a)
|
||||
const local = addresses.find(row => !isTrue(row.disabled) && !isTrue(row.invalid) && row.interface === name && sameIP(row.address?.split("/")[0], path.probe))
|
||||
if (!local) throw new IxConflict("Адрес IX для проверки не назначен интерфейсу " + name)
|
||||
const allowedVrf = (value: string) => value === "main" || value === ixNamespace(segmentId)
|
||||
if (local.vrf) {
|
||||
if (!allowedVrf(local.vrf)) throw new IxConflict("Адрес принадлежит другой VRF: " + name)
|
||||
} else {
|
||||
const names = new Set((await readRows(client, "/interface", ["name"])).map(row => row.name))
|
||||
let owner: string | undefined
|
||||
for (const row of vrfs.filter(v => !isTrue(v.disabled))) {
|
||||
const selectors = row.interfaces?.split(",") ?? []
|
||||
if (selectors.some(s => s === name || s === "all")) { owner = row.name; break }
|
||||
// Older RouterOS may omit address.vrf. An unexpanded list could match before main.
|
||||
if (selectors.some(s => s !== "none" && !names.has(s))) break
|
||||
}
|
||||
if (!owner || !allowedVrf(owner)) throw new IxConflict("Не подтверждена принадлежность интерфейса VRF узла: " + name)
|
||||
}
|
||||
if (path.kind === "gre-ipsec") {
|
||||
const [interfaces, policies] = await Promise.all([readRows(client, "/interface/gre", [...greColumns, "disabled"]),
|
||||
readRows(client, "/ip/ipsec/policy", ipsecPolicyColumns)])
|
||||
const gre = verifyGreBinding({ name, kind: path.kind, localEndpoint: path.endpoint, endpoint: path.remoteEndpoint, prefixes: [] }, interfaces, policies)
|
||||
if (isTrue(gre.disabled)) throw new IxConflict("Интерфейс отключён: " + name)
|
||||
if (!sameIP(local.network, path.address) && !inIxNetwork(local.address, path.address)) {
|
||||
const routes = await readRows(client, isIP(path.address) === 4 ? "/ip/route" : "/ipv6/route", ["dst-address", "gateway", "immediate-gw", "disabled"])
|
||||
const host = path.address + (isIP(path.address) === 4 ? "/32" : "/128")
|
||||
if (!routes.some(r => !isTrue(r.disabled) && r["dst-address"] === host &&
|
||||
[r.gateway, r["immediate-gw"]].some(gw => gw?.split("@")[0] === name || gw?.split("%")[1]?.split("@")[0] === name))) {
|
||||
throw new IxConflict("Адрес VPS не подтверждён подсетью или хост-маршрутом GRE: " + name)
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
const [wireguard, peers, outer] = await Promise.all([readRows(client, "/interface/wireguard", ["name", "public-key", "disabled"]),
|
||||
readRows(client, "/interface/wireguard/peers", ["interface", "public-key", "allowed-address", "disabled"]),
|
||||
addrPath(path.endpoint) === addrPath(path.probe) ? addresses : readAddresses(path.endpoint)])
|
||||
if (!outer.some(r => !isTrue(r.disabled) && !isTrue(r.invalid) && r.interface !== name && sameIP(r.address?.split("/")[0], path.endpoint))) {
|
||||
throw new IxConflict("Внешний адрес WireGuard не найден на узле IX")
|
||||
}
|
||||
const hub = wireguard.find(r => r.name === name && !isTrue(r.disabled))
|
||||
const peer = peers.find(r => r.interface === name && !isTrue(r.disabled) && r["public-key"] === path.clientPublicKey &&
|
||||
r["allowed-address"]?.split(",").some(cidr => cidr.includes("/") && inIxNetwork(cidr.trim(), path.address)))
|
||||
if (!peer || !ixWireguardPublicKey.safeParse(hub?.["public-key"]).success) throw new IxConflict("Не подтверждены WireGuard, публичный ключ VPS или allowed-address на " + name)
|
||||
return hub!["public-key"]
|
||||
}
|
||||
|
||||
function validateBindings(configuration: IxConfiguration, id: string, devices: NativeDevice[], knownObjects: IxRouterObject[]) {
|
||||
for (const site of configuration.sites) {
|
||||
const device = devices.find(entry => entry.serverId === site.serverId)!
|
||||
if (rowsFor(device, "/interface/bridge/port").some(row => row.bridge === ixDiscardInterface(id))) {
|
||||
throw new IxConflict("Изолированный bridge отбрасывания IX содержит порты")
|
||||
}
|
||||
// Активация WAN-выхода создаёт в main обратный маршрут через клиентский туннель.
|
||||
const ownedMainRoutes = new Map<string, IxRouterObject[]>()
|
||||
for (const object of knownObjects) {
|
||||
if (object.serverId !== site.serverId || !["/ip/route", "/ipv6/route"].includes(object.path) || object.fields["routing-table"] !== "main") continue
|
||||
const key = objectMarker(object)
|
||||
const known = ownedMainRoutes.get(key) ?? []
|
||||
known.push(object)
|
||||
ownedMainRoutes.set(key, known)
|
||||
}
|
||||
const foreignMainRoutes = ["/ip/route", "/ipv6/route"].flatMap(path => rowsFor(device, path).filter(row => {
|
||||
if (row["routing-table"] !== "main" || isTrue(row.dynamic)) return false
|
||||
return !ownedMainRoutes.get(marker(path, row.comment ?? ""))?.some(known => matches(row, known.fields))
|
||||
}))
|
||||
for (const binding of site.interfaces) {
|
||||
const iface = rowsFor(device, "/interface").find(row => row.name === binding.name)
|
||||
if (!iface && (binding.provisionWireguard || binding.provisionGre || binding.provisionTransit)) continue
|
||||
@@ -463,8 +575,8 @@ function validateBindings(configuration: IxConfiguration, id: string, devices: N
|
||||
throw new IxConflict("Интерфейс " + binding.name + " не выделен для данного сегмента IX")
|
||||
}
|
||||
const foreignVrf = rowsFor(device, "/ip/vrf").find(row => row.name !== "main" && row.name !== ixNamespace(id) && row.interfaces?.split(",").includes(binding.name))
|
||||
const mainRoutes = [...rowsFor(device, "/ip/route"), ...rowsFor(device, "/ipv6/route")].filter(row => row["routing-table"] === "main" && !isTrue(row.dynamic))
|
||||
if (foreignVrf || mainRoutes.some(row => row.gateway === binding.name || row.gateway?.includes("%" + binding.name))) {
|
||||
if (foreignVrf || foreignMainRoutes.some(row => row.gateway?.split(",").some(gateway =>
|
||||
gateway.trim().split("@")[0].split("%").at(-1) === binding.name))) {
|
||||
throw new IxConflict("Интерфейс " + binding.name + " уже используется другой маршрутизацией")
|
||||
}
|
||||
if (binding.kind === "gre-ipsec") {
|
||||
@@ -511,6 +623,7 @@ async function resolveIxCredentials(id: string, objects: IxRouterObject[], exist
|
||||
}
|
||||
|
||||
async function prepareNative(id: string, configuration: IxConfiguration | null, previousConfiguration: IxConfiguration | null, resume = false): Promise<IxNativeChange> {
|
||||
if (configuration) await assertIxBondClientAssignments(id, configuration)
|
||||
for (const site of configuration?.sites ?? []) for (const binding of site.interfaces) {
|
||||
const wg = binding.provisionWireguard
|
||||
if (!wg?.credentialId) continue
|
||||
@@ -535,7 +648,7 @@ async function prepareNative(id: string, configuration: IxConfiguration | null,
|
||||
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId), !configuration))
|
||||
verifyIxMainGateways(before.at(-1)!, objects.filter(object => object.serverId === serverId))
|
||||
}
|
||||
if (configuration) validateBindings(configuration, id, before)
|
||||
if (configuration) validateBindings(configuration, id, before, resume ? objects.concat(previous) : previous)
|
||||
for (const device of before) verifyEgressMembers(device, id, resume ? previous.concat(objects) : previous)
|
||||
for (const old of previousConfiguration?.sites ?? []) {
|
||||
const next = configuration?.sites.find(site => site.serverId === old.serverId)
|
||||
@@ -570,12 +683,13 @@ async function assertIxResume(id: string, revision: number, native: IxNativeChan
|
||||
function verifyRemovalScope(id: string, device: NativeDevice, previous: IxRouterObject[]) {
|
||||
const namespace = ixNamespace(id)
|
||||
const managed = previous.filter(object => object.serverId === device.serverId)
|
||||
const known = new Set(managed.map(objectMarker))
|
||||
const known = new Set(managed.filter(object => object.fields.comment).map(objectMarker))
|
||||
const named = new Set(managed.filter(object => !object.fields.comment && object.fields.name).map(objectMarker))
|
||||
const interfaces = new Set(managed.filter(object => ["/interface/wireguard", "/interface/bridge", "/ip/vrf"].includes(object.path))
|
||||
.map(object => object.fields.name))
|
||||
for (const [path, rows] of Object.entries(device.rows)) {
|
||||
if (path === "/interface") continue // RouterOS mirrors WireGuard and bridge objects here.
|
||||
if (rows.some(row => !isTrue(row.dynamic) && !known.has(marker(path, row.comment ?? "")) &&
|
||||
if (rows.some(row => !isTrue(row.dynamic) && !known.has(marker(path, row.comment ?? "")) && !named.has(marker(path, row.name ?? "")) &&
|
||||
(row.comment?.startsWith(namespace + ":") || row["routing-table"] === namespace ||
|
||||
[row.interface, row.bridge, row["in-interface"], row["out-interface"], ...(row.gateway?.split(/[@%]/) ?? [])].some(value => interfaces.has(value)) ||
|
||||
[row["in-interface-list"], row["out-interface-list"]].includes(ixEgressList(id)) ||
|
||||
@@ -586,6 +700,7 @@ function verifyRemovalScope(id: string, device: NativeDevice, previous: IxRouter
|
||||
}
|
||||
|
||||
export async function prepareIxRemoval(id: string, revision: number) {
|
||||
await assertIxSegmentWithoutBonds(id)
|
||||
const segment = await readIxSegment(id)
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
assertIxRevision(segment, revision)
|
||||
@@ -699,23 +814,30 @@ export async function listIxLinuxClients(segment: IxSegment) {
|
||||
const observedAt = new Date().toISOString()
|
||||
try {
|
||||
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",
|
||||
["interface", "public-key", "last-handshake", "rx", "tx"]) : [],
|
||||
bindings.some(binding => binding.linux && binding.provisionGre) ? readRows(client, "/ip/ipsec/active-peers", ["remote-address", "state"]) : [],
|
||||
["interface", "public-key", "last-handshake", "rx", "tx"]).catch(() => null) : [],
|
||||
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()) {
|
||||
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 age = handshake && /^\d+:\d{2}:\d{2}$/.test(handshake)
|
||||
? handshake.split(":").reduce((total, part) => total * 60 + Number(part), 0)
|
||||
: handshake && /^(?:(\d+)m)?(?:(\d+)s)?$/.exec(handshake)
|
||||
const fresh = typeof age === "number" ? age < 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 + ":")))
|
||||
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 {
|
||||
for (const item of items) if (item.enabled) item.connection = { observedAt, state: "unknown" }
|
||||
@@ -748,7 +870,7 @@ export async function observeIxLinuxPath(segment: IxSegment, serverId: number, n
|
||||
})) }
|
||||
}
|
||||
|
||||
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false): Promise<IxLinuxAccess> {
|
||||
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false, transportOnly = false): Promise<IxLinuxAccess> {
|
||||
if (segment.appliedRevision === null) throw new IxConflict("Сначала примените конфигурацию площадки")
|
||||
const configuration = await readIxRevision(segment.id, segment.appliedRevision)
|
||||
const site = configuration.sites.find(site => site.serverId === serverId)
|
||||
@@ -780,7 +902,7 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
|
||||
throw new IxConflict("Действующий PSK не совпал с применённой ревизией. Выполните сверку")
|
||||
}
|
||||
}
|
||||
return { ...clientInfo, kind: "gre-ipsec", ...ixGreClientTemplate(binding, serverId, peer, credential) }
|
||||
return { ...clientInfo, kind: "gre-ipsec", ...ixGreClientTemplate(binding, serverId, peer, credential, transportOnly) }
|
||||
}
|
||||
if (ixLinuxBindingKind(binding) !== "wireguard") throw new IxConflict("Нет параметров WireGuard для Linux")
|
||||
const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "listen-port", "comment", "disabled"])
|
||||
@@ -792,8 +914,7 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
|
||||
}
|
||||
const routes = binding.linux ? [...binding.linux.destinations,
|
||||
...(binding.linux.exit ? [isIP(binding.provisionWireguard!.peerAddress) === 4 ? "0.0.0.0/0" : "::/0"] : [])]
|
||||
: configuration.sites.flatMap(entry => entry.interfaces
|
||||
.filter(connection => connection !== binding && connection.kind !== "uplink").flatMap(connection => connection.prefixes))
|
||||
: ixLegacyWireguardRoutes(configuration, binding)
|
||||
let privateKey: string | undefined
|
||||
if (includeCredential) {
|
||||
const wg = binding.provisionWireguard
|
||||
@@ -809,7 +930,8 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
|
||||
...clientInfo,
|
||||
kind: "wireguard",
|
||||
filename: ixLinuxInterfaceName("ixw", serverId, binding) + ".conf",
|
||||
template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes, privateKey),
|
||||
hubPublicKey: iface?.["public-key"],
|
||||
template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes, privateKey, transportOnly),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -859,6 +981,7 @@ export async function removeIxSegment(id: string, revision: number, expectedDige
|
||||
authorize = assertVerifiedConfigurationAccess) {
|
||||
return withApplicationMutationLock(async () => {
|
||||
await authorize()
|
||||
await assertIxSegmentWithoutBonds(id)
|
||||
const segment = await readIxSegment(id)
|
||||
assertIxRevision(segment, revision)
|
||||
const applied = segment?.appliedRevision ? await readIxRevision(id, segment.appliedRevision) : null
|
||||
|
||||
@@ -14,7 +14,8 @@ interface SegmentRow {
|
||||
updated_at: Date
|
||||
}
|
||||
|
||||
const columns = "id,revision,applied_revision,configuration,updated_at"
|
||||
// VPS bond metadata has its own revision and never enters a RouterOS plan or segment export.
|
||||
const columns = "id,revision,applied_revision,(configuration - 'linuxBonds') AS configuration,updated_at"
|
||||
const visible = "(configuration->>'deleted') IS DISTINCT FROM 'true'"
|
||||
function segment(row: SegmentRow): IxSegment {
|
||||
return { id: row.id, revision: row.revision, appliedRevision: row.applied_revision,
|
||||
@@ -41,6 +42,46 @@ export async function isIxSegmentArchived(id: string, revision: number) {
|
||||
return rowCount === 1
|
||||
}
|
||||
|
||||
export async function assertIxSegmentWithoutBonds(id: string) {
|
||||
const { rowCount } = await pool.query(`SELECT 1 FROM ix_segments s
|
||||
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') g
|
||||
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true'
|
||||
AND (s.id=$1::uuid OR EXISTS (SELECT FROM jsonb_array_elements(g->'members') m WHERE m->>'segmentId'=$1::text))
|
||||
LIMIT 1`, [id])
|
||||
if (rowCount) throw new IxConflict("Сначала исключите сегмент из групп туннелей Linux")
|
||||
}
|
||||
|
||||
export async function ixBondClientId(segmentId: string, serverId: number, interfaceName: string) {
|
||||
const { rows } = await pool.query<{ id: string }>(`SELECT g->>'clientId' AS id FROM ix_segments s
|
||||
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') g
|
||||
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND g->'members' @> $1::jsonb LIMIT 1`,
|
||||
[JSON.stringify([{ segmentId, serverId, interfaceName }])])
|
||||
return rows[0]?.id
|
||||
}
|
||||
|
||||
export async function ixKnownVpsClient(id: string) {
|
||||
const { rowCount } = await pool.query(`SELECT 1 FROM ix_segments s
|
||||
JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
|
||||
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND
|
||||
(s.configuration->'linuxBonds' @> $1::jsonb OR r.configuration->'sites' @> $2::jsonb) LIMIT 1`,
|
||||
[JSON.stringify([{ clientId: id }]), JSON.stringify([{ interfaces: [{ linux: { clientId: id, enabled: true } }] }])])
|
||||
return !!rowCount
|
||||
}
|
||||
|
||||
export async function assertIxBondClientAssignments(segmentId: string, configuration: IxConfiguration) {
|
||||
const assignments = configuration.sites.flatMap(site => site.interfaces.flatMap(binding => binding.linux?.clientId
|
||||
? [{ server_id: site.serverId, iface: binding.name, client_id: binding.linux.clientId }] : []))
|
||||
if (!assignments.length) return
|
||||
const { rowCount } = await pool.query(`SELECT 1 FROM ix_segments s
|
||||
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') g
|
||||
CROSS JOIN LATERAL jsonb_array_elements(g->'members') m
|
||||
JOIN jsonb_to_recordset($2::jsonb) AS a(server_id bigint, iface text, client_id uuid)
|
||||
ON m->>'serverId' = a.server_id::text AND m->>'interfaceName' = a.iface
|
||||
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND m->>'segmentId'=$1 AND g->>'clientId'<>a.client_id::text LIMIT 1`,
|
||||
[segmentId, JSON.stringify(assignments)])
|
||||
if (rowCount) throw new IxConflict("Сначала исключите подключение из действующей группы VPS")
|
||||
}
|
||||
|
||||
export async function readIxRevision(id: string, revision: number) {
|
||||
const { rows: [row] } = await pool.query("SELECT configuration FROM ix_segment_revisions WHERE segment_id=$1 AND revision=$2", [id, revision])
|
||||
if (!row) throw new IxConflict("Ревизия IX не найдена", 404)
|
||||
@@ -78,19 +119,36 @@ export async function ixReservedRouterIds(id?: string, sql: Pick<PoolClient, "qu
|
||||
return new Set(rows.map(row => row.router_id))
|
||||
}
|
||||
|
||||
export async function ixReservedTunnelBindings(serverId: number) {
|
||||
const { rows } = await pool.query<{ configuration: unknown }>(`
|
||||
SELECT s.configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id
|
||||
WHERE d.server_id=$1 AND (s.configuration->>'deleted') IS DISTINCT FROM 'true'
|
||||
export async function ixReservedTunnelBindings(serverId: number, excludeSegmentId?: string, sql: Pick<PoolClient, "query"> = pool) {
|
||||
const { rows } = await sql.query<{ configuration: unknown }>(`
|
||||
SELECT s.configuration - 'linuxBonds' AS configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id
|
||||
WHERE d.server_id=$1 AND ($2::uuid IS NULL OR s.id<>$2) AND (s.configuration->>'deleted') IS DISTINCT FROM 'true'
|
||||
UNION ALL
|
||||
SELECT r.configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id
|
||||
JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
|
||||
WHERE d.server_id=$1 AND (s.configuration->>'deleted') IS DISTINCT FROM 'true'
|
||||
`, [serverId])
|
||||
WHERE d.server_id=$1 AND ($2::uuid IS NULL OR s.id<>$2) AND (s.configuration->>'deleted') IS DISTINCT FROM 'true'
|
||||
`, [serverId, excludeSegmentId ?? null])
|
||||
return rows.flatMap(({ configuration }) => ixSegmentConfigurationSchema.parse(configuration).sites
|
||||
.flatMap(site => site.interfaces.filter(binding => site.serverId === serverId || binding.peerServerId === serverId)))
|
||||
}
|
||||
|
||||
export async function ixReservedLinuxPoolBlocks() {
|
||||
const { rows } = await pool.query<{ address: string }>(`
|
||||
SELECT DISTINCT address
|
||||
FROM ix_segments s LEFT JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
|
||||
CROSS JOIN LATERAL jsonb_array_elements(COALESCE(s.configuration->'sites','[]'::jsonb) ||
|
||||
COALESCE(r.configuration->'sites','[]'::jsonb)) site
|
||||
CROSS JOIN LATERAL jsonb_array_elements(site->'interfaces') binding
|
||||
CROSS JOIN LATERAL (VALUES
|
||||
(split_part(COALESCE(binding->'provisionWireguard'->>'localAddress',binding->'provisionGre'->>'localAddress'),'/',1)),
|
||||
(COALESCE(binding->'provisionWireguard'->>'peerAddress',binding->'provisionGre'->>'peerAddress'))) hosts(address)
|
||||
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND binding ? 'linux' AND address LIKE '10.254.%'`)
|
||||
return new Set(rows.map(row => {
|
||||
const [, , third, last] = row.address.split(".").map(Number)
|
||||
return third * 256 + (last & ~3)
|
||||
}))
|
||||
}
|
||||
|
||||
export function nextIxRouterId(used: ReadonlySet<string>) {
|
||||
const [address, mask] = (process.env.MMAPP_IX_ROUTER_ID_POOL ?? "10.255.0.0/16").split("/")
|
||||
const length = Number(mask)
|
||||
@@ -134,7 +192,8 @@ export async function writeIxRevision(id: string, expected: number, configuratio
|
||||
? await client.query<SegmentRow>(`INSERT INTO ix_segments(id,name,revision,configuration,applied_revision)
|
||||
VALUES ($1,$2,$3,$4::jsonb,$5) ON CONFLICT DO NOTHING RETURNING ${columns}`,
|
||||
[id, configuration.name, revision, JSON.stringify(configuration), applied ? revision : null])
|
||||
: await client.query<SegmentRow>(`UPDATE ix_segments SET name=$2,revision=$3,configuration=$4::jsonb,
|
||||
: await client.query<SegmentRow>(`UPDATE ix_segments SET name=$2,revision=$3,configuration=$4::jsonb ||
|
||||
CASE WHEN configuration ? 'linuxBonds' THEN jsonb_build_object('linuxBonds', configuration->'linuxBonds') ELSE '{}'::jsonb END,
|
||||
applied_revision=CASE WHEN $5::boolean THEN $3 ELSE applied_revision END,updated_at=now()
|
||||
WHERE id=$1 AND revision=$6 AND ${visible} RETURNING ${columns}`,
|
||||
[id, configuration.name, revision, JSON.stringify(configuration), applied, expected])
|
||||
|
||||
@@ -47,7 +47,7 @@ async function getSettingsRow() {
|
||||
retentionDays: 14,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
}).onConflictDoNothing({ target: internetPathSettings.id })
|
||||
return (await db.select().from(internetPathSettings).where(eq(internetPathSettings.id, 1)).limit(1))[0]
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { readFileSync } from "node:fs"
|
||||
import { test } from "node:test"
|
||||
import { ixBondBundleSchema, type IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import { ixGreClientTemplate, ixWireguardClientTemplate } from "./internet-exchange-client.js"
|
||||
|
||||
const bundle = ixBondBundleSchema.parse(JSON.parse(readFileSync(
|
||||
new URL("../../../packages/contracts/testdata/ix-bond-v1.json", import.meta.url), "utf8")))
|
||||
|
||||
test("the shared ix-client fixture accepts weighted members and rejects overlapping tunnel addresses", () => {
|
||||
assert.deepEqual(bundle.members.map(path => path.weight), [3, 1])
|
||||
const changed = structuredClone(bundle)
|
||||
changed.members[0].probe = changed.members[1].address
|
||||
assert.equal(ixBondBundleSchema.safeParse(changed).success, false)
|
||||
const invalidKey = structuredClone(bundle)
|
||||
invalidKey.members[0].peerPublicKey = "B".repeat(43) + "="
|
||||
assert.equal(ixBondBundleSchema.safeParse(invalidKey).success, false)
|
||||
})
|
||||
|
||||
test("group transport brings up an encrypted link without claiming routes used by other members", () => {
|
||||
const [wg, gre] = bundle.members
|
||||
const linux = { name: bundle.name, enabled: true, exit: "wan", destinations: [], peerEndpoint: "192.0.2.99" }
|
||||
const binding: IxSite["interfaces"][number] = {
|
||||
name: "wg-test", kind: "wireguard", linux, prefixes: [], provisionWireguard: {
|
||||
listenPort: 51820, endpointPort: 51820, localAddress: wg.probe + "/30", peerAddress: wg.address,
|
||||
hubEndpoint: wg.endpoint, peerPublicKey: wg.peerPublicKey!,
|
||||
},
|
||||
}
|
||||
const wgConfig = ixWireguardClientTemplate(binding, wg.peerPublicKey!, bundle.destinations, undefined, true)
|
||||
assert.match(wgConfig, /Table = off/)
|
||||
assert.doesNotMatch(wgConfig, /PostUp|PreDown/)
|
||||
assert.match(wgConfig, /0\.0\.0\.0\/0/)
|
||||
assert.match(ixWireguardClientTemplate(binding, wg.peerPublicKey!, bundle.destinations), /Table = auto/)
|
||||
const greConfig = ixGreClientTemplate({ name: "gre-test", kind: "gre-ipsec", linux, prefixes: [],
|
||||
localEndpoint: gre.endpoint, endpoint: linux.peerEndpoint, provisionGre: {
|
||||
localAddress: gre.probe + "/30", peerAddress: gre.address, credentialId: bundle.id,
|
||||
} }, 17, undefined, undefined, true)
|
||||
assert.match(greConfig.template, /start_action = trap/)
|
||||
assert.match(greConfig.setup, /systemctl enable --now ix-gre-/)
|
||||
assert.match(greConfig.setup, /ExecStart=.*ip address add 10\.123\.2\.2\/32/)
|
||||
assert.doesNotMatch(greConfig.setup, /ip -[46] rule|route replace|secret =/)
|
||||
})
|
||||
@@ -1,5 +1,4 @@
|
||||
import {assertOwnedBandwidthSql,prepareOwnedBandwidthState} from "./bandwidth-admission-process.sql-helper.js"
|
||||
|
||||
assertOwnedBandwidthSql();await prepareOwnedBandwidthState()
|
||||
const {pool,closePool}=await import("../db/index.js")
|
||||
const {applySqlMigrations}=await import("../db/migrate.js")
|
||||
@@ -12,6 +11,8 @@ try{
|
||||
const {acceptRoutingMeasurementPoolSql}=await import("../modules/mcp/routing-measurement-pool.sql-helper.js")
|
||||
const routing=await acceptRoutingMeasurementPoolSql(ids)
|
||||
console.log("Owned operation lock routing: "+JSON.stringify(routing))
|
||||
const { checkCatalogReadContention } = await import("./routing-catalog-observation.sql-helper.js")
|
||||
await checkCatalogReadContention(ids[0])
|
||||
const {acceptAutomaticSchedulerSql}=await import("./scheduler-automatic-root.sql-helper.js")
|
||||
console.log("Owned automatic scheduler: "+JSON.stringify(await acceptAutomaticSchedulerSql(ids)))
|
||||
}finally{
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { AsyncResource } from "node:async_hooks"
|
||||
import { mock } from "node:test"
|
||||
import { setTimeout as delay } from "node:timers/promises"
|
||||
|
||||
import { assertOwnedBandwidthSql } from "./bandwidth-admission-process.sql-helper.js"
|
||||
|
||||
export async function checkCatalogReadContention(serverId: number) {
|
||||
assertOwnedBandwidthSql()
|
||||
const { db, pool } = await import("../db/index.js")
|
||||
const { default: Fastify } = await import("fastify")
|
||||
const { installDatabaseRequestGate } = await import("../plugins/database-request-gate.js")
|
||||
const app = Fastify()
|
||||
installDatabaseRequestGate(app)
|
||||
let releaseHttp!: () => void
|
||||
const httpGate = new Promise<void>(resolve => { releaseHttp = resolve })
|
||||
let activeReads = 0
|
||||
app.get("/api/test/catalog", async () => { activeReads++; await httpGate; return { ok: true } })
|
||||
app.put("/api/test/catalog", async () => ({ ok: true }))
|
||||
await app.ready()
|
||||
const requests = Promise.all(Array.from({ length: 12 }, () => app.inject({ method: "GET", url: "/api/test/catalog" })))
|
||||
try {
|
||||
const until = Date.now() + 5000
|
||||
while (activeReads < 8) { assert(Date.now() < until, "REST read pool did not fill"); await delay(10) }
|
||||
assert.equal((await app.inject({ method: "PUT", url: "/api/test/catalog" })).statusCode, 200)
|
||||
assert.equal(activeReads, 8, "Write admitted while every ordinary REST lease was held by a GET")
|
||||
} finally {
|
||||
releaseHttp()
|
||||
try { assert((await requests).every(response => response.statusCode === 200)) }
|
||||
finally { await app.close() }
|
||||
}
|
||||
const { ensurePartitionFor } = await import("../db/partitions.js")
|
||||
await ensurePartitionFor(pool, "internet_path_snapshots", "week", new Date())
|
||||
const { getSettings } = await import("./uptime-collector.js")
|
||||
const { getTrafficSettings } = await import("./traffic-collector.js")
|
||||
const { getInternetPathSettings } = await import("./internet-path-collector.js")
|
||||
const { getServersApiPingSettings } = await import("./servers-rest-ping-collector.js")
|
||||
for (const [table, get] of [["uptime_settings", getSettings], ["traffic_settings", getTrafficSettings],
|
||||
["internet_path_settings", getInternetPathSettings], ["servers_api_ping_settings", getServersApiPingSettings]] as const) {
|
||||
// Two readers see the missing row before either INSERT can commit.
|
||||
await pool.query(`DELETE FROM ${table} WHERE id=1`)
|
||||
const gate = await pool.connect()
|
||||
let results
|
||||
try {
|
||||
await gate.query("BEGIN")
|
||||
await gate.query(`LOCK TABLE ${table} IN SHARE MODE`)
|
||||
results = Promise.allSettled([get(), get()])
|
||||
const until = Date.now() + 5000
|
||||
while ((await gate.query("SELECT count(*)::int AS n FROM pg_locks WHERE relation=$1::regclass AND NOT granted", [table])).rows[0].n < 2) {
|
||||
assert(Date.now() < until, "Concurrent initializers did not reach INSERT: " + table)
|
||||
await delay(10)
|
||||
}
|
||||
} finally { await gate.query("ROLLBACK"); gate.release() }
|
||||
const [first, second] = await results
|
||||
assert(first.status === "fulfilled" && second.status === "fulfilled", table)
|
||||
assert.deepEqual(first.value, second.value)
|
||||
}
|
||||
const { readFilterRulesCatalog } = await import("../routes/filters.js")
|
||||
const { readRecursiveRoutesForServer, readRecursiveCatalogForServer, applyRecursiveToServer } = await import("../routes/recursive-routes.js")
|
||||
const { servers } = await import("../db/schema.js")
|
||||
const { eq } = await import("drizzle-orm")
|
||||
const { runSchedulerJobNow } = await import("./scheduler.js")
|
||||
const { MikrotikClient } = await import("./mikrotik.js")
|
||||
const { coalesceCatalogReads, readCatalogWithObservedCache } = await import("./routing-catalog-observation.js")
|
||||
const { ConfigurationBusyError, withApplicationCollectorLock, withApplicationMutationLock } = await import("./config-mutation-lock.js")
|
||||
const [fixture] = await db.select().from(servers).where(eq(servers.id, serverId))
|
||||
const server = { ...fixture, enabled: true }
|
||||
let attempts = 0
|
||||
const poll = coalesceCatalogReads(async () => {
|
||||
attempts++
|
||||
if (attempts === 1) throw new Error("RouterOS unavailable")
|
||||
return attempts
|
||||
})
|
||||
const first = poll(server)
|
||||
assert.equal(first, poll(server))
|
||||
assert.equal(await poll({ ...server, routingEndpointEpoch: "new-source" }), 2)
|
||||
await assert.rejects(first, /RouterOS unavailable/)
|
||||
assert.equal(await poll(server), 3, "Errors must not be cached")
|
||||
assert.equal(await poll(server), 4, "A later refresh must start a new poll")
|
||||
const independent = new AsyncResource("other-catalog-request")
|
||||
const route = { id: "", dstAddress: "192.0.2.1/32", gateway: "192.0.2.2", distance: 1, scope: 30, targetScope: 10,
|
||||
routingTable: "main", checkGateway: "ping", disabled: false, country: "", comment: "test" }
|
||||
let native: Record<string, string>[] = [], blocked = 0, hold = false
|
||||
let resume!: () => void
|
||||
const gate = new Promise<void>(resolve => { resume = resolve })
|
||||
const readRouter = async (path: string) => {
|
||||
if (path === "/interface/gre") return []
|
||||
assert(["/routing/filter/rule", "/ip/route/print"].includes(path))
|
||||
const snapshot = path === "/ip/route/print" ? [...native] : []
|
||||
if (hold) { blocked++; await gate }
|
||||
return snapshot
|
||||
}
|
||||
const get = mock.method(MikrotikClient.prototype, "get", readRouter)
|
||||
const post = mock.method(MikrotikClient.prototype, "post", readRouter)
|
||||
const put = mock.method(MikrotikClient.prototype, "put", async (path: string, body: Record<string, string>) => {
|
||||
assert.equal(path, "/ip/route")
|
||||
native = [{ ...body, ".id": "*A", static: "true" }]
|
||||
return { ".id": "*A" }
|
||||
})
|
||||
const load = () => Promise.all([readFilterRulesCatalog([server], { source: "live", persistObserved: true }),
|
||||
readRecursiveCatalogForServer(server), readRecursiveRoutesForServer(server)])
|
||||
try {
|
||||
const cold = await Promise.all(Array.from({ length: 24 }, load))
|
||||
assert(cold.every(([filters, catalog, routes]) => filters[0].live && catalog.live && routes.live))
|
||||
const revisions = () => pool.query("SELECT section,source FROM config_revisions WHERE server_id=$1 ORDER BY section,created_at", [server.id])
|
||||
assert.equal((await revisions()).rowCount, 2)
|
||||
hold = true
|
||||
const reading = Promise.all(Array.from({ length: 24 }, load))
|
||||
try {
|
||||
const until = Date.now() + 5000
|
||||
while (blocked < 2) { assert(Date.now() < until, "Read traffic blocked before reaching RouterOS"); await delay(10) }
|
||||
assert.equal(blocked, 2, "72 simultaneous requests share one RouterOS poll per catalogue")
|
||||
hold = false
|
||||
for (const job of ["uptime_resources", "uptime_ping", "traffic", "internet_path"]) {
|
||||
const run = await runSchedulerJobNow(job)
|
||||
assert.equal(run.status, "ok", job + ": " + run.error)
|
||||
}
|
||||
const apply = () => independent.runInAsyncScope(() => applyRecursiveToServer(server, [route], "apply", () =>
|
||||
independent.runInAsyncScope(() => assert.rejects(withApplicationMutationLock(async () => assert.fail("Overlapping writer")), ConfigurationBusyError))))
|
||||
let pending!: Promise<PromiseSettledResult<Awaited<ReturnType<typeof apply>>>[]>
|
||||
await withApplicationCollectorLock(async () => {
|
||||
pending = Promise.allSettled([apply(), apply()])
|
||||
await delay(500)
|
||||
assert.equal(put.mock.callCount(), 0)
|
||||
})
|
||||
const results = await pending
|
||||
assert.equal(results.filter(result => result.status === "fulfilled" && result.value.pushed === 1).length, 1)
|
||||
assert.equal(results.filter(result => result.status === "rejected" && result.reason.code === "STATE_CONFLICT").length, 1)
|
||||
} finally { hold = false; resume(); await reading }
|
||||
for (const [filters, catalog, routes] of await reading) {
|
||||
assert(filters[0].live && catalog.live && routes.live)
|
||||
assert.equal(catalog.routes[0].dstAddress, route.dstAddress)
|
||||
assert.match(routes.routes[0].id, /^\d+$/)
|
||||
}
|
||||
assert.equal(put.mock.callCount(), 1)
|
||||
assert.equal((await revisions()).rowCount, 3, "Late reads must not overwrite the applied revision")
|
||||
let writes = 0
|
||||
await assert.rejects(readCatalogWithObservedCache(server, async () => ({ current: false }), async () => {
|
||||
writes++; throw new ConfigurationBusyError()
|
||||
}), ConfigurationBusyError)
|
||||
assert.equal(writes, 1)
|
||||
await assert.rejects(readCatalogWithObservedCache({ ...server, routingEndpointEpoch: "retired" },
|
||||
async () => ({ current: false }), async () => assert.fail("Old endpoint wrote to cache")), { code: "STATE_CONFLICT" })
|
||||
console.log("Catalog contention: 72 simultaneous WebUI reads, two shared catalogue polls, four scheduler jobs, one verified route write and no stale cache publication")
|
||||
} finally { get.mock.restore(); post.mock.restore(); put.mock.restore(); independent.emitDestroy() }
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { setTimeout as delay } from "node:timers/promises"
|
||||
import { and, desc, eq } from "drizzle-orm"
|
||||
import { db } from "../db/index.js"
|
||||
import { configRevisions, servers, type Server } from "../db/schema.js"
|
||||
import { McpError } from "../modules/mcp/security.js"
|
||||
import { fingerprintPayload, type ConfigSection } from "./config-revisions.js"
|
||||
import { ConfigurationBusyError, withApplicationCollectorLock, withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
|
||||
|
||||
/** Web reads share only the in-flight poll of this catalogue and endpoint generation. */
|
||||
export function coalesceCatalogReads<T>(poll: (server: Server) => Promise<T>) {
|
||||
const pending = new Map<string, Promise<T>>()
|
||||
return (server: Server) => {
|
||||
const key = server.id + ":" + server.routingEndpointEpoch
|
||||
const current = pending.get(key)
|
||||
if (current) return current
|
||||
const request = poll(server).finally(() => { pending.delete(key) })
|
||||
pending.set(key, request)
|
||||
return request
|
||||
}
|
||||
}
|
||||
|
||||
async function latestRevision(serverId: number, section: ConfigSection) {
|
||||
const [latest] = await db.select({ id: configRevisions.id, fingerprint: configRevisions.fingerprint }).from(configRevisions)
|
||||
.where(and(eq(configRevisions.serverId, serverId), eq(configRevisions.section, section)))
|
||||
.orderBy(desc(configRevisions.createdAt)).limit(1)
|
||||
return latest
|
||||
}
|
||||
|
||||
/** A live read matching both the cache and its revision has nothing to persist. */
|
||||
export async function observationIsCurrent(serverId: number, section: ConfigSection, live: unknown[], cached: unknown[]) {
|
||||
const fingerprint = fingerprintPayload(live)
|
||||
return fingerprint === fingerprintPayload(cached) && (await latestRevision(serverId, section))?.fingerprint === fingerprint
|
||||
}
|
||||
|
||||
async function assertCatalogSource(server: Server) {
|
||||
const [source] = await db.select({ epoch: servers.routingEndpointEpoch }).from(servers).where(eq(servers.id, server.id))
|
||||
if (!source || source.epoch !== server.routingEndpointEpoch) throw new McpError("STATE_CONFLICT", "Источник опроса изменился. Обновите каталог.", 409)
|
||||
}
|
||||
|
||||
/** Retry only lock admission. Release DB clients before sleeping and never replay admitted work. */
|
||||
async function enterCatalogLock<T>(lock: (run: () => Promise<T>) => Promise<T>, run: () => Promise<T>) {
|
||||
const deadline = performance.now() + 5000
|
||||
for (;;) {
|
||||
let admitted = false
|
||||
try { return await lock(() => { admitted = true; return run() }) }
|
||||
catch (error) {
|
||||
if (admitted || !(error instanceof ConfigurationBusyError) || performance.now() >= deadline) throw error
|
||||
}
|
||||
await delay(200)
|
||||
}
|
||||
}
|
||||
|
||||
export async function withCatalogWriteLock<T>(server: Server, section: ConfigSection, run: () => Promise<T>) {
|
||||
const before = await latestRevision(server.id, section)
|
||||
return enterCatalogLock(work => withApplicationMutationLock(() => withConfigMutationLock([server.id], work)), async () => {
|
||||
await assertCatalogSource(server)
|
||||
if ((await latestRevision(server.id, section))?.id !== before?.id) throw new McpError("STATE_CONFLICT", "Конфигурация изменилась во время ожидания. Обновите каталог.", 409)
|
||||
return run()
|
||||
})
|
||||
}
|
||||
|
||||
// Waiting for a cache refresh must not occupy the DB connections needed by writers.
|
||||
const catalogRefreshes = new Map<number, Promise<void>>()
|
||||
export async function readCatalogWithObservedCache<T extends { current: boolean }>(
|
||||
server: Server, read: (fresh: boolean) => Promise<T>, save: (observed: T) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const observed = await read(false)
|
||||
if (observed.current) return observed
|
||||
const serverId = server.id
|
||||
while (catalogRefreshes.has(serverId) || catalogRefreshes.size >= 2) {
|
||||
const refreshing = catalogRefreshes.get(serverId)
|
||||
await (refreshing ?? Promise.race(catalogRefreshes.values()))
|
||||
if (refreshing) {
|
||||
const latest = await read(false)
|
||||
if (latest.current) return latest
|
||||
}
|
||||
}
|
||||
let done!: () => void
|
||||
catalogRefreshes.set(serverId, new Promise(resolve => { done = resolve }))
|
||||
try {
|
||||
return await enterCatalogLock(work => withApplicationCollectorLock(() => withConfigMutationLock([serverId], work)), async () => {
|
||||
await assertCatalogSource(server)
|
||||
const latest = await read(true)
|
||||
return latest.current ? latest : save(latest)
|
||||
})
|
||||
} finally { catalogRefreshes.delete(serverId); done() }
|
||||
}
|
||||
@@ -216,7 +216,7 @@ export async function runSchedulerJobNow(jobKey: string): Promise<SchedulerRunRe
|
||||
throw new Error(`Unknown job key: ${jobKey}`)
|
||||
}
|
||||
if (!tryBeginSchedulerJob(jobKey)) {
|
||||
const err = new Error(isSchedulerJobsPaused() ? "Планировщик приостановлен для операции с базой" : "Job already running")
|
||||
const err = new Error(isSchedulerJobsPaused() ? "Планировщик приостановлен для операции с базой" : "Задача уже выполняется")
|
||||
;(err as Error & { statusCode?: number }).statusCode = 409
|
||||
if (isSchedulerJobsPaused()) (err as Error & { code?: string }).code = "SCHEDULER_PAUSED"
|
||||
throw err
|
||||
|
||||
@@ -20,7 +20,7 @@ async function getSettingsRow() {
|
||||
intervalSec: 120,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
}).onConflictDoNothing({ target: serversApiPingSettings.id })
|
||||
return (await db.select().from(serversApiPingSettings).where(eq(serversApiPingSettings.id, 1)).limit(1))[0]
|
||||
}
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ async function getSettingsRow() {
|
||||
...trafficSettingsDefaults,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
}).onConflictDoNothing({ target: trafficSettings.id })
|
||||
return readSettingsRow()
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import * as proof from "./traffic-flow-batch-proof.js"
|
||||
import * as accumulator from "./traffic-flow-fact-accumulator.js"
|
||||
import * as serial from "./serial-operation.js"
|
||||
import * as parse from "./traffic-flow-parse.js"
|
||||
import * as planes from "./traffic-flow-planes.js"
|
||||
import * as ip from "./traffic-flow-ip.js"
|
||||
import * as ifindex from "./traffic-flow-ifindex.js"
|
||||
import { pruneRipeSqlite } from "./traffic-flow-ripe.js"
|
||||
@@ -46,7 +47,7 @@ const dependencies:Record<string,unknown>={
|
||||
reconcileFlowWrite:async()=>({committed:receiptPresent,result:receiptPresent?{buckets:1,ingestQuality:identified?.ingestQuality}:null}),
|
||||
},
|
||||
"../db/partitions.js":{specForParent:()=>null,ensurePartitionFor:()=>{throw Error("unexpected DDL")}},
|
||||
"./traffic-flow-planes.js":{classifyFlowPlaneLite:()=>"internet"},
|
||||
"./traffic-flow-planes.js":planes,
|
||||
"./traffic-flow-map-exporter.js":{pickServerIdForExporter:()=>1},
|
||||
"./traffic-flow-apps.js":{applicationName:()=>"https"},
|
||||
"./traffic-flow-ripe.js":{enqueueRipeMisses:()=>{throw Error("unexpected RIPE enqueue")},pruneRipeSqlite},
|
||||
|
||||
@@ -9,7 +9,7 @@ import { createFlowFactAccumulator, type FactRow } from "./traffic-flow-fact-acc
|
||||
import { createSerialOperation } from "./serial-operation.js"
|
||||
import { ensurePartitionFor, specForParent } from "../db/partitions.js"
|
||||
import { normalizeParsedFlow, parseFlowPacket, FlowTemplateRefused, protoName, type ParsedFlow, type ParsedFlowInput, type FlowDatagramTransport } from "./traffic-flow-parse.js"
|
||||
import { classifyFlowPlaneLite } from "./traffic-flow-planes.js"
|
||||
import { classifyFlowPlane, classifyFlowPlaneLite } from "./traffic-flow-planes.js"
|
||||
import { pickServerIdForExporter, type OverlayPeerRef } from "./traffic-flow-map-exporter.js"
|
||||
import { applicationName } from "./traffic-flow-apps.js"
|
||||
import { enqueueRipeMisses, pruneRipeSqlite } from "./traffic-flow-ripe.js"
|
||||
@@ -45,6 +45,8 @@ export const DAILY_ASN_TOP = 500
|
||||
export const DAILY_RETENTION_DAYS = 396
|
||||
export const MINUTE_RETENTION_HOURS = 48
|
||||
export const OBSERVED_FLOW_IFACE_DIM = "observed-iface-v1"
|
||||
export const FLOW_IFACE_RX_DIM = "iface-rx-v1"
|
||||
export const FLOW_IFACE_TX_DIM = "iface-tx-v1"
|
||||
export const OBSERVED_FLOW_IFACE_COVERAGE_DIM = "observed-iface-coverage-v1"
|
||||
export const ADMITTED_FLOW_DAY_DIM = "admitted-v1"
|
||||
|
||||
@@ -437,10 +439,13 @@ export function queueParsedFlows(serverId: number, flows: ParsedFlowInput[]): vo
|
||||
serverId,inIface:flow.inIface,outIface:flow.outIface,topo,natSrc:flow.natSrc,natDst:flow.natDst,natSrcPort:flow.natSrcPort,natDstPort:flow.natDstPort})
|
||||
const classified=destMeta.classified,country=destMeta.country
|
||||
const seenIfaces = new Map<string, string>()
|
||||
const directions: Array<{dim: string; key: string}> = []
|
||||
const ingress = resolveIfaceName(serverId, flow.inIface), egress = resolveIfaceName(serverId, flow.outIface)
|
||||
const plane = classifyFlowPlane({ ...flow, inIface: ingress.name, outIface: egress.name }, topo?.plane)
|
||||
let interfaceUncertain = false
|
||||
for (const rawIface of [flow.inIface, flow.outIface]) {
|
||||
const {name, index} = resolveIfaceName(serverId, rawIface)
|
||||
for (const [dim, {name, index}] of [[FLOW_IFACE_RX_DIM, ingress], [FLOW_IFACE_TX_DIM, egress]] as const) {
|
||||
if (name === "—") continue
|
||||
if (plane !== "mgmt") directions.push({ dim: dim + ":" + plane, key: name })
|
||||
if (index && name === `#${index}`) interfaceUncertain = true
|
||||
if (index || !seenIfaces.has(name)) seenIfaces.set(name, index ? String(Number(index)) : name)
|
||||
}
|
||||
@@ -451,7 +456,7 @@ export function queueParsedFlows(serverId: number, flows: ParsedFlowInput[]): vo
|
||||
]
|
||||
const dims=[{dim:"proto",key:protoName(flow.proto)},{dim:"app",key:applicationName(flow.proto,flow.dstPort,flow.srcPort)},
|
||||
{dim:"iface",key:flow.inIface||"__unknown__"},{dim:"category",key:classified.category},{dim:"service",key:classified.service},
|
||||
...observedDimensions,
|
||||
...observedDimensions, ...directions,
|
||||
{dim:"country",key:country||"unknown"},{dim:"asn",key:destMeta.asn?String(destMeta.asn):"unknown"}].map(row=>({...row,cacheKey:dimKey(serverId,bucketAt,row.dim,row.key)}))
|
||||
const fact:FactRow|null=shouldWriteFlowFact({serverId,serverType,inIface:flow.inIface,outIface:flow.outIface,proto:flow.proto,
|
||||
srcPort:flow.srcPort,dstPort:flow.dstPort,src:flow.src,dst:flow.dst,topo,dest:destMeta.dest,
|
||||
@@ -471,8 +476,9 @@ export function queueParsedFlows(serverId: number, flows: ParsedFlowInput[]): vo
|
||||
if (prev) {
|
||||
prev.bytes += flow.bytes
|
||||
prev.packets += flow.packets
|
||||
if (flow.outIface && !prev.flow.outIface) prev.flow.outIface = flow.outIface
|
||||
if (flow.nextHop && !prev.flow.nextHop) prev.flow.nextHop = flow.nextHop
|
||||
// This tuple is keyed by ingress. Only retain egress metadata shared by all its bytes.
|
||||
if (prev.flow.outIface !== flow.outIface) prev.flow.outIface = ""
|
||||
if (prev.flow.nextHop !== flow.nextHop) prev.flow.nextHop = ""
|
||||
if (flow.natSrc && !prev.flow.natSrc) prev.flow.natSrc = flow.natSrc
|
||||
if (flow.natDst && !prev.flow.natDst) prev.flow.natDst = flow.natDst
|
||||
if (flow.natSrcPort && !prev.flow.natSrcPort) prev.flow.natSrcPort = flow.natSrcPort
|
||||
@@ -549,8 +555,8 @@ function mergeInto(map: Map<string, PendingFlowRow>, row: PendingFlowRow): void
|
||||
if (prev) {
|
||||
prev.bytes += row.bytes
|
||||
prev.packets += row.packets
|
||||
if (row.outIface && !prev.outIface) prev.outIface = row.outIface
|
||||
if (row.nextHop && !prev.nextHop) prev.nextHop = row.nextHop
|
||||
if (prev.outIface !== row.outIface) prev.outIface = ""
|
||||
if (prev.nextHop !== row.nextHop) prev.nextHop = ""
|
||||
if (row.natSrc && !prev.natSrc) prev.natSrc = row.natSrc
|
||||
if (row.natDst && !prev.natDst) prev.natDst = row.natDst
|
||||
if (row.natSrcPort && !prev.natSrcPort) prev.natSrcPort = row.natSrcPort
|
||||
@@ -959,8 +965,8 @@ async function upsertFlowBucketsBatch(rows: PendingFlowRow[]): Promise<void> {
|
||||
DO UPDATE SET
|
||||
bytes = flow_buckets.bytes + excluded.bytes,
|
||||
packets = flow_buckets.packets + excluded.packets,
|
||||
out_iface = CASE WHEN excluded.out_iface != '' THEN excluded.out_iface ELSE flow_buckets.out_iface END,
|
||||
next_hop = COALESCE(excluded.next_hop, flow_buckets.next_hop),
|
||||
out_iface = CASE WHEN flow_buckets.out_iface = excluded.out_iface THEN excluded.out_iface ELSE '' END,
|
||||
next_hop = CASE WHEN flow_buckets.next_hop = excluded.next_hop THEN excluded.next_hop END,
|
||||
flow_start_ms = CASE
|
||||
WHEN excluded.flow_start_ms > 0 AND (flow_buckets.flow_start_ms = 0 OR excluded.flow_start_ms < flow_buckets.flow_start_ms)
|
||||
THEN excluded.flow_start_ms ELSE flow_buckets.flow_start_ms END,
|
||||
|
||||
@@ -429,8 +429,8 @@ function mergeInto(map: Map<string, PendingFlowRow>, row: PendingFlowRow): void
|
||||
if (prev) {
|
||||
prev.bytes += row.bytes
|
||||
prev.packets += row.packets
|
||||
if (row.outIface && !prev.outIface) prev.outIface = row.outIface
|
||||
if (row.nextHop && !prev.nextHop) prev.nextHop = row.nextHop
|
||||
if (prev.outIface !== row.outIface) prev.outIface = ""
|
||||
if (prev.nextHop !== row.nextHop) prev.nextHop = ""
|
||||
if (row.natSrc && !prev.natSrc) prev.natSrc = row.natSrc
|
||||
if (row.natDst && !prev.natDst) prev.natDst = row.natDst
|
||||
if (row.natSrcPort && !prev.natSrcPort) prev.natSrcPort = row.natSrcPort
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { mock } from "node:test"
|
||||
import { dbQuery } from "../db/index.js"
|
||||
import { configureEngine, flushEngineNow } from "./traffic-flow-engine.js"
|
||||
import { parseFlowPacket } from "./traffic-flow-parse.js"
|
||||
import { rememberServerIfaces, resetIfaceCacheForTests } from "./traffic-flow-ifindex.js"
|
||||
import {
|
||||
ingestParsedFlowsForServerForTests,
|
||||
@@ -98,6 +102,20 @@ disableRipePersistForTests()
|
||||
resetRipeCacheForTests()
|
||||
disableRipeEnqueueForTests()
|
||||
|
||||
const bucket = Math.floor(Date.now() / 60000) * 60000 - 60000
|
||||
function ingestClosed(serverId: number, flows: Parameters<typeof ingestParsedFlowsForServerForTests>[1], at = bucket) {
|
||||
const clock = mock.method(Date, "now", () => at)
|
||||
try { ingestParsedFlowsForServerForTests(serverId, flows) } finally { clock.mock.restore() }
|
||||
}
|
||||
|
||||
const { rows: [snapshot] } = await dbQuery<{id: number}>(`
|
||||
INSERT INTO internet_path_snapshots(sampled_at,payload_json) VALUES (?,?::jsonb) RETURNING id
|
||||
`, [new Date(bucket).toISOString(), JSON.stringify({ collectionComplete: true, greTunnels: [
|
||||
{serverId: "7", name: "gre-jh-en", remoteAddress: "198.51.100.1", enabled: true},
|
||||
{serverId: "7", name: "SWE-VEESP", remoteAddress: "198.51.100.1", enabled: true},
|
||||
{serverId: "7", name: "gre-second", remoteAddress: "198.51.100.2", enabled: true},
|
||||
] })])
|
||||
|
||||
const topo: FlowTopology = {
|
||||
clientIfaces: new Map([[7, new Set(["gre-client"])]]),
|
||||
clientByIface: new Map([["7|gre-client", {
|
||||
@@ -130,7 +148,7 @@ rememberServerIfaces(3, [
|
||||
{ ".id": "*1", name: "ether1-rt" },
|
||||
])
|
||||
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
{
|
||||
src: "10.100.1.17",
|
||||
dst: "8.8.8.8",
|
||||
@@ -177,7 +195,7 @@ ingestParsedFlowsForServerForTests(7, [
|
||||
outIface: "",
|
||||
},
|
||||
])
|
||||
ingestParsedFlowsForServerForTests(3, [
|
||||
ingestClosed(3, [
|
||||
{
|
||||
src: "192.168.1.10",
|
||||
dst: "8.8.4.4",
|
||||
@@ -288,7 +306,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
googleRipe()
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 600),
|
||||
payloadFlow("11.0.113.50", 9400),
|
||||
])
|
||||
@@ -320,7 +338,7 @@ try {
|
||||
assert.ok(usPath)
|
||||
assert.equal(usPath.clientName, "Alice")
|
||||
|
||||
ingestParsedFlowsForServerForTests(7, [{ ...payloadFlow("8.8.8.8", 2000), proto: 17, dstPort: 51820 }])
|
||||
ingestClosed(7, [{ ...payloadFlow("8.8.8.8", 2000), proto: 17, dstPort: 51820 }])
|
||||
const mixedPeer = await buildFlowMapHops({ minutes: 5, serverId: 7, excludeOverlay: false })
|
||||
assert.equal(mixedPeer.totalBytes, 12_000)
|
||||
assert.equal(mixedPeer.namedBytes, 600, "WireGuard to the same peer is separate from the HTTPS service")
|
||||
@@ -340,7 +358,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
googleRipe()
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 400),
|
||||
payloadFlow("11.0.113.50", 9600),
|
||||
])
|
||||
@@ -374,7 +392,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*2", name: "gre-client" },
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 400),
|
||||
payloadFlow("104.18.35.51", 400),
|
||||
payloadFlow("11.0.113.50", 9200),
|
||||
@@ -407,7 +425,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
seedRipeAsn("162.254.192.71", 32590, "VALVE-CORP")
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("162.254.192.71", 2000),
|
||||
])
|
||||
try {
|
||||
@@ -429,7 +447,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*2", name: "gre-client" },
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("64.233.161.1", 10_000),
|
||||
payloadFlow("11.0.113.50", 20_000),
|
||||
])
|
||||
@@ -480,7 +498,7 @@ rememberServerIfaces(7, [
|
||||
])
|
||||
googleRipe()
|
||||
for (const b of smallBrands) seedRipeAsn(b.ip, b.asn, b.holder)
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 5000),
|
||||
...smallBrands.map((b) => payloadFlow(b.ip, b.bytes)),
|
||||
])
|
||||
@@ -508,7 +526,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*2", name: "gre-client" },
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
{
|
||||
src: "203.0.113.10",
|
||||
dst: "198.51.100.1",
|
||||
@@ -544,7 +562,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
googleRipe()
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
{
|
||||
src: "10.100.1.17",
|
||||
dst: "8.8.8.8",
|
||||
@@ -609,7 +627,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*2", name: "gre-client" },
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
{
|
||||
src: "173.194.151.65",
|
||||
dst: "10.200.100.53",
|
||||
@@ -618,9 +636,9 @@ ingestParsedFlowsForServerForTests(7, [
|
||||
dstPort: 57182,
|
||||
bytes: 9_000,
|
||||
packets: 90,
|
||||
inIface: "2",
|
||||
outIface: "3",
|
||||
nextHop: "198.51.100.1",
|
||||
inIface: "3",
|
||||
outIface: "2",
|
||||
nextHop: "",
|
||||
},
|
||||
{
|
||||
src: "104.18.35.51",
|
||||
@@ -630,9 +648,9 @@ ingestParsedFlowsForServerForTests(7, [
|
||||
dstPort: 53880,
|
||||
bytes: 1_000,
|
||||
packets: 10,
|
||||
inIface: "2",
|
||||
outIface: "3",
|
||||
nextHop: "198.51.100.1",
|
||||
inIface: "3",
|
||||
outIface: "2",
|
||||
nextHop: "",
|
||||
},
|
||||
])
|
||||
try {
|
||||
@@ -659,7 +677,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*2", name: "gre-client" },
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 500),
|
||||
{
|
||||
src: "173.194.151.65",
|
||||
@@ -697,9 +715,9 @@ resetRipeCacheForTests()
|
||||
disableRipeEnqueueForTests()
|
||||
seedFlowTopologyForTests(topo)
|
||||
rememberServerIfaces(7, [
|
||||
{ ".id": "*1", name: "SWE-VEESP" },
|
||||
{ ".id": "*1", name: "ether1" },
|
||||
])
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
{
|
||||
src: "173.194.151.65",
|
||||
dst: "10.200.100.53",
|
||||
@@ -716,16 +734,12 @@ ingestParsedFlowsForServerForTests(7, [
|
||||
try {
|
||||
resetFlowMapHopsCacheForTests()
|
||||
const wanOnly = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
|
||||
const googleEdge = wanOnly.serviceEdges?.find((e) => e.toId === "svc:youtube")
|
||||
assert.ok(googleEdge, "YouTube WAN без GRE payload")
|
||||
assert.equal(googleEdge.fromId, "9", "единственный EN, даже без nextHop")
|
||||
assert.ok(googleEdge.bps > 0, "скорость на hop EN→сервис")
|
||||
assert.ok(!(wanOnly.serviceEdges ?? []).some((e) => e.fromId === "7"), "нет пунктира с JH")
|
||||
const googlePath = wanOnly.servicePaths?.find((p) => p.serviceId === "svc:youtube")
|
||||
assert.ok(googlePath, "путь WAN YouTube")
|
||||
assert.equal(googlePath.viaId, "7", "via = JH exporter")
|
||||
assert.equal(googlePath.enId, "9", "якорь EN")
|
||||
assert.ok(googlePath.bps > 0, "скорость на пути клиента")
|
||||
assert.equal(wanOnly.services?.find(s => s.id === "svc:youtube")?.bytes, 9000)
|
||||
assert.deepEqual(wanOnly.serviceEdges, [])
|
||||
assert.deepEqual(wanOnly.servicePaths, [])
|
||||
assert.deepEqual(wanOnly.countryEdges, [])
|
||||
assert.ok(wanOnly.countryServiceGroups?.every(group => !group.edges.length && !group.paths.length))
|
||||
|
||||
} finally {
|
||||
seedFlowTopologyForTests(null)
|
||||
resetFlowRingsForTests()
|
||||
@@ -747,8 +761,8 @@ rememberServerIfaces(9, [
|
||||
{ ".id": "*1", name: "ether1" },
|
||||
])
|
||||
googleRipe()
|
||||
ingestParsedFlowsForServerForTests(7, [payloadFlow("8.8.8.8", 12_000)])
|
||||
ingestParsedFlowsForServerForTests(9, [{
|
||||
ingestClosed(7, [payloadFlow("8.8.8.8", 12_000)])
|
||||
ingestClosed(9, [{
|
||||
src: "10.100.1.17",
|
||||
dst: "8.8.8.8",
|
||||
proto: 6,
|
||||
@@ -792,7 +806,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
googleRipe()
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 8_000),
|
||||
{
|
||||
src: "8.8.8.8",
|
||||
@@ -818,6 +832,8 @@ try {
|
||||
assert.ok(!(bothDir.servicePaths ?? []).some((p) => p.serviceId === "svc:google" && p.clientId === "—"))
|
||||
const googleEdge = bothDir.serviceEdges?.find((e) => e.toId === "svc:google" && e.fromId === "9")
|
||||
assert.ok(googleEdge)
|
||||
assert.equal(googleEdge.bpsFwd, 8000 * 8 / 300)
|
||||
assert.equal(googleEdge.bpsRev, 4000 * 8 / 300)
|
||||
assert.equal(googleEdge.bytes, 12_000)
|
||||
assert.equal(googleEdge.bps, googlePaths[0]?.bps)
|
||||
} finally {
|
||||
@@ -848,7 +864,7 @@ seedRipeCacheForTests({
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 5000),
|
||||
payloadFlow("185.45.12.10", 5000),
|
||||
])
|
||||
@@ -885,7 +901,7 @@ rememberServerIfaces(7, [
|
||||
{ ".id": "*3", name: "gre-jh-en" },
|
||||
])
|
||||
googleRipe()
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 600),
|
||||
payloadFlow("11.0.113.50", 9400),
|
||||
])
|
||||
@@ -938,7 +954,7 @@ seedRipeCacheForTests({
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 5000),
|
||||
payloadFlow("185.45.12.10", 5000),
|
||||
])
|
||||
@@ -974,7 +990,7 @@ rememberServerIfaces(7, [
|
||||
])
|
||||
googleRipe()
|
||||
for (const b of smallBrands) seedRipeAsn(b.ip, b.asn, b.holder)
|
||||
ingestParsedFlowsForServerForTests(7, [
|
||||
ingestClosed(7, [
|
||||
payloadFlow("8.8.8.8", 5000),
|
||||
...smallBrands.map((b) => payloadFlow(b.ip, b.bytes)),
|
||||
])
|
||||
@@ -1005,3 +1021,91 @@ try {
|
||||
}
|
||||
|
||||
console.log("traffic-flow-map-hops.test.ts: ok")
|
||||
|
||||
// Identical destination/ports on two exits and the local WAN must remain separate.
|
||||
seedFlowTopologyForTests({ ...topo, enNodes: [...topo.enNodes, {id: 10, name: "FIN", hosts: ["198.51.100.2"]}] })
|
||||
try {
|
||||
const flow = { ...payloadFlow("173.194.151.65", 0), nextHop: "", inIface: "gre-client" }
|
||||
ingestClosed(7, [
|
||||
{ ...flow, src: "10.0.0.1", bytes: 1000, outIface: "SWE-VEESP" },
|
||||
{ ...flow, src: "10.0.0.2", bytes: 2000, outIface: "gre-second" },
|
||||
{ ...flow, src: "10.0.0.3", bytes: 9000, outIface: "ether1" },
|
||||
])
|
||||
// This open minute must affect neither the service nor the link rate.
|
||||
ingestParsedFlowsForServerForTests(7, [{ ...flow, bytes: 90000, outIface: "SWE-VEESP" }])
|
||||
const map = await buildFlowMapHops({ serverId: 7, minutes: 5, minSharePct: 0 })
|
||||
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.bytes, 12000)
|
||||
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes]), [["10", 2000], ["9", 1000]])
|
||||
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 3000)
|
||||
} finally {
|
||||
await dbQuery("DELETE FROM internet_path_snapshots WHERE id=?", [snapshot.id])
|
||||
resetFlowRingsForTests()
|
||||
seedFlowTopologyForTests(null)
|
||||
}
|
||||
|
||||
// Captured on the test CHR. Three 64-byte UDP packets traversed GRE A -> GRE B.
|
||||
// RouterOS also exported three 88-byte outer GRE packets on GRE B -> underlay.
|
||||
const datagram = Buffer.from(
|
||||
"0005000201dd5ad06b0530a3227e55740000000000000000" +
|
||||
"c612971ec612970e00000000000a000b00000003000000c0" +
|
||||
"01dd470c01dd470c4e388866000011000000000000000000" +
|
||||
"c6129705c612970600000000000b00090000000300000108" +
|
||||
"01dd470c01dd470c0000000000002f000000000000000000",
|
||||
"hex",
|
||||
)
|
||||
const decoded = parseFlowPacket(datagram, "198.18.151.1")
|
||||
assert.equal(decoded.length, 2)
|
||||
const { rows: [fixture] } = await dbQuery<{id: number}>("INSERT INTO servers(name, host, enabled) VALUES ('flow-map-gre-test', '127.0.0.1', false) RETURNING id")
|
||||
const sid = fixture.id
|
||||
try {
|
||||
resetFlowRingsForTests()
|
||||
configureEngine({ topN: 200 })
|
||||
seedFlowTopologyForTests(topo)
|
||||
rememberServerIfaces(sid, [{ ifindex: "10", name: "gre-a" }, { ifindex: "11", name: "gre-b" }, { ifindex: "9", name: "underlay" }])
|
||||
const now = Date.now()
|
||||
const clock = mock.method(Date, "now", () => now - 10 * 60000)
|
||||
try {
|
||||
ingestParsedFlowsForServerForTests(sid, [{ ...decoded[0], inIface: "quiet-old", outIface: "0" }])
|
||||
clock.mock.mockImplementation(() => now - 60000)
|
||||
const busy = Array.from({length: 201}, (_, i) => ({ ...decoded[0], srcPort: 5000 + i, bytes: 16000, inIface: "wan", outIface: "lan" }))
|
||||
const privatePing = { ...decoded[0], src: "10.1.0.1", dst: "10.2.0.1", proto: 1, srcPort: 0, dstPort: 0,
|
||||
inIface: "site-gre", outIface: "site-lan", bytes: 84, packets: 1 }
|
||||
ingestParsedFlowsForServerForTests(sid, [...busy, privatePing, ...decoded])
|
||||
} finally { clock.mock.restore() }
|
||||
await flushEngineNow({ prune: false })
|
||||
assert.equal((await dbQuery("SELECT 1 FROM flow_buckets WHERE server_id=? AND in_iface IN ('10','11')", [sid])).rowCount, 0)
|
||||
const map = await buildFlowMapHops({ serverId: sid, minutes: 5 })
|
||||
const quiet = map.interfaceTraffic?.find(row => row.iface === "quiet-old")
|
||||
assert(quiet && !quiet.inWindow && quiet.lastBucketAt && quiet.rxBytes === 0)
|
||||
assert.equal(map.interfaceTraffic?.find(row => row.iface === "site-gre")?.rxBytes, 84)
|
||||
const a = map.interfaceTraffic?.find(row => row.iface === "gre-a")
|
||||
const b = map.interfaceTraffic?.find(row => row.iface === "gre-b")
|
||||
assert(a?.inWindow && b?.inWindow)
|
||||
assert.deepEqual([a.rxBytes, a.txBytes, a.rxPackets, a.txPackets], [192, 0, 3, 0])
|
||||
assert.deepEqual([b.rxBytes, b.txBytes, b.rxPackets, b.txPackets], [0, 192, 0, 3])
|
||||
const overlay = await buildFlowMapHops({ serverId: sid, minutes: 5, iface: "gre-b", excludeOverlay: false })
|
||||
assert.deepEqual(overlay.interfaceTraffic?.map(row => [row.iface, row.rxBytes, row.txBytes]), [["gre-b", 264, 192]])
|
||||
// One tuple reroutes within a minute, first in memory and then across SQL flushes.
|
||||
const routed = { ...payloadFlow("173.194.151.65", 1000), inIface: "mixed-lan", outIface: "uplink-a" }
|
||||
const rerouted = { ...routed, outIface: "uplink-b", nextHop: "198.51.100.2" }
|
||||
const split = { ...routed, srcPort: 40001 }
|
||||
ingestClosed(sid, [routed, rerouted, routed, split], bucket - 60000)
|
||||
await flushEngineNow({ prune: false })
|
||||
ingestClosed(sid, [{ ...rerouted, srcPort: split.srcPort }], bucket - 60000)
|
||||
await flushEngineNow({ prune: false })
|
||||
ingestClosed(sid, [split], bucket - 60000)
|
||||
const mixed = await buildFlowMapHops({serverId: sid, minutes: 5, iface: "mixed-lan"})
|
||||
assert.equal(mixed.totalBytes, 6000)
|
||||
assert.deepEqual(mixed.serviceEdges, [])
|
||||
await flushEngineNow({ prune: false })
|
||||
assert.deepEqual((await dbQuery("SELECT out_iface,next_hop FROM flow_buckets WHERE server_id=? AND in_iface='mixed-lan'", [sid])).rows,
|
||||
[{out_iface: "", next_hop: null}, {out_iface: "", next_hop: null}])
|
||||
const user = await buildFlowMapHops({serverId: sid, minutes: 5, userId: "no-interface-binding"})
|
||||
assert.equal(user.interfaceTraffic, undefined)
|
||||
console.log("CHR NetFlow v5 through PostgreSQL and map: GRE A RX / GRE B TX both 192 B, 3 packets; Top-200 and GRE encapsulation verified")
|
||||
} finally {
|
||||
await dbQuery("DELETE FROM servers WHERE id=?", [sid])
|
||||
resetFlowRingsForTests()
|
||||
seedFlowTopologyForTests(null)
|
||||
resetIfaceCacheForTests()
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { flowReadDbAll } from "./traffic-flow-read-policy.js"
|
||||
import { isDeepStrictEqual } from "node:util"
|
||||
import { readFlowMapSourceLimits } from "./traffic-flow-source-limits.js"
|
||||
import { flowCounterSum } from "./traffic-flow-observed-values.js"
|
||||
import { flowCounter, flowCounterSum } from "./traffic-flow-observed-values.js"
|
||||
import type { FlowMapInterfaceTraffic } from "@mmapp/contracts/traffic-flow"
|
||||
import type { ScopedFlowAnalyticsRead } from "./traffic-flow-analytics.js"
|
||||
import type { FlowMapCountryServiceGroup, FlowMapHop, FlowMapHopsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import { flowRowMatchesFilter } from "./traffic-flow-apps.js"
|
||||
@@ -9,15 +10,15 @@ import { OTHER_SERVICE, isNamedInternetService, mapCountryNodeId, mapCountryServ
|
||||
import type { FlowIpMeta } from "./traffic-flow-ripe.js"
|
||||
import { refreshFlowCatalogInBackground } from "./traffic-flow-classify.js"
|
||||
import { collapseGreEspRows, dedupFlowRowsAcrossExporters, dedupFlowRowsMaxBytes } from "./traffic-flow-dedup.js"
|
||||
import { getFlowListenerState, listFlowRowsForWindow } from "./traffic-flow-ingest.js"
|
||||
import { getFlowListenerState, listStoredFlowRows } from "./traffic-flow-ingest.js"
|
||||
import { resolveIfaceName } from "./traffic-flow-ifaces.js"
|
||||
import { classifyFlowPlane, shouldKeepPlane } from "./traffic-flow-planes.js"
|
||||
import { destCtxForIface, flowRateDirection, mapInternetBrand } from "./traffic-flow-dest.js"
|
||||
import { resolveFlowEndpoints } from "./traffic-flow-ip.js"
|
||||
import { geoipReadersStatus, resolveFlowIp } from "./traffic-flow-geoip.js"
|
||||
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
|
||||
import { loadFlowTopology, resolveClient, resolveEn, getServerCatalog, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { flowDataEpoch } from "./traffic-flow-engine.js"
|
||||
import { loadFlowTopology, resolveClient, getServerCatalog, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM } from "./traffic-flow-engine.js"
|
||||
|
||||
export const DEFAULT_MAP_SERVICE_MIN_SHARE_PCT = 5
|
||||
export const MAP_SERVICE_NODE_CAP = 20
|
||||
@@ -60,6 +61,9 @@ interface ClientAcc {
|
||||
}
|
||||
|
||||
interface FromAcc {
|
||||
exporterId: string
|
||||
enId: string
|
||||
reverseBytes: number
|
||||
bytes: number
|
||||
clients: Map<string, ClientAcc>
|
||||
}
|
||||
@@ -110,16 +114,13 @@ function bumpClient(clients: Map<string, ClientAcc>, bytes: number, client: { us
|
||||
clients.set(id, { name, bytes })
|
||||
}
|
||||
|
||||
function bumpFrom(acc: DstAcc, exporterId: string, bytes: number, client: { userId: string; name: string } | null): void {
|
||||
const prev = acc.fromBytes.get(exporterId)
|
||||
if (prev) {
|
||||
prev.bytes += bytes
|
||||
bumpClient(prev.clients, bytes, client)
|
||||
return
|
||||
}
|
||||
const clients = new Map<string, ClientAcc>()
|
||||
bumpClient(clients, bytes, client)
|
||||
acc.fromBytes.set(exporterId, { bytes, clients })
|
||||
function bumpFrom(acc: DstAcc, exporterId: string, enId: string, bytes: number, reverse: boolean, client: { userId: string; name: string } | null): void {
|
||||
const key = exporterId + "|" + enId
|
||||
const from = acc.fromBytes.get(key) ?? { exporterId, enId, bytes: 0, reverseBytes: 0, clients: new Map<string, ClientAcc>() }
|
||||
from.bytes += bytes
|
||||
if (reverse) from.reverseBytes += bytes
|
||||
bumpClient(from.clients, bytes, client)
|
||||
acc.fromBytes.set(key, from)
|
||||
}
|
||||
|
||||
let hopsCache: { key: string; at: number; dto: FlowMapHopsDto } | null = null
|
||||
@@ -179,27 +180,24 @@ function bumpDestFrom(
|
||||
}
|
||||
if (prevEdge) {
|
||||
prevEdge.bytes += from.bytes
|
||||
prevEdge.bytesFwd += from.bytes
|
||||
prevEdge.bytesFwd += from.bytes - from.reverseBytes
|
||||
prevEdge.bytesRev += from.reverseBytes
|
||||
for (const [id, name] of namedClients) prevEdge.clients.set(id, name)
|
||||
} else {
|
||||
edges.set(edgeKey, {
|
||||
fromId: edgeFromId,
|
||||
toId,
|
||||
bytes: from.bytes,
|
||||
bytesFwd: from.bytes,
|
||||
bytesRev: 0,
|
||||
bytesFwd: from.bytes - from.reverseBytes,
|
||||
bytesRev: from.reverseBytes,
|
||||
clients: namedClients,
|
||||
})
|
||||
}
|
||||
for (const [clientId, c] of from.clients) {
|
||||
const pathKey = `${clientId}|${fromId}|${toId}`
|
||||
const pathKey = `${clientId}|${exporterId}|${fromId}|${toId}`
|
||||
const prevPath = paths.get(pathKey)
|
||||
if (prevPath) {
|
||||
prevPath.bytes += c.bytes
|
||||
if (exporterId !== fromId && prevPath.viaId === fromId) {
|
||||
prevPath.viaId = exporterId
|
||||
prevPath.viaName = viaName
|
||||
}
|
||||
if (prevPath.clientName === "—" && c.name !== "—") prevPath.clientName = c.name
|
||||
} else {
|
||||
paths.set(pathKey, {
|
||||
@@ -411,6 +409,73 @@ async function resolveMinSharePct(q: FlowMapHopsQuery): Promise<number> {
|
||||
}
|
||||
}
|
||||
|
||||
// Closed minute buckets from every admitted export. Keep an hour of last-seen context for idle links.
|
||||
async function readInterfaceTraffic(serverIds: number[], iface: string, q: FlowMapHopsQuery, end: number): Promise<FlowMapInterfaceTraffic[]> {
|
||||
if (!serverIds.length) return []
|
||||
const { minutes } = q
|
||||
// Private site-to-site flows are traffic on the link even when the destination graph hides mesh paths.
|
||||
const planes = q.excludeOverlay === false ? ["payload", "client_mesh", "overlay"] : ["payload", "client_mesh"]
|
||||
const dimensions = planes.flatMap(plane => [FLOW_IFACE_RX_DIM + ":" + plane, FLOW_IFACE_TX_DIM + ":" + plane])
|
||||
const start = new Date(end - minutes * 60000).toISOString()
|
||||
const rows = await flowReadDbAll<{server_id: number; key: string; dim: string; bytes: string; packets: string; last_at: Date | string}>(`
|
||||
SELECT server_id, key, dim, COALESCE(SUM(bytes) FILTER (WHERE bucket_at >= ?), 0) AS bytes,
|
||||
COALESCE(SUM(packets) FILTER (WHERE bucket_at >= ?), 0) AS packets, MAX(bucket_at) AS last_at
|
||||
FROM flow_minute_dims
|
||||
WHERE server_id = ANY(?::bigint[]) AND bucket_at >= ? AND bucket_at < ? AND dim = ANY(?::text[])
|
||||
GROUP BY server_id, key, dim
|
||||
`, [start, start, serverIds, new Date(end - Math.max(minutes, 60) * 60000).toISOString(),
|
||||
new Date(end).toISOString(), dimensions])
|
||||
const totals = new Map<string, FlowMapInterfaceTraffic>()
|
||||
for (const row of rows) {
|
||||
const name = resolveIfaceName(row.server_id, row.key).name
|
||||
if (iface && name !== resolveIfaceName(row.server_id, iface).name) continue
|
||||
const key = JSON.stringify([row.server_id, name])
|
||||
const last = new Date(row.last_at).toISOString()
|
||||
const value = totals.get(key) ?? { serverId: String(row.server_id), iface: name, rxBytes: 0, txBytes: 0,
|
||||
rxPackets: 0, txPackets: 0, lastBucketAt: last, inWindow: false }
|
||||
const rx = row.dim.startsWith(FLOW_IFACE_RX_DIM + ":")
|
||||
const bytes = rx ? "rxBytes" : "txBytes", packets = rx ? "rxPackets" : "txPackets"
|
||||
value[bytes] = flowCounterSum([value[bytes], flowCounter(row.bytes)])
|
||||
value[packets] = flowCounterSum([value[packets], flowCounter(row.packets)])
|
||||
if (last > value.lastBucketAt) value.lastBucketAt = last
|
||||
value.inWindow = value.lastBucketAt >= start
|
||||
totals.set(key, value)
|
||||
}
|
||||
return [...totals.values()].sort((a,b) => a.serverId.localeCompare(b.serverId) || a.iface.localeCompare(b.iface))
|
||||
}
|
||||
|
||||
// Interface names are local to the exporter; match them against the GRE inventory for the flow minute.
|
||||
async function readMapGrePeers(rows: { serverId: number; bucketAt: string; inIface: string; outIface: string }[]) {
|
||||
const peers = new Map<string, Map<string, string>>()
|
||||
if (!rows.length) return peers
|
||||
const buckets = new Set<string>(), names = new Set<string>()
|
||||
for (const row of rows) {
|
||||
buckets.add(row.bucketAt)
|
||||
for (const iface of [row.inIface, row.outIface]) names.add(row.serverId + "|" + resolveIfaceName(row.serverId, iface).name)
|
||||
}
|
||||
const bindings = await flowReadDbAll<{ bucket: string; key: string; remote: string }>(`
|
||||
SELECT b.bucket, (t->>'serverId') || '|' || (t->>'name') AS key, t->>'remoteAddress' AS remote
|
||||
FROM unnest(?::text[]) AS b(bucket)
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT payload_json FROM internet_path_snapshots
|
||||
WHERE sampled_at < b.bucket::timestamptz + interval '1 minute'
|
||||
AND sampled_at >= b.bucket::timestamptz - interval '15 minutes'
|
||||
ORDER BY sampled_at DESC, id DESC LIMIT 1
|
||||
) snapshot
|
||||
CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(payload_json->'greTunnels')='array'
|
||||
THEN payload_json->'greTunnels' ELSE '[]'::jsonb END) AS t
|
||||
WHERE payload_json->>'collectionComplete'='true' AND t->>'serverId' ~ '^[1-9][0-9]*$'
|
||||
AND ((t->>'serverId') || '|' || (t->>'name'))=ANY(?::text[])
|
||||
AND t->>'enabled'='true' AND t->>'name'<>'' AND t->>'remoteAddress'<>''
|
||||
`, [[...buckets], [...names]])
|
||||
for (const row of bindings) {
|
||||
const interfaces = peers.get(row.bucket) ?? new Map<string, string>()
|
||||
interfaces.set(row.key, interfaces.has(row.key) ? "" : row.remote.trim().toLowerCase())
|
||||
peers.set(row.bucket, interfaces)
|
||||
}
|
||||
return peers
|
||||
}
|
||||
|
||||
async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number, scope?: ScopedFlowAnalyticsRead): Promise<FlowMapHopsDto> {
|
||||
const authorize = scope?.authorize ?? (async () => {})
|
||||
if (!scope) refreshFlowCatalogInBackground()
|
||||
@@ -418,7 +483,9 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const limits = scope ? await readFlowMapSourceLimits() : undefined
|
||||
const windowSec = Math.max(60, q.minutes * 60)
|
||||
await authorize()
|
||||
const raw = await listFlowRowsForWindow(q.minutes, q.serverId, { ...(scope ? { maxRows: scope.maxRows } : {}), untilIso: new Date().toISOString() })
|
||||
const end = Math.floor(Date.now() / 60000) * 60000
|
||||
const start = new Date(end - windowSec * 1000).toISOString()
|
||||
const raw = await listStoredFlowRows(start, q.serverId, { ...(scope ? { maxRows: scope.maxRows } : {}), untilIso: new Date(end - 1).toISOString() })
|
||||
if (scope && raw.some(row => row.serverId !== q.serverId)) throw new Error("Строка карты вне выбранного сервера")
|
||||
await authorize()
|
||||
const catalog = await getServerCatalog(scope?.serverIds)
|
||||
@@ -472,7 +539,16 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
if (scope) flowCounterSum(working.map(row => row.bytes))
|
||||
const hops = new Map<string, HopAcc>()
|
||||
const dstAcc = new Map<string, DstAcc>()
|
||||
const jhToEn = new Map<number, number>()
|
||||
const hostIds = new Map<string, number | null>()
|
||||
for (const node of topo.enNodes) for (const host of node.hosts) {
|
||||
const key = host.trim().split("/")[0]!.toLowerCase()
|
||||
if (!key || key === "0.0.0.0" || key === "::") continue
|
||||
const previous = hostIds.get(key)
|
||||
hostIds.set(key, previous === undefined || previous === node.id ? node.id : null)
|
||||
}
|
||||
await authorize()
|
||||
const peers = await readMapGrePeers(working)
|
||||
const observed = new Map<(typeof working)[number], { endpoints: ReturnType<typeof resolveFlowEndpoints>; exitId?: number; reverse: boolean }>()
|
||||
const enIds = new Set(topo.enNodes.map((n) => n.id))
|
||||
let totalBytes = 0
|
||||
|
||||
@@ -482,15 +558,6 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
return resolveMapClient(topo, r.serverId, inName, outName)
|
||||
}
|
||||
|
||||
const payloadRows = wantDedup
|
||||
? dedupFlowRowsAcrossExporters(working, (a, b) => {
|
||||
const aCli = Boolean(rowClient(a))
|
||||
const bCli = Boolean(rowClient(b))
|
||||
if (aCli !== bCli) return aCli ? a : b
|
||||
return a.bytes >= b.bytes ? a : b
|
||||
})
|
||||
: working
|
||||
|
||||
for (const r of working) {
|
||||
const inRes = resolveIfaceName(r.serverId, r.inIface)
|
||||
const outRes = resolveIfaceName(r.serverId, r.outIface)
|
||||
@@ -535,20 +602,37 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
}
|
||||
}
|
||||
|
||||
const enOut = ifaceUsable(outName) ? resolveEn(topo, r.nextHop, outName) : null
|
||||
const enIn = ifaceUsable(inName) ? resolveEn(topo, "", inName) : null
|
||||
const en = (enOut && enOut.id !== r.serverId ? enOut : null)
|
||||
?? (enIn && enIn.id !== r.serverId ? enIn : null)
|
||||
if (en) {
|
||||
jhToEn.set(r.serverId, en.id)
|
||||
const toId = String(en.id)
|
||||
const dir: "fwd" | "rev" = enOut && enOut.id === en.id ? "fwd" : "rev"
|
||||
const bindings = peers.get(r.bucketAt)
|
||||
const outPeer = bindings?.get(fromId + "|" + outName)
|
||||
const outId = outPeer === undefined ? hostIds.get(r.nextHop) : hostIds.get(outPeer)
|
||||
const inId = hostIds.get(bindings?.get(fromId + "|" + inName) ?? "")
|
||||
const peerId = outId && inId && outId !== inId ? null : outId ?? inId
|
||||
const endpoints = resolveFlowEndpoints({
|
||||
src: r.src,
|
||||
dst: r.dst,
|
||||
srcPort: r.srcPort,
|
||||
dstPort: r.dstPort,
|
||||
ctx: destCtxForIface(topo, r.serverId, inName, {
|
||||
outIface: outName,
|
||||
natSrc: r.natSrc,
|
||||
natDst: r.natDst,
|
||||
natSrcPort: r.natSrcPort,
|
||||
natDstPort: r.natDstPort,
|
||||
}),
|
||||
})
|
||||
const reverse = !!endpoints.internetPeer && (endpoints.internetPeer === endpoints.packetSrc || endpoints.internetPeer === r.natSrc)
|
||||
const serviceSide = endpoints.internetPeer ? (reverse ? inId : outId) : peerId
|
||||
const exitId = enIds.has(r.serverId) ? r.serverId : serviceSide ?? undefined
|
||||
observed.set(r, { endpoints, exitId, reverse })
|
||||
if (peerId && peerId !== r.serverId) {
|
||||
const toId = String(peerId)
|
||||
const dir = outId === peerId ? "fwd" : "rev"
|
||||
const greIface = dir === "fwd" && ifaceUsable(outName) ? outName : (ifaceUsable(inName) ? inName : undefined)
|
||||
bump(hops, `gre|${fromId}|${toId}`, {
|
||||
bump(hops, JSON.stringify(["gre", fromId, toId, greIface]), {
|
||||
fromId,
|
||||
fromLabel,
|
||||
toId,
|
||||
toLabel: en.name,
|
||||
toLabel: nodeName(toId),
|
||||
kind: "gre",
|
||||
iface: greIface,
|
||||
}, r.bytes, dir)
|
||||
@@ -578,44 +662,32 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
}
|
||||
}
|
||||
|
||||
const payloadRows = wantDedup
|
||||
? dedupFlowRowsAcrossExporters(working, (a, b) => {
|
||||
const aRouted = observed.get(a)?.exitId !== undefined
|
||||
const bRouted = observed.get(b)?.exitId !== undefined
|
||||
if (aRouted !== bRouted) return aRouted ? a : b
|
||||
const aCli = Boolean(rowClient(a))
|
||||
const bCli = Boolean(rowClient(b))
|
||||
if (aCli !== bCli) return aCli ? a : b
|
||||
return a.bytes >= b.bytes ? a : b
|
||||
})
|
||||
: working
|
||||
|
||||
for (const r of payloadRows) {
|
||||
const inName = resolveIfaceName(r.serverId, r.inIface).name
|
||||
const outName = resolveIfaceName(r.serverId, r.outIface).name
|
||||
totalBytes += r.bytes
|
||||
const ep = resolveFlowEndpoints({
|
||||
src: r.src,
|
||||
dst: r.dst,
|
||||
srcPort: r.srcPort,
|
||||
dstPort: r.dstPort,
|
||||
ctx: destCtxForIface(topo, r.serverId, inName, {
|
||||
outIface: outName,
|
||||
natSrc: r.natSrc,
|
||||
natDst: r.natDst,
|
||||
natSrcPort: r.natSrcPort,
|
||||
natDstPort: r.natDstPort,
|
||||
}),
|
||||
})
|
||||
const { endpoints: ep, exitId, reverse } = observed.get(r)!
|
||||
const dst = ep.internetPeer
|
||||
const dstPort = ep.peerPort || r.dstPort
|
||||
const srcPort = ep.otherPort || r.srcPort
|
||||
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : ""
|
||||
const client = resolveMapClient(topo, r.serverId, inName, outName)
|
||||
const prevDst = dstAcc.get(destKey)
|
||||
if (prevDst) {
|
||||
prevDst.bytes += r.bytes
|
||||
bumpFrom(prevDst, String(r.serverId), r.bytes, client)
|
||||
} else {
|
||||
const acc: DstAcc = {
|
||||
dst,
|
||||
bytes: r.bytes,
|
||||
proto: r.proto,
|
||||
dstPort,
|
||||
srcPort,
|
||||
fromBytes: new Map(),
|
||||
}
|
||||
bumpFrom(acc, String(r.serverId), r.bytes, client)
|
||||
dstAcc.set(destKey, acc)
|
||||
}
|
||||
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, proto: r.proto, dstPort, srcPort, fromBytes: new Map<string, FromAcc>() }
|
||||
acc.bytes += r.bytes
|
||||
if (exitId !== undefined) bumpFrom(acc, String(r.serverId), String(exitId), r.bytes, reverse, client)
|
||||
dstAcc.set(destKey, acc)
|
||||
}
|
||||
|
||||
const svcTotals = new Map<string, DestTotal>()
|
||||
@@ -628,25 +700,6 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const nestedEdges = new Map<string, DestEdgeAcc>()
|
||||
const nestedPaths = new Map<string, DestPathAcc>()
|
||||
|
||||
for (const h of hops.values()) {
|
||||
if (h.kind !== "gre" || !h.toId) continue
|
||||
const from = Number(h.fromId)
|
||||
const to = Number(h.toId)
|
||||
if (!Number.isFinite(from) || !Number.isFinite(to)) continue
|
||||
if (enIds.has(to) && !enIds.has(from)) jhToEn.set(from, to)
|
||||
}
|
||||
|
||||
const soleEnId = topo.enNodes.length === 1 ? String(topo.enNodes[0]!.id) : null
|
||||
|
||||
function anchorEnId(exporterId: string): string | null {
|
||||
const n = Number(exporterId)
|
||||
if (enIds.has(n)) return exporterId
|
||||
const mapped = jhToEn.get(n)
|
||||
if (mapped != null) return String(mapped)
|
||||
if (soleEnId) return soleEnId
|
||||
return null
|
||||
}
|
||||
|
||||
function nodeName(id: string): string {
|
||||
const n = Number(id)
|
||||
if (Number.isFinite(n)) {
|
||||
@@ -670,9 +723,8 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes)
|
||||
const nestedId = mapCountryServiceNodeId(country.id, svcId)
|
||||
bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes)
|
||||
for (const [exporterId, from] of acc.fromBytes) {
|
||||
const fromId = anchorEnId(exporterId)
|
||||
if (!fromId) continue
|
||||
for (const from of acc.fromBytes.values()) {
|
||||
const { exporterId, enId: fromId } = from
|
||||
const enName = nodeName(fromId)
|
||||
const viaName = nodeName(exporterId)
|
||||
bumpDestFrom(svcEdges, svcPaths, svcId, from, exporterId, fromId, enName, viaName)
|
||||
@@ -702,7 +754,11 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
await authorize()
|
||||
if (scope && (!isDeepStrictEqual(topo, await loadFlowTopology(scope.serverIds, authorize)) || !isDeepStrictEqual(limits, await readFlowMapSourceLimits()))) throw new Error("Топология или пределы карты NetFlow изменились во время чтения")
|
||||
await authorize()
|
||||
// Whole-interface counters must never be exposed as per-user payload or added to totalBytes.
|
||||
const interfaceTraffic = q.userId ? undefined : await readInterfaceTraffic(q.serverId ? [q.serverId] : [...catalog.byId.keys()], ifaceFilter, q, end)
|
||||
await authorize()
|
||||
return {
|
||||
...(interfaceTraffic ? { interfaceTraffic } : {}),
|
||||
hops: [...hops.values()]
|
||||
.map((a) => toHop(a, windowSec))
|
||||
.sort((a, b) => a.bytes === b.bytes ? 0 : b.bytes - a.bytes),
|
||||
|
||||
@@ -72,7 +72,7 @@ export async function getSettings() {
|
||||
retentionDays: 14,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
}).onConflictDoNothing({ target: uptimeSettings.id })
|
||||
return (await db.select().from(uptimeSettings).where(eq(uptimeSettings.id, 1)).limit(1))[0]
|
||||
}
|
||||
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
import { useEffect, useRef } from "react"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
|
||||
export function NetworkMapLegend() {
|
||||
export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
|
||||
const details = useRef<HTMLDetailsElement>(null)
|
||||
useEffect(() => {
|
||||
if (window.matchMedia("(max-width: 767px)").matches && details.current) details.current.open = false
|
||||
}, [])
|
||||
if ((compact || window.matchMedia("(max-width: 767px)").matches) && details.current) details.current.open = false
|
||||
}, [compact])
|
||||
return (
|
||||
<details ref={details} open data-map-legend className="absolute left-3 top-3 z-20 max-w-[calc(100%-1.5rem)] rounded-lg border bg-popover text-popover-foreground shadow-sm">
|
||||
<summary className="cursor-pointer px-3 py-2 text-xs font-semibold focus-visible:outline-2 focus-visible:outline-ring">Легенда карты</summary>
|
||||
@@ -40,6 +40,7 @@ export function NetworkMapLegend() {
|
||||
))}
|
||||
<p className="text-muted-foreground">RTT · задержка пробы. «—» · нет измерения.</p>
|
||||
<p className="text-muted-foreground">NetFlow · трафик за 5 минут, не пропускная способность канала.</p>
|
||||
<p className="text-muted-foreground">Live GRE · текущие RX/TX в деталях туннеля.</p>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
+16
-1
@@ -61,7 +61,22 @@
|
||||
|
||||
- **WireGuard.** IX автоматически создаёт пару ключей Linux. После применения скачайте готовый `.conf` из карточки клиента, сохраните под исходным именем в `/etc/wireguard/` с правами `0600` и запустите `sudo wg-quick up <имя-файла-без-.conf>`. Указанный внешний IP Linux сохраняет исходный путь управления при полном туннеле. Для клиента со своей парой ключей доступен шаблон с полем для его приватного ключа.
|
||||
- **Получение WireGuard через MCP.** Вызовите `mm_wireguard_export_plan` с полями `serverId`, `interfaceName` клиента, `ixSegmentId` и `format: "peer-conf"`. После подтверждения и выполнения плана ссылка на готовый файл доступна авторизованному владельцу подключения 15 минут. Ключ находится только в скачиваемом файле.
|
||||
- **GRE/IPsec.** Укажите два фиксированных внешних IPv4-адреса. Менеджер создаёт на CHR GRE с выключенным FastPath и IKEv2/IPsec в транспортном режиме. Оператор с правами записи скачивает конфиг strongSwan с индивидуальным PSK и команды настройки Linux. Старые вручную подготовленные подключения остаются доступны по прежнему шаблону.
|
||||
- **Два протокола.** Отметьте WireGuard и GRE/IPsec при создании. Для существующего клиента откройте **Доступ и выход**, выберите свободный протокол и нажмите **Добавить туннель**. Туннели имеют отдельные адреса и ключи, входят в одну VRF сегмента на выбранном IX, настраиваются и отключаются отдельно. Для второго туннеля по умолчанию предложен доступ к разрешённым сетям. Если на VPS одновременно запущены оба туннеля с маршрутом по умолчанию, сгенерированные правила GRE направляют обычный трафик через GRE.
|
||||
- **GRE/IPsec.** Укажите два фиксированных внешних IPv4-адреса. После применения скачайте конфиг strongSwan и скрипт GRE в одну папку на VPS. На Ubuntu установите `charon-systemd strongswan-swanctl`, запустите `sudo systemctl start strongswan` и выполните показанную в карточке команду `sudo sh ./…-setup.sh`. Скрипт копирует профиль с правами `0600`, устанавливает IKEv2/IPsec, создаёт GRE и использует отдельную таблицу для туннельных маршрутов. Транспорт до IX и ответы с внешнего IPv4 VPS, включая SSH, идут по основной таблице Linux.
|
||||
|
||||
### Несколько туннелей на одном VPS
|
||||
|
||||
Карточка Linux-клиента объединяет его туннели и группы резервирования. Для нового интерфейса RouterOS имя включает протокол, имя клиента и уникальный суффикс, например `il-gre-tg-a1b2c3d4e5f6`. Существующие подключения сохраняют свои имена. RX и TX в строке GRE/IPsec показывают накопленные байты интерфейса на CHR.
|
||||
|
||||
1. В **Linux-клиенты** откройте меню действующего подключения и выберите **Создать группу с этим туннелем**. Интерфейс уже будет первым в списке. Для участника существующей группы это же меню открывает её редактор. Ключи VPS и CHR при создании группы сохраняются. Для нового транспорта откройте меню клиента и скачайте **Конфиг для группы ix-client**.
|
||||
2. Добавьте второе подключение одного VPS. Старые управляемые подключения без идентификатора VPS можно выбрать вместе, подтвердив их принадлежность одному серверу. Для исправления прежней привязки свободного подключения откройте **Доступ и выход → Привязка к VPS**, выберите VPS и сохраните ревизию. У всех участников должны различаться внутренние IP-адреса VPS и IX и совпадать семейство адресов и сети назначения. В режиме резервирования первым поставьте основной, затем резервы в порядке предпочтения. В параллельном режиме задайте равное распределение или веса. В прямые исключения внесите сети, к которым VPS должен обращаться через WAN.
|
||||
3. Нажмите **Скачать для ix-client** и импортируйте JSON группы через **B → I**. Если имя интерфейса на VPS отличается от имени в JSON, ix-client сопоставит существующий транспорт по адресам и параметрам пира. Проверьте найденное локальное имя и соответствие туннеля в предварительном просмотре **F2**. Нажмите **Enter** для применения и **Y** для подтверждения. Без подтверждения через 60 секунд восстановится предыдущая конфигурация. Одиночные интерфейсы можно продолжать использовать отдельно.
|
||||
|
||||
**Интерфейсы, созданные вручную на CHR и VPS.** Пользователь с правом управления сетью может открыть **Группы туннелей VPS → Создать группу → Добавить из интерфейсов RouterOS** и выбрать узел применённого сегмента и действующий WG или GRE. Укажите фактическое имя интерфейса Linux, внутренние адреса обеих сторон, внешний IP IX и сети назначения. Для WG укажите публичный ключ **VPS**. Manager проверит, что он принадлежит включённому пиру, что его `allowed-address` включает адрес VPS и внешний IP назначен узлу IX. Для GRE укажите внешний IPv4 VPS. Manager сверит пару внешних адресов, выключенный FastPath и обязательную транспортную политику IPsec. Внутренний адрес VPS должен подтверждаться подсетью, адресом point-to-point или отдельным хост-маршрутом через GRE.
|
||||
|
||||
При сохранении и экспорте Manager читает RouterOS. Параметры ручного подключения сохраняются в группе, а существующие ключи, VRF, маршруты и интерфейсы CHR продолжают работать. Для межузловых туннелей, BGP-подключений и интерфейсов другой VRF используйте их собственную схему маршрутизации. У ручного подключения оператор указывает назначения, которые уже доступны через IX. При экспорте JSON для WG Manager подставляет публичный ключ CHR. Ручной импорт WG через внешний NAT поддерживает только адреса, назначенные самой CHR. Если публичный адрес есть лишь на вышестоящем NAT, проверка Manager отклонит его.
|
||||
|
||||
Фактический активный путь, состояние резервов и распределение соединений видны на VPS в **B → Группы** или в выводе `sudo ix-client bond status`. Клиент раз в секунду посылает ICMP-пробу на внутренний адрес IX через каждый туннель, в том числе в отсутствие пользовательского трафика. Разрешите ответы на эти пробы. После трёх пропущенных ответов клиент исключает путь. Если резерв работает, клиент возвращает новые соединения на основной после 30 секунд устойчивых ответов. Уже открытое соединение через упавший туннель может потребовать переподключения. Ответы на входящие прямые соединения возвращаются через тот WAN, на который пришёл запрос.
|
||||
|
||||
### Выход и резерв
|
||||
|
||||
|
||||
+36
-34
@@ -1,4 +1,4 @@
|
||||
import type { FlowMapHop } from "@mmapp/contracts/traffic-flow"
|
||||
import type { FlowMapHop, FlowMapInterfaceTraffic } from "@mmapp/contracts/traffic-flow"
|
||||
import { fmtRate } from "@/lib/fmt-rate"
|
||||
|
||||
export interface MatchedNetflowHop {
|
||||
@@ -9,19 +9,17 @@ export interface MatchedNetflowHop {
|
||||
}
|
||||
|
||||
export interface GreNetflowHop extends MatchedNetflowHop {
|
||||
exactInterface: boolean
|
||||
source: "interface" | "retained"
|
||||
peerObservation?: boolean
|
||||
packets?: number
|
||||
lastBucketAt?: string
|
||||
inWindow: boolean
|
||||
}
|
||||
|
||||
function ifaceNorm(s: string | undefined): string {
|
||||
return (s ?? "").trim().toLowerCase()
|
||||
}
|
||||
|
||||
function pairKey(a: string, b: string): string {
|
||||
const x = String(a)
|
||||
const y = String(b)
|
||||
return x <= y ? `${x}\t${y}` : `${y}\t${x}`
|
||||
}
|
||||
|
||||
function mergeDirected(hops: FlowMapHop[], mapFromId: string): MatchedNetflowHop {
|
||||
let bytes = 0
|
||||
let bpsFwd = 0
|
||||
@@ -45,41 +43,45 @@ export function hopHasRate(h: MatchedNetflowHop | undefined): h is MatchedNetflo
|
||||
}
|
||||
|
||||
export function formatNetflowRate<T extends Pick<MatchedNetflowHop, "bps">>(hop: T): string {
|
||||
if (hop.bps > 0 && hop.bps < 1000) return hop.bps < 1 ? "<1 бит/с" : `${Math.round(hop.bps)} бит/с`
|
||||
return fmtRate(hop.bps / 1_000_000)
|
||||
}
|
||||
|
||||
export function formatNetflowDir(hop: Pick<MatchedNetflowHop, "bpsFwd" | "bpsRev">): string {
|
||||
return `↓${fmtRate(hop.bpsFwd / 1_000_000)} ↑${fmtRate(hop.bpsRev / 1_000_000)}`
|
||||
return `↓${formatNetflowRate({ bps: hop.bpsFwd })} ↑${formatNetflowRate({ bps: hop.bpsRev })}`
|
||||
}
|
||||
|
||||
/** Собственный интерфейс GRE даёт точную привязку, совпадение пары узлов — только оценку. */
|
||||
export function matchNetflowForGreEdge(
|
||||
edge: {
|
||||
tunnel: { name: string; serverId: string }
|
||||
fromServer: { id: string }
|
||||
toServer: { id: string }
|
||||
},
|
||||
/** GRE rates use RX/TX at the tunnel owner, regardless of its position on the map. */
|
||||
function greInterfaceObservation(
|
||||
tunnel: { name: string; serverId: string },
|
||||
hops: FlowMapHop[],
|
||||
traffic: FlowMapInterfaceTraffic[] | undefined,
|
||||
windowSec: number,
|
||||
): GreNetflowHop | undefined {
|
||||
const name = ifaceNorm(edge.tunnel.name)
|
||||
const fromId = String(edge.fromServer.id)
|
||||
const toId = String(edge.toServer.id)
|
||||
const ownerId = edge.tunnel.serverId
|
||||
const peerId = ownerId === fromId ? toId : fromId
|
||||
const want = pairKey(fromId, toId)
|
||||
if (name) {
|
||||
const local = hops.filter((h) => h.kind === "iface" && h.fromId === ownerId && ifaceNorm(h.iface) === name)
|
||||
if (local.length) return { ...mergeDirected(local, fromId), exactInterface: true }
|
||||
const named = hops.filter((h) =>
|
||||
h.kind === "gre" && h.fromId === ownerId && h.toId === peerId && ifaceNorm(h.iface) === name,
|
||||
)
|
||||
if (named.length) return { ...mergeDirected(named, fromId), exactInterface: true }
|
||||
const owner = tunnel.serverId, name = tunnel.name
|
||||
const observed = traffic?.find(row => row.serverId === owner && row.iface === name)
|
||||
if (observed) {
|
||||
const bytes = observed.rxBytes + observed.txBytes
|
||||
return { bytes, packets: observed.rxPackets + observed.txPackets, bps: bytes * 8 / windowSec, bpsFwd: observed.rxBytes * 8 / windowSec,
|
||||
bpsRev: observed.txBytes * 8 / windowSec, source: "interface", lastBucketAt: observed.lastBucketAt, inWindow: observed.inWindow }
|
||||
}
|
||||
const pairHits = hops.filter((h) =>
|
||||
h.kind === "gre" && Boolean(h.toId) && pairKey(h.fromId, h.toId) === want,
|
||||
)
|
||||
if (pairHits.length) return { ...mergeDirected(pairHits, fromId), exactInterface: false }
|
||||
return undefined
|
||||
// Older collectors only retained the busiest flows. An inferred pair has no interface identity.
|
||||
const legacy = hops.find(h => h.kind === "iface" && h.fromId === owner && h.iface === name)
|
||||
if (legacy) return { bytes: legacy.bytes, bps: legacy.bps, bpsFwd: legacy.bpsRev, bpsRev: legacy.bpsFwd,
|
||||
source: "retained", inWindow: true }
|
||||
}
|
||||
|
||||
export function matchNetflowForGreEdge(
|
||||
edge: { tunnel: {name: string; serverId: string}; peerTunnel?: {name: string; serverId: string} },
|
||||
hops: FlowMapHop[], traffic: FlowMapInterfaceTraffic[] | undefined, windowSec: number,
|
||||
): GreNetflowHop | undefined {
|
||||
const local = greInterfaceObservation(edge.tunnel, hops, traffic, windowSec)
|
||||
if (!edge.peerTunnel || local?.inWindow && local.source === "interface") return local
|
||||
const peer = greInterfaceObservation(edge.peerTunnel, hops, traffic, windowSec)
|
||||
if (!peer) return local
|
||||
if (local?.inWindow && (peer.source === "retained" || !peer.inWindow)) return local
|
||||
if (local && !peer.inWindow && (local.lastBucketAt ?? "") >= (peer.lastBucketAt ?? "")) return local
|
||||
return { ...peer, bpsFwd: peer.bpsRev, bpsRev: peer.bpsFwd, peerObservation: true }
|
||||
}
|
||||
|
||||
/** WAN-аплинк HR: kind wan, иначе iface с тем же именем на homeId. */
|
||||
|
||||
+11
-13
@@ -785,6 +785,7 @@ function greEndpointAnchor(
|
||||
/** GRE на карте только между узлами каталога; у HR конец туннеля — у соответствующего WAN-спутника. */
|
||||
export interface GreMapEdge {
|
||||
tunnel: GreTunnel
|
||||
peerTunnel?: GreTunnel
|
||||
from: { x: number; y: number }
|
||||
to: { x: number; y: number }
|
||||
fromServer: Server
|
||||
@@ -798,8 +799,7 @@ export function buildGreMapEdges(
|
||||
wanSatPos: Record<string, { x: number; y: number }[]>,
|
||||
resolvedIpv4ByHost?: ReadonlyMap<string, string>,
|
||||
): GreMapEdge[] {
|
||||
const out: GreMapEdge[] = []
|
||||
const seenByLink = new Map<string, number>()
|
||||
const links = new Map<string, GreMapEdge[]>()
|
||||
|
||||
const statusRank: Record<GreTunnel["status"], number> = {
|
||||
up: 3,
|
||||
@@ -854,18 +854,16 @@ export function buildGreMapEdges(
|
||||
const to = greEndpointAnchor(toServer, t, "peer", nodePos, wanSatPos, resolvedIpv4ByHost)
|
||||
const edge: GreMapEdge = { tunnel: t, from, to, fromServer, toServer }
|
||||
const key = canonicalLinkKey(t, fromServer, toServer)
|
||||
const prevIdx = seenByLink.get(key)
|
||||
if (prevIdx == null) {
|
||||
seenByLink.set(key, out.length)
|
||||
out.push(edge)
|
||||
continue
|
||||
}
|
||||
const prev = out[prevIdx]
|
||||
if (tunnelPriority(t) > tunnelPriority(prev.tunnel)) {
|
||||
out[prevIdx] = edge
|
||||
}
|
||||
const group = links.get(key)
|
||||
if (group) group.push(edge)
|
||||
else links.set(key, [edge])
|
||||
}
|
||||
return out
|
||||
return [...links.values()].flatMap(group => {
|
||||
if (group.length !== 2 || group[0].tunnel.serverId === group[1].tunnel.serverId) return group
|
||||
const [one, two] = group
|
||||
const [edge, peer] = tunnelPriority(two.tunnel) > tunnelPriority(one.tunnel) ? [two, one] : [one, two]
|
||||
return [{ ...edge, peerTunnel: peer.tunnel }]
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -27,7 +27,7 @@ export function validateNetworkMapSnapshot(servers:unknown,gre:unknown,probes:un
|
||||
|
||||
import {flowMapHopsDtoSchema} from "@mmapp/contracts/traffic-flow"
|
||||
import {isIpv4String} from "./gre-endpoint-resolve"
|
||||
export const networkMapFlowSchema = flowMapHopsDtoSchema.required().partial({ sourceWindow: true }).refine(data =>
|
||||
export const networkMapFlowSchema = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true }).refine(data =>
|
||||
(data.sourceWindow
|
||||
? data.sourceWindow.requestedMinutes === 5 && data.sourceWindow.effectiveMinutes === data.rangeMinutes
|
||||
: data.rangeMinutes === 5) &&
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { z } from "zod"
|
||||
export * from "./ix-bond-management.js"
|
||||
export * from "./ix-bond.js"
|
||||
|
||||
const key = z.string().regex(/^[a-z][a-z0-9-]{0,23}$/)
|
||||
const interfaceName = z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/)
|
||||
@@ -43,6 +45,7 @@ const greProvision = z.object({
|
||||
|
||||
const linuxPolicy = z.object({
|
||||
name: z.string().trim().min(1).max(80),
|
||||
clientId: z.string().uuid().optional(),
|
||||
enabled: z.boolean(),
|
||||
destinations: z.array(prefix).max(64),
|
||||
exit: key.optional(),
|
||||
@@ -139,6 +142,9 @@ export const ixLinuxClientRequest = z.object({
|
||||
name: linuxPolicy.shape.name,
|
||||
enabled: z.boolean().default(true),
|
||||
kind: z.enum(["wireguard", "gre-ipsec"]),
|
||||
additionalGre: z.boolean().optional(),
|
||||
vpsClientId: z.uuid().optional(),
|
||||
companionOf: interfaceName.optional(),
|
||||
hubEndpoint: address,
|
||||
peerEndpoint: address.optional(),
|
||||
peerPublicKey: wireguardProvision.shape.peerPublicKey.optional(),
|
||||
@@ -151,6 +157,11 @@ export const ixLinuxClientRequest = z.object({
|
||||
rotate: z.boolean().optional(),
|
||||
}).strict().refine(input => !input.transit || !input.exit || input.exit === input.transit.name,
|
||||
{ path: ["exit"], message: "Выход клиента должен совпадать с выбранным транзитом" })
|
||||
.refine(input => !input.vpsClientId || !input.companionOf,
|
||||
"Новый туннель наследует VPS исходного подключения.")
|
||||
.refine(input => (!input.companionOf || !input.interfaceName) &&
|
||||
(!input.additionalGre || input.kind === "wireguard" && !input.interfaceName && !input.companionOf),
|
||||
"Оба протокола можно создать для нового клиента. Для существующего добавьте второй протокол.")
|
||||
|
||||
export type IxLinuxClientRequest = z.infer<typeof ixLinuxClientRequest>
|
||||
|
||||
@@ -209,6 +220,7 @@ export interface IxLinuxBinding {
|
||||
}
|
||||
|
||||
export interface IxLinuxAccess {
|
||||
hubPublicKey?: string
|
||||
kind: IxLinuxBinding["kind"]
|
||||
revision: number
|
||||
filename: string
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { z } from "zod"
|
||||
import { ixBondModeSchema, ixWireguardPublicKey } from "./ix-bond.js"
|
||||
|
||||
const ip = z.union([z.ipv4(), z.ipv6()])
|
||||
const existing = z.object({
|
||||
linuxInterface: z.string().regex(/^[a-zA-Z0-9_=-][a-zA-Z0-9_.=-]{0,14}$/),
|
||||
address: ip, probe: ip, endpoint: ip,
|
||||
destinations: z.array(z.union([z.cidrv4(), z.cidrv6()])).min(1).max(64),
|
||||
})
|
||||
export const ixExistingTransportSchema = z.discriminatedUnion("kind", [
|
||||
existing.extend({ kind: z.literal("wireguard"), clientPublicKey: ixWireguardPublicKey }).strict(),
|
||||
existing.extend({ kind: z.literal("gre-ipsec"), endpoint: z.ipv4(), remoteEndpoint: z.ipv4() }).strict(),
|
||||
]).refine(path => path.address.includes(":") === path.probe.includes(":") && path.address !== path.probe &&
|
||||
path.destinations.every(cidr => cidr.includes(":") === path.address.includes(":")), "Проверьте внутренние адреса и семейство назначений")
|
||||
export type IxExistingTransport = z.infer<typeof ixExistingTransportSchema>
|
||||
|
||||
const memberRef = z.object({
|
||||
segmentId: z.uuid(), serverId: z.number().int().positive().safe(),
|
||||
interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/),
|
||||
appliedRevision: z.number().int().positive().safe(), weight: z.number().int().min(1).max(100),
|
||||
existing: ixExistingTransportSchema.optional(),
|
||||
}).strict()
|
||||
|
||||
export const ixBondEditSchema = z.object({
|
||||
id: z.uuid().optional(), revision: z.number().int().nonnegative().safe(),
|
||||
name: z.string().trim().min(1).max(80).regex(/^[^\x00-\x1f\x7f]+$/), mode: ixBondModeSchema,
|
||||
directCidrs: z.array(z.union([z.cidrv4(), z.cidrv6()])).max(64),
|
||||
members: z.array(memberRef).min(2).max(16),
|
||||
}).strict().refine(value => !!value.id === (value.revision > 0), "Укажите текущую ревизию группы")
|
||||
|
||||
export type IxBondEdit = z.infer<typeof ixBondEditSchema>
|
||||
export const ixSavedBondSchema = ixBondEditSchema.safeExtend({
|
||||
id: z.uuid(), revision: z.number().int().positive().safe(), clientId: z.uuid(), ownerSegmentId: z.uuid(),
|
||||
})
|
||||
export type IxSavedBond = z.infer<typeof ixSavedBondSchema>
|
||||
export interface IxBondCandidate extends Omit<IxBondEdit["members"][number], "weight"> {
|
||||
segmentName: string
|
||||
clientId?: string
|
||||
name: string
|
||||
kind: "wireguard" | "gre-ipsec"
|
||||
endpoint: string
|
||||
address: string
|
||||
probe: string
|
||||
destinations: string[]
|
||||
}
|
||||
export interface IxBondCatalog { groups: IxSavedBond[]; candidates: IxBondCandidate[] }
|
||||
@@ -0,0 +1,50 @@
|
||||
import { z } from "zod"
|
||||
|
||||
const ip = z.union([z.ipv4(), z.ipv6()])
|
||||
const cidr = z.union([z.cidrv4(), z.cidrv6()])
|
||||
export const ixWireguardPublicKey = z.string().regex(/^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$/)
|
||||
.refine(key => key !== "A".repeat(43) + "=", "Недопустимый нулевой ключ WireGuard")
|
||||
export const ixBondModeSchema = z.enum(["failover", "equal", "weighted"])
|
||||
const member = z.object({
|
||||
interfaceName: z.string().regex(/^[a-zA-Z0-9_=-][a-zA-Z0-9_.=-]{0,14}$/),
|
||||
kind: z.enum(["wireguard", "gre-ipsec"]),
|
||||
address: ip,
|
||||
probe: ip,
|
||||
endpoint: ip,
|
||||
weight: z.number().int().min(1).max(100),
|
||||
// A 32-byte WireGuard key ends with two zero padding bits and one '='.
|
||||
peerPublicKey: ixWireguardPublicKey.optional(),
|
||||
}).strict()
|
||||
|
||||
export const ixBondBundleSchema = z.object({
|
||||
version: z.literal(1),
|
||||
id: z.string().uuid(),
|
||||
revision: z.number().int().positive().safe(),
|
||||
clientId: z.string().uuid(),
|
||||
name: z.string().trim().min(1).max(80).regex(/^[^\x00-\x1f\x7f]+$/),
|
||||
mode: ixBondModeSchema,
|
||||
destinations: z.array(cidr).min(1).max(64),
|
||||
directCidrs: z.array(cidr).max(64),
|
||||
members: z.array(member).min(2).max(16),
|
||||
}).strict().superRefine((group, ctx) => {
|
||||
const problem = (message: string) => ctx.addIssue({ code: "custom", message })
|
||||
const names = new Set<string>()
|
||||
const hosts = new Set<string>()
|
||||
const ipv6 = group.destinations[0]?.includes(":")
|
||||
if (group.destinations.some(prefix => prefix.includes(":") !== ipv6)) problem("Назначения должны быть одного семейства")
|
||||
for (const path of group.members) {
|
||||
if (names.has(path.interfaceName)) problem("Интерфейс повторяется в группе")
|
||||
names.add(path.interfaceName)
|
||||
for (const address of [path.address, path.probe]) {
|
||||
if (address.includes(":") !== ipv6) problem("Адрес туннеля и назначения должны быть одного семейства")
|
||||
const canonical = ipv6 && z.ipv6().safeParse(address).success ? new URL("http://[" + address + "]").hostname : address
|
||||
if (hosts.has(canonical)) problem("Внутренние адреса путей должны быть уникальны")
|
||||
hosts.add(canonical)
|
||||
}
|
||||
if (path.kind === "gre-ipsec" && path.peerPublicKey) problem("Ключ WireGuard указан для GRE")
|
||||
}
|
||||
})
|
||||
|
||||
export type IxBondMode = z.infer<typeof ixBondModeSchema>
|
||||
export type IxBondBundle = z.infer<typeof ixBondBundleSchema>
|
||||
export type IxBondMember = z.infer<typeof member>
|
||||
@@ -412,6 +412,13 @@ export const flowMapCountryServiceGroupDtoSchema = z.object({
|
||||
|
||||
export const flowMapHopsDtoSchema = z.object({
|
||||
sourceWindow: flowSourceWindowSchema.optional(),
|
||||
/** Link counters include private routed payload. Mesh visibility applies to the inferred graph. */
|
||||
interfaceTraffic: z.array(z.object({
|
||||
serverId: z.string(), iface: z.string(),
|
||||
rxBytes: z.number().int().nonnegative(), txBytes: z.number().int().nonnegative(),
|
||||
rxPackets: z.number().int().nonnegative(), txPackets: z.number().int().nonnegative(),
|
||||
lastBucketAt: z.string().datetime(), inWindow: z.boolean(),
|
||||
})).optional(),
|
||||
hops: z.array(flowMapHopDtoSchema),
|
||||
live: z.boolean(),
|
||||
rangeMinutes: z.number().int().positive(),
|
||||
@@ -454,3 +461,4 @@ export type FlowMapServiceEdge = z.infer<typeof flowMapServiceEdgeDtoSchema>
|
||||
export type FlowMapServicePath = z.infer<typeof flowMapServicePathDtoSchema>
|
||||
export type FlowMapCountryServiceGroup = z.infer<typeof flowMapCountryServiceGroupDtoSchema>
|
||||
export type FlowMapHopsDto = z.infer<typeof flowMapHopsDtoSchema>
|
||||
export type FlowMapInterfaceTraffic = NonNullable<FlowMapHopsDto["interfaceTraffic"]>[number]
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"version": 1,
|
||||
"id": "50b82c5c-4ada-4ffd-a907-510dce60ac50",
|
||||
"revision": 1,
|
||||
"clientId": "6761aeb0-7b3d-45f0-9bea-c6166839490b",
|
||||
"name": "vps-01",
|
||||
"mode": "weighted",
|
||||
"destinations": ["0.0.0.0/0"],
|
||||
"directCidrs": ["203.0.113.64/27"],
|
||||
"members": [
|
||||
{"interfaceName": "wg-ix-a", "kind": "wireguard", "address": "10.123.1.2", "probe": "10.123.1.1", "endpoint": "192.0.2.2", "weight": 3, "peerPublicKey": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8="},
|
||||
{"interfaceName": "gre-ix-b", "kind": "gre-ipsec", "address": "10.123.2.2", "probe": "10.123.2.1", "endpoint": "198.51.100.2", "weight": 1}
|
||||
]
|
||||
}
|
||||
@@ -71,7 +71,9 @@ test("Filters: чтение под общей блокировкой повто
|
||||
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
|
||||
await page.route("**/api/**", async route => {
|
||||
const { pathname, searchParams } = new URL(route.request().url())
|
||||
const conflict = () => route.fulfill({ status: 409, json: { error: "Глобальная конфигурация изменяется другой операцией" } })
|
||||
const conflict = () => route.fulfill({ status: 409, json: lock === "held"
|
||||
? { code: "CONFIGURATION_BUSY", error: "Конфигурация временно занята другой операцией" }
|
||||
: { error: "Глобальная конфигурация изменяется другой операцией" } })
|
||||
if (pathname === "/api/filters/rules" && searchParams.has("serverId")) {
|
||||
if (lock === "held" || lock === "brief") {
|
||||
conflicts++
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { readFile } from "node:fs/promises"
|
||||
import { expect, test } from "@playwright/test"
|
||||
import { ixChangeSchema, ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
|
||||
import { ixBondEditSchema, ixChangeSchema, ixSegmentConfigurationSchema, type IxSavedBond } from "@mmapp/contracts/internet-exchange"
|
||||
|
||||
const id = "fa58fa40-4bcb-4616-9316-cb69463b3150"
|
||||
const observedAt = "2026-11-20T00:00:00Z"
|
||||
@@ -9,6 +9,87 @@ const nodes = [
|
||||
{ id: 2, name: "ix-node-02", site: "TEST-2", country: "FI", enabled: true },
|
||||
]
|
||||
|
||||
test("IX: сборка группы VPS из двух площадок с весами и исключением WAN", async ({ page }) => {
|
||||
const remote = "0b59555b-c920-4b74-b350-977309a4b84a"
|
||||
const segments = [id, remote].map((segmentId, i) => ({
|
||||
id: segmentId, revision: 1, appliedRevision: 1, updatedAt: observedAt,
|
||||
configuration: ixSegmentConfigurationSchema.parse({ name: "site-" + (i + 1),
|
||||
sites: [{ serverId: nodes[i].id, autonomousSystem: 64512, routerId: "192.0.2." + (i + 1), interfaces: i ? [] : [
|
||||
{ name: "gre-local", kind: "gre-ipsec", localEndpoint: "192.0.2.1", endpoint: "198.51.100.2" },
|
||||
] }] }),
|
||||
}))
|
||||
const candidates = segments.map((s, i) => ({ segmentId: s.id, serverId: nodes[i].id,
|
||||
interfaceName: i ? "gre-vps" : "wg-vps", appliedRevision: 1, segmentName: s.configuration.name, name: "vps",
|
||||
kind: i ? "gre-ipsec" : "wireguard", endpoint: "192.0.2." + (i + 1), address: "10.0." + i + ".2", probe: "10.0." + i + ".1", destinations: ["0.0.0.0/0"] }))
|
||||
let groups: IxSavedBond[] = []
|
||||
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
|
||||
await page.route("**/api/**", async route => {
|
||||
const p = new URL(route.request().url()).pathname
|
||||
const json = (body: unknown) => route.fulfill({ json: body })
|
||||
if (p === "/api/auth/config") return json({ required: false })
|
||||
if (p === "/api/ix/nodes") return json({ items: nodes })
|
||||
if (p === "/api/ix/nodes/1/inventory") return json({ observedAt, routerId: "192.0.2.1", defaultRoutes: [], wireguardPorts: [],
|
||||
interfaces: [{ name: "wg-console", type: "wg", running: true, disabled: false, restriction: null, addresses: ["10.8.0.1/30"] },
|
||||
{ name: "gre-local", type: "gre-tunnel", running: true, disabled: false, restriction: null, addresses: ["10.9.0.1/30"] }] })
|
||||
if (p === "/api/ix/segments") return json({ items: segments })
|
||||
if (p === "/api/ix/segments/" + id + "/linux") return json({ items: [{ serverId: 1, kind: "wireguard", interfaceName: "wg-vps" },
|
||||
{ serverId: 1, kind: "gre-ipsec", interfaceName: "gre-local" }], revision: 1 })
|
||||
if (p === "/api/ix/linux-bonds") return json({ groups, candidates })
|
||||
if (p === "/api/ix/segments/" + id + "/linux-bonds") {
|
||||
const body = ixBondEditSchema.parse(route.request().postDataJSON())
|
||||
expect(body.members.slice(0, 2).map(m => [m.segmentId, m.weight])).toEqual([[remote, 3], [id, 1]])
|
||||
if (body.id) expect(body.members[2].existing).toMatchObject({ kind: "wireguard", linuxInterface: "wg0", address: "10.8.0.2",
|
||||
probe: "10.8.0.1", endpoint: "192.0.2.1", destinations: ["0.0.0.0/0"] })
|
||||
expect(body.directCidrs).toEqual(["192.0.2.0/24"])
|
||||
groups = [{ ...body, id: remote, revision: body.revision + 1, clientId: id, ownerSegmentId: id }]
|
||||
return json(groups[0])
|
||||
}
|
||||
return json({ items: [], revision: 1 })
|
||||
})
|
||||
await page.goto("/ix")
|
||||
await page.getByRole("button", { name: "site-1", exact: true }).click()
|
||||
await page.getByRole("button", { name: "Действия клиента wg-vps" }).click()
|
||||
await page.getByRole("menuitem", { name: "Создать группу с этим туннелем" }).click()
|
||||
const editor = page.getByRole("dialog", { name: "Группа туннелей VPS" })
|
||||
await expect(editor.getByLabel("Имя группы")).toHaveValue("vps")
|
||||
await expect(editor.getByText(/1\. vps .*wg-vps/)).toBeVisible()
|
||||
await editor.getByLabel("Имя группы").fill("vps-01")
|
||||
await editor.getByLabel("Режим", { exact: true }).click()
|
||||
await page.getByRole("option", { name: "Параллельно, по весам" }).click()
|
||||
await editor.getByLabel("Добавить туннель этого VPS").click()
|
||||
await expect(page.getByRole("option", { name: /wg-vps/ })).toHaveCount(0)
|
||||
await page.getByRole("option", { name: /gre-vps/ }).click()
|
||||
await editor.getByRole("button", { name: "Выше" }).last().click()
|
||||
await editor.getByLabel("Вес", { exact: true }).first().fill("3")
|
||||
await editor.getByLabel("Прямой выход для сетей (CIDR)").fill("192.0.2.0/24")
|
||||
await expect(editor.getByRole("button", { name: "Сохранить" })).toBeDisabled()
|
||||
await editor.getByRole("checkbox", { name: "Подтверждаю, что выбранные интерфейсы настроены на одном VPS" }).check()
|
||||
await editor.getByRole("button", { name: "Сохранить" }).click()
|
||||
const clientCard = page.getByRole("region", { name: "Клиент wg-vps", exact: true })
|
||||
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("menuitem", { name: "Открыть группу «vps-01»" }).click()
|
||||
await expect(editor.getByLabel("Имя группы")).toHaveValue("vps-01")
|
||||
await expect(editor.getByRole("checkbox", { name: "Подтверждаю, что выбранные интерфейсы настроены на одном VPS" })).toHaveCount(0)
|
||||
await editor.getByRole("button", { name: "Добавить из интерфейсов RouterOS" }).click()
|
||||
await editor.getByLabel("Интерфейс RouterOS").click()
|
||||
await page.getByRole("option", { name: "wg-console" }).click()
|
||||
await editor.getByLabel("Имя интерфейса на VPS").fill("wg0")
|
||||
await editor.getByLabel("Адрес VPS внутри туннеля").fill("10.8.0.2")
|
||||
await editor.getByLabel("Внешний адрес IX", { exact: true }).fill("192.0.2.1")
|
||||
await editor.getByLabel("Публичный ключ WireGuard VPS").fill(Buffer.alloc(32, 23).toString("base64"))
|
||||
await editor.getByRole("button", { name: "Включить в список" }).click()
|
||||
await editor.getByRole("checkbox", { name: "Подтверждаю, что выбранные интерфейсы настроены на одном VPS" }).check()
|
||||
await editor.getByRole("button", { name: "Сохранить" }).click()
|
||||
await expect(page.getByText(/Вес 1 · wg0 .*wg-console/)).toBeVisible()
|
||||
await page.getByRole("button", { name: "Действия клиента gre-local" }).click()
|
||||
await page.getByRole("menuitem", { name: "Создать группу с этим туннелем" }).click()
|
||||
await expect(editor.getByLabel("Интерфейс RouterOS")).toContainText("gre-local")
|
||||
await expect(editor.getByLabel("Адрес IX внутри туннеля")).toContainText("10.9.0.1")
|
||||
await expect(editor.getByLabel("Внешний IPv4 VPS")).toBeVisible()
|
||||
})
|
||||
|
||||
test("IX: редактирование и применение сохранённой ревизии из WebUI без MCP", async ({ page }, testInfo) => {
|
||||
const configuration = ixSegmentConfigurationSchema.parse({ name: "ix-central", sites: [
|
||||
{ serverId: 1, autonomousSystem: 64512, routerId: "192.0.2.10", interfaces: [{ name: "wg-member", kind: "wireguard" }] },
|
||||
@@ -24,6 +105,7 @@ test("IX: редактирование и применение сохранён
|
||||
const path = new URL(request.url()).pathname
|
||||
const json = (body: unknown) => route.fulfill({ json: body })
|
||||
if (path === "/api/auth/config") return json({ required: false })
|
||||
if (path === "/api/ix/linux-bonds") return json({ groups: [], candidates: [] })
|
||||
if (path === "/api/ix/nodes") return json({ items: nodes, peers: nodes })
|
||||
if (/\/api\/ix\/nodes\/\d+\/inventory$/.test(path)) return json({ observedAt, routerId: "10.255.0.1", defaultRoutes: [], wireguardPorts: [],
|
||||
interfaces: [{ name: "wg-member", type: "wg", running: true, disabled: false, addresses: [], restriction: null }] })
|
||||
@@ -146,6 +228,7 @@ test("IX: черновик удаляется после подтвержден
|
||||
const path = new URL(request.url()).pathname
|
||||
if (path === "/api/auth/config") return route.fulfill({ json: { required: false } })
|
||||
if (path === "/api/ix/nodes") return route.fulfill({ json: { items: nodes } })
|
||||
if (path === "/api/ix/linux-bonds") return route.fulfill({ json: { groups: [], candidates: [] } })
|
||||
if (path === "/api/ix/segments") return route.fulfill({ json: { items: deleted ? [] : [draft] } })
|
||||
if (path === `/api/ix/segments/${id}/removal-plan`) {
|
||||
expect(request.postDataJSON()).toEqual({ revision: 1 })
|
||||
@@ -187,6 +270,7 @@ test("IX: новый сегмент сохраняется одним подтв
|
||||
const json = (body: unknown) => route.fulfill({ json: body })
|
||||
if (path === "/api/auth/config") return json({ required: false })
|
||||
if (path === "/api/ix/nodes") return json({ items: [nodes[0]] })
|
||||
if (path === "/api/ix/linux-bonds") return json({ groups: [], candidates: [] })
|
||||
if (path === "/api/ix/segments" && req.method() === "POST") {
|
||||
const change = ixChangeSchema.parse(req.postDataJSON())
|
||||
expect(change.configuration.sites[0]).toMatchObject({ serverId: 1, autoRouterId: true })
|
||||
@@ -219,14 +303,17 @@ test("IX: новый сегмент сохраняется одним подтв
|
||||
expect(applies).toBe(1)
|
||||
})
|
||||
|
||||
for (const mode of ["WAN IX", "новый ExitNode", "ExitNode с двумя WAN-адресами"]) test("IX: VPS подключается через " + mode, async ({ page }, testInfo) => {
|
||||
const remote = mode !== "WAN IX", manual = mode === "ExitNode с двумя WAN-адресами"
|
||||
for (const mode of ["WAN IX", "два протокола", "новый ExitNode", "ExitNode с двумя WAN-адресами"]) test("IX: VPS подключается · " + mode, async ({ page }, testInfo) => {
|
||||
const both = mode === "два протокола"
|
||||
const remote = mode.includes("ExitNode"), manual = mode === "ExitNode с двумя WAN-адресами"
|
||||
const configuration = ixSegmentConfigurationSchema.parse({ name: "ix-vps", sites: [
|
||||
{ serverId: 1, autonomousSystem: 64512, routerId: "10.255.0.1", autoRouterId: true },
|
||||
] })
|
||||
let segment = { id, revision: 1, appliedRevision: 1, configuration, updatedAt: observedAt }
|
||||
const digest = "c".repeat(64)
|
||||
let client: { name: string; kind: "wireguard"; serverId: number; interfaceName: string; managedWireguard: boolean } | undefined
|
||||
let extended = false
|
||||
const clientId = "6677cc81-0ac8-48fd-902a-cecd0ce8633a"
|
||||
const configFile = "[Interface]\nPrivateKey = TEST_PRIVATE_KEY\n[Peer]\nAllowedIPs = 0.0.0.0/0\n"
|
||||
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
|
||||
await page.route("**/api/**", async route => {
|
||||
@@ -234,6 +321,7 @@ for (const mode of ["WAN IX", "новый ExitNode", "ExitNode с двумя WAN
|
||||
const json = (body: unknown) => route.fulfill({ json: body })
|
||||
if (path === "/api/auth/config") return json({ required: false })
|
||||
if (path === "/api/ix/nodes") return json({ items: nodes, peers: [...nodes, { id: 3, name: "exit-arn", type: "exit-node", enabled: true }] })
|
||||
if (path === "/api/ix/linux-bonds") return json({ groups: [], candidates: [] })
|
||||
if (path === "/api/ix/nodes/3/inventory") return json({ interfaces: [{ name: "wan", disabled: false, addresses: manual ? ["192.0.2.12/24", "192.0.2.13/24"] : ["192.0.2.13/24"] }],
|
||||
defaultRoutes: [{ family: 4, interface: "wan" }] })
|
||||
if (path === "/api/ix/nodes/1/inventory") return json({ observedAt, routerId: "10.255.0.1", wireguardPorts: [],
|
||||
@@ -241,14 +329,32 @@ for (const mode of ["WAN IX", "новый ExitNode", "ExitNode с двумя WAN
|
||||
defaultRoutes: [{ family: 4, gateway: "192.0.2.1", interface: "ether1" }] })
|
||||
if (path === "/api/ix/segments") return json({ items: [segment] })
|
||||
if (path === `/api/ix/segments/${id}/linux` && req.method() === "POST") {
|
||||
if (req.postDataJSON().companionOf) {
|
||||
expect(req.postDataJSON()).toMatchObject({ revision: 3, serverId: 1, name: "vps-01", kind: "gre-ipsec",
|
||||
companionOf: "il-vps", hubEndpoint: "192.0.2.11", peerEndpoint: "123.123.123.123", prefixes: [], destinations: [] })
|
||||
expect(req.postDataJSON()).not.toHaveProperty("interfaceName")
|
||||
expect(req.postDataJSON()).not.toHaveProperty("exit")
|
||||
const site = segment.configuration.sites[0]
|
||||
segment = { ...segment, revision: 4, configuration: ixSegmentConfigurationSchema.parse({
|
||||
...segment.configuration, sites: [{ ...site, interfaces: [
|
||||
{ ...site.interfaces[0], linux: { ...site.interfaces[0].linux, clientId } },
|
||||
{ name: "il-gre", kind: "gre-ipsec", linux: { name: "vps-01", enabled: true, destinations: [], clientId } },
|
||||
] }],
|
||||
}) }
|
||||
extended = true
|
||||
return json({ segment, interfaceName: "il-gre" })
|
||||
}
|
||||
expect(req.postDataJSON()).toMatchObject({ name: "vps-01", kind: "wireguard", hubEndpoint: "192.0.2.11",
|
||||
peerEndpoint: "123.123.123.123", ...(remote ? { transit: { targetServerId: 3, localEndpoint: "192.0.2.11", remoteEndpoint: "192.0.2.13", family: 4 } } : { exit: "local-wan" }) })
|
||||
expect(req.postDataJSON()).not.toHaveProperty("peerPublicKey")
|
||||
expect(req.postDataJSON().additionalGre).toBe(both ? true : undefined)
|
||||
client = { name: "vps-01", kind: "wireguard", serverId: 1, interfaceName: "il-vps", managedWireguard: true }
|
||||
const exit = remote ? req.postDataJSON().transit.name : "ix-wan4"
|
||||
segment = { ...segment, revision: 2, configuration: ixSegmentConfigurationSchema.parse({
|
||||
...configuration, sites: [{ ...configuration.sites[0], interfaces: [
|
||||
{ name: "il-vps", kind: "wireguard", linux: { name: "vps-01", enabled: true, destinations: [], exit } },
|
||||
{ name: "il-vps", kind: "wireguard", linux: { name: "vps-01", enabled: true, destinations: [], exit, clientId: both ? clientId : undefined,
|
||||
peerEndpoint: "123.123.123.123" } },
|
||||
...(both ? [{ name: "il-gre", kind: "gre-ipsec", linux: { name: "vps-01", enabled: true, destinations: [], exit, clientId } }] : []),
|
||||
...(remote ? [{ name: "it-to-exit", kind: "wireguard", peerServerId: 3 }] : []),
|
||||
], groups: [{ id: exit, gateway: "198.19.253.5", onFailure: "block",
|
||||
primary: { interface: remote ? "it-to-exit" : "ether1", nextHop: "192.0.2.1", probe: "192.0.2.1", viaMain: !remote } }] }],
|
||||
@@ -257,16 +363,26 @@ for (const mode of ["WAN IX", "новый ExitNode", "ExitNode с двумя WAN
|
||||
}
|
||||
if (path === `/api/ix/segments/${id}/linux/credential`) {
|
||||
expect(req.method()).toBe("POST")
|
||||
if (req.postDataJSON().interfaceName === "il-gre") {
|
||||
expect(both || extended).toBe(true)
|
||||
return json({ kind: "gre-ipsec", revision: 3, filename: "vps-gre.conf", template: "secret = TEST_PSK", setup: "ip tunnel add vps-gre mode gre" })
|
||||
}
|
||||
expect(req.postDataJSON()).toEqual({ serverId: 1, interfaceName: "il-vps" })
|
||||
return json({ kind: "wireguard", revision: 3, filename: "vps.conf", template: configFile })
|
||||
}
|
||||
if (path === `/api/ix/segments/${id}/linux`) {
|
||||
return json({ revision: segment.appliedRevision, items: segment.appliedRevision === 3 && client ? [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",
|
||||
connection: { observedAt, state: "connected", rx: "1536", tx: "2048" },
|
||||
policy: segment.configuration.sites[0].interfaces[1].linux }] : []),
|
||||
] : [] })
|
||||
}
|
||||
if (path.endsWith("/plan")) return json({ revision: 2, digest, changes: [{ serverId: 1, action: "create", path: "/interface/wireguard", fields: {} }] })
|
||||
if (path.endsWith("/plan")) return json({ revision: segment.revision, digest, changes: [
|
||||
{ serverId: 1, action: "create", path: extended ? "/interface/gre" : "/interface/wireguard", fields: {} },
|
||||
] })
|
||||
if (path.endsWith("/apply")) {
|
||||
expect(req.postDataJSON()).toEqual({ revision: 2, digest })
|
||||
segment = { ...segment, revision: 3, appliedRevision: 3 }
|
||||
expect(req.postDataJSON()).toEqual({ revision: extended ? 4 : 2, digest })
|
||||
segment = { ...segment, revision: segment.revision + 1, appliedRevision: segment.revision + 1 }
|
||||
return json({ segment })
|
||||
}
|
||||
expect(path.startsWith("/api/mcp/")).toBe(false)
|
||||
@@ -279,6 +395,13 @@ for (const mode of ["WAN IX", "новый ExitNode", "ExitNode с двумя WAN
|
||||
await page.getByLabel("Имя клиента").fill("vps-01")
|
||||
await page.getByLabel("Внешний адрес Linux").fill("123.123.123.123")
|
||||
await expect(page.getByLabel("Публичный ключ Linux")).toBeHidden()
|
||||
const protocols = page.getByRole("group", { name: "Протоколы подключения" })
|
||||
await expect(protocols.getByRole("button", { name: "WireGuard" })).toHaveAttribute("aria-pressed", "true")
|
||||
if (both) {
|
||||
await protocols.getByRole("button", { name: "GRE/IPsec" }).click()
|
||||
await expect(protocols.getByRole("button", { name: "GRE/IPsec" })).toHaveAttribute("aria-pressed", "true")
|
||||
await expect(protocols.getByRole("button", { name: "WireGuard" })).toHaveAttribute("aria-pressed", "true")
|
||||
}
|
||||
await page.getByLabel("Выход трафика").click()
|
||||
await page.getByRole("option", { name: remote ? "Через exit-arn · ExitNode" : "Интернет с этого IX" }).click()
|
||||
await expect(page.getByLabel("Внешний адрес IX")).toHaveValue("192.0.2.11")
|
||||
@@ -291,11 +414,25 @@ for (const mode of ["WAN IX", "новый ExitNode", "ExitNode с двумя WAN
|
||||
await page.getByRole("button", { name: "Сохранить", exact: true }).click()
|
||||
await page.getByRole("dialog", { name: "Подтвердите сохранение" }).getByRole("button", { name: "Подтвердить" }).click()
|
||||
const download = page.waitForEvent("download")
|
||||
await page.getByRole("button", { name: "Получить конфиг vps-01" }).click()
|
||||
await page.getByRole("button", { name: both ? "Получить конфиг vps-01 · WireGuard" : "Получить конфиг vps-01", exact: true }).click()
|
||||
const file = await download
|
||||
expect(file.suggestedFilename()).toBe("vps.conf")
|
||||
expect(await readFile((await file.path())!, "utf8")).toBe(configFile)
|
||||
await expect(page.getByText("TEST_PRIVATE_KEY")).toHaveCount(0)
|
||||
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 expect(page.getByText(/sudo sh .\/vps-gre-setup\.sh/)).toBeVisible()
|
||||
await expect(page.getByText("TEST_PSK")).toHaveCount(0)
|
||||
const greDownload = page.waitForEvent("download")
|
||||
await page.getByRole("button", { name: "Скачать скрипт GRE" }).click()
|
||||
const greFile = await greDownload
|
||||
expect(greFile.suggestedFilename()).toBe("vps-gre-setup.sh")
|
||||
expect(await readFile((await greFile.path())!, "utf8")).toContain("ip tunnel add")
|
||||
return
|
||||
}
|
||||
const editExit = page.getByRole("button", { name: "Доступ и выход клиента vps-01" })
|
||||
await expect(editExit).toContainText(remote ? "Через exit-arn" : "Интернет с этого IX")
|
||||
if (remote) {
|
||||
@@ -303,5 +440,26 @@ for (const mode of ["WAN IX", "новый ExitNode", "ExitNode с двумя WAN
|
||||
await page.getByLabel("Выход трафика").click()
|
||||
await expect(page.getByRole("option", { name: /Через exit-arn/ })).toHaveCount(1)
|
||||
await expect(page.getByRole("option", { name: /Через exit-arn/ })).toHaveAttribute("aria-selected", "true")
|
||||
} else {
|
||||
await editExit.click()
|
||||
await page.getByLabel("Имя клиента").fill("Несохранённое имя")
|
||||
const gre = protocols.getByRole("button", { name: "GRE/IPsec" })
|
||||
await expect(gre).toBeEnabled()
|
||||
await gre.click()
|
||||
await expect(page.getByRole("heading", { name: "Добавить другой протокол" })).toBeVisible()
|
||||
await expect(page.getByLabel("Имя клиента")).toHaveValue("vps-01")
|
||||
await expect(page.getByLabel("Внешний адрес Linux")).toHaveValue("123.123.123.123")
|
||||
await expect(gre).toHaveAttribute("aria-pressed", "true")
|
||||
await expect(protocols.getByRole("button", { name: "WireGuard" })).toHaveAttribute("aria-pressed", "true")
|
||||
await gre.click()
|
||||
await expect(page.getByLabel("Имя клиента")).toHaveValue("Несохранённое имя")
|
||||
await gre.click()
|
||||
await page.getByRole("button", { name: "Добавить туннель", exact: true }).click()
|
||||
const dialog = page.getByRole("dialog", { name: "Подтвердите сохранение" })
|
||||
await expect(dialog.getByText("/interface/gre", { exact: true })).toBeVisible()
|
||||
await dialog.getByRole("button", { name: "Подтвердить" }).click()
|
||||
await expect(page.getByRole("button", { name: "Получить конфиг vps-01 · GRE/IPsec", exact: true })).toBeVisible()
|
||||
await expect(page.getByRole("button", { name: "Получить конфиг vps-01 · WireGuard", exact: true })).toBeVisible()
|
||||
expect(segment.configuration.sites[0].interfaces[0].linux?.exit).toBe("ix-wan4")
|
||||
}
|
||||
})
|
||||
@@ -42,7 +42,7 @@ test("Карта: неизвестный статус не становится
|
||||
await expect(page.getByText("1 неизвестно",{exact:true})).toBeVisible()
|
||||
await expect(page.getByText("0 оффлайн",{exact:true})).toBeVisible()
|
||||
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true}).click()
|
||||
await expect(page.locator("span").filter({hasText:/^Неизвестно$/}).first()).toBeVisible()
|
||||
await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible()
|
||||
await page.getByRole("button",{name:"Неизвестно",exact:true}).click()
|
||||
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true})).toBeVisible()
|
||||
})
|
||||
|
||||
@@ -12,7 +12,7 @@ test("Карта: открытые детали обновляются вмес
|
||||
await expect(page.getByText("20%",{exact:true})).toBeVisible()
|
||||
const sessions=page.getByText("Сессий",{exact:true}).locator("..");await expect(sessions).toHaveText("Сессий—")
|
||||
changed=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
||||
await expect(page.getByText("0%",{exact:true})).toBeVisible();await expect(page.locator("span").filter({hasText:/^Неизвестно$/}).first()).toBeVisible()
|
||||
await expect(page.getByText("0%",{exact:true})).toBeVisible();await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible()
|
||||
await expect(page.getByText("Jump",{exact:true})).toHaveCount(0);await expect(page.getByText("Новый Jump",{exact:true}).last()).toBeVisible()
|
||||
})
|
||||
test("Карта: модель WAN не утверждает активный маршрут и RTT линии",async({page})=>{
|
||||
|
||||
@@ -4,7 +4,34 @@ const flowPath="/api/traffic/flow/map-hops"
|
||||
test.beforeEach(async({page})=>{await page.route("**/health",r=>r.fulfill({json:{ok:true}}))})
|
||||
const server={id:1,name:"Router",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online"}
|
||||
|
||||
for (const reverse of [false, true]) test(`Карта: GRE без NetFlow своего интерфейса показывает текущие RX/TX RouterOS, reverse=${reverse}`, async ({ page }) => {
|
||||
test("Карта не приписывает весь YouTube единственному выходу ARN", async ({page}) => {
|
||||
const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1}
|
||||
const edge = {fromId: "1", toId: service.id, bytes: 300000, bps: 8000, bpsFwd: 2000, bpsRev: 6000}
|
||||
let known = false
|
||||
await page.route("**/api/**", route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
const responses: Record<string, unknown> = {
|
||||
"/api/auth/config": {required: false}, "/api/servers": [{...server, type: "exit-node", name: "ARN"}],
|
||||
"/api/filters/gre-tunnels": {tunnels: [], failures: []}, "/api/uptime/speed-probes": {probes: []},
|
||||
[flowPath]: {...empty, totalBytes: service.bytes, namedBytes: service.bytes, services: [service], serviceEdges: known ? [edge] : []},
|
||||
}
|
||||
return route.fulfill({json: responses[path] ?? {}})
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
await page.getByRole("button", {name: "Сервис YouTube", exact: true}).press("Enter")
|
||||
const unknown = page.getByText("Выход не определён", {exact: true}).locator("..")
|
||||
const badges = page.getByRole("button", {name: "Поток NetFlow между узлами"})
|
||||
await expect(unknown).toContainText("24 Кбит/с")
|
||||
await expect(badges).toHaveCount(0)
|
||||
known = true
|
||||
await page.getByRole("button", {name: "Обновить", exact: true}).click()
|
||||
await expect(unknown).toContainText("16 Кбит/с")
|
||||
await expect(badges).toHaveCount(1)
|
||||
await expect(badges).toContainText("8 Кбит/с")
|
||||
await expect(badges).toContainText("↓6 Кбит/с ↑2 Кбит/с")
|
||||
})
|
||||
|
||||
for (const reverse of [false, true]) test(`Карта: малый NetFlow и текущие RX/TX GRE показаны отдельно, reverse=${reverse}`, async ({ page }) => {
|
||||
const exit = { ...server, name: "ARN", type: "exit-node" }
|
||||
const jump = { ...server, id: 2, name: "MSK-02", host: "192.0.2.2", type: "jump-host" }
|
||||
const owner = reverse ? exit : jump
|
||||
@@ -13,6 +40,9 @@ for (const reverse of [false, true]) test(`Карта: GRE без NetFlow сво
|
||||
localAddress: owner.host, remoteAddress: peer.host, localInnerIp: "10.0.0.1", remoteInnerIp: "10.0.0.2",
|
||||
poolId: "", ipsec: { secret: "" }, mtu: 1400, keepaliveInterval: 10, keepaliveRetries: 3, dscp: "inherit",
|
||||
clampTcpMss: true, allowFastPath: false, comment: "" }
|
||||
const opposite = { ...tunnel, id: String(peer.id) + ":*e", name: "other-end", serverId: String(peer.id),
|
||||
localAddress: peer.host, remoteAddress: owner.host, localInnerIp: tunnel.remoteInnerIp, remoteInnerIp: tunnel.localInnerIp }
|
||||
const observer = reverse ? opposite : tunnel
|
||||
const estimate = { fromId: "1", fromLabel: "ARN", toId: "2", toLabel: "MSK-02", kind: "gre", iface: "other-gre",
|
||||
bytes: 300, bps: 8, bpsFwd: 8, bpsRev: 0 }
|
||||
const exact = { fromId: String(owner.id), fromLabel: owner.name, toId: "", toLabel: "", kind: "iface", iface: tunnel.name,
|
||||
@@ -31,24 +61,53 @@ for (const reverse of [false, true]) test(`Карта: GRE без NetFlow сво
|
||||
const json = {
|
||||
"/api/auth/config": { required: false },
|
||||
"/api/servers": [exit, jump],
|
||||
"/api/filters/gre-tunnels": { tunnels: [tunnel], failures: [] },
|
||||
"/api/filters/gre-tunnels": { tunnels: reverse ? [tunnel, opposite] : [tunnel], failures: [] },
|
||||
"/api/uptime/speed-probes": { probes: [] },
|
||||
[flowPath]: { ...empty, live: true, hops: [estimate, { ...exact, fromId: String(peer.id), fromLabel: peer.name }, ...(exactNetflow ? [exact] : [])] },
|
||||
[flowPath]: { ...empty, live: true, hops: [estimate, { ...exact, fromId: String(peer.id), fromLabel: peer.name }],
|
||||
interfaceTraffic: [{ serverId: observer.serverId, iface: observer.name, rxBytes: exactNetflow && !reverse ? 525 : 0,
|
||||
txBytes: exactNetflow && reverse ? 525 : 0, rxPackets: exactNetflow && !reverse ? 3 : 0, txPackets: exactNetflow && reverse ? 3 : 0,
|
||||
inWindow: exactNetflow, lastBucketAt: "2026-11-23T07:00:00Z" }] },
|
||||
}[url.pathname] ?? {}
|
||||
return route.fulfill({ json })
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
const live = page.getByRole("button", { name: "Текущий трафик GRE " + tunnel.name })
|
||||
await expect(live).toContainText("281 Кбит/с")
|
||||
await expect(live).toContainText("Live GRE")
|
||||
await live.click()
|
||||
await expect(page.getByText("Текущий RX/TX GRE", { exact: true })).toBeVisible()
|
||||
expect(liveReads).toBeGreaterThan(0)
|
||||
|
||||
const badge = page.getByRole("button", { name: "Поток NetFlow между узлами" })
|
||||
await expect(badge).toContainText("Нет записей")
|
||||
expect(liveReads).toBe(0)
|
||||
await badge.click()
|
||||
const live = page.getByText("Live GRE · RX/TX сейчас", {exact: true}).locator("..")
|
||||
await expect(live).toContainText("↓162 Кбит/с ↑119 Кбит/с")
|
||||
await expect(page.getByText(/Последняя минута с данными/)).toBeVisible()
|
||||
exactNetflow = true
|
||||
await page.getByRole("button", { name: "Обновить", exact: true }).click()
|
||||
await expect(live).toHaveCount(0)
|
||||
await expect(page.getByRole("button", { name: "Поток NetFlow между узлами" })).toContainText("100 Кбит/с")
|
||||
await expect(badge).toContainText("14 бит/с", {timeout: 12000})
|
||||
await expect(live).toContainText("↓162 Кбит/с ↑119 Кбит/с")
|
||||
await expect(badge).toContainText("↓14 бит/с ↑0 Кбит/с")
|
||||
await expect(page.getByText("За интервал · 525 Б · 3 пак.")).toBeVisible()
|
||||
await expect(badge).not.toContainText("Live GRE")
|
||||
|
||||
})
|
||||
|
||||
test("Карта: два GRE одного роутера к одному узлу сохраняют отдельные счётчики", async ({ page }) => {
|
||||
const peer = { ...server, id: 2, name: "Exit", host: "192.0.2.2", type: "exit-node" }
|
||||
const tunnels = ["gre-low", "gre-other"].map(name => ({
|
||||
name, id: name, serverId: "1", enabled: true, status: "up", localAddress: server.host, remoteAddress: peer.host,
|
||||
localInnerIp: "", remoteInnerIp: "", poolId: "", ipsec: null, mtu: 1400, keepaliveInterval: 10, keepaliveRetries: 3,
|
||||
dscp: "inherit", clampTcpMss: true, allowFastPath: false, comment: "",
|
||||
}))
|
||||
const interfaceTraffic = tunnels.map(({name}, i) => ({ serverId: "1", iface: name, rxBytes: 600 * (i + 1), txBytes: 0,
|
||||
rxPackets: i + 1, txPackets: 0, inWindow: true, lastBucketAt: "2026-11-23T07:00:00Z" }))
|
||||
await page.route("**/api/**", route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
return route.fulfill({ json: path === "/api/servers" ? [{ ...server, type: "jump-host" }, peer]
|
||||
: path === "/api/filters/gre-tunnels" ? { tunnels, failures: [] }
|
||||
: path === flowPath ? { ...empty, live: true, interfaceTraffic }
|
||||
: path === "/api/uptime/speed-probes" ? { probes: [] } : path === "/api/auth/config" ? { required: false } : {} })
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
const badges = page.getByRole("button", { name: "Поток NetFlow между узлами" })
|
||||
await expect(badges).toHaveCount(2)
|
||||
await expect(badges.filter({hasText: "↓16 бит/с"})).toHaveCount(1)
|
||||
await expect(badges.filter({hasText: "↓32 бит/с"})).toHaveCount(1)
|
||||
})
|
||||
|
||||
for(const malformed of [false,true])test("Карта: NetFlow отказ и повтор "+malformed,async({page})=>{
|
||||
|
||||
Reference in new issue
Block a user