294 lines
10 KiB
TypeScript
294 lines
10 KiB
TypeScript
import { and, eq } from "drizzle-orm"
|
|
import { db } from "../db/index.js"
|
|
import { servers } from "../db/schema.js"
|
|
import { MikrotikClient } from "./mikrotik.js"
|
|
import { readGreComment } from "./gre-comment.js"
|
|
import { observedDurationMs, observedInteger } from "./ospf-observed-values.js"
|
|
import {
|
|
canonicalGreSnapshot,
|
|
greAddressPath,
|
|
type GreLiveAddr,
|
|
type GreLiveIface,
|
|
type GreSnapshot,
|
|
} from "./entity-snapshots.js"
|
|
import { captureAndAppendRevision } from "./config-revisions.js"
|
|
import { readGreObservedState, readGreNativeRows } from "./gre-observed-state.js"
|
|
import { observeGreCatalog } from "./gre-observed-read.js"
|
|
|
|
type ServerRow = typeof servers.$inferSelect
|
|
|
|
export interface RosGre {
|
|
".id"?: string
|
|
name?: string
|
|
"local-address"?: string
|
|
"remote-address"?: string
|
|
"allow-fast-path"?: string
|
|
"clamp-tcp-mss"?: string
|
|
mtu?: string
|
|
keepalive?: string
|
|
dscp?: string
|
|
running?: string
|
|
disabled?: string
|
|
comment?: string
|
|
"ipsec-secret"?: string
|
|
}
|
|
|
|
interface RosIpAddress {
|
|
".id"?: string
|
|
address?: string
|
|
interface?: string
|
|
disabled?: string
|
|
network?: string
|
|
dynamic?: string
|
|
advertise?: string
|
|
comment?: string
|
|
"no-dad"?: string
|
|
"from-pool"?: string
|
|
"eui-64"?: string
|
|
}
|
|
|
|
export interface LiveGreTunnel {
|
|
id: string
|
|
rosId: string
|
|
name: string
|
|
serverId: string
|
|
localAddress: string
|
|
remoteAddress: string
|
|
localInnerIp: string
|
|
remoteInnerIp: string
|
|
poolId: string
|
|
ipsec: { secret: string } | null
|
|
mtu: number
|
|
keepaliveInterval: number
|
|
keepaliveRetries: number
|
|
dscp: "inherit" | number
|
|
clampTcpMss: boolean
|
|
allowFastPath: boolean
|
|
comment: string
|
|
enabled: boolean
|
|
status: "up" | "down" | "degraded"
|
|
}
|
|
|
|
export function parseKeepalive(value: string | undefined): { interval: number; retries: number } {
|
|
if (!value || value.toLowerCase() === "none") return { interval: 0, retries: 0 }
|
|
const [intervalRaw, retriesRaw] = value.split(",")
|
|
const intervalText = intervalRaw?.trim()
|
|
const interval = intervalText && /^\d+$/.test(intervalText)
|
|
? observedInteger(intervalText)
|
|
: (observedDurationMs(intervalText) ?? 0) / 1000
|
|
const retries = observedInteger(retriesRaw)
|
|
return {
|
|
interval: interval ?? 0,
|
|
retries: retries ?? 0,
|
|
}
|
|
}
|
|
|
|
export function formatKeepalive(interval: number, retries: number): string {
|
|
if (!interval || interval <= 0) return "0"
|
|
return `${interval}s,${retries > 0 ? retries : 10}`
|
|
}
|
|
|
|
function parseDscp(value: string | undefined): "inherit" | number {
|
|
if (!value || value === "inherit") return "inherit"
|
|
const n = Number.parseInt(value, 10)
|
|
return Number.isFinite(n) ? n : "inherit"
|
|
}
|
|
|
|
function parseInnerFromComment(comment: string | undefined): { localInnerIp: string; remoteInnerIp: string } {
|
|
if (!comment) return { localInnerIp: "", remoteInnerIp: "" }
|
|
const local = comment.match(/address\s*=\s*([0-9a-fA-F:.]+\/\d+)/)?.[1] ?? ""
|
|
const remote = readGreComment(comment).remoteInnerIp
|
|
return { localInnerIp: local, remoteInnerIp: remote }
|
|
}
|
|
|
|
function rosDisabled(v: string | undefined): boolean {
|
|
return v === "true" || v === "yes"
|
|
}
|
|
|
|
export function mapGreLive(
|
|
server: ServerRow,
|
|
greRaw: RosGre[],
|
|
addrsRaw: RosIpAddress[],
|
|
): {
|
|
tunnels: LiveGreTunnel[]
|
|
snapshot: GreSnapshot
|
|
gre: GreLiveIface[]
|
|
addrs: GreLiveAddr[]
|
|
} {
|
|
const observedGre = readGreNativeRows(greRaw)
|
|
const addrsByIface = new Map<string, GreLiveAddr[]>()
|
|
const greNames = new Set(observedGre.map(g => g.name.trim()))
|
|
for (const a of addrsRaw) {
|
|
if (rosDisabled(a.dynamic)) continue
|
|
const iface = (a.interface ?? "").trim()
|
|
const address = (a.address ?? "").trim()
|
|
const rosId = String(a[".id"] ?? "")
|
|
if (!iface || !address || !rosId || !greNames.has(iface)) continue
|
|
const list = addrsByIface.get(iface) ?? []
|
|
const family = greAddressPath(address)
|
|
list.push({ address, rosId, interfaceName: iface, disabled: rosDisabled(a.disabled), comment: a.comment ?? "",
|
|
...(family === "/ipv6/address" ? { advertise: rosDisabled(a.advertise), noDad: rosDisabled(a["no-dad"]), fromPool: a["from-pool"] ?? "", eui64: rosDisabled(a["eui-64"]) } : {}),
|
|
})
|
|
addrsByIface.set(iface, list)
|
|
}
|
|
|
|
const gre: GreLiveIface[] = []
|
|
const addrs: GreLiveAddr[] = []
|
|
const tunnels: LiveGreTunnel[] = []
|
|
|
|
observedGre.forEach((g) => {
|
|
const rosId = g[".id"]
|
|
const name = g.name.trim()
|
|
const keepalive = parseKeepalive(g.keepalive)
|
|
const fromComment = parseInnerFromComment(g.comment)
|
|
const ifaceAddrs = addrsByIface.get(name) ?? []
|
|
ifaceAddrs.sort((a, b) => Number(Boolean(a.disabled)) - Number(Boolean(b.disabled)) || a.address.localeCompare(b.address))
|
|
const localInnerIp = ifaceAddrs[0]?.address || fromComment.localInnerIp
|
|
const secret = g["ipsec-secret"] ?? ""
|
|
const { disabled, status } = readGreObservedState(g, name)
|
|
const numericMtu = Number.parseInt(g.mtu ?? "1476", 10) || 1476
|
|
|
|
gre.push({
|
|
name,
|
|
rosId,
|
|
localAddress: g["local-address"] ?? "",
|
|
remoteAddress: g["remote-address"] ?? "",
|
|
comment: g.comment ?? "",
|
|
disabled,
|
|
mtu: g.mtu === "auto" ? g.mtu : numericMtu,
|
|
keepalive: g.keepalive ?? "0",
|
|
dscp: g.dscp ?? "inherit",
|
|
clampTcpMss: g["clamp-tcp-mss"] !== "false" && g["clamp-tcp-mss"] !== "no",
|
|
allowFastPath: g["allow-fast-path"] !== "false" && g["allow-fast-path"] !== "no",
|
|
ipsecSecret: secret,
|
|
})
|
|
|
|
for (const a of ifaceAddrs) {
|
|
addrs.push(a)
|
|
}
|
|
|
|
tunnels.push({
|
|
id: rosId || `${server.id}:${name}`,
|
|
rosId,
|
|
name,
|
|
serverId: String(server.id),
|
|
localAddress: g["local-address"] ?? "",
|
|
remoteAddress: g["remote-address"] ?? "",
|
|
localInnerIp,
|
|
remoteInnerIp: fromComment.remoteInnerIp,
|
|
poolId: "live",
|
|
ipsec: secret ? { secret } : null,
|
|
mtu: numericMtu,
|
|
keepaliveInterval: keepalive.interval,
|
|
keepaliveRetries: keepalive.retries,
|
|
dscp: parseDscp(g.dscp),
|
|
clampTcpMss: g["clamp-tcp-mss"] !== "false" && g["clamp-tcp-mss"] !== "no",
|
|
allowFastPath: g["allow-fast-path"] !== "false" && g["allow-fast-path"] !== "no",
|
|
comment: readGreComment(g.comment).comment,
|
|
enabled: !disabled,
|
|
status,
|
|
})
|
|
})
|
|
|
|
return {
|
|
tunnels,
|
|
snapshot: canonicalGreSnapshot({
|
|
tunnels: gre.map((g) => ({
|
|
name: g.name,
|
|
localAddress: g.localAddress,
|
|
remoteAddress: g.remoteAddress,
|
|
localInnerIp: tunnels.find(t => t.name === g.name)?.localInnerIp ?? "",
|
|
innerAddresses: addrs.filter(a => a.interfaceName === g.name).map(a => ({ address: a.address, disabled: Boolean(a.disabled), comment: a.comment,
|
|
...(a.advertise === undefined ? {} : { advertise: a.advertise, noDad: a.noDad, fromPool: a.fromPool, eui64: a.eui64 }),
|
|
})),
|
|
remoteInnerIp: tunnels.find(t => t.name === g.name)?.remoteInnerIp ?? "",
|
|
comment: g.comment,
|
|
disabled: g.disabled,
|
|
mtu: g.mtu,
|
|
keepalive: g.keepalive,
|
|
dscp: g.dscp,
|
|
clampTcpMss: g.clampTcpMss,
|
|
allowFastPath: g.allowFastPath,
|
|
ipsecSecret: g.ipsecSecret,
|
|
})),
|
|
}),
|
|
gre,
|
|
addrs,
|
|
}
|
|
}
|
|
|
|
export async function fetchGreNativeState(server: ServerRow) {
|
|
const client = MikrotikClient.fromServer(server)
|
|
const [greRaw, addrsRaw, ipv6Raw] = await Promise.all([
|
|
client.get<RosGre[]>("/interface/gre"),
|
|
client.get<RosIpAddress[]>("/ip/address"),
|
|
client.get<RosIpAddress[]>("/ipv6/address"),
|
|
])
|
|
if (![greRaw, addrsRaw, ipv6Raw].every(Array.isArray)) throw new Error("RouterOS: неполный каталог GRE/адресов")
|
|
return { client, greRaw, addrsRaw, ipv6Raw }
|
|
}
|
|
|
|
export async function fetchGreState(server: ServerRow) {
|
|
const { client, greRaw, addrsRaw, ipv6Raw } = await fetchGreNativeState(server)
|
|
return {
|
|
client,
|
|
...mapGreLive(server, Array.isArray(greRaw) ? greRaw : [], [...(Array.isArray(addrsRaw) ? addrsRaw : []), ...(Array.isArray(ipv6Raw) ? ipv6Raw : [])]),
|
|
}
|
|
}
|
|
|
|
export async function captureGreSnapshot(server: ServerRow): Promise<GreSnapshot> {
|
|
const state = await fetchGreState(server)
|
|
return state.snapshot
|
|
}
|
|
|
|
export async function listGreTunnels(opts?: { serverId?: string }): Promise<{
|
|
tunnels: LiveGreTunnel[]
|
|
failures: Array<{ serverId: string; serverName?: string; error: string }>
|
|
}> {
|
|
let serverRows: ServerRow[]
|
|
if (opts?.serverId) {
|
|
const id = Number.parseInt(String(opts.serverId), 10)
|
|
if (!Number.isFinite(id)) {
|
|
return { tunnels: [], failures: [{ serverId: String(opts.serverId), error: "Некорректный serverId" }] }
|
|
}
|
|
const row = (await db.select().from(servers).where(and(eq(servers.id, id), eq(servers.enabled, true))).limit(1))[0]
|
|
serverRows = row ? [row] : []
|
|
} else {
|
|
serverRows = await db.select().from(servers).where(eq(servers.enabled, true))
|
|
}
|
|
|
|
const { tunnels, failures } = await pollGreServers(serverRows, true)
|
|
return { tunnels, failures }
|
|
}
|
|
|
|
/** REST retains observed revisions; MCP reads deliberately do not store secret-bearing history. */
|
|
export async function pollGreServers(serverRows: ServerRow[], recordHistory = false) {
|
|
const failures: Array<{ serverId: string; serverName?: string; error: string }> = []
|
|
const chunks = await Promise.all(
|
|
serverRows.filter(server => server.enabled).map(async (server) => {
|
|
try {
|
|
if (!recordHistory) {
|
|
const { greRaw, addrsRaw, ipv6Raw } = await fetchGreNativeState(server)
|
|
return { tunnels: [] as LiveGreTunnel[], observed: observeGreCatalog(server.id, greRaw, addrsRaw, ipv6Raw) }
|
|
}
|
|
const state = await fetchGreState(server)
|
|
if (recordHistory) await captureAndAppendRevision({
|
|
serverId: server.id,
|
|
section: "gre",
|
|
source: "observed",
|
|
capture: async () => state.snapshot,
|
|
})
|
|
return { tunnels: state.tunnels, observed: [] as ReturnType<typeof observeGreCatalog> }
|
|
} catch (e) {
|
|
failures.push({
|
|
serverId: String(server.id),
|
|
serverName: server.name ?? undefined,
|
|
error: recordHistory ? e instanceof Error ? e.message : String(e) : "Не удалось подтвердить каталог GRE/адресов",
|
|
})
|
|
return { tunnels: [] as LiveGreTunnel[], observed: [] as ReturnType<typeof observeGreCatalog> }
|
|
}
|
|
}),
|
|
)
|
|
return { tunnels: chunks.flatMap(chunk => chunk.tunnels), observed: chunks.flatMap(chunk => chunk.observed), failures }
|
|
}
|