feat(mcp): добавить диагностику инцидентов и проверку отказоустойчивости сети
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m31s
Docker images / frontend-image (push) Successful in 2m18s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 31s
Docker images / backend-image (push) Successful in 2m11s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m31s
Docker images / frontend-image (push) Successful in 2m18s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 31s
Docker images / backend-image (push) Successful in 2m11s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
This commit is contained in:
1 parent
c44bcd8f59
commit
b896e469a7
22 files changed
+1695
-28
No files matched your search
@@ -1,7 +1,7 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { setTimeout as delay } from "node:timers/promises"
|
||||
import { MikrotikClient } from "./mikrotik.js"
|
||||
import { dispatchTerminalCommand, executeTerminalDiagnostic, parseTerminalCommand, terminalDiagnosticSchema } from "./terminal-diagnostics.js"
|
||||
import { dispatchTerminalCommand, executeTerminalDiagnostic, parseTerminalCommand, readTerminalInterfaceCounters, terminalDiagnosticSchema, terminalInterfaceCountersSchema } from "./terminal-diagnostics.js"
|
||||
import { withTerminalDiagnosticClient } from "./terminal-diagnostic-client.js"
|
||||
import { createTerminalDiagnosticFixture, terminalDiagnosticCases } from "../test/terminal-diagnostic-fixture.js"
|
||||
|
||||
@@ -22,6 +22,24 @@ try {
|
||||
for (const bad of [{ diagnostic: "execute", command: "/system reboot" }, { diagnostic: "interfaces", target: "host" }, { diagnostic: "logs", count: 2 }, { diagnostic: "ping" }, { diagnostic: "ping", target: "192.0.2.1", count: 21 }, { diagnostic: "logs", limit: 201 }]) assert.equal(terminalDiagnosticSchema.safeParse(bad).success, false)
|
||||
for (const bad of ["/system reboot", ":execute /system resource print", "ip address print;system reboot", "log print limit=0", "ping host count=1junk"]) assert.throws(() => parseTerminalCommand(bad))
|
||||
const oldInterfaces = fixture.payloads["/interface"]
|
||||
fixture.payloads["/interface"] = [
|
||||
{ name: "ether-a", running: "true", "rx-byte": "18446744073709551615", "rx-error": "0", "tx-error": "-1", "rx-drop": "2", "link-downs": "3", "last-link-down-time": "2026-01-01 00:00:00", comment: endpoint.password },
|
||||
{ name: "ether-b", "tx-queue-drop": "4" },
|
||||
]
|
||||
const counters = (args: object) => withTerminalDiagnosticClient(endpoint, { authorize }, native => readTerminalInterfaceCounters(native,
|
||||
terminalInterfaceCountersSchema.parse({ diagnostic: "interface_counters", ...args }), value => value))
|
||||
const first = await counters({ limit: 1 })
|
||||
assert.equal(first.total, 2)
|
||||
assert.equal(first.truncated, true)
|
||||
assert.equal(first.rows.length, 1)
|
||||
assert.equal(first.rows[0].lastLinkDownAt, "2026-01-01 00:00:00")
|
||||
assert.equal(first.rows[0].running, true)
|
||||
assert.deepEqual(first.rows[0].counters, { rxBytes: "18446744073709551615", txBytes: null, rxPackets: null, txPackets: null, rxDrops: "2", txDrops: null, txQueueDrops: null, rxErrors: "0", txErrors: null, linkDowns: "3" })
|
||||
assert.equal(first.resetHistoryAvailable, false)
|
||||
assert.ok(first.routerUptime)
|
||||
assert.ok(!JSON.stringify(first).includes(endpoint.password))
|
||||
assert.equal((await counters({ interface: "ether-b" })).rows[0].counters.txQueueDrops, "4")
|
||||
assert.equal(terminalInterfaceCountersSchema.safeParse({ diagnostic: "interface_counters", limit: 51 }).success, false)
|
||||
fixture.payloads["/interface"] = Array.from({ length: 1001 }, () => ({ name: "x" }))
|
||||
await assert.rejects(withTerminalDiagnosticClient(endpoint, { authorize }, native => native.getInterfaces()))
|
||||
fixture.payloads["/interface"] = [{ name: "x".repeat(1048577) }]
|
||||
|
||||
@@ -236,6 +236,46 @@ export const terminalDiagnosticSchema = z.object({
|
||||
})
|
||||
export type TerminalDiagnostic = z.infer<typeof terminalDiagnosticSchema>
|
||||
export type TerminalDiagnosticClient = Pick<MikrotikClient, "getIpAddresses" | "getInterfaces" | "getResource" | "getIdentity" | "getIpRoutes" | "getFirewallFilters" | "getBgpSessions" | "getOspfNeighbors" | "getOspfAreas" | "getOspfInstances" | "getOspfInterfaceTemplates" | "getBfdSessions" | "getLogs" | "ping">
|
||||
export const terminalInterfaceCountersSchema = z.object({
|
||||
diagnostic: z.literal("interface_counters"),
|
||||
interface: z.string().min(1).max(128).regex(/^[^\p{Cc}]+$/u).optional(),
|
||||
limit: z.number().int().min(1).max(50).default(20),
|
||||
}).strict()
|
||||
|
||||
export async function readTerminalInterfaceCounters(
|
||||
client: Pick<TerminalDiagnosticClient, "getInterfaces" | "getResource">,
|
||||
input: z.infer<typeof terminalInterfaceCountersSchema>,
|
||||
protect: (value: string) => string,
|
||||
) {
|
||||
const [interfaces, resource] = await Promise.all([client.getInterfaces(), client.getResource()])
|
||||
const properties = {
|
||||
rxBytes: "rx-byte", txBytes: "tx-byte", rxPackets: "rx-packet", txPackets: "tx-packet",
|
||||
rxDrops: "rx-drop", txDrops: "tx-drop", txQueueDrops: "tx-queue-drop",
|
||||
rxErrors: "rx-error", txErrors: "tx-error", linkDowns: "link-downs",
|
||||
} as const
|
||||
const text = (value: unknown, max: number) =>
|
||||
typeof value === "string" && value.length <= max && /^[^\p{Cc}]+$/u.test(value) ? protect(value) : null
|
||||
const counter = (value: unknown) => {
|
||||
if (typeof value !== "string" || !/^\d{1,20}$/.test(value) || BigInt(value) > 18446744073709551615n) return null
|
||||
return protect(value) === value ? value : null
|
||||
}
|
||||
const flag = (value: unknown) => value === "true" ? true : value === "false" ? false : null
|
||||
const selected = interfaces.filter(row => input.interface === undefined || row.name === input.interface)
|
||||
const rows = selected.slice(0, input.limit).map(row => {
|
||||
const native = row as typeof row & Partial<Record<(typeof properties)[keyof typeof properties] | "last-link-down-time" | "last-link-up-time", unknown>>
|
||||
const counters = Object.fromEntries(Object.entries(properties).map(([key, property]) => [key, counter(native[property])])) as Record<keyof typeof properties, string | null>
|
||||
return {
|
||||
name: text(row.name, 128), type: text(row.type, 64), running: flag(row.running), disabled: flag(row.disabled),
|
||||
counters,
|
||||
lastLinkDownAt: text(native["last-link-down-time"], 40), lastLinkUpAt: text(native["last-link-up-time"], 40),
|
||||
}
|
||||
})
|
||||
return {
|
||||
rows, total: selected.length, limit: input.limit, truncated: rows.length < selected.length,
|
||||
observedAt: new Date().toISOString(), routerUptime: text(resource.uptime, 64),
|
||||
countersAreCumulative: true, lastCounterResetAt: null, resetHistoryAvailable: false,
|
||||
}
|
||||
}
|
||||
export class ExecValidationError extends Error { readonly statusCode = 400 }
|
||||
|
||||
/** REST grammar is intentionally an allowlist, never a RouterOS script. */
|
||||
|
||||
@@ -27,6 +27,7 @@ import { resolveIfaceName } from "./traffic-flow-ifaces.js"
|
||||
import { factIfaceAliases } from "./traffic-flow-ifindex.js"
|
||||
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
|
||||
import { applicationName, flowRowMatchesFilter } from "./traffic-flow-apps.js"
|
||||
import { canonicalIp, ipv6ToInt } from "./traffic-flow-ip.js"
|
||||
import { collapseGreEspRows, dedupFlowRowsMaxBytes, flowTupleKey } from "./traffic-flow-dedup.js"
|
||||
import { enqueueRipeMisses } from "./traffic-flow-ripe.js"
|
||||
import { classifyFlowPlane, flowBps, shouldKeepPlane } from "./traffic-flow-planes.js"
|
||||
@@ -50,6 +51,7 @@ export interface FlowAnalyticsQuery {
|
||||
serverId?: number
|
||||
userId?: string
|
||||
iface?: string
|
||||
tuple?: { srcIp?: string; dstIp?: string; srcPort?: number; dstPort?: number; protocol?: number }
|
||||
/** Default true: один 5-tuple за минуту = max байт по ifaces. */
|
||||
dedup?: boolean
|
||||
/** Default true: скрыть GRE/WG между клиентами JH. */
|
||||
@@ -171,6 +173,7 @@ function analyticsQueryKey(q: FlowAnalyticsQuery): string {
|
||||
serverId: q.serverId ?? null,
|
||||
userId: q.userId ?? null,
|
||||
iface: q.iface ?? null,
|
||||
tuple: q.tuple ?? null,
|
||||
dedup: q.dedup !== false,
|
||||
excludeMesh: q.excludeMesh !== false,
|
||||
excludeOverlay: q.excludeOverlay !== false,
|
||||
@@ -242,8 +245,21 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
const ingress = matchesIngress(row), egress = matchesEgress(row)
|
||||
return ingress === egress ? null : ingress ? "rx" : "tx"
|
||||
}
|
||||
const selected = ifaceFilter || allow ? raw.filter(row => (matchesIngress(row) || matchesEgress(row)) &&
|
||||
const visible = ifaceFilter || allow ? raw.filter(row => (matchesIngress(row) || matchesEgress(row)) &&
|
||||
(!q.userId || resolveFlowClient(topo, row.serverId, resolveIfaceName(row.serverId, row.inIface).name, resolveIfaceName(row.serverId, row.outIface).name)?.userId === q.userId)) : raw
|
||||
const tuple = q.tuple
|
||||
const ipKey = (value: string) => {
|
||||
const ip = canonicalIp(value)
|
||||
return ip.includes(":") ? ipv6ToInt(ip) ?? ip : ip
|
||||
}
|
||||
const src = tuple?.srcIp === undefined ? undefined : ipKey(tuple.srcIp)
|
||||
const dst = tuple?.dstIp === undefined ? undefined : ipKey(tuple.dstIp)
|
||||
const selected = tuple ? visible.filter(row =>
|
||||
(src === undefined || src === ipKey(row.src)) &&
|
||||
(dst === undefined || dst === ipKey(row.dst)) &&
|
||||
(tuple.srcPort === undefined || tuple.srcPort === row.srcPort) &&
|
||||
(tuple.dstPort === undefined || tuple.dstPort === row.dstPort) &&
|
||||
(tuple.protocol === undefined || tuple.protocol === row.proto)) : visible
|
||||
const { rows, espDirections } = collapseGreEspRows(selected, ifaceFilter ? interfaceDirection : serverDirection)
|
||||
const previousMinute = new Date(Math.floor(now / 60_000) * 60_000 - 60_000).toISOString()
|
||||
const ifacesForWire = new Set<string>()
|
||||
@@ -479,7 +495,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
const topCategory = topLabel(categories)
|
||||
|
||||
const ringServer = q.serverId ?? (matched[0]?.serverId ?? 0)
|
||||
const ring = ringServer && !ifaceFilter && !allow && excludeOverlay ? getRingMbps(ringServer) : null
|
||||
const ring = ringServer && !ifaceFilter && !allow && !tuple && excludeOverlay ? getRingMbps(ringServer) : null
|
||||
|
||||
// The live ring covers about one minute; historical charts must use the requested window.
|
||||
const fromBuckets = seriesFromRows(working, q.minutes, row => {
|
||||
@@ -540,7 +556,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
await authorize()
|
||||
const wire = ringServer ? await latestWireBps(ringServer, greNames, Boolean(scope)) : { bps: 0, bytes: 0 }
|
||||
await authorize()
|
||||
const admittedTotals = q.serverId !== undefined && !q.userId
|
||||
const admittedTotals = q.serverId !== undefined && !q.userId && !tuple
|
||||
? await readAdmittedFlowTotals(q.serverId, ifaceFilter, q.minutes, now)
|
||||
: undefined
|
||||
|
||||
|
||||
@@ -165,6 +165,21 @@ try{
|
||||
assert.equal(series.rxSeries.reduce((sum,value)=>sum+value,0),50*8/60/1e6)
|
||||
assert.equal(series.txSeries.reduce((sum,value)=>sum+value,0),100*8/60/1e6)
|
||||
}
|
||||
const tuple = await client.callTool({name:'mm_netflow_analytics_report_get',arguments:{
|
||||
serverId:1, minutes:5, srcIp:'::ffff:198.18.1.1', dstIp:'8.8.8.8', srcPort:1, dstPort:443, protocol:6, limit:1,
|
||||
}})
|
||||
assert.ok(!tuple.isError,JSON.stringify(tuple))
|
||||
const filtered = (tuple.structuredContent as {result:{
|
||||
analytics:{bytes:number;admittedTotals?:unknown}; sourceWindow:unknown;
|
||||
pages:{conversationsList:{total:number;nextOffset:number|null}};
|
||||
historicalDetail:{rowLimitAppliedBeforeFilters:boolean;exactTupleTotalsVerified:boolean};
|
||||
}}).result
|
||||
assert.equal(filtered.analytics.bytes,100)
|
||||
assert.equal(filtered.analytics.admittedTotals,undefined)
|
||||
assert.deepEqual(filtered.pages.conversationsList,{total:1,nextOffset:null})
|
||||
assert.deepEqual(filtered.sourceWindow,{requestedMinutes:5,effectiveMinutes:5,incomplete:false})
|
||||
assert.equal(filtered.historicalDetail.rowLimitAppliedBeforeFilters,true)
|
||||
assert.equal(filtered.historicalDetail.exactTupleTotalsVerified,false)
|
||||
} finally {
|
||||
applyHeartbeatForTests(heartbeat)
|
||||
invalidateFlowAnalyticsCache()
|
||||
|
||||
Reference in new issue
Block a user