Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4097e1a6fc |
No files matched your search
@@ -2241,9 +2241,9 @@ function NetworkMapContent() {
|
||||
const recentIncidents = eventRows.filter(event => (event.tone === "er" || event.tone === "wn") && event.ts >= eventsAt - 86_400_000)
|
||||
const mapHeadSub = (
|
||||
<>
|
||||
<span title={readAt ? `Снимок API ${new Date(readAt).toLocaleTimeString("ru-RU")}` : undefined}>{useLiveData ? (readAt ? "Текущий срез" : "Данные карты неизвестны") : "Демонстрационные данные"}</span>
|
||||
<span title={readAt ? `Снимок API ${new Date(readAt).toLocaleTimeString("ru-RU")}` : undefined}>{useLiveData ? (readAt ? "Снимок сети" : "Данные карты неизвестны") : "Демонстрационные данные"}</span>
|
||||
{" · "}<span>{nodes.length} {ruPlural(nodes.length, "узел", "узла", "узлов")} · {mapLinkCount} {ruPlural(mapLinkCount, "связь", "связи", "связей")}</span>
|
||||
{useLiveData && (showNetflow || showServices) && <>{" · "}{flowReadAt ? <span title={`NetFlow · ${mapWindow}${mapWindowSec >= 120 && mapWindowSec < 300 ? " из 5 запрошенных" : ""} · ответ ${new Date(flowReadAt).toLocaleTimeString("ru-RU")} · ${flowListener ? "приёмник включён" : "приёмник выключен"}`}>IPFIX · {mapWindow}{!flowListener ? " · приёмник выключен" : ""}</span> : <span>Данные NetFlow неизвестны</span>}</>}
|
||||
{useLiveData && (showNetflow || showServices) && <>{" · "}{flowReadAt ? <span title={`NetFlow · ${destinationWindow}${destinationWindowSec >= 120 && destinationWindowSec < 300 ? " из 5 запрошенных" : ""} · ответ ${new Date(destinationReadAt ?? flowReadAt).toLocaleTimeString("ru-RU")} · ${flowListener ? "приёмник включён" : "приёмник выключен"} · средняя скорость по сохранённым потокам`}>IPFIX · среднее за {destinationWindow}{!flowListener ? " · приёмник выключен" : ""}</span> : <span>Данные NetFlow неизвестны</span>}</>}
|
||||
</>
|
||||
)
|
||||
// Подсказки поиска макета: узлы и назначения текущего снимка.
|
||||
@@ -2435,6 +2435,7 @@ function NetworkMapContent() {
|
||||
<li>Слева выберите пользователя. Карта покажет правее его узлы подключения, выход в интернет и сервисы.</li>
|
||||
<li>Откройте узел или линию. Справа появятся источник данных, состояние связи и доступные измерения.</li>
|
||||
<li>Метка IPFIX показывает, где замечен трафик. Дальнейший маршрут для такой линии требует подтверждения.</li>
|
||||
<li>На сервисах показана средняя скорость по сохранённым потокам IPFIX. RX/TX на узлах берутся из счётчиков RouterOS.</li>
|
||||
</ol>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
@@ -421,8 +421,8 @@ try {
|
||||
assert.equal(def.excludeOverlayApplied, true)
|
||||
assert.equal(def.excludeMeshApplied, true)
|
||||
assert.ok(!def.conversationsList.some((r) => r.proto === 47))
|
||||
assert.equal(def.conversationsList[0]?.service, "Google")
|
||||
assert.equal(def.conversationsList[0]?.category, "Веб")
|
||||
assert.equal(def.conversationsList[0]?.service, "YouTube")
|
||||
assert.equal(def.conversationsList[0]?.category, "Видео / стриминг")
|
||||
assert.equal(def.conversationsList[0]?.clientName, "Alice")
|
||||
assert.equal(def.conversationsList[0]?.enName, "NSK-SERVHOST-RTK")
|
||||
assert.equal(def.conversationsList[0]?.plane, "payload")
|
||||
@@ -520,8 +520,8 @@ try {
|
||||
const google = rev.conversationsList.find((r) => r.src === "74.125.104.196")
|
||||
const cf = rev.conversationsList.find((r) => r.src === "104.18.35.51")
|
||||
const fastly = rev.conversationsList.find((r) => r.src === "146.75.118.132")
|
||||
assert.equal(google?.service, "Google")
|
||||
assert.equal(google?.category, "Веб")
|
||||
assert.equal(google?.service, "YouTube")
|
||||
assert.equal(google?.category, "Видео / стриминг")
|
||||
assert.equal(google?.internetPeer, "74.125.104.196")
|
||||
assert.equal(google?.internetPeerPort, 443)
|
||||
assert.equal(google?.clientIp, "10.200.100.53")
|
||||
|
||||
@@ -85,11 +85,16 @@ assert.equal(isSteamGamePort(6, 443, 50000), false)
|
||||
assert.equal(resolveFlowBrand("104.18.35.51", 32590, "VALVE-CORPORATION", 6, 443, 1)?.service, "Cloudflare")
|
||||
assert.equal(resolveFlowBrand("203.0.113.9", 32590, "", 17, 27015, 50000)?.service, "Steam")
|
||||
assert.equal(resolveFlowBrand("8.8.8.8", 15169, "GOOGLE", 6, 443, 51234)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("173.194.160.163", 15169, "GOOGLE", 6, 443, 51234)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 17, 443, 50000)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("173.194.160.163", 15169, "GOOGLE", 6, 443, 51234)?.service, "YouTube")
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 17, 443, 50000)?.service, "YouTube")
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 6, 80, 50000)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("2001:4860:4860::8888", 15169, "GOOGLE", 17, 53, 53000)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("2001:4860:4860::8888", 15169, "GOOGLE", 17, 443, 50000)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("2001:4860:4860:0:0:0:0:8844/128", 15169, "GOOGLE", 6, 443)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("::ffff:8.8.4.4", 15169, "", 17, 443)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("2607:f8b0::123", 15169, "", 17, 443)?.service, "YouTube")
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 396982, "", 6, 443)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 6, 50000, 443)?.service, "Google", "443 на стороне клиента")
|
||||
|
||||
assert.equal(brandByAsn(32934)?.service, "Meta")
|
||||
assert.equal(lookupBrand("157.240.12.52", 0)?.service, "Meta")
|
||||
@@ -99,13 +104,13 @@ assert.equal(mapServiceNodeId("Instagram"), "svc:instagram")
|
||||
assert.equal(isNamedInternetService("Instagram", "Видео / стриминг"), true)
|
||||
assert.equal(
|
||||
resolveFlowBrand("157.240.12.52", 32934, "FACEBOOK", 6, 443, 51234)?.service,
|
||||
"Meta",
|
||||
"Общий адрес Meta не идентифицирует Instagram",
|
||||
"Instagram",
|
||||
"HTTPS в сети Meta",
|
||||
)
|
||||
assert.equal(
|
||||
resolveFlowBrand("57.144.22.192", 0, "", 17, 443, 50000)?.service,
|
||||
"Meta",
|
||||
"Общий префикс Meta не идентифицирует Instagram",
|
||||
"Instagram",
|
||||
"QUIC в префиксе Meta без ASN",
|
||||
)
|
||||
assert.equal(
|
||||
resolveFlowBrand("157.240.12.52", 32934, "FACEBOOK", 6, 80, 50000)?.service,
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { ipInCidrV4, parseCidrV4 } from "./traffic-flow-ip.js"
|
||||
import { canonicalIp, ipInCidrV4, ipv6ToInt, parseCidrV4 } from "./traffic-flow-ip.js"
|
||||
|
||||
export const OTHER_SERVICE = "Прочее"
|
||||
|
||||
export interface BrandHit {
|
||||
service: string
|
||||
category: string
|
||||
operator?: string
|
||||
heuristic?: true
|
||||
}
|
||||
|
||||
const CDN = { category: "CDN" } as const
|
||||
@@ -40,7 +42,7 @@ const TIMEWEB: BrandHit = { service: "Timeweb", ...CDN }
|
||||
const BEGET: BrandHit = { service: "Beget", ...CDN }
|
||||
const DDOS_GUARD: BrandHit = { service: "DDoS-Guard", ...CDN }
|
||||
const META: BrandHit = { service: "Meta", ...CDN }
|
||||
const INSTAGRAM: BrandHit = { service: "Instagram", ...VIDEO }
|
||||
const INSTAGRAM: BrandHit = { service: "Instagram", operator: META.service, ...VIDEO }
|
||||
|
||||
const GOOGLE: BrandHit = { service: "Google", ...WEB }
|
||||
const GITHUB: BrandHit = { service: "GitHub", ...WEB }
|
||||
@@ -55,7 +57,9 @@ const WIKIPEDIA: BrandHit = { service: "Wikipedia", ...WEB }
|
||||
const PAYPAL: BrandHit = { service: "PayPal", ...WEB }
|
||||
const SALESFORCE: BrandHit = { service: "Salesforce", ...WEB }
|
||||
|
||||
const YOUTUBE: BrandHit = { service: "YouTube", ...VIDEO }
|
||||
const YOUTUBE: BrandHit = { service: "YouTube", operator: GOOGLE.service, ...VIDEO }
|
||||
const LIKELY_YOUTUBE: BrandHit = { ...YOUTUBE, heuristic: true }
|
||||
const LIKELY_INSTAGRAM: BrandHit = { ...INSTAGRAM, heuristic: true }
|
||||
const NETFLIX: BrandHit = { service: "Netflix", ...VIDEO }
|
||||
const TWITCH: BrandHit = { service: "Twitch", ...VIDEO }
|
||||
const TIKTOK: BrandHit = { service: "TikTok", ...VIDEO }
|
||||
@@ -223,6 +227,14 @@ const HOLDER_BRANDS: Array<{ re: RegExp; hit: BrandHit }> = [
|
||||
const NON_ISO = new Set(["EU", "AP", "ZZ", "XX", "A1", "A2", "O1"])
|
||||
|
||||
const STEAM_ASN = 32590
|
||||
const GOOGLE_DNS_V6 = new Set([ipv6ToInt("2001:4860:4860::8888")!, ipv6ToInt("2001:4860:4860::8844")!])
|
||||
|
||||
function isGooglePublicDns(ip: string): boolean {
|
||||
const host = canonicalIp(ip)
|
||||
if (host === "8.8.8.8" || host === "8.8.4.4") return true
|
||||
const ipv6 = host.includes(":") ? ipv6ToInt(host) : null
|
||||
return ipv6 !== null && GOOGLE_DNS_V6.has(ipv6)
|
||||
}
|
||||
|
||||
export function isIsoCountry(code: string): boolean {
|
||||
const c = String(code ?? "").trim().toUpperCase()
|
||||
@@ -286,7 +298,7 @@ export function lookupBrand(ip: string, asn: number): BrandHit | null {
|
||||
/**
|
||||
* Cloudflare CIDR бьёт holder (витрина на CF не становится Steam).
|
||||
* Holder (YouTube / Instagram и др.) бьёт остальные CIDR/ASN.
|
||||
* Общий ASN Google или Meta сообщает об операторе, а не о приложении.
|
||||
* На порту 443 интернет-узла общие сети Google и Meta дают вероятную атрибуцию.
|
||||
* Порты Steam — только AS32590 и не выше Cloudflare CIDR.
|
||||
*/
|
||||
export function resolveFlowBrand(
|
||||
@@ -303,6 +315,11 @@ export function resolveFlowBrand(
|
||||
if (holderBrand) return holderBrand
|
||||
const asnBrand = brandByAsn(asn)
|
||||
const fromLookup = cidrBrand || asnBrand
|
||||
if (asnBrand === YOUTUBE && cidrBrand === GOOGLE) return YOUTUBE
|
||||
if ((proto === 6 || proto === 17) && dstPort === 443) {
|
||||
if (fromLookup === GOOGLE && (!asn || asn === 15169) && !isGooglePublicDns(ip)) return LIKELY_YOUTUBE
|
||||
if (fromLookup === META && (!asn || asn === 32934 || asn === 63293)) return LIKELY_INSTAGRAM
|
||||
}
|
||||
if (fromLookup) return fromLookup
|
||||
if (asn === STEAM_ASN && isSteamGamePort(proto, dstPort, srcPort)) return STEAM
|
||||
return null
|
||||
|
||||
@@ -8,6 +8,9 @@ seedFlowCatalogForTests({
|
||||
cidrs: [{ cidr: "192.0.2.0/24", purpose: "steam-gaming" },
|
||||
{ cidr: "198.51.100.0/25", purpose: "Игры" },
|
||||
{ cidr: "198.51.100.128/25", purpose: "Видео / стриминг" },
|
||||
{ cidr: "173.194.0.0/16", purpose: "GOOGLE" },
|
||||
{ cidr: "173.194.1.0/24", purpose: "Work" },
|
||||
{ cidr: "57.144.0.0/16", purpose: "Meta" },
|
||||
{ cidr: "203.0.113.128/25", purpose: "main" }],
|
||||
})
|
||||
|
||||
@@ -39,11 +42,11 @@ const google = classifyFlowDst("173.194.160.163", 6, 443, 1, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(google.service, "Google")
|
||||
assert.equal(google.category, "Веб")
|
||||
assert.deepEqual(google, { service: "YouTube", category: "Видео / стриминг", basis: "heuristic" })
|
||||
assert.equal(classifyFlowDst("173.194.1.1", 17, 443, 50000, null).service, "Work")
|
||||
|
||||
const googleCidr = classifyFlowDst("173.194.151.65", 6, 80, 50000, null)
|
||||
assert.equal(googleCidr.service, "Google")
|
||||
assert.equal(googleCidr.service, "GOOGLE")
|
||||
assert.equal(googleCidr.category, "Веб")
|
||||
|
||||
const youtube = classifyFlowDst("173.194.160.163", 6, 443, 1, {
|
||||
@@ -58,6 +61,8 @@ const youtube = classifyFlowDst("173.194.160.163", 6, 443, 1, {
|
||||
})
|
||||
assert.equal(youtube.service, "YouTube")
|
||||
assert.equal(youtube.category, "Видео / стриминг")
|
||||
assert.equal(youtube.basis, "network")
|
||||
assert.equal(classifyFlowDst("208.65.153.1", 17, 443, 50000, null).basis, "network")
|
||||
|
||||
const valve = classifyFlowDst("203.0.113.40", 17, 27015, 50000, {
|
||||
prefix: "203.0.113.0/24",
|
||||
@@ -174,8 +179,7 @@ const instagram = classifyFlowDst("157.240.12.52", 6, 443, 62598, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(instagram.service, "Meta")
|
||||
assert.equal(instagram.category, "CDN")
|
||||
assert.deepEqual(instagram, { service: "Instagram", category: "Видео / стриминг", basis: "heuristic" })
|
||||
|
||||
const metaHttp = classifyFlowDst("157.240.12.52", 6, 80, 50000, {
|
||||
prefix: "157.240.0.0/16",
|
||||
@@ -201,10 +205,10 @@ const igHolder = classifyFlowDst("203.0.113.80", 6, 443, 1, {
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(igHolder.service, "Instagram")
|
||||
assert.equal(igHolder.basis, "network")
|
||||
|
||||
const igCidr = classifyFlowDst("57.144.22.192", 17, 443, 50000, null)
|
||||
assert.equal(igCidr.service, "Meta")
|
||||
assert.equal(igCidr.category, "CDN")
|
||||
assert.deepEqual(igCidr, { service: "Instagram", category: "Видео / стриминг", basis: "heuristic" })
|
||||
|
||||
const esp = classifyFlowDst("198.51.100.1", 50, 0, 0, null)
|
||||
assert.equal(esp.category, "Туннель")
|
||||
|
||||
@@ -97,13 +97,14 @@ export function classifyFlowDst(
|
||||
const prefixPurpose = servicePurpose(matchCidr(dst,opts?.catalog?.cidrs)?.purpose)
|
||||
const holder = ripe?.holder ?? ""
|
||||
const brand = resolveFlowBrand(dst, ripe?.asn ?? 0, holder, proto, dstPort, srcPort)
|
||||
if (prefixPurpose && prefixPurpose.toLowerCase() !== brand?.operator?.toLowerCase()) {
|
||||
return { service: prefixPurpose, category: categoryFromPurpose(prefixPurpose, proto, dstPort, srcPort), basis: "catalog" }
|
||||
}
|
||||
if (brand) return { service: brand.service, category: brand.category, basis: brand.heuristic ? "heuristic" : "network" }
|
||||
const asnName = ripe?.asn ? servicePurpose((opts?.catalog?.asnPurpose??asnPurpose).get(ripe.asn)) : undefined
|
||||
const service = prefixPurpose || brand?.service || asnName || OTHER_SERVICE
|
||||
const category = prefixPurpose
|
||||
? categoryFromPurpose(prefixPurpose, proto, dstPort, srcPort)
|
||||
: (brand?.category || categoryFromPurpose(asnName || "", proto, dstPort, srcPort))
|
||||
const basis = prefixPurpose ? "catalog" : brand ? "network" : asnName ? "catalog" : category !== OTHER_SERVICE ? "port" : "unknown"
|
||||
return { service, category, basis }
|
||||
const category = categoryFromPurpose(asnName || "", proto, dstPort, srcPort)
|
||||
const basis = asnName ? "catalog" : category !== OTHER_SERVICE ? "port" : "unknown"
|
||||
return { service: asnName || OTHER_SERVICE, category, basis }
|
||||
}
|
||||
|
||||
/** Copies already-observed data only; never fetches the EvoBGP catalog. */
|
||||
|
||||
@@ -185,8 +185,8 @@ assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
}).service, "Google")
|
||||
assert.equal(mapInternetBrand("64.233.161.1", 17, 443, 50000, null).service, "Google")
|
||||
assert.equal(mapInternetBrand("142.250.1.10", 6, 443, 1, null).service, "Google")
|
||||
assert.equal(mapInternetBrand("64.233.161.1", 17, 443, 50000, null).service, "YouTube")
|
||||
assert.equal(mapInternetBrand("142.250.1.10", 6, 443, 1, null).service, "YouTube")
|
||||
|
||||
{
|
||||
const meta = resolveInternetDest({
|
||||
@@ -200,7 +200,7 @@ assert.equal(mapInternetBrand("142.250.1.10", 6, 443, 1, null).service, "Google"
|
||||
topo,
|
||||
})
|
||||
assert.equal(meta.dest, "74.125.104.196")
|
||||
assert.equal(meta.classified.service, "Google")
|
||||
assert.equal(meta.classified.service, "YouTube")
|
||||
assert.notEqual(meta.classified.service, "Прочее")
|
||||
assert.equal(meta.endpoints.direction, "to_client")
|
||||
assert.equal(meta.endpoints.clientIp, "10.200.100.53")
|
||||
|
||||
@@ -117,7 +117,7 @@ assert.equal(v6meta?.asn, 15169)
|
||||
assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, v6meta).service, "Google")
|
||||
assert.notEqual(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, v6meta).service, "Прочее")
|
||||
const cidrYt = mapInternetBrand("64.233.161.1", 17, 443, 50000, resolveFlowIp("64.233.161.1"))
|
||||
assert.equal(cidrYt.service, "Google")
|
||||
assert.equal(cidrYt.service, "YouTube")
|
||||
|
||||
// ── движок: dims country/asn наполняются из geoip-ридеров ────────────────────
|
||||
resetEngineForTests()
|
||||
|
||||
@@ -462,13 +462,13 @@ try {
|
||||
assert.equal(leak.totalBytes, 30_000)
|
||||
assert.equal(leak.namedBytes, 10_000)
|
||||
assert.equal(leak.unclassifiedBytes, 20_000)
|
||||
const google = leak.services?.find((s) => s.id === "svc:google")
|
||||
const youtube = leak.services?.find((s) => s.id === "svc:youtube")
|
||||
const other = leak.services?.find((s) => s.id === "svc:other")
|
||||
assert.ok(google, "Общий диапазон Google без RIPE")
|
||||
assert.ok(youtube, "YouTube по общему диапазону Google без RIPE")
|
||||
assert.ok(other, "dest без бренда → Прочее")
|
||||
assert.equal(google.bytes, 10_000)
|
||||
assert.equal(youtube.bytes, 10_000)
|
||||
assert.equal(other.bytes, 20_000)
|
||||
assert.ok(Math.abs(google.share - 10 / 30) < 0.01)
|
||||
assert.ok(Math.abs(youtube.share - 10 / 30) < 0.01)
|
||||
assert.ok(Math.abs(other.share - 20 / 30) < 0.01)
|
||||
assert.equal((leak.serviceEdges ?? []).reduce((n, e) => n + e.bytes, 0), hop.bytes)
|
||||
} finally {
|
||||
@@ -658,9 +658,9 @@ ingestClosed(7, [
|
||||
try {
|
||||
resetFlowMapHopsCacheForTests()
|
||||
const rev = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
|
||||
assert.ok(rev.services?.some((s) => s.id === "svc:google"), "Публичная сторона ответного потока относится к Google")
|
||||
assert.ok(rev.services?.some((s) => s.id === "svc:youtube"), "Ответный поток с порта 443 сети Google учитывается как YouTube")
|
||||
assert.ok(rev.services?.some((s) => s.id === "svc:cloudflare"), "реверс Cloudflare:443 → 10.x")
|
||||
assert.ok(rev.serviceEdges?.some((e) => e.toId === "svc:google" && e.fromId === "9"))
|
||||
assert.ok(rev.serviceEdges?.some((e) => e.toId === "svc:youtube" && e.fromId === "9"))
|
||||
} finally {
|
||||
seedFlowTopologyForTests(null)
|
||||
resetFlowRingsForTests()
|
||||
@@ -737,9 +737,10 @@ ingestClosed(7, [
|
||||
try {
|
||||
resetFlowMapHopsCacheForTests()
|
||||
const wanOnly = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
|
||||
assert.equal(wanOnly.services?.find(s => s.id === "svc:google")?.bytes, 9000)
|
||||
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:google")?.trafficTypes,
|
||||
[{transport: "TCP", application: "HTTPS", bytes: 9000}])
|
||||
const youtube = wanOnly.services?.find(s => s.id === "svc:youtube")
|
||||
assert.equal(youtube?.bytes, 9000)
|
||||
assert.deepEqual(youtube.serviceEvidence, [{basis: "heuristic", bytes: 9000}])
|
||||
assert.deepEqual(youtube.trafficTypes, [{transport: "TCP", application: "HTTPS", bytes: 9000}])
|
||||
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.trafficTypes,
|
||||
[{transport: "UDP", application: "DNS", bytes: 6000}])
|
||||
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.serviceEvidence, [{basis: "port", bytes: 6000}])
|
||||
@@ -1050,7 +1051,8 @@ try {
|
||||
const clock = mock.method(Date, "now", () => bucket + 90_000)
|
||||
try {
|
||||
const map = await buildFlowMapHops({ serverId: 7, minutes: 5, minSharePct: 0 })
|
||||
assert.equal(map.services?.find(s => s.id === "svc:google")?.bytes, 12000)
|
||||
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.bytes, 12000)
|
||||
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, new Date(bucket).toISOString())
|
||||
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes, Boolean(e.observedOnly)]), [["7", 9000, true], ["10", 2000, false], ["9", 1000, false]])
|
||||
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 12000)
|
||||
assert.equal(map.nodeUsers?.["7"]?.find(u => u.clientName === "Alice")?.bytes, 12000)
|
||||
@@ -1058,8 +1060,16 @@ try {
|
||||
|
||||
const recent = await buildFlowMapHops({ serverId: 7, minutes: 1, includeCurrentMinute: true, minSharePct: 0 })
|
||||
assert.equal(recent.windowSec, 90)
|
||||
assert.equal(recent.services?.find(s => s.id === "svc:google")?.bps, 900_012_000 * 8 / 90)
|
||||
const lastMinute = new Date(bucket + 60_000).toISOString()
|
||||
assert.equal(recent.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, lastMinute)
|
||||
assert.equal(recent.countryServiceGroups?.flatMap(g => g.services).find(s => s.label === "YouTube")?.lastBucketAt, lastMinute)
|
||||
assert.equal(recent.services?.find(s => s.id === "svc:youtube")?.bps, 900_012_000 * 8 / 90)
|
||||
assert.equal(recent.serviceEdges?.find(edge => edge.fromId === "9")?.bps, 900_001_000 * 8 / 90)
|
||||
const later = bucket + 150_000
|
||||
clock.mock.mockImplementation(() => later)
|
||||
ingestParsedFlowsForServerForTests(7, [{ ...flow, bytes: 0, packets: 1, outIface: "ether1" }])
|
||||
const idle = await buildFlowMapHops({ serverId: 7, minutes: 3, includeCurrentMinute: true, minSharePct: 0 })
|
||||
assert.equal(idle.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, lastMinute)
|
||||
} finally { clock.mock.restore() }
|
||||
} finally {
|
||||
await dbQuery("DELETE FROM internet_path_snapshots WHERE id=?", [snapshot.id])
|
||||
|
||||
@@ -19,7 +19,7 @@ import { resolveFlowEndpoints } from "./traffic-flow-ip.js"
|
||||
import { geoipReadersStatus, resolveFlowIp } from "./traffic-flow-geoip.js"
|
||||
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
|
||||
import { loadFlowTopology, resolveFlowClient, flowClientInterfaces, getServerCatalog, type FlowClientBinding } from "./traffic-flow-topology.js"
|
||||
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM } from "./traffic-flow-engine.js"
|
||||
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM, minuteBucketIso } from "./traffic-flow-engine.js"
|
||||
|
||||
export const DEFAULT_MAP_SERVICE_MIN_SHARE_PCT = 5
|
||||
export const MAP_SERVICE_NODE_CAP = 20
|
||||
@@ -74,6 +74,7 @@ interface FromAcc {
|
||||
interface DstAcc {
|
||||
dst: string
|
||||
bytes: number
|
||||
lastBucketAt: string
|
||||
proto: number
|
||||
dstPort: number
|
||||
srcPort: number
|
||||
@@ -85,6 +86,7 @@ interface DestTotal {
|
||||
label: string
|
||||
category: string
|
||||
bytes: number
|
||||
lastBucketAt: string
|
||||
trafficTypes?: Map<string, NonNullable<FlowMapService["trafficTypes"]>[number]>
|
||||
serviceEvidence?: Map<FlowServiceBasis, number>
|
||||
}
|
||||
@@ -159,10 +161,11 @@ export function pickMapServices(
|
||||
.slice(0, cap)
|
||||
}
|
||||
|
||||
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number,
|
||||
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number, lastBucketAt: string,
|
||||
detail?: { transport: string; application: string | null; basis: FlowServiceBasis }): void {
|
||||
const total = totals.get(id) ?? { label, category, bytes: 0 }
|
||||
const total = totals.get(id) ?? { label, category, bytes: 0, lastBucketAt }
|
||||
total.bytes += bytes
|
||||
if (lastBucketAt > total.lastBucketAt) total.lastBucketAt = lastBucketAt
|
||||
if (detail && bytes > 0) {
|
||||
const { transport, application, basis } = detail
|
||||
const types = total.trafficTypes ??= new Map()
|
||||
@@ -249,6 +252,7 @@ function finalizeDestLayer(
|
||||
label: s.label,
|
||||
category: s.category,
|
||||
bytes: s.bytes,
|
||||
...(s.lastBucketAt ? { lastBucketAt: minuteBucketIso(Date.parse(s.lastBucketAt)) } : {}),
|
||||
bps: (s.bytes * 8) / windowSec,
|
||||
share: shareBase > 0 ? s.bytes / shareBase : 0,
|
||||
...(s.trafficTypes ? { trafficTypes: [...s.trafficTypes.values()].sort((a, b) => b.bytes - a.bytes).slice(0, 5) } : {}),
|
||||
@@ -704,8 +708,9 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const srcPort = ep.otherPort || r.srcPort
|
||||
const application = flowPortApplication(r.proto, dstPort) ?? flowPortApplication(r.proto, srcPort)
|
||||
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : JSON.stringify([r.proto, application])
|
||||
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, proto: r.proto, dstPort, srcPort, application, fromBytes: new Map<string, FromAcc>() }
|
||||
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, lastBucketAt: "", proto: r.proto, dstPort, srcPort, application, fromBytes: new Map<string, FromAcc>() }
|
||||
acc.bytes += bytes
|
||||
if (bytes > 0 && r.bucketAt > acc.lastBucketAt) acc.lastBucketAt = r.bucketAt
|
||||
bumpFrom(acc, String(r.serverId), exitId === undefined ? "" : String(exitId), viaIface, bytes, reverse, client)
|
||||
dstAcc.set(destKey, acc)
|
||||
}
|
||||
@@ -739,11 +744,11 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
: OTHER_BRAND
|
||||
const svcId = mapServiceNodeId(classified.service)
|
||||
const detail = { transport: protoName(acc.proto), application: acc.application, basis: classified.basis }
|
||||
bumpDestTotal(svcTotals, svcId, classified.service, classified.category, acc.bytes, detail)
|
||||
bumpDestTotal(svcTotals, svcId, classified.service, classified.category, acc.bytes, acc.lastBucketAt, detail)
|
||||
const country = countryDestFromRipe(ripe, dst)
|
||||
bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes)
|
||||
bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes, acc.lastBucketAt)
|
||||
const nestedId = mapCountryServiceNodeId(country.id, svcId)
|
||||
bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes, detail)
|
||||
bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes, acc.lastBucketAt, detail)
|
||||
for (const from of acc.fromBytes.values()) {
|
||||
const { exporterId, enId: fromId } = from
|
||||
const enName = nodeName(fromId)
|
||||
|
||||
@@ -22,6 +22,7 @@ const evidenceLabel: Record<FlowServiceBasis, string> = {
|
||||
catalog: "По каталогу",
|
||||
network: "По IP / ASN",
|
||||
port: "По протоколу / порту",
|
||||
heuristic: "Оценка по сети и порту",
|
||||
unknown: "Сервис не определён",
|
||||
}
|
||||
const percent = new Intl.NumberFormat("ru-RU", {style: "percent", maximumFractionDigits: 1})
|
||||
@@ -180,7 +181,7 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
|
||||
</header>
|
||||
<div className="mx-0.5 mb-0.5 min-h-0 overflow-y-auto rounded-lg border">
|
||||
<InspectorMetrics rows={[
|
||||
["Скорость", formatNetflowRate({ bps: service.bps }), "Средняя скорость NetFlow за " + windowLabel],
|
||||
["Средняя скорость IPFIX", formatNetflowRate({ bps: service.bps }), "Сохранённые потоки за " + windowLabel],
|
||||
[country ? "Доля страны" : "Доля трафика", percent.format(service.share)],
|
||||
["Объём · " + (currentVolume ? windowLabel : volume?.window ?? "24 ч"), <>{currentVolume ? formatBytes(service.bytes) : volume?.bytes == null ? "—" : formatBytes(volume.bytes)}{volume && <time dateTime={volume.at} title={new Date(volume.at).toLocaleString("ru-RU")} className="block text-[10px] font-normal text-muted-foreground">ответ {new Date(volume.at).toLocaleTimeString("ru-RU")}</time>}</>],
|
||||
exitIds.length || !exporterIds.length
|
||||
@@ -197,8 +198,14 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
|
||||
{otherTypeBytes > 0 && <div className="flex justify-between gap-2"><dt>Остальные типы</dt><dd className="font-mono tabular-nums">{typeShare(otherTypeBytes)}</dd></div>}
|
||||
</dl>
|
||||
{trafficTypes.some(row => row.application) && <p className="text-muted-foreground">Приложения определены по портам.</p>}
|
||||
{service.lastBucketAt && <p className="text-muted-foreground">Последняя минута с потоками <time dateTime={service.lastBucketAt} className="font-mono">{new Date(service.lastBucketAt).toLocaleTimeString("ru-RU", {hour: "2-digit", minute: "2-digit"})}</time></p>}
|
||||
{serviceEvidence.length ? <ul aria-label="Основание классификации" className="flex flex-wrap gap-1">
|
||||
{serviceEvidence.map(row => <li key={row.basis}><Badge size="sm" variant="secondary">{evidenceLabel[row.basis]}{serviceEvidence.length > 1 && ` · ${typeShare(row.bytes)}`}</Badge></li>)}
|
||||
{serviceEvidence.map(row => <li key={row.basis}>
|
||||
<Badge size="sm" variant={row.basis === "heuristic" ? "info-light" : "secondary"}
|
||||
title={row.basis === "heuristic" ? "Сервис предполагается по сети назначения и порту 443" : undefined}>
|
||||
{evidenceLabel[row.basis]}{serviceEvidence.length > 1 && ` · ${typeShare(row.bytes)}`}
|
||||
</Badge>
|
||||
</li>)}
|
||||
</ul> : null}
|
||||
</section>}
|
||||
<InspectorUsers users={serviceUsers(service, paths)} windowLabel={windowLabel} />
|
||||
|
||||
@@ -23,8 +23,12 @@ test("live GRE does not hash metrics and probe values retain zero and fractions"
|
||||
|
||||
test("a filtered topology does not inherit a service's full-network traffic composition", () => {
|
||||
const service = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 100, bps: 10, share: 1,
|
||||
trafficTypes: [{transport: "UDP", application: "DNS", bytes: 100}]}
|
||||
trafficTypes: [{transport: "UDP", application: "DNS", bytes: 100}], lastBucketAt: "2026-11-26T18:30:00.000Z"}
|
||||
const edges = ["1", "2"].map(fromId => ({fromId, toId: service.id, bytes: 50, bps: 5, bpsFwd: 5, bpsRev: 0}))
|
||||
assert.equal(scopeMapDestinations([service], edges, [], id => id === "1").services[0]?.trafficTypes, undefined)
|
||||
assert.deepEqual(scopeMapDestinations([service], edges, [], () => true).services[0]?.trafficTypes, service.trafficTypes)
|
||||
const partial = scopeMapDestinations([service], edges, [], id => id === "1").services[0]
|
||||
const complete = scopeMapDestinations([service], edges, [], () => true).services[0]
|
||||
assert.equal(partial?.trafficTypes, undefined)
|
||||
assert.equal(partial?.lastBucketAt, undefined)
|
||||
assert.deepEqual(complete?.trafficTypes, service.trafficTypes)
|
||||
assert.equal(complete?.lastBucketAt, service.lastBucketAt)
|
||||
})
|
||||
@@ -57,9 +57,9 @@ export function scopeMapDestinations(
|
||||
services: services.flatMap(service => {
|
||||
const total = totals.get(service.id)
|
||||
if (!total) return []
|
||||
const { trafficTypes, serviceEvidence, ...destination } = service
|
||||
const { trafficTypes, serviceEvidence, lastBucketAt, ...destination } = service
|
||||
return [{ ...destination, ...total, share: bytes ? total.bytes / bytes : 0,
|
||||
...(total.bytes === service.bytes ? { trafficTypes, serviceEvidence } : {}) }]
|
||||
...(total.bytes === service.bytes ? { trafficTypes, serviceEvidence, lastBucketAt } : {}) }]
|
||||
}).sort((a, b) => b.bytes - a.bytes || a.label.localeCompare(b.label)),
|
||||
edges: visibleEdges,
|
||||
paths: visiblePaths,
|
||||
|
||||
@@ -366,7 +366,7 @@ export const flowMapHopDtoSchema = z.object({
|
||||
bpsRev: z.number().nonnegative(),
|
||||
})
|
||||
|
||||
export const flowServiceBasisSchema = z.enum(["catalog", "network", "port", "unknown"])
|
||||
export const flowServiceBasisSchema = z.enum(["catalog", "network", "heuristic", "port", "unknown"])
|
||||
export type FlowServiceBasis = z.infer<typeof flowServiceBasisSchema>
|
||||
|
||||
export const flowMapServiceDtoSchema = z.object({
|
||||
@@ -376,6 +376,7 @@ export const flowMapServiceDtoSchema = z.object({
|
||||
bytes: z.number().nonnegative(),
|
||||
bps: z.number().nonnegative(),
|
||||
share: z.number().min(0).max(1),
|
||||
lastBucketAt: z.string().datetime().optional(),
|
||||
trafficTypes: z.array(z.object({
|
||||
transport: z.string(),
|
||||
application: z.string().nullable(),
|
||||
@@ -384,7 +385,7 @@ export const flowMapServiceDtoSchema = z.object({
|
||||
serviceEvidence: z.array(z.object({
|
||||
basis: flowServiceBasisSchema,
|
||||
bytes: z.number().positive(),
|
||||
})).max(4).optional(),
|
||||
})).max(flowServiceBasisSchema.options.length).optional(),
|
||||
})
|
||||
|
||||
export const flowMapServiceEdgeDtoSchema = z.object({
|
||||
|
||||
@@ -69,7 +69,9 @@ test("Карта и трафик сохраняют пользователя и
|
||||
})
|
||||
|
||||
test("Карта не приписывает весь YouTube единственному выходу ARN", async ({page}) => {
|
||||
const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1}
|
||||
const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1,
|
||||
trafficTypes: [{transport: "UDP", application: "QUIC", bytes: 900000}],
|
||||
serviceEvidence: [{basis: "heuristic", bytes: 900000}], lastBucketAt: "2026-11-26T18:30:00.000Z"}
|
||||
const edge = {fromId: "1", toId: service.id, bytes: 300000, bps: 8000, bpsFwd: 2000, bpsRev: 6000}
|
||||
let known = false
|
||||
await page.route("**/api/**", route => {
|
||||
@@ -88,6 +90,10 @@ test("Карта не приписывает весь YouTube единствен
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
await page.getByRole("button", {name: "Сервис YouTube", exact: true}).press("Enter")
|
||||
const composition = page.getByRole("region", {name: "Состав трафика IPFIX"})
|
||||
await expect(composition.getByText("Оценка по сети и порту")).toBeVisible()
|
||||
await expect(composition.locator("time")).toHaveAttribute("datetime", service.lastBucketAt)
|
||||
await expect(page.getByText("IPFIX · среднее за 5 мин")).toBeVisible()
|
||||
const unknown = page.getByText("Выход не определён", {exact: true}).locator("..")
|
||||
const badges = page.locator("[data-map-ribbon] > title")
|
||||
await expect(unknown).toContainText("24 Кбит/с")
|
||||
|
||||
Reference in new issue
Block a user