Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m33s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 2m0s
Docker images / frontend-image (push) Successful in 7m41s
Docker images / publish-release (push) Successful in 33s
Docker images / notify-webhook (push) Successful in 1m55s
809 lines
31 KiB
TypeScript
809 lines
31 KiB
TypeScript
import { flowReadDbAll } from "./traffic-flow-read-policy.js"
|
|
import { isDeepStrictEqual } from "node:util"
|
|
import { readFlowMapSourceLimits } from "./traffic-flow-source-limits.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"
|
|
import { OTHER_SERVICE, isNamedInternetService, mapCountryNodeId, mapCountryServiceNodeId, mapServiceNodeId, resolveRipeCountry } from "./traffic-flow-brands.js"
|
|
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, 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, 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
|
|
/** Минимум узлов-брендов на карте, даже если доля ниже порога. */
|
|
export const MAP_SERVICE_MIN_NODES = 8
|
|
/** Cap сервисов внутри раскрытой страны (база доли — байты страны, не окна). */
|
|
export const MAP_COUNTRY_SERVICE_NODE_CAP = 8
|
|
/** Минимум узлов-сервисов внутри страны, даже если доля ниже порога. */
|
|
export const MAP_COUNTRY_SERVICE_MIN_NODES = 4
|
|
export const MAP_COUNTRY_CATEGORY = "Страна"
|
|
const HOPS_CACHE_TTL_MS = 2000
|
|
|
|
export interface FlowMapHopsQuery {
|
|
minutes: number
|
|
serverId?: number
|
|
userId?: string
|
|
iface?: string
|
|
dedup?: boolean
|
|
excludeMesh?: boolean
|
|
excludeOverlay?: boolean
|
|
/** Переопределение порога (тесты). Иначе из настроек NetFlow. */
|
|
minSharePct?: number
|
|
}
|
|
|
|
interface HopAcc {
|
|
fromId: string
|
|
fromLabel: string
|
|
toId: string
|
|
toLabel: string
|
|
kind: FlowMapHop["kind"]
|
|
iface?: string
|
|
bytes: number
|
|
bytesFwd: number
|
|
bytesRev: number
|
|
}
|
|
|
|
interface ClientAcc {
|
|
name: string
|
|
bytes: number
|
|
}
|
|
|
|
interface FromAcc {
|
|
exporterId: string
|
|
enId: string
|
|
reverseBytes: number
|
|
bytes: number
|
|
clients: Map<string, ClientAcc>
|
|
}
|
|
|
|
interface DstAcc {
|
|
dst: string
|
|
bytes: number
|
|
proto: number
|
|
dstPort: number
|
|
srcPort: number
|
|
fromBytes: Map<string, FromAcc>
|
|
}
|
|
|
|
interface DestTotal {
|
|
label: string
|
|
category: string
|
|
bytes: number
|
|
}
|
|
|
|
interface DestEdgeAcc {
|
|
fromId: string
|
|
toId: string
|
|
bytes: number
|
|
bytesFwd: number
|
|
bytesRev: number
|
|
clients: Map<string, string>
|
|
}
|
|
|
|
interface DestPathAcc {
|
|
clientId: string
|
|
clientName: string
|
|
viaId: string
|
|
viaName: string
|
|
enId: string
|
|
enName: string
|
|
serviceId: string
|
|
bytes: number
|
|
}
|
|
|
|
function bumpClient(clients: Map<string, ClientAcc>, bytes: number, client: { userId: string; name: string } | null): void {
|
|
const id = client?.userId || "—"
|
|
const name = client?.name || "—"
|
|
const prev = clients.get(id)
|
|
if (prev) {
|
|
prev.bytes += bytes
|
|
return
|
|
}
|
|
clients.set(id, { name, bytes })
|
|
}
|
|
|
|
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
|
|
|
|
export const resetFlowMapHopsCacheForTests = invalidateFlowMapHopsCache
|
|
|
|
export function invalidateFlowMapHopsCache(): void {
|
|
hopsCache = null
|
|
}
|
|
|
|
export function clampMapServiceMinSharePct(n: unknown): number {
|
|
const v = typeof n === "number" ? n : Number(n)
|
|
if (!Number.isFinite(v)) return DEFAULT_MAP_SERVICE_MIN_SHARE_PCT
|
|
return Math.min(100, Math.max(0, v))
|
|
}
|
|
|
|
/** Доля от payload окна; порог ИЛИ топ-N, затем cap. */
|
|
export function pickMapServices(
|
|
ranked: FlowMapService[],
|
|
minSharePct: number,
|
|
cap: number = MAP_SERVICE_NODE_CAP,
|
|
minNodes: number = MAP_SERVICE_MIN_NODES,
|
|
): FlowMapService[] {
|
|
if (minSharePct <= 0) return ranked.slice(0, cap)
|
|
const minShare = minSharePct / 100
|
|
return ranked
|
|
.filter((s, i) => s.share >= minShare || i < minNodes)
|
|
.slice(0, cap)
|
|
}
|
|
|
|
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number): void {
|
|
const prev = totals.get(id)
|
|
if (prev) {
|
|
prev.bytes += bytes
|
|
return
|
|
}
|
|
totals.set(id, { label, category, bytes })
|
|
}
|
|
|
|
function bumpDestFrom(
|
|
edges: Map<string, DestEdgeAcc>,
|
|
paths: Map<string, DestPathAcc>,
|
|
toId: string,
|
|
from: FromAcc,
|
|
exporterId: string,
|
|
fromId: string,
|
|
enName: string,
|
|
viaName: string,
|
|
/** fromId ребра, если отличается от EN (вложенный слой: страна → сервис). */
|
|
edgeFromId: string = fromId,
|
|
): void {
|
|
const edgeKey = `${edgeFromId}|${toId}`
|
|
const prevEdge = edges.get(edgeKey)
|
|
const namedClients = new Map<string, string>()
|
|
for (const [id, c] of from.clients) {
|
|
if (id !== "—") namedClients.set(id, c.name)
|
|
}
|
|
if (prevEdge) {
|
|
prevEdge.bytes += 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 - from.reverseBytes,
|
|
bytesRev: from.reverseBytes,
|
|
clients: namedClients,
|
|
})
|
|
}
|
|
for (const [clientId, c] of from.clients) {
|
|
const pathKey = `${clientId}|${exporterId}|${fromId}|${toId}`
|
|
const prevPath = paths.get(pathKey)
|
|
if (prevPath) {
|
|
prevPath.bytes += c.bytes
|
|
if (prevPath.clientName === "—" && c.name !== "—") prevPath.clientName = c.name
|
|
} else {
|
|
paths.set(pathKey, {
|
|
clientId,
|
|
clientName: c.name,
|
|
viaId: exporterId,
|
|
viaName,
|
|
enId: fromId,
|
|
enName,
|
|
serviceId: toId,
|
|
bytes: c.bytes,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
function finalizeDestLayer(
|
|
totals: Map<string, DestTotal>,
|
|
edges: Map<string, DestEdgeAcc>,
|
|
paths: Map<string, DestPathAcc>,
|
|
windowSec: number,
|
|
minSharePct: number,
|
|
shareBase: number,
|
|
cap: number = MAP_SERVICE_NODE_CAP,
|
|
minNodes: number = MAP_SERVICE_MIN_NODES,
|
|
): { nodes: FlowMapService[]; edges: FlowMapServiceEdge[]; paths: FlowMapServicePath[] } {
|
|
const nodes = pickMapServices(
|
|
[...totals.entries()]
|
|
.map(([id, s]) => ({
|
|
id,
|
|
label: s.label,
|
|
category: s.category,
|
|
bytes: s.bytes,
|
|
bps: (s.bytes * 8) / windowSec,
|
|
share: shareBase > 0 ? s.bytes / shareBase : 0,
|
|
}))
|
|
.sort((a, b) => b.bytes - a.bytes),
|
|
minSharePct,
|
|
cap,
|
|
minNodes,
|
|
)
|
|
const keep = new Set(nodes.map((s) => s.id))
|
|
const outEdges: FlowMapServiceEdge[] = [...edges.values()]
|
|
.filter((e) => keep.has(e.toId))
|
|
.map((e) => {
|
|
const clients = [...e.clients.entries()].map(([id, name]) => ({ id, name }))
|
|
const first = clients[0]
|
|
return {
|
|
fromId: e.fromId,
|
|
toId: e.toId,
|
|
bytes: e.bytes,
|
|
bps: (e.bytes * 8) / windowSec,
|
|
bpsFwd: (e.bytesFwd * 8) / windowSec,
|
|
bpsRev: (e.bytesRev * 8) / windowSec,
|
|
...(first ? { clientId: first.id, clientName: first.name } : {}),
|
|
...(clients.length ? { clients } : {}),
|
|
}
|
|
})
|
|
.sort((a, b) => b.bytes - a.bytes)
|
|
const outPaths: FlowMapServicePath[] = [...paths.values()]
|
|
.filter((p) => keep.has(p.serviceId))
|
|
.map((p) => ({
|
|
clientId: p.clientId,
|
|
clientName: p.clientName,
|
|
viaId: p.viaId,
|
|
viaName: p.viaName,
|
|
enId: p.enId,
|
|
enName: p.enName,
|
|
serviceId: p.serviceId,
|
|
bytes: p.bytes,
|
|
bps: (p.bytes * 8) / windowSec,
|
|
}))
|
|
.sort((a, b) => b.bps - a.bps)
|
|
return { nodes, edges: outEdges, paths: outPaths }
|
|
}
|
|
|
|
/** Группы сервисов по странам: только страны, прошедшие отбор слоя стран; доля — от байтов страны, не окна. */
|
|
function buildCountryServiceGroups(
|
|
nestedTotals: Map<string, DestTotal>,
|
|
nestedEdges: Map<string, DestEdgeAcc>,
|
|
nestedPaths: Map<string, DestPathAcc>,
|
|
countryNodes: FlowMapService[],
|
|
windowSec: number,
|
|
minSharePct: number,
|
|
): FlowMapCountryServiceGroup[] {
|
|
const groups: FlowMapCountryServiceGroup[] = []
|
|
for (const country of countryNodes) {
|
|
const prefix = `${country.id}|`
|
|
const totals = new Map<string, DestTotal>()
|
|
const edges = new Map<string, DestEdgeAcc>()
|
|
const paths = new Map<string, DestPathAcc>()
|
|
for (const [id, t] of nestedTotals) {
|
|
if (id.startsWith(prefix)) totals.set(id, t)
|
|
}
|
|
if (totals.size === 0) continue
|
|
for (const [key, e] of nestedEdges) {
|
|
if (e.toId.startsWith(prefix)) edges.set(key, e)
|
|
}
|
|
for (const [key, p] of nestedPaths) {
|
|
if (p.serviceId.startsWith(prefix)) paths.set(key, p)
|
|
}
|
|
const out = finalizeDestLayer(
|
|
totals,
|
|
edges,
|
|
paths,
|
|
windowSec,
|
|
minSharePct,
|
|
country.bytes,
|
|
MAP_COUNTRY_SERVICE_NODE_CAP,
|
|
MAP_COUNTRY_SERVICE_MIN_NODES,
|
|
)
|
|
groups.push({ countryId: country.id, services: out.nodes, edges: out.edges, paths: out.paths })
|
|
}
|
|
return groups
|
|
}
|
|
|
|
function countryDestFromRipe(ripe: FlowIpMeta | null, destKey: string): { id: string; label: string; category: string } {
|
|
if (!destKey || !ripe?.ok) {
|
|
return { id: mapCountryNodeId(""), label: OTHER_SERVICE, category: MAP_COUNTRY_CATEGORY }
|
|
}
|
|
const iso = resolveRipeCountry(ripe.country, ripe.asn, ripe.holder)
|
|
if (!iso) {
|
|
return { id: mapCountryNodeId(""), label: OTHER_SERVICE, category: MAP_COUNTRY_CATEGORY }
|
|
}
|
|
return { id: mapCountryNodeId(iso), label: iso, category: MAP_COUNTRY_CATEGORY }
|
|
}
|
|
|
|
function hopsQueryKey(q: FlowMapHopsQuery, minSharePct: number): string {
|
|
return JSON.stringify({
|
|
epoch: flowDataEpoch(),
|
|
minutes: q.minutes,
|
|
serverId: q.serverId ?? null,
|
|
userId: q.userId ?? null,
|
|
iface: q.iface ?? null,
|
|
dedup: q.dedup !== false,
|
|
excludeMesh: q.excludeMesh !== false,
|
|
excludeOverlay: q.excludeOverlay !== false,
|
|
minSharePct,
|
|
})
|
|
}
|
|
|
|
async function userIfaceAllow(userId: string): Promise<Map<number, Set<string>> | null> {
|
|
if (!userId) return null
|
|
const binds = await flowReadDbAll<{serverId:number;interfaceName:string}>('SELECT server_id AS "serverId",interface_name AS "interfaceName" FROM user_interface_bindings WHERE user_id=?',[userId])
|
|
const allow = new Map<number, Set<string>>()
|
|
for (const b of binds) {
|
|
const set = allow.get(b.serverId) ?? new Set<string>()
|
|
set.add(b.interfaceName)
|
|
allow.set(b.serverId, set)
|
|
}
|
|
return allow
|
|
}
|
|
|
|
function ifaceUsable(name: string): boolean {
|
|
return Boolean(name) && name !== "—"
|
|
}
|
|
|
|
function resolveMapClient(
|
|
topo: FlowTopology,
|
|
serverId: number,
|
|
inName: string,
|
|
outName: string,
|
|
) {
|
|
return resolveClient(topo, serverId, inName)
|
|
?? (ifaceUsable(outName) ? resolveClient(topo, serverId, outName) : null)
|
|
}
|
|
|
|
function bump(acc: Map<string, HopAcc>, key: string, seed: Omit<HopAcc, "bytes" | "bytesFwd" | "bytesRev">, bytes: number, dir: "fwd" | "rev" | "both"): void {
|
|
const prev = acc.get(key)
|
|
const addFwd = dir === "fwd" || dir === "both" ? bytes : 0
|
|
const addRev = dir === "rev" || dir === "both" ? bytes : 0
|
|
if (prev) {
|
|
prev.bytes += bytes
|
|
prev.bytesFwd += addFwd
|
|
prev.bytesRev += addRev
|
|
if (seed.iface && !prev.iface) prev.iface = seed.iface
|
|
return
|
|
}
|
|
acc.set(key, {
|
|
...seed,
|
|
bytes,
|
|
bytesFwd: addFwd,
|
|
bytesRev: addRev,
|
|
})
|
|
}
|
|
|
|
function toHop(a: HopAcc, windowSec: number): FlowMapHop {
|
|
return {
|
|
fromId: a.fromId,
|
|
fromLabel: a.fromLabel,
|
|
toId: a.toId,
|
|
toLabel: a.toLabel,
|
|
kind: a.kind,
|
|
...(a.iface ? { iface: a.iface } : {}),
|
|
bytes: a.bytes,
|
|
bps: (a.bytes * 8) / windowSec,
|
|
bpsFwd: (a.bytesFwd * 8) / windowSec,
|
|
bpsRev: (a.bytesRev * 8) / windowSec,
|
|
}
|
|
}
|
|
|
|
async function resolveMinSharePct(q: FlowMapHopsQuery): Promise<number> {
|
|
if (q.minSharePct != null) return clampMapServiceMinSharePct(q.minSharePct)
|
|
try {
|
|
const row = await getTrafficFlowSettingsRow()
|
|
return clampMapServiceMinSharePct(row.mapServiceMinSharePct ?? DEFAULT_MAP_SERVICE_MIN_SHARE_PCT)
|
|
} catch {
|
|
return DEFAULT_MAP_SERVICE_MIN_SHARE_PCT
|
|
}
|
|
}
|
|
|
|
// 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()
|
|
await authorize()
|
|
const limits = scope ? await readFlowMapSourceLimits() : undefined
|
|
const windowSec = Math.max(60, q.minutes * 60)
|
|
await authorize()
|
|
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)
|
|
const nameById = new Map([...catalog.byId].map(([id, s]) => [id, s.name]))
|
|
const ifaceFilter = q.iface && q.iface !== "__all__" ? q.iface : ""
|
|
const wantDedup = q.dedup !== false && !ifaceFilter
|
|
const excludeMesh = q.excludeMesh !== false
|
|
const excludeOverlay = q.excludeOverlay !== false
|
|
await authorize()
|
|
const topo = await loadFlowTopology(scope?.serverIds, authorize)
|
|
let allow: Map<number, Set<string>> | null = null
|
|
if (q.userId) {
|
|
if (!scope) allow = await userIfaceAllow(q.userId)
|
|
else {
|
|
allow = new Map()
|
|
for (const binding of topo.clientByIface.values()) if (binding.userId === q.userId) {
|
|
const names = allow.get(binding.serverId) ?? new Set<string>(); names.add(binding.interfaceName); allow.set(binding.serverId, names)
|
|
}
|
|
if (!allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
|
|
}
|
|
}
|
|
|
|
const matches = (serverId: number, iface: string) =>
|
|
flowRowMatchesFilter({ serverId, inIface: iface }, resolveIfaceName(serverId, iface).name, q, allow)
|
|
const selected = raw.filter(r => matches(r.serverId, r.inIface) || matches(r.serverId, r.outIface))
|
|
const { rows } = collapseGreEspRows(selected, r => {
|
|
if (ifaceFilter) {
|
|
const ingress = matches(r.serverId, r.inIface), egress = matches(r.serverId, r.outIface)
|
|
return ingress === egress ? null : ingress ? "rx" : "tx"
|
|
}
|
|
return flowRateDirection(r.serverId, r, topo, catalog.byId.get(r.serverId)?.host)
|
|
})
|
|
const matched = []
|
|
for (const r of rows) {
|
|
const resolved = resolveIfaceName(r.serverId, r.inIface)
|
|
const outResolved = resolveIfaceName(r.serverId, r.outIface)
|
|
const plane = classifyFlowPlane({
|
|
src: r.src,
|
|
dst: r.dst,
|
|
proto: r.proto,
|
|
srcPort: r.srcPort,
|
|
dstPort: r.dstPort,
|
|
inIface: resolved.name,
|
|
outIface: outResolved.name,
|
|
}, topo.plane)
|
|
if (!shouldKeepPlane(plane, { excludeMesh, excludeOverlay })) continue
|
|
matched.push(r)
|
|
}
|
|
|
|
const working = wantDedup ? dedupFlowRowsMaxBytes(matched) : matched
|
|
if (scope) flowCounterSum(working.map(row => row.bytes))
|
|
const hops = new Map<string, HopAcc>()
|
|
const dstAcc = new Map<string, DstAcc>()
|
|
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
|
|
|
|
function rowClient(r: (typeof working)[number]) {
|
|
const inName = resolveIfaceName(r.serverId, r.inIface).name
|
|
const outName = resolveIfaceName(r.serverId, r.outIface).name
|
|
return resolveMapClient(topo, r.serverId, inName, outName)
|
|
}
|
|
|
|
for (const r of working) {
|
|
const inRes = resolveIfaceName(r.serverId, r.inIface)
|
|
const outRes = resolveIfaceName(r.serverId, r.outIface)
|
|
const inName = inRes.name
|
|
const outName = outRes.name
|
|
const fromId = String(r.serverId)
|
|
const fromLabel = nameById.get(r.serverId) ?? fromId
|
|
const wanSet = topo.wanIfaces.get(r.serverId)
|
|
|
|
const inOk = ifaceUsable(inName)
|
|
const outOk = ifaceUsable(outName)
|
|
const sameIface = inOk && outOk && inName.toLowerCase() === outName.toLowerCase()
|
|
if (sameIface) {
|
|
bump(hops, `iface|${fromId}|${inName.toLowerCase()}`, {
|
|
fromId,
|
|
fromLabel,
|
|
toId: "",
|
|
toLabel: "",
|
|
kind: "iface",
|
|
iface: inName,
|
|
}, r.bytes, "fwd")
|
|
} else {
|
|
if (inOk) {
|
|
bump(hops, `iface|${fromId}|${inName.toLowerCase()}`, {
|
|
fromId,
|
|
fromLabel,
|
|
toId: "",
|
|
toLabel: "",
|
|
kind: "iface",
|
|
iface: inName,
|
|
}, r.bytes, "rev")
|
|
}
|
|
if (outOk) {
|
|
bump(hops, `iface|${fromId}|${outName.toLowerCase()}`, {
|
|
fromId,
|
|
fromLabel,
|
|
toId: "",
|
|
toLabel: "",
|
|
kind: "iface",
|
|
iface: outName,
|
|
}, r.bytes, "fwd")
|
|
}
|
|
}
|
|
|
|
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, JSON.stringify(["gre", fromId, toId, greIface]), {
|
|
fromId,
|
|
fromLabel,
|
|
toId,
|
|
toLabel: nodeName(toId),
|
|
kind: "gre",
|
|
iface: greIface,
|
|
}, r.bytes, dir)
|
|
}
|
|
|
|
if (wanSet?.size) {
|
|
if (ifaceUsable(inName) && wanSet.has(inName)) {
|
|
bump(hops, `wan|${fromId}|${inName.toLowerCase()}`, {
|
|
fromId,
|
|
fromLabel,
|
|
toId: "",
|
|
toLabel: "",
|
|
kind: "wan",
|
|
iface: inName,
|
|
}, r.bytes, "rev")
|
|
}
|
|
if (ifaceUsable(outName) && wanSet.has(outName) && outName.toLowerCase() !== inName.toLowerCase()) {
|
|
bump(hops, `wan|${fromId}|${outName.toLowerCase()}`, {
|
|
fromId,
|
|
fromLabel,
|
|
toId: "",
|
|
toLabel: "",
|
|
kind: "wan",
|
|
iface: outName,
|
|
}, r.bytes, "fwd")
|
|
}
|
|
}
|
|
}
|
|
|
|
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 { 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 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>()
|
|
const svcEdges = new Map<string, DestEdgeAcc>()
|
|
const svcPaths = new Map<string, DestPathAcc>()
|
|
const ccTotals = new Map<string, DestTotal>()
|
|
const ccEdges = new Map<string, DestEdgeAcc>()
|
|
const ccPaths = new Map<string, DestPathAcc>()
|
|
const nestedTotals = new Map<string, DestTotal>()
|
|
const nestedEdges = new Map<string, DestEdgeAcc>()
|
|
const nestedPaths = new Map<string, DestPathAcc>()
|
|
|
|
function nodeName(id: string): string {
|
|
const n = Number(id)
|
|
if (Number.isFinite(n)) {
|
|
const fromDb = nameById.get(n)
|
|
if (fromDb) return fromDb
|
|
}
|
|
const en = topo.enNodes.find((node) => String(node.id) === id)
|
|
if (en?.name) return en.name
|
|
return id
|
|
}
|
|
|
|
for (const acc of dstAcc.values()) {
|
|
const { dst } = acc
|
|
const ripe = dst ? resolveFlowIp(dst) : null
|
|
const classified = dst
|
|
? mapInternetBrand(dst, acc.proto, acc.dstPort, acc.srcPort, ripe)
|
|
: { service: OTHER_SERVICE, category: OTHER_SERVICE }
|
|
const svcId = mapServiceNodeId(classified.service)
|
|
bumpDestTotal(svcTotals, svcId, classified.service, classified.category, acc.bytes)
|
|
const country = countryDestFromRipe(ripe, dst)
|
|
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 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)
|
|
bumpDestFrom(ccEdges, ccPaths, country.id, from, exporterId, fromId, enName, viaName)
|
|
bumpDestFrom(nestedEdges, nestedPaths, nestedId, from, exporterId, fromId, enName, viaName, country.id)
|
|
}
|
|
}
|
|
|
|
const namedBytes = [...svcTotals.values()]
|
|
.filter((s) => isNamedInternetService(s.label, s.category))
|
|
.reduce((n, s) => n + s.bytes, 0)
|
|
const unclassifiedBytes = Math.max(0, totalBytes - namedBytes)
|
|
const shareBase = totalBytes > 0 ? totalBytes : namedBytes
|
|
const servicesOut = finalizeDestLayer(svcTotals, svcEdges, svcPaths, windowSec, minSharePct, shareBase)
|
|
const countriesOut = finalizeDestLayer(ccTotals, ccEdges, ccPaths, windowSec, minSharePct, shareBase)
|
|
const countryServiceGroups = buildCountryServiceGroups(
|
|
nestedTotals,
|
|
nestedEdges,
|
|
nestedPaths,
|
|
countriesOut.nodes,
|
|
windowSec,
|
|
minSharePct,
|
|
)
|
|
|
|
const listener = getFlowListenerState()
|
|
const geo = geoipReadersStatus()
|
|
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),
|
|
live: listener.bound,
|
|
rangeMinutes: q.minutes,
|
|
windowSec,
|
|
totalBytes,
|
|
namedBytes,
|
|
unclassifiedBytes,
|
|
asnLoaded: geo.asnLoaded,
|
|
countryLoaded: geo.countryLoaded,
|
|
services: servicesOut.nodes,
|
|
serviceEdges: servicesOut.edges,
|
|
servicePaths: servicesOut.paths,
|
|
countries: countriesOut.nodes,
|
|
countryEdges: countriesOut.edges,
|
|
countryPaths: countriesOut.paths,
|
|
countryServiceGroups,
|
|
mapServiceMinSharePct: minSharePct,
|
|
dedupApplied: wantDedup,
|
|
excludeMeshApplied: excludeMesh,
|
|
excludeOverlayApplied: excludeOverlay,
|
|
}
|
|
}
|
|
|
|
/** Hop-rates для карты сети: те же фильтры, что у общего NetFlow (dedup / mesh / overlay). */
|
|
export async function buildFlowMapHops(q: FlowMapHopsQuery, scope?: ScopedFlowAnalyticsRead): Promise<FlowMapHopsDto> {
|
|
if (scope) {
|
|
if (!Number.isSafeInteger(q.serverId) || !scope.serverIds.includes(q.serverId!) || !Number.isSafeInteger(scope.maxRows) || scope.maxRows < 1 || scope.maxRows > 50000 || !Number.isSafeInteger(q.minutes) || q.minutes < 1 || q.minutes > 1440 || q.minSharePct !== undefined) throw new Error("Некорректная область карты NetFlow")
|
|
await scope.authorize()
|
|
const limits = await readFlowMapSourceLimits()
|
|
const dto = await buildFlowMapHopsUncached(q, limits.mapServiceMinSharePct, scope)
|
|
await scope.authorize()
|
|
if (!isDeepStrictEqual(limits, await readFlowMapSourceLimits())) throw new Error("Предел карты NetFlow изменился во время чтения")
|
|
await scope.authorize()
|
|
return dto
|
|
}
|
|
const minSharePct = await resolveMinSharePct(q)
|
|
const key = hopsQueryKey(q, minSharePct)
|
|
const now = Date.now()
|
|
if (hopsCache && hopsCache.key === key && now - hopsCache.at < HOPS_CACHE_TTL_MS) {
|
|
return hopsCache.dto
|
|
}
|
|
const dto = await buildFlowMapHopsUncached(q, minSharePct)
|
|
hopsCache = { key, at: now, dto }
|
|
return dto
|
|
}
|