Compare commits

...
1 Commits
Author SHA1 Message Date
Denozordec 42efc3191b fix(netflow): устранить двойной учёт потоков туннеля
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 11m32s
Docker images / frontend-image (push) Successful in 2m20s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 2m14s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-22 13:48:18 +07:00
6 changed files with 166 additions and 24 deletions

No files matched your search

@@ -68,14 +68,14 @@ export function registerFlowAnalyticsActions(register: typeof add) {
analytics[key] = value.slice(offset, offset + limit)
pages[key] = { total: value.length, nextOffset: offset + limit < value.length ? offset + limit : null }
}
// Ring rates are server context, including when the retained rows are filtered by user/interface.
// Wire rate uses interface counters. Keep rate estimates separate from retained volume.
const { bpsNow: _bpsNow, bpsWire: _bpsWire, bpsOverlay: _bpsOverlay, bytesWire: _bytesWire, live: _live, ...retained } = analytics
await authorize()
if ((await readFlowSourceLimits()).topN !== limits.topN) throw new McpError("STATE_CONFLICT", "Предел источника NetFlow изменился во время чтения", 409)
await authorize()
const output = { serverId: server.id, minutes: sourceWindow?.effectiveMinutes ?? Number(input.minutes), sourceWindow, interface: input.interface ?? null, userId: input.userId ?? null,
analytics: retained, pages, contextRates: { bpsNowEstimate: _bpsNow, bpsWireEstimate: _bpsWire, bpsOverlayEstimate: _bpsOverlay, bytesWireEstimate: _bytesWire,
listenerBound: _live, userAttributionVerified: false, semantics: "REST estimates: current server/interface ring with retained-window fallback; wire projection uses current interface snapshots" },
listenerBound: _live, userAttributionVerified: false, semantics: "REST estimates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback; wire uses current interface snapshots" },
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false,
source: "retained flow_buckets plus pending; same REST analytics engine with scoped topology",
rowLimit: 20000, topRowsPerBucketLimit: Math.max(20, limits.topN), engineTopListLimit: Math.min(50, Math.max(10, limits.topN)),
+1 -1
View File
@@ -57,7 +57,7 @@ export function registerFlowLiveActions(register: typeof add) {
source: "REST live sample engine: current ring estimates and rolling flow_buckets plus pending; uncached scoped reads",
rowLimit: 20000, incomplete: true, coverageVerified: false, forwardingVerified: false, rowSumIsNetworkTotal: false,
historicalOwnershipVerified: false, currentTrafficVerified: false,
rateSemantics: "REST live rates: current server/interface ring; retained-window fallback; user filter does not attribute ring rates",
rateSemantics: "REST live rates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback",
liveMeaning: "events[].data.live means listener bound; it does not prove exporter freshness or forwarding",
attribution: "current named whole-interface bindings; users with hidden bindings excluded",
collectorStarted: false, backgroundEnrichmentStarted: false }
+40 -21
View File
@@ -22,11 +22,11 @@ import {
listFlowRowsForWindow,
type PendingFlowRow,
} from "./traffic-flow-ingest.js"
import { flowDataEpoch, MAX_PENDING, RING_OVERLAY } from "./traffic-flow-engine.js"
import { flowDataEpoch, MAX_PENDING } from "./traffic-flow-engine.js"
import { resolveIfaceName } from "./traffic-flow-ifaces.js"
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
import { applicationName, flowRowMatchesFilter } from "./traffic-flow-apps.js"
import { dedupFlowRowsMaxBytes, flowTupleKey } from "./traffic-flow-dedup.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"
import { flowRateDirection, resolveInternetDest } from "./traffic-flow-dest.js"
@@ -215,6 +215,23 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
if (!scope) refreshFlowCatalogInBackground()
const matchesIngress = (row: PendingFlowRow) => flowRowMatchesFilter(row, resolveIfaceName(row.serverId, row.inIface).name, q, allow)
const matchesEgress = (row: PendingFlowRow) => flowRowMatchesFilter({ serverId: row.serverId, inIface: row.outIface }, resolveIfaceName(row.serverId, row.outIface).name, q, allow)
const serverDirection = (row: PendingFlowRow) => flowRateDirection(row.serverId, row, topo, catalog.byId.get(row.serverId)?.host)
const interfaceDirection = (row: PendingFlowRow) => {
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)) : raw
const { rows, espDirections } = collapseGreEspRows(selected, ifaceFilter ? interfaceDirection : serverDirection)
const previousMinute = new Date(Math.floor(Date.now() / 60_000) * 60_000 - 60_000).toISOString()
const ifacesForWire = new Set<string>()
for (const row of selected) {
ifacesForWire.add(resolveIfaceName(row.serverId, row.inIface).name)
const egress = resolveIfaceName(row.serverId, row.outIface).name
if (egress && egress !== "—") ifacesForWire.add(egress)
}
const applications = new Map<string, { bytes: number; packets: number; label?: string }>()
const protocols = new Map<string, { bytes: number; packets: number; label?: string }>()
const sources = new Map<string, { bytes: number; packets: number; label?: string }>()
@@ -234,16 +251,12 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
const skipHeavy = Boolean(q.skipHeavy)
let bytesPayload = 0
let bytesOverlay = 0
let recentOverlayBytes = 0
let bytesMesh = 0
const ifacesForWire = new Set<string>()
for (const r of raw) {
for (const r of rows) {
const resolved = resolveIfaceName(r.serverId, r.inIface)
const outResolved = resolveIfaceName(r.serverId, r.outIface)
if (!flowRowMatchesFilter(r, resolved.name, q, allow)
&& !flowRowMatchesFilter({ serverId: r.serverId, inIface: r.outIface }, outResolved.name, q, allow)) continue
ifacesForWire.add(resolved.name)
if (outResolved.name && outResolved.name !== "—") ifacesForWire.add(outResolved.name)
const plane = classifyFlowPlane({
src: r.src,
dst: r.dst,
@@ -254,7 +267,10 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
outIface: outResolved.name,
}, topo.plane)
if (plane === "payload") bytesPayload += r.bytes
else if (plane === "overlay") bytesOverlay += r.bytes
else if (plane === "overlay") {
bytesOverlay += r.bytes
if (r.bucketAt === previousMinute) recentOverlayBytes += r.bytes
}
else if (plane === "client_mesh") bytesMesh += r.bytes
if (!shouldKeepPlane(plane, { excludeMesh, excludeOverlay })) continue
matched.push(r)
@@ -444,9 +460,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
const topCategory = topLabel(categories)
const ringServer = q.serverId ?? (matched[0]?.serverId ?? 0)
const ring = ringServer
? getRingMbps(ringServer, ifaceFilter === "" ? "__all__" : (ifacesMap.get(ifaceFilter)?.index || ifaceFilter))
: { rx: Array(60).fill(0) as number[], tx: Array(60).fill(0) as number[], rxNow: 0, txNow: 0 }
const ring = ringServer && !ifaceFilter && !allow && excludeOverlay ? getRingMbps(ringServer) : null
// The live ring covers about one minute; historical charts must use the requested window.
// Keep the winning interface's individual minute buckets when deduplicating.
@@ -454,13 +468,16 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
const chartRows = chosenIfaces ? matched.filter(r => chosenIfaces.get(flowTupleKey(r)) === r.inIface) : matched
const fromBuckets = seriesFromRows(chartRows, q.minutes, row => {
if (ifaceFilter || allow) {
const ingress = flowRowMatchesFilter(row, resolveIfaceName(row.serverId, row.inIface).name, q, allow)
const egress = flowRowMatchesFilter({ serverId: row.serverId, inIface: row.outIface }, resolveIfaceName(row.serverId, row.outIface).name, q, allow)
if (ingress && egress) return "both"
const ingress = matchesIngress(row), egress = matchesEgress(row)
if (ingress && egress) {
// A repeated WAN interface in an overlay record does not prove two wire directions.
if (ifaceFilter && (row.proto === 47 || row.proto === 50)) return espDirections.get(row) ?? serverDirection(row)
return "both"
}
// At a client binding, ingress is the client's upload.
return allow && !ifaceFilter ? (ingress ? "tx" : "rx") : (ingress ? "rx" : "tx")
}
return flowRateDirection(row.serverId, row, topo, catalog.byId.get(row.serverId)?.host)
return espDirections.get(row) ?? serverDirection(row)
})
const rxSeries = fromBuckets.rx
const txSeries = fromBuckets.tx
@@ -499,9 +516,11 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
.sort((a, b) => b.bytes - a.bytes)
.slice(0, top)
const overlayRing = ringServer
? getRingMbps(ringServer, RING_OVERLAY)
: { rxNow: 0, txNow: 0 }
// Filtered and overlay-inclusive rates must use the same records as their totals.
const recentBytes = ring ? 0 : chartRows.reduce((sum, row) => sum + (row.bucketAt === previousMinute ? row.bytes : 0), 0)
const bpsNow = ring
? (!fromBuckets.undirectedBytes && (ring.rxNow + ring.txNow) * 1_000_000) || (totalBytes * 8) / windowSec
: (recentBytes * 8) / 60 || (totalBytes * 8) / windowSec
const greNames = ringServer ? enGreIfaceNames(topo, ringServer, [...ifacesForWire]) : []
await authorize()
const wire = ringServer ? await latestWireBps(ringServer, greNames, Boolean(scope)) : { bps: 0, bytes: 0 }
@@ -511,7 +530,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
if (scope && (!isDeepStrictEqual(topo, await loadFlowTopology(scope.serverIds, authorize)) || (await readFlowSourceLimits()).topN !== settings.topN)) throw new Error("Топология или предел источника NetFlow изменились во время чтения")
await authorize()
return {
bpsNow: (!fromBuckets.undirectedBytes && (ring.rxNow + ring.txNow) * 1_000_000) || (totalBytes * 8) / windowSec,
bpsNow,
bytes: totalBytes,
packets: totalPackets,
conversations: conv.size,
@@ -549,7 +568,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
bytesOverlay,
bytesMesh,
bytesWire: wire.bytes,
bpsOverlay: (overlayRing.rxNow + overlayRing.txNow) * 1_000_000 || (bytesOverlay * 8) / windowSec,
bpsOverlay: (recentOverlayBytes * 8) / 60 || (bytesOverlay * 8) / windowSec,
bpsWire: wire.bps,
excludeMeshApplied: excludeMesh,
excludeOverlayApplied: excludeOverlay,
@@ -1,5 +1,6 @@
import assert from "node:assert/strict"
import {
collapseGreEspRows,
dedupFlowRowsAcrossExporters,
dedupFlowRowsMaxBytes,
flowConversationKey,
@@ -36,4 +37,28 @@ assert.equal(across.length, 1)
assert.equal(across[0]?.serverId, 7)
assert.equal(across[0]?.bytes, 9_000)
const minute = "2026-11-22T06:26:00.000Z"
const nextMinute = "2026-11-22T06:27:00.000Z"
const gre = { ...a, bucketAt: minute, proto: 47, srcPort: 0, dstPort: 0 }
const esp = { ...gre, proto: 50, bytes: gre.bytes + gre.packets * 40, inIface: "10" }
const plain = { ...gre, dst: "198.51.100.3" }
const reverse = { ...esp, src: esp.dst, dst: esp.src }
const foreign = { ...esp, serverId: 9 }
const collapse = (rows: typeof gre[]) => collapseGreEspRows(rows, row => row.inIface === "2" ? "tx" : null)
const layerPair = collapse([gre, esp, plain, reverse, foreign])
assert.deepEqual(layerPair.rows, [esp, plain, reverse, foreign])
assert.equal(layerPair.espDirections.get(esp), "tx")
const splitGre = [{ ...gre, bytes: 8_400, packets: 7 }, { ...gre, bucketAt: nextMinute, bytes: 3_600, packets: 3 }]
const laterEsp = { ...esp, bucketAt: nextMinute }
assert.deepEqual(collapse([...splitGre, laterEsp]).rows, [laterEsp])
for (const unrelated of [
{ ...esp, packets: esp.packets - 1 },
{ ...esp, bytes: gre.bytes },
{ ...esp, bytes: gre.bytes + gre.packets * 500 },
{ ...esp, bucketAt: "2026-11-22T06:29:00.000Z" },
{ ...esp, srcPort: 123 },
]) assert.deepEqual(collapse([gre, unrelated]).rows, [gre, unrelated])
assert.deepEqual(collapseGreEspRows([gre, esp], row => row.proto === 47 ? "rx" : "tx").rows, [gre, esp])
console.log("traffic-flow-dedup.test.ts: ok")
@@ -1,3 +1,5 @@
import { isUnspecifiedIp } from "./traffic-flow-ip.js"
export interface FlowTupleRow {
serverId: number
src: string
@@ -68,3 +70,66 @@ export function dedupFlowRowsMaxBytes<T extends FlowTupleRow>(rows: T[]): T[] {
}
return [...byTuple.values()]
}
type TimedFlowRow = FlowTupleRow & { bucketAt: string }
type FlowDirection = "rx" | "tx"
type OverlayRows<T> = { gre: T[]; esp: T[] }
function account(rows: readonly FlowTupleRow[]) {
return rows.reduce((total, row) => ({ bytes: total.bytes + row.bytes, packets: total.packets + row.packets }), { bytes: 0, packets: 0 })
}
/** GRE and its IPsec envelope can both be exported for the same packet sequence. */
export function collapseGreEspRows<T extends TimedFlowRow>(rows: readonly T[], direction: (row: T) => FlowDirection | null) {
const groups = new Map<string, OverlayRows<T>>()
for (const row of rows) {
if ((row.proto !== 47 && row.proto !== 50) || row.srcPort !== 0 || row.dstPort !== 0 ||
row.packets <= 0 || isUnspecifiedIp(row.src) || isUnspecifiedIp(row.dst) || row.src === row.dst) continue
const key = JSON.stringify([row.serverId, row.src, row.dst])
const group = groups.get(key) ?? { gre: [], esp: [] }
if (row.proto === 47) group.gre.push(row)
else group.esp.push(row)
groups.set(key, group)
}
const copies = new Set<T>()
const espDirections = new Map<T, FlowDirection>()
const match = (gre: T[], esp: T[]) => {
if (!gre.length || !esp.length) return
const inner = account(gre), outer = account(esp)
if (inner.packets !== outer.packets) return
const overhead = (outer.bytes - inner.bytes) / inner.packets
// Keep ambiguous records. An ESP envelope adds its headers, trailer and padding.
if (overhead < 8 || overhead > 128) return
const directions = new Set([...gre, ...esp].map(direction).filter(side => side !== null))
if (directions.size > 1) return
const [side] = directions
if (side) for (const row of esp) espDirections.set(row, side)
for (const row of gre) copies.add(row)
}
for (const group of groups.values()) {
if (!group.gre.length || !group.esp.length) continue
const byMinute = new Map<string, OverlayRows<T>>()
for (const plane of ["gre", "esp"] as const) for (const row of group[plane]) {
const bucket = byMinute.get(row.bucketAt) ?? { gre: [], esp: [] }
bucket[plane].push(row)
byMinute.set(row.bucketAt, bucket)
}
const unmatched: OverlayRows<T> = { gre: [], esp: [] }
for (const [, bucket] of [...byMinute].sort(([a], [b]) => a.localeCompare(b))) {
match(bucket.gre, bucket.esp)
if (!bucket.gre.length || !copies.has(bucket.gre[0])) {
unmatched.gre.push(...bucket.gre)
unmatched.esp.push(...bucket.esp)
}
}
// The exporter can flush the two layers in different minute buckets.
if (unmatched.gre.length && unmatched.esp.length &&
Math.abs(Date.parse(unmatched.gre[0].bucketAt) - Date.parse(unmatched.esp[0].bucketAt)) <= 60_000 &&
Math.abs(Date.parse(unmatched.gre.at(-1)!.bucketAt) - Date.parse(unmatched.esp.at(-1)!.bucketAt)) <= 60_000) {
match(unmatched.gre, unmatched.esp)
}
}
return { rows: rows.filter(row => !copies.has(row)), espDirections }
}
@@ -9,6 +9,7 @@ import { applySqlMigrations } from '../db/migrate.js'
import { ensurePartitionFor } from '../db/partitions.js'
import { createMcpConnection,updateMcpSettings,setConnectionStatus } from '../modules/mcp/store.js'
import { mcpConnectionCreateSchema } from '@mmapp/contracts/mcp'
import type { FlowAnalyticsDto } from '@mmapp/contracts/traffic-flow'
import mcpTransport from '../routes/mcp-transport.js'
import trafficFlowRoutes from '../routes/traffic-flow.js'
import logsRoutes from '../routes/logs.js'
@@ -167,6 +168,38 @@ try{
invalidateFlowAnalyticsCache()
}
console.log('PASS five-minute REST analysis uses one latest counter per interface despite 50,010 historical samples')
const overlayBucket = new Date(Math.floor(Date.now()/60000)*60000-120000)
await ensurePartitionFor(pool,'flow_buckets','day',overlayBucket)
await pool.query(`INSERT INTO flow_buckets(server_id,bucket_at,src,dst,proto,src_port,dst_port,bytes,packets,in_iface,out_iface) VALUES
(1,$1,'192.0.2.1','203.0.113.9',47,0,0,12000,10,'gre-test','ether1'),
(1,$1,'192.0.2.1','203.0.113.9',50,0,0,12400,10,'ether1','ether1'),
(1,$1,'203.0.113.9','192.0.2.1',47,0,0,24000,20,'ether1','gre-test'),
(1,$1,'203.0.113.9','192.0.2.1',50,0,0,24800,20,'ether1','ether1'),
(1,$1,'203.0.113.10','192.0.2.1',47,0,0,1000,1,'ether1','gre-other'),
(1,$1,'203.0.113.11','203.0.113.12',50,0,0,2000,2,'ether1','ether1')`,[overlayBucket])
try {
const args={serverId:1,interface:'ether1',dedup:false,excludeOverlay:false}
const rest=await fetch(endpoint+'/api/traffic/flow/analytics?range=5m&serverId=1&iface=ether1&dedup=false&excludeOverlay=false')
assert.equal(rest.status,200,await rest.clone().text())
const filtered=await client.callTool({name:'mm_netflow_analytics_report_get',arguments:{...args,minutes:5}})
const live=await client.callTool({name:'mm_netflow_live_observe',arguments:args})
assert.ok(!filtered.isError,JSON.stringify(filtered))
assert.ok(!live.isError,JSON.stringify(live))
const mcp=(filtered.structuredContent as {result:{analytics:FlowAnalyticsDto}}).result.analytics
const sample=(live.structuredContent as {result:{events:{data:FlowAnalyticsDto}[]}}).result.events[0].data
const fromSeries=(series:number[])=>Math.round(series.reduce((sum,value)=>sum+value,0)*60*1e6/8)
for(const analytics of [await rest.json() as FlowAnalyticsDto,mcp,sample]){
assert.equal(analytics.bytes,40300,'Each overlay packet sequence contributes only the ESP bytes')
assert.equal(analytics.bytesOverlay,40200,'Plain GRE and undirected ESP remain part of the volume')
assert.equal(fromSeries(analytics.rxSeries),25900)
assert.equal(fromSeries(analytics.txSeries),12400)
}
assert.equal(sample.bpsOverlay,40200*8/300)
}finally{
await pool.query("DELETE FROM flow_buckets WHERE server_id=1 AND bucket_at=$1 AND proto IN (47,50)",[overlayBucket])
invalidateFlowAnalyticsCache()
}
console.log('PASS REST and MCP history and live analytics collapse GRE/ESP and place each confirmed ESP direction once')
const globalAccess=await createMcpConnection(mcpConnectionCreateSchema.parse({name:'owned global telemetry',mode:'observer',permissions:['mm:traffic:read'],expiresAt:new Date(Date.now()+600000).toISOString(),scope:{serverIds:[1],operationIds:['traffic.flow.talkers.read','netflow.settings.read'],allowGlobal:true},limits:{callsPerMinute:240}}),actor)
const globalClient=new Client({name:'owned-global-quality',version:'1'})
try{