mirror of
https://github.com/nxtrace/NTrace-core.git
synced 2026-12-02 09:13:21 +00:00
test(bench): 建立 geo mtr websocket 性能与输出基线
This commit is contained in:
1 parent
40ac803ca2
commit
2cab379924
18 files changed
+1420
No files matched your search
@@ -0,0 +1 @@
|
||||
*.golden.json text eol=lf
|
||||
@@ -0,0 +1,169 @@
|
||||
package dn42
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const benchmarkGeoFeedEntryCount = 4096
|
||||
|
||||
var (
|
||||
benchmarkGeoFeedRowsSink []GeoFeedRow
|
||||
benchmarkGeoFeedRowSink GeoFeedRow
|
||||
benchmarkGeoFeedFoundSink bool
|
||||
)
|
||||
|
||||
func BenchmarkReadGeoFeedCSV(b *testing.B) {
|
||||
content := buildBenchmarkGeoFeedCSV(false, benchmarkGeoFeedEntryCount/2) +
|
||||
buildBenchmarkGeoFeedCSV(true, benchmarkGeoFeedEntryCount/2)
|
||||
setBenchmarkGeoFeedPath(b, writeBenchmarkGeoFeed(b, content))
|
||||
|
||||
b.ReportAllocs()
|
||||
var (
|
||||
rows []GeoFeedRow
|
||||
err error
|
||||
)
|
||||
for b.Loop() {
|
||||
rows, err = ReadGeoFeed()
|
||||
if err != nil {
|
||||
b.Fatalf("ReadGeoFeed() error = %v", err)
|
||||
}
|
||||
}
|
||||
benchmarkGeoFeedRowsSink = rows
|
||||
}
|
||||
|
||||
func BenchmarkFindGeoFeedRow(b *testing.B) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
ipv6 bool
|
||||
}{
|
||||
{name: "IPv4", ipv6: false},
|
||||
{name: "IPv6", ipv6: true},
|
||||
} {
|
||||
b.Run(tc.name, func(b *testing.B) {
|
||||
content := buildBenchmarkGeoFeedCSV(tc.ipv6, benchmarkGeoFeedEntryCount)
|
||||
setBenchmarkGeoFeedPath(b, writeBenchmarkGeoFeed(b, content))
|
||||
rows, err := ReadGeoFeed()
|
||||
if err != nil {
|
||||
b.Fatalf("ReadGeoFeed() setup error = %v", err)
|
||||
}
|
||||
if len(rows) != benchmarkGeoFeedEntryCount {
|
||||
b.Fatalf("ReadGeoFeed() rows = %d, want %d", len(rows), benchmarkGeoFeedEntryCount)
|
||||
}
|
||||
|
||||
lookupCases := []struct {
|
||||
name string
|
||||
target string
|
||||
wantCIDR string
|
||||
wantHit bool
|
||||
}{
|
||||
{
|
||||
name: "HeadHit",
|
||||
target: rows[0].IPNet.IP.String(),
|
||||
wantCIDR: rows[0].CIDR,
|
||||
wantHit: true,
|
||||
},
|
||||
{
|
||||
name: "MiddleHit",
|
||||
target: rows[len(rows)/2].IPNet.IP.String(),
|
||||
wantCIDR: rows[len(rows)/2].CIDR,
|
||||
wantHit: true,
|
||||
},
|
||||
{
|
||||
name: "TailHit",
|
||||
target: rows[len(rows)-1].IPNet.IP.String(),
|
||||
wantCIDR: rows[len(rows)-1].CIDR,
|
||||
wantHit: true,
|
||||
},
|
||||
{
|
||||
name: "Miss",
|
||||
target: benchmarkGeoFeedMissTarget(tc.ipv6),
|
||||
wantHit: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, lookup := range lookupCases {
|
||||
b.Run(lookup.name, func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
var (
|
||||
row GeoFeedRow
|
||||
found bool
|
||||
)
|
||||
for b.Loop() {
|
||||
row, found = FindGeoFeedRow(lookup.target, rows)
|
||||
}
|
||||
if found != lookup.wantHit || found && row.CIDR != lookup.wantCIDR {
|
||||
b.Fatalf(
|
||||
"FindGeoFeedRow(%q) = (%+v, %v), want CIDR %q, found %v",
|
||||
lookup.target,
|
||||
row,
|
||||
found,
|
||||
lookup.wantCIDR,
|
||||
lookup.wantHit,
|
||||
)
|
||||
}
|
||||
benchmarkGeoFeedRowSink = row
|
||||
benchmarkGeoFeedFoundSink = found
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func benchmarkGeoFeedMissTarget(ipv6 bool) string {
|
||||
if ipv6 {
|
||||
return "2001:db8::1"
|
||||
}
|
||||
return "192.0.2.1"
|
||||
}
|
||||
|
||||
func buildBenchmarkGeoFeedCSV(ipv6 bool, entries int) string {
|
||||
var content strings.Builder
|
||||
content.Grow(entries * 72)
|
||||
for i := 0; i < entries; i++ {
|
||||
if ipv6 {
|
||||
_, _ = fmt.Fprintf(
|
||||
&content,
|
||||
"fd00:%x::/64,us,US,City-%d,AS%d,Owner-%d\n",
|
||||
i,
|
||||
i,
|
||||
64512+i,
|
||||
i,
|
||||
)
|
||||
continue
|
||||
}
|
||||
_, _ = fmt.Fprintf(
|
||||
&content,
|
||||
"10.%d.%d.0/24,us,US,City-%d,AS%d,Owner-%d\n",
|
||||
(i/256)%256,
|
||||
i%256,
|
||||
i,
|
||||
64512+i,
|
||||
i,
|
||||
)
|
||||
}
|
||||
return content.String()
|
||||
}
|
||||
|
||||
func writeBenchmarkGeoFeed(b *testing.B, content string) string {
|
||||
b.Helper()
|
||||
path := filepath.Join(b.TempDir(), "geofeed.csv")
|
||||
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
|
||||
b.Fatalf("write benchmark geofeed: %v", err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func setBenchmarkGeoFeedPath(b *testing.B, path string) {
|
||||
b.Helper()
|
||||
previous := viper.Get("geoFeedPath")
|
||||
viper.Set("geoFeedPath", path)
|
||||
b.Cleanup(func() {
|
||||
viper.Set("geoFeedPath", previous)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package nali
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var naliBenchmarkSpansSink []Span
|
||||
|
||||
func BenchmarkFindIPSpans(b *testing.B) {
|
||||
line := strings.Repeat(
|
||||
" 1 192.0.2.1 1.25 ms 2 198.51.100.2:443 2.50 ms 3 [2001:db8::3] 3.75 ms via fe80::1%en0\n",
|
||||
8,
|
||||
)
|
||||
if spans := FindIPSpans(line); len(spans) != 32 {
|
||||
b.Fatalf("FindIPSpans() found %d spans, want 32", len(spans))
|
||||
}
|
||||
b.SetBytes(int64(len(line)))
|
||||
b.ReportAllocs()
|
||||
|
||||
for b.Loop() {
|
||||
naliBenchmarkSpansSink = FindIPSpans(line)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
# Performance evidence
|
||||
|
||||
Run benchmarks on the same idle machine, with the same Go toolchain and power
|
||||
settings. The scripts default to `GOMAXPROCS=10`, ten samples, one second per
|
||||
sample, and store raw results below the ignored `.cache/perf` directory.
|
||||
|
||||
```sh
|
||||
scripts/perf/run_benchmarks.sh base
|
||||
scripts/perf/run_benchmarks.sh head
|
||||
scripts/perf/compare_benchmarks.sh .cache/perf/base.bench.txt .cache/perf/head.bench.txt
|
||||
scripts/perf/measure_binaries.sh head
|
||||
```
|
||||
|
||||
If a result crosses a merge threshold without a statistically clear result,
|
||||
repeat both sides with `BENCH_COUNT=20`. Generate CPU and heap profiles for a
|
||||
single representative benchmark with:
|
||||
|
||||
```sh
|
||||
scripts/perf/profile_benchmark.sh ./trace BenchmarkMTRAggregatorSnapshot64TTL4Paths profile-name
|
||||
```
|
||||
|
||||
Record `go version`, `go env GOEXPERIMENT`, the exact commit IDs, machine,
|
||||
operating system, `GOMAXPROCS`, sample count, and any profiler or UPX version in
|
||||
the pull request. Keep raw profiles and binaries as CI artifacts rather than
|
||||
committing them.
|
||||
|
||||
`measure_binaries.sh` records stripped local-platform sizes. Set `UPX_BIN` to an
|
||||
exact UPX executable when that target format is supported; use the same binary
|
||||
and flags for both sides of a comparison.
|
||||
Executable
+28
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -Eeuo pipefail
|
||||
|
||||
if [[ "$#" -ne 2 ]]; then
|
||||
echo "Usage: $0 BASE.bench.txt HEAD.bench.txt" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
CALLER_DIR="${PWD}"
|
||||
|
||||
resolve_input_path() {
|
||||
local path="$1"
|
||||
if [[ "${path}" == /* ]]; then
|
||||
printf '%s\n' "${path}"
|
||||
return
|
||||
fi
|
||||
printf '%s/%s\n' "${CALLER_DIR}" "${path}"
|
||||
}
|
||||
|
||||
BASE_FILE="$(resolve_input_path "$1")"
|
||||
HEAD_FILE="$(resolve_input_path "$2")"
|
||||
|
||||
(
|
||||
cd "${ROOT_DIR}"
|
||||
go tool benchstat "${BASE_FILE}" "${HEAD_FILE}"
|
||||
)
|
||||
Executable
+59
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -Eeuo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
CALLER_DIR="${PWD}"
|
||||
RESULT_NAME="${1:-$(git -C "${ROOT_DIR}" rev-parse --short HEAD)}"
|
||||
RESULT_DIR="${PERF_RESULT_DIR:-${ROOT_DIR}/.cache/perf}"
|
||||
BUILD_DIR="$(mktemp -d)"
|
||||
|
||||
if [[ "${RESULT_DIR}" != /* ]]; then
|
||||
RESULT_DIR="${CALLER_DIR}/${RESULT_DIR}"
|
||||
fi
|
||||
|
||||
cleanup() {
|
||||
rm -rf -- "${BUILD_DIR}"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
mkdir -p "${RESULT_DIR}"
|
||||
OUTPUT_FILE="${RESULT_DIR}/${RESULT_NAME}.sizes.tsv"
|
||||
|
||||
printf 'flavor\tuncompressed_bytes\tupx_bytes\n' >"${OUTPUT_FILE}"
|
||||
|
||||
measure_flavor() {
|
||||
local flavor="$1"
|
||||
local tags="$2"
|
||||
local binary="${BUILD_DIR}/${flavor}"
|
||||
local -a tags_flag=()
|
||||
if [[ -n "${tags}" ]]; then
|
||||
tags_flag=(-tags "${tags}")
|
||||
fi
|
||||
|
||||
go build -buildvcs=false -trimpath "${tags_flag[@]}" -ldflags '-s -w -buildid=' -o "${binary}" .
|
||||
|
||||
local plain_size
|
||||
plain_size="$(wc -c <"${binary}" | tr -d ' ')"
|
||||
local upx_size="n/a"
|
||||
if [[ -n "${UPX_BIN:-}" ]]; then
|
||||
local packed="${binary}.upx"
|
||||
local -a upx_flags
|
||||
read -r -a upx_flags <<<"${UPX_FLAGS:--9}"
|
||||
cp "${binary}" "${packed}"
|
||||
if ! "${UPX_BIN}" "${upx_flags[@]}" "${packed}" >/dev/null; then
|
||||
echo "UPX failed for ${flavor}: ${UPX_BIN}" >&2
|
||||
return 1
|
||||
fi
|
||||
upx_size="$(wc -c <"${packed}" | tr -d ' ')"
|
||||
fi
|
||||
|
||||
printf '%s\t%s\t%s\n' "${flavor}" "${plain_size}" "${upx_size}" >>"${OUTPUT_FILE}"
|
||||
}
|
||||
|
||||
cd "${ROOT_DIR}"
|
||||
measure_flavor nexttrace ''
|
||||
measure_flavor nexttrace-tiny flavor_tiny
|
||||
measure_flavor ntr flavor_ntr
|
||||
|
||||
cat "${OUTPUT_FILE}"
|
||||
Executable
+55
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -Eeuo pipefail
|
||||
|
||||
if [[ "$#" -lt 2 || "$#" -gt 3 ]]; then
|
||||
echo "Usage: $0 PACKAGE BENCHMARK [RESULT_NAME]" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
CALLER_DIR="${PWD}"
|
||||
PACKAGE="$1"
|
||||
BENCHMARK="$2"
|
||||
RESULT_NAME="${3:-$(git -C "${ROOT_DIR}" rev-parse --short HEAD)}"
|
||||
RESULT_DIR="${PERF_RESULT_DIR:-${ROOT_DIR}/.cache/perf}"
|
||||
PROFILE_TIME="${PROFILE_TIME:-30s}"
|
||||
BENCH_GOMAXPROCS="${BENCH_GOMAXPROCS:-10}"
|
||||
|
||||
if [[ "${RESULT_DIR}" != /* ]]; then
|
||||
RESULT_DIR="${CALLER_DIR}/${RESULT_DIR}"
|
||||
fi
|
||||
|
||||
mkdir -p "${RESULT_DIR}"
|
||||
export GOMAXPROCS="${BENCH_GOMAXPROCS}"
|
||||
|
||||
benchmark_list="$(
|
||||
cd "${ROOT_DIR}"
|
||||
go test -run '^$' -list "^${BENCHMARK}$" "${PACKAGE}"
|
||||
)"
|
||||
benchmark_found=false
|
||||
while IFS= read -r name; do
|
||||
if [[ "${name}" == "${BENCHMARK}" ]]; then
|
||||
benchmark_found=true
|
||||
break
|
||||
fi
|
||||
done <<<"${benchmark_list}"
|
||||
if [[ "${benchmark_found}" != true ]]; then
|
||||
echo "Benchmark not found in ${PACKAGE}: ${BENCHMARK}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
(
|
||||
cd "${ROOT_DIR}"
|
||||
go test \
|
||||
-run '^$' \
|
||||
-bench "^${BENCHMARK}$" \
|
||||
-benchtime "${PROFILE_TIME}" \
|
||||
-count 1 \
|
||||
-cpuprofile "${RESULT_DIR}/${RESULT_NAME}.cpu.pprof" \
|
||||
-memprofile "${RESULT_DIR}/${RESULT_NAME}.heap.pprof" \
|
||||
"${PACKAGE}"
|
||||
)
|
||||
|
||||
echo "CPU profile: ${RESULT_DIR}/${RESULT_NAME}.cpu.pprof"
|
||||
echo "heap profile: ${RESULT_DIR}/${RESULT_NAME}.heap.pprof"
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -Eeuo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
CALLER_DIR="${PWD}"
|
||||
RESULT_NAME="${1:-$(git -C "${ROOT_DIR}" rev-parse --short HEAD)}"
|
||||
RESULT_DIR="${PERF_RESULT_DIR:-${ROOT_DIR}/.cache/perf}"
|
||||
BENCH_COUNT="${BENCH_COUNT:-10}"
|
||||
BENCH_TIME="${BENCH_TIME:-1s}"
|
||||
BENCH_GOMAXPROCS="${BENCH_GOMAXPROCS:-10}"
|
||||
|
||||
if [[ "${RESULT_DIR}" != /* ]]; then
|
||||
RESULT_DIR="${CALLER_DIR}/${RESULT_DIR}"
|
||||
fi
|
||||
|
||||
mkdir -p "${RESULT_DIR}"
|
||||
|
||||
export GOMAXPROCS="${BENCH_GOMAXPROCS}"
|
||||
|
||||
(
|
||||
cd "${ROOT_DIR}"
|
||||
go test \
|
||||
-run '^$' \
|
||||
-bench '^Benchmark' \
|
||||
-benchmem \
|
||||
-benchtime "${BENCH_TIME}" \
|
||||
-count "${BENCH_COUNT}" \
|
||||
./dn42 ./util ./trace ./trace/internal ./trace/mtu ./server ./internal/nali
|
||||
) | tee "${RESULT_DIR}/${RESULT_NAME}.bench.txt"
|
||||
|
||||
echo "benchmark results: ${RESULT_DIR}/${RESULT_NAME}.bench.txt"
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
[
|
||||
{
|
||||
"type": "start",
|
||||
"data": {
|
||||
"data_provider": "NextTrace-API",
|
||||
"language": "en",
|
||||
"protocol": "UDP",
|
||||
"resolved_ip": "2001:db8::9",
|
||||
"target": "example.test"
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "mtr_raw",
|
||||
"data": {
|
||||
"iteration": 1,
|
||||
"ttl": 2,
|
||||
"success": true,
|
||||
"ip": "2001:db8::2",
|
||||
"host": "router.example",
|
||||
"rtt_ms": 12.5,
|
||||
"lat": 0,
|
||||
"lng": 0,
|
||||
"mpls": [
|
||||
"[MPLS: Lbl 16000, TC 0, S 1, TTL 63]"
|
||||
],
|
||||
"response": {
|
||||
"kind": "unreachable",
|
||||
"description": "ICMP Host Unreachable",
|
||||
"marker": "!H"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "path_end",
|
||||
"data": {
|
||||
"hop": 2,
|
||||
"reason": "unreachable",
|
||||
"responses": [
|
||||
"ICMP Host Unreachable"
|
||||
],
|
||||
"markers": [
|
||||
"!H"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "complete",
|
||||
"data": {
|
||||
"iteration": 1,
|
||||
"path_end": {
|
||||
"hop": 2,
|
||||
"reason": "unreachable",
|
||||
"responses": [
|
||||
"ICMP Host Unreachable"
|
||||
],
|
||||
"markers": [
|
||||
"!H"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,94 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/trace"
|
||||
)
|
||||
|
||||
var (
|
||||
wsJSONBytesSink []byte
|
||||
wsJSONRequestSink traceRequest
|
||||
)
|
||||
|
||||
func BenchmarkWebSocketJSONMarshalEnvelope(b *testing.B) {
|
||||
envelope := wsEnvelope{
|
||||
Type: "mtr_raw",
|
||||
Data: trace.MTRRawRecord{
|
||||
Iteration: 8,
|
||||
TTL: 12,
|
||||
Success: true,
|
||||
IP: "2001:db8::12",
|
||||
Host: "router.example",
|
||||
RTTMs: 12.75,
|
||||
ASN: "AS64512",
|
||||
Country: "ZZ",
|
||||
City: "Example City",
|
||||
Owner: "Example Network",
|
||||
Lat: 31.25,
|
||||
Lng: 121.5,
|
||||
MPLS: []string{"[MPLS: Lbl 16000, TC 0, S 1, TTL 63]"},
|
||||
Response: &trace.MTRProbeResponse{
|
||||
Kind: trace.MTRResponseTransit,
|
||||
Description: "ICMP Time Exceeded",
|
||||
},
|
||||
},
|
||||
}
|
||||
sample, err := json.Marshal(envelope)
|
||||
if err != nil {
|
||||
b.Fatalf("marshal sample envelope: %v", err)
|
||||
}
|
||||
b.SetBytes(int64(len(sample)))
|
||||
b.ReportAllocs()
|
||||
|
||||
for b.Loop() {
|
||||
encoded, err := json.Marshal(envelope)
|
||||
if err != nil {
|
||||
b.Fatalf("marshal websocket envelope: %v", err)
|
||||
}
|
||||
wsJSONBytesSink = encoded
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkWebSocketJSONUnmarshalRequest(b *testing.B) {
|
||||
payload := []byte(`{"target":"example.test","protocol":"udp","port":33494,"queries":3,"max_hops":64,"timeout_ms":2000,"packet_size":84,"tos":32,"parallel_requests":16,"begin_hop":1,"ipv6_only":true,"data_provider":"NextTrace-API","dot_server":"dns.example:853","always_rdns":true,"disable_maptrace":true,"language":"en","source_address":"2001:db8::10","source_device":"en0","packet_interval":50,"ttl_interval":300,"mode":"mtr","hop_interval_ms":1000,"max_rounds":10}`)
|
||||
var sample traceRequest
|
||||
if err := json.Unmarshal(payload, &sample); err != nil {
|
||||
b.Fatalf("unmarshal sample websocket request: %v", err)
|
||||
}
|
||||
if sample.Target != "example.test" {
|
||||
b.Fatalf("sample Target = %q, want example.test", sample.Target)
|
||||
}
|
||||
if sample.PacketSize == nil || *sample.PacketSize != 84 {
|
||||
b.Fatalf("sample PacketSize = %v, want 84", sample.PacketSize)
|
||||
}
|
||||
if sample.TOS == nil || *sample.TOS != 32 {
|
||||
b.Fatalf("sample TOS = %v, want 32", sample.TOS)
|
||||
}
|
||||
if sample.Mode != "mtr" {
|
||||
b.Fatalf("sample Mode = %q, want mtr", sample.Mode)
|
||||
}
|
||||
if sample.HopIntervalMs != 1000 {
|
||||
b.Fatalf("sample HopIntervalMs = %d, want 1000", sample.HopIntervalMs)
|
||||
}
|
||||
if sample.Protocol != "udp" || !sample.IPv6Only || sample.MaxRounds != 10 {
|
||||
b.Fatalf(
|
||||
"sample representative fields = (protocol=%q, ipv6_only=%v, max_rounds=%d), want (udp, true, 10)",
|
||||
sample.Protocol,
|
||||
sample.IPv6Only,
|
||||
sample.MaxRounds,
|
||||
)
|
||||
}
|
||||
b.SetBytes(int64(len(payload)))
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
|
||||
for b.Loop() {
|
||||
var request traceRequest
|
||||
if err := json.Unmarshal(payload, &request); err != nil {
|
||||
b.Fatalf("unmarshal websocket request: %v", err)
|
||||
}
|
||||
wsJSONRequestSink = request
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/internal/service"
|
||||
"github.com/nxtrace/NTrace-core/trace"
|
||||
)
|
||||
|
||||
func TestWebSocketEnvelopeGolden(t *testing.T) {
|
||||
pathEnd := &service.TraceStopReason{
|
||||
Hop: 2,
|
||||
Reason: trace.StopReasonUnreachable,
|
||||
Responses: []string{"ICMP Host Unreachable"},
|
||||
Markers: []string{"!H"},
|
||||
}
|
||||
envelopes := []wsEnvelope{
|
||||
{
|
||||
Type: "start",
|
||||
Data: gin.H{
|
||||
"target": "example.test",
|
||||
"resolved_ip": "2001:db8::9",
|
||||
"protocol": "UDP",
|
||||
"data_provider": "NextTrace-API",
|
||||
"language": "en",
|
||||
},
|
||||
},
|
||||
{
|
||||
Type: "mtr_raw",
|
||||
Data: trace.MTRRawRecord{
|
||||
Iteration: 1,
|
||||
TTL: 2,
|
||||
Success: true,
|
||||
IP: "2001:db8::2",
|
||||
Host: "router.example",
|
||||
RTTMs: 12.5,
|
||||
MPLS: []string{"[MPLS: Lbl 16000, TC 0, S 1, TTL 63]"},
|
||||
Response: &trace.MTRProbeResponse{
|
||||
Kind: trace.MTRResponseUnreachable,
|
||||
Description: "ICMP Host Unreachable",
|
||||
Marker: "!H",
|
||||
},
|
||||
},
|
||||
},
|
||||
{Type: "path_end", Data: pathEnd},
|
||||
{Type: "complete", Data: gin.H{"iteration": 1, "path_end": pathEnd}},
|
||||
}
|
||||
|
||||
gotJSON, err := json.Marshal(envelopes)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal websocket envelopes: %v", err)
|
||||
}
|
||||
wantJSON, err := os.ReadFile("testdata/ws_envelopes.golden.json")
|
||||
if err != nil {
|
||||
t.Fatalf("read websocket envelope golden: %v", err)
|
||||
}
|
||||
|
||||
var got any
|
||||
if err := json.Unmarshal(gotJSON, &got); err != nil {
|
||||
t.Fatalf("decode generated websocket envelopes: %v", err)
|
||||
}
|
||||
var want any
|
||||
if err := json.Unmarshal(wantJSON, &want); err != nil {
|
||||
t.Fatalf("decode websocket envelope golden: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
formatted, _ := json.MarshalIndent(got, "", " ")
|
||||
t.Fatalf("websocket envelope schema changed\n--- got ---\n%s\n--- want ---\n%s", formatted, wantJSON)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package trace
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/ipgeo"
|
||||
)
|
||||
|
||||
var (
|
||||
benchmarkGeoCacheDataSink *ipgeo.IPGeoData
|
||||
benchmarkGeoCacheValueSink any
|
||||
benchmarkGeoCacheOKSink bool
|
||||
)
|
||||
|
||||
func BenchmarkGeoCacheAccess(b *testing.B) {
|
||||
const (
|
||||
hitKey = "benchmark-geo-cache-hit"
|
||||
missKey = "benchmark-geo-cache-miss"
|
||||
)
|
||||
geoCache.Store(hitKey, &ipgeo.IPGeoData{IP: "1.1.1.1", Asnumber: "13335"})
|
||||
geoCache.Delete(missKey)
|
||||
b.Cleanup(func() {
|
||||
geoCache.Delete(hitKey)
|
||||
geoCache.Delete(missKey)
|
||||
})
|
||||
|
||||
b.Run("Hit", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
var (
|
||||
data *ipgeo.IPGeoData
|
||||
ok bool
|
||||
)
|
||||
for b.Loop() {
|
||||
value, loaded := geoCache.Load(hitKey)
|
||||
if loaded {
|
||||
data, ok = value.(*ipgeo.IPGeoData)
|
||||
} else {
|
||||
data, ok = nil, false
|
||||
}
|
||||
}
|
||||
if !ok || data == nil {
|
||||
b.Fatal("geo cache hit benchmark did not load the seeded value")
|
||||
}
|
||||
benchmarkGeoCacheDataSink = data
|
||||
benchmarkGeoCacheOKSink = ok
|
||||
})
|
||||
|
||||
b.Run("Miss", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
var (
|
||||
value any
|
||||
ok bool
|
||||
)
|
||||
for b.Loop() {
|
||||
value, ok = geoCache.Load(missKey)
|
||||
}
|
||||
if ok {
|
||||
b.Fatal("geo cache miss benchmark unexpectedly loaded a value")
|
||||
}
|
||||
benchmarkGeoCacheValueSink = value
|
||||
benchmarkGeoCacheOKSink = ok
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/gopacket"
|
||||
"github.com/google/gopacket/layers"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
)
|
||||
|
||||
var (
|
||||
decodeBenchmarkFinishSink time.Time
|
||||
decodeBenchmarkSrcPortSink int
|
||||
decodeBenchmarkSeqSink int
|
||||
decodeBenchmarkAckSink int
|
||||
decodeBenchmarkDataSink []byte
|
||||
decodeBenchmarkResponseSink ICMPResponse
|
||||
decodeBenchmarkPeerSink net.Addr
|
||||
decodeBenchmarkOKSink bool
|
||||
)
|
||||
|
||||
func BenchmarkDecodeICMPSocketMessage(b *testing.B) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ipVersion int
|
||||
dstIP net.IP
|
||||
peerIP net.IP
|
||||
echoID int
|
||||
seq int
|
||||
}{
|
||||
{
|
||||
name: "IPv4TimeExceeded",
|
||||
ipVersion: 4,
|
||||
dstIP: net.ParseIP("192.0.2.9"),
|
||||
peerIP: net.ParseIP("198.51.100.1"),
|
||||
echoID: 401,
|
||||
seq: 1234,
|
||||
},
|
||||
{
|
||||
name: "IPv6TimeExceeded",
|
||||
ipVersion: 6,
|
||||
dstIP: net.ParseIP("2001:db8::9"),
|
||||
peerIP: net.ParseIP("2001:db8::1"),
|
||||
echoID: 402,
|
||||
seq: 2345,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
b.Run(tt.name, func(b *testing.B) {
|
||||
inner := benchmarkEmbeddedICMPPacket(tt.ipVersion, tt.dstIP, tt.echoID, tt.seq)
|
||||
raw := benchmarkICMPTimeExceeded(b, tt.ipVersion, inner)
|
||||
spec := &ICMPSpec{IPVersion: tt.ipVersion, EchoID: tt.echoID, DstIP: tt.dstIP}
|
||||
msg := ReceivedMessage{Peer: &net.IPAddr{IP: tt.peerIP}, Msg: raw}
|
||||
if _, seq, response, ok := spec.decodeICMPSocketMessage(msg); !ok || seq != tt.seq || response.Kind != ICMPResponseTransit {
|
||||
b.Fatalf("decodeICMPSocketMessage() = (_, %d, %#v, %v), want (_, %d, Transit, true)", seq, response, ok, tt.seq)
|
||||
}
|
||||
b.SetBytes(int64(len(raw)))
|
||||
b.ReportAllocs()
|
||||
|
||||
for b.Loop() {
|
||||
decodeBenchmarkFinishSink, decodeBenchmarkSeqSink, decodeBenchmarkResponseSink, decodeBenchmarkOKSink = spec.decodeICMPSocketMessage(msg)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkDecodeTCPProbePacket(b *testing.B) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ipVersion int
|
||||
dstPort int
|
||||
packet func(*testing.B) gopacket.Packet
|
||||
}{
|
||||
{
|
||||
name: "IPv4RSTAck",
|
||||
ipVersion: 4,
|
||||
dstPort: 443,
|
||||
packet: func(b *testing.B) gopacket.Packet {
|
||||
return benchmarkSerializeTCPPacket(b, &layers.IPv4{
|
||||
Version: 4,
|
||||
IHL: 5,
|
||||
Protocol: layers.IPProtocolTCP,
|
||||
SrcIP: net.ParseIP("198.51.100.1").To4(),
|
||||
DstIP: net.ParseIP("192.0.2.9").To4(),
|
||||
}, &layers.TCP{SrcPort: 443, DstPort: 32100, ACK: true, RST: true, Ack: 200})
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "IPv6SYNAck",
|
||||
ipVersion: 6,
|
||||
dstPort: 8443,
|
||||
packet: func(b *testing.B) gopacket.Packet {
|
||||
return benchmarkSerializeTCPPacket(b, &layers.IPv6{
|
||||
Version: 6,
|
||||
NextHeader: layers.IPProtocolTCP,
|
||||
SrcIP: net.ParseIP("2001:db8::1"),
|
||||
DstIP: net.ParseIP("2001:db8::9"),
|
||||
}, &layers.TCP{SrcPort: 8443, DstPort: 45678, ACK: true, SYN: true, Ack: 91})
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
b.Run(tt.name, func(b *testing.B) {
|
||||
packet := tt.packet(b)
|
||||
if _, _, _, _, ok := decodeTCPProbePacket(tt.ipVersion, tt.dstPort, packet); !ok {
|
||||
b.Fatal("decodeTCPProbePacket() ok = false")
|
||||
}
|
||||
b.ReportAllocs()
|
||||
|
||||
for b.Loop() {
|
||||
decodeBenchmarkSrcPortSink, decodeBenchmarkSeqSink, decodeBenchmarkAckSink, decodeBenchmarkPeerSink, decodeBenchmarkOKSink = decodeTCPProbePacket(tt.ipVersion, tt.dstPort, packet)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkDecodeUDPSocketMessage(b *testing.B) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ipVersion int
|
||||
dstIP net.IP
|
||||
peerIP net.IP
|
||||
srcPort int
|
||||
dstPort int
|
||||
}{
|
||||
{
|
||||
name: "IPv4TimeExceeded",
|
||||
ipVersion: 4,
|
||||
dstIP: net.ParseIP("192.0.2.9"),
|
||||
peerIP: net.ParseIP("198.51.100.1"),
|
||||
srcPort: 40000,
|
||||
dstPort: 33494,
|
||||
},
|
||||
{
|
||||
name: "IPv6TimeExceeded",
|
||||
ipVersion: 6,
|
||||
dstIP: net.ParseIP("2001:db8::9"),
|
||||
peerIP: net.ParseIP("2001:db8::1"),
|
||||
srcPort: 40001,
|
||||
dstPort: 33494,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
b.Run(tt.name, func(b *testing.B) {
|
||||
inner := benchmarkEmbeddedUDPPacket(tt.ipVersion, tt.dstIP, tt.srcPort, tt.dstPort)
|
||||
raw := benchmarkICMPTimeExceeded(b, tt.ipVersion, inner)
|
||||
spec := &UDPSpec{IPVersion: tt.ipVersion, DstIP: tt.dstIP, DstPort: tt.dstPort}
|
||||
msg := ReceivedMessage{Peer: &net.IPAddr{IP: tt.peerIP}, Msg: raw}
|
||||
if _, data, response, ok := spec.decodeICMPSocketMessage(msg); !ok || len(data) != len(inner) || response.Kind != ICMPResponseTransit {
|
||||
b.Fatalf("decodeICMPSocketMessage() = (_, %d bytes, %#v, %v), want (_, %d bytes, Transit, true)", len(data), response, ok, len(inner))
|
||||
}
|
||||
b.SetBytes(int64(len(raw)))
|
||||
b.ReportAllocs()
|
||||
|
||||
for b.Loop() {
|
||||
decodeBenchmarkFinishSink, decodeBenchmarkDataSink, decodeBenchmarkResponseSink, decodeBenchmarkOKSink = spec.decodeICMPSocketMessage(msg)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func benchmarkICMPTimeExceeded(b *testing.B, ipVersion int, inner []byte) []byte {
|
||||
b.Helper()
|
||||
|
||||
var messageType icmp.Type = ipv4.ICMPTypeTimeExceeded
|
||||
if ipVersion == 6 {
|
||||
messageType = ipv6.ICMPTypeTimeExceeded
|
||||
}
|
||||
raw, err := (&icmp.Message{
|
||||
Type: messageType,
|
||||
Code: 0,
|
||||
Body: &icmp.TimeExceeded{Data: inner},
|
||||
}).Marshal(nil)
|
||||
if err != nil {
|
||||
b.Fatalf("marshal ICMP time-exceeded message: %v", err)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
func benchmarkEmbeddedICMPPacket(ipVersion int, dstIP net.IP, echoID, seq int) []byte {
|
||||
if ipVersion == 4 {
|
||||
packet := make([]byte, 28)
|
||||
packet[0] = 0x45
|
||||
packet[9] = 1
|
||||
copy(packet[16:20], dstIP.To4())
|
||||
binary.BigEndian.PutUint16(packet[24:26], uint16(echoID))
|
||||
binary.BigEndian.PutUint16(packet[26:28], uint16(seq))
|
||||
return packet
|
||||
}
|
||||
|
||||
packet := make([]byte, 48)
|
||||
packet[0] = 0x60
|
||||
packet[6] = 58
|
||||
copy(packet[24:40], dstIP.To16())
|
||||
binary.BigEndian.PutUint16(packet[44:46], uint16(echoID))
|
||||
binary.BigEndian.PutUint16(packet[46:48], uint16(seq))
|
||||
return packet
|
||||
}
|
||||
|
||||
func benchmarkEmbeddedUDPPacket(ipVersion int, dstIP net.IP, srcPort, dstPort int) []byte {
|
||||
if ipVersion == 4 {
|
||||
packet := make([]byte, 28)
|
||||
packet[0] = 0x45
|
||||
packet[9] = 17
|
||||
copy(packet[16:20], dstIP.To4())
|
||||
binary.BigEndian.PutUint16(packet[20:22], uint16(srcPort))
|
||||
binary.BigEndian.PutUint16(packet[22:24], uint16(dstPort))
|
||||
return packet
|
||||
}
|
||||
|
||||
packet := make([]byte, 48)
|
||||
packet[0] = 0x60
|
||||
packet[6] = 17
|
||||
copy(packet[24:40], dstIP.To16())
|
||||
binary.BigEndian.PutUint16(packet[40:42], uint16(srcPort))
|
||||
binary.BigEndian.PutUint16(packet[42:44], uint16(dstPort))
|
||||
return packet
|
||||
}
|
||||
|
||||
func benchmarkSerializeTCPPacket(b *testing.B, ipLayer gopacket.NetworkLayer, tcp *layers.TCP) gopacket.Packet {
|
||||
b.Helper()
|
||||
|
||||
if err := tcp.SetNetworkLayerForChecksum(ipLayer); err != nil {
|
||||
b.Fatalf("set TCP network layer: %v", err)
|
||||
}
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
opts := gopacket.SerializeOptions{ComputeChecksums: true, FixLengths: true}
|
||||
switch ip := ipLayer.(type) {
|
||||
case *layers.IPv4:
|
||||
if err := gopacket.SerializeLayers(buf, opts, ip, tcp); err != nil {
|
||||
b.Fatalf("serialize IPv4 TCP packet: %v", err)
|
||||
}
|
||||
return gopacket.NewPacket(buf.Bytes(), layers.LayerTypeIPv4, gopacket.NoCopy)
|
||||
case *layers.IPv6:
|
||||
if err := gopacket.SerializeLayers(buf, opts, ip, tcp); err != nil {
|
||||
b.Fatalf("serialize IPv6 TCP packet: %v", err)
|
||||
}
|
||||
return gopacket.NewPacket(buf.Bytes(), layers.LayerTypeIPv6, gopacket.NoCopy)
|
||||
default:
|
||||
b.Fatalf("unexpected IP layer type %T", ipLayer)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package trace
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
mtrBenchmarkTTLCount = 64
|
||||
mtrBenchmarkPathCount = 4
|
||||
)
|
||||
|
||||
var (
|
||||
mtrBenchmarkStatsSink []MTRHopStat
|
||||
mtrBenchmarkCloneSink *MTRAggregator
|
||||
)
|
||||
|
||||
func newMTRBenchmarkResult() *Result {
|
||||
res := &Result{Hops: make([][]Hop, mtrBenchmarkTTLCount)}
|
||||
for ttl := 1; ttl <= mtrBenchmarkTTLCount; ttl++ {
|
||||
attempts := make([]Hop, 0, mtrBenchmarkPathCount)
|
||||
for path := 1; path <= mtrBenchmarkPathCount; path++ {
|
||||
attempts = append(attempts, Hop{
|
||||
Success: true,
|
||||
Address: &net.IPAddr{IP: net.IPv4(198, 18, byte(ttl), byte(path))},
|
||||
Hostname: fmt.Sprintf("hop-%02d-path-%d.example", ttl, path),
|
||||
TTL: ttl,
|
||||
RTT: time.Duration(ttl*path) * time.Millisecond,
|
||||
MPLS: []string{
|
||||
fmt.Sprintf("[MPLS: Lbl %d, TC 0, S 0, TTL %d]", ttl*100+path, ttl),
|
||||
fmt.Sprintf("[MPLS: Lbl %d, TC 1, S 1, TTL %d]", ttl*1000+path, ttl),
|
||||
},
|
||||
})
|
||||
}
|
||||
res.Hops[ttl-1] = attempts
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func newMTRBenchmarkPartialResult(ttl int) *Result {
|
||||
full := newMTRBenchmarkResult()
|
||||
partial := &Result{Hops: make([][]Hop, len(full.Hops))}
|
||||
partial.Hops[ttl-1] = full.Hops[ttl-1]
|
||||
return partial
|
||||
}
|
||||
|
||||
func newPopulatedMTRBenchmarkAggregator(res *Result) *MTRAggregator {
|
||||
agg := NewMTRAggregator()
|
||||
agg.Update(res, mtrBenchmarkPathCount)
|
||||
return agg
|
||||
}
|
||||
|
||||
func BenchmarkMTRAggregatorUpdate64TTL4Paths(b *testing.B) {
|
||||
res := newMTRBenchmarkResult()
|
||||
agg := newPopulatedMTRBenchmarkAggregator(res)
|
||||
b.ReportAllocs()
|
||||
|
||||
for b.Loop() {
|
||||
mtrBenchmarkStatsSink = agg.Update(res, mtrBenchmarkPathCount)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkMTRAggregatorClone64TTL4Paths(b *testing.B) {
|
||||
res := newMTRBenchmarkResult()
|
||||
agg := newPopulatedMTRBenchmarkAggregator(res)
|
||||
b.ReportAllocs()
|
||||
|
||||
for b.Loop() {
|
||||
mtrBenchmarkCloneSink = agg.Clone()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkMTRAggregatorSnapshot64TTL4Paths(b *testing.B) {
|
||||
res := newMTRBenchmarkResult()
|
||||
agg := newPopulatedMTRBenchmarkAggregator(res)
|
||||
b.ReportAllocs()
|
||||
|
||||
for b.Loop() {
|
||||
mtrBenchmarkStatsSink = agg.Snapshot()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkMTRAggregatorPreviewCloneUpdate64TTL4Paths(b *testing.B) {
|
||||
res := newMTRBenchmarkResult()
|
||||
agg := newPopulatedMTRBenchmarkAggregator(res)
|
||||
partial := newMTRBenchmarkPartialResult(mtrBenchmarkTTLCount / 2)
|
||||
b.ReportAllocs()
|
||||
|
||||
for b.Loop() {
|
||||
preview := agg.Clone()
|
||||
mtrBenchmarkStatsSink = preview.Update(partial, mtrBenchmarkPathCount)
|
||||
}
|
||||
b.ReportMetric(1, "affected-TTLs/op")
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package trace
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMTRAggregatorSnapshotGolden(t *testing.T) {
|
||||
agg := NewMTRAggregator()
|
||||
|
||||
agg.Update(mtrGoldenResult(1,
|
||||
Hop{
|
||||
Success: true,
|
||||
Address: &net.IPAddr{IP: net.ParseIP("192.0.2.1")},
|
||||
Hostname: "edge.example",
|
||||
TTL: 1,
|
||||
RTT: 10 * time.Millisecond,
|
||||
MPLS: []string{
|
||||
"[MPLS: Lbl 200, TC 0, S 1, TTL 63]",
|
||||
"[MPLS: Lbl 100, TC 0, S 0, TTL 64]",
|
||||
},
|
||||
},
|
||||
Hop{TTL: 1},
|
||||
), 2)
|
||||
agg.Update(mtrGoldenResult(2, Hop{
|
||||
Success: true,
|
||||
Address: &net.IPAddr{IP: net.ParseIP("198.51.100.1")},
|
||||
Hostname: "core-a.example",
|
||||
TTL: 2,
|
||||
RTT: 20 * time.Millisecond,
|
||||
}), 1)
|
||||
agg.Update(mtrGoldenResult(2, Hop{
|
||||
Success: true,
|
||||
Address: &net.IPAddr{IP: net.ParseIP("198.51.100.2")},
|
||||
Hostname: "core-b.example",
|
||||
TTL: 2,
|
||||
RTT: 30 * time.Millisecond,
|
||||
}), 1)
|
||||
agg.Update(mtrGoldenResult(2, Hop{TTL: 2}), 1)
|
||||
agg.Update(mtrGoldenResult(3, Hop{
|
||||
Success: true,
|
||||
Address: &net.IPAddr{IP: net.ParseIP("2001:db8::3")},
|
||||
TTL: 3,
|
||||
RTT: 40 * time.Millisecond,
|
||||
}), 1)
|
||||
|
||||
got, err := json.MarshalIndent(MTRSnapshot{Iteration: 3, Stats: agg.Snapshot()}, "", " ")
|
||||
if err != nil {
|
||||
t.Fatalf("marshal MTR snapshot: %v", err)
|
||||
}
|
||||
got = append(got, '\n')
|
||||
|
||||
want, err := os.ReadFile("testdata/mtr_snapshot.golden.json")
|
||||
if err != nil {
|
||||
t.Fatalf("read MTR snapshot golden: %v", err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("MTR snapshot changed\n--- got ---\n%s--- want ---\n%s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func mtrGoldenResult(ttl int, attempts ...Hop) *Result {
|
||||
res := &Result{Hops: make([][]Hop, ttl)}
|
||||
res.Hops[ttl-1] = attempts
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package mtu
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"net"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var (
|
||||
embeddedUDPBenchmarkPacketSink embeddedUDPPacket
|
||||
embeddedUDPBenchmarkOKSink bool
|
||||
)
|
||||
|
||||
func BenchmarkParseEmbeddedUDPPacket(b *testing.B) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ipVersion int
|
||||
packet []byte
|
||||
}{
|
||||
{name: "IPv4", ipVersion: 4, packet: benchmarkEmbeddedIPv4UDP()},
|
||||
{name: "IPv6ExtensionHeader", ipVersion: 6, packet: benchmarkEmbeddedIPv6UDP()},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
b.Run(tt.name, func(b *testing.B) {
|
||||
if _, ok := parseEmbeddedUDPPacket(tt.packet, tt.ipVersion); !ok {
|
||||
b.Fatal("parseEmbeddedUDPPacket() ok = false")
|
||||
}
|
||||
b.SetBytes(int64(len(tt.packet)))
|
||||
b.ReportAllocs()
|
||||
|
||||
for b.Loop() {
|
||||
embeddedUDPBenchmarkPacketSink, embeddedUDPBenchmarkOKSink = parseEmbeddedUDPPacket(tt.packet, tt.ipVersion)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func benchmarkEmbeddedIPv4UDP() []byte {
|
||||
dstIP := net.ParseIP("203.0.113.9").To4()
|
||||
packet := make([]byte, 28)
|
||||
packet[0] = 0x45
|
||||
packet[9] = 17
|
||||
copy(packet[16:20], dstIP)
|
||||
binary.BigEndian.PutUint16(packet[20:22], 40000)
|
||||
binary.BigEndian.PutUint16(packet[22:24], 33494)
|
||||
return packet
|
||||
}
|
||||
|
||||
func benchmarkEmbeddedIPv6UDP() []byte {
|
||||
dstIP := net.ParseIP("2001:db8::9").To16()
|
||||
packet := make([]byte, 56)
|
||||
packet[0] = 0x60
|
||||
packet[6] = 0
|
||||
copy(packet[24:40], dstIP)
|
||||
packet[40] = 17
|
||||
packet[41] = 0
|
||||
binary.BigEndian.PutUint16(packet[48:50], 40001)
|
||||
binary.BigEndian.PutUint16(packet[50:52], 33494)
|
||||
return packet
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
{
|
||||
"iteration": 3,
|
||||
"stats": [
|
||||
{
|
||||
"ttl": 1,
|
||||
"host": "edge.example",
|
||||
"ip": "192.0.2.1",
|
||||
"loss_percent": 50,
|
||||
"snt": 2,
|
||||
"last_ms": 10,
|
||||
"avg_ms": 10,
|
||||
"best_ms": 10,
|
||||
"wrst_ms": 10,
|
||||
"stdev_ms": 0,
|
||||
"mpls": [
|
||||
"[MPLS: Lbl 100, TC 0, S 0, TTL 64]",
|
||||
"[MPLS: Lbl 200, TC 0, S 1, TTL 63]"
|
||||
],
|
||||
"received": 1
|
||||
},
|
||||
{
|
||||
"ttl": 2,
|
||||
"host": "core-a.example",
|
||||
"ip": "198.51.100.1",
|
||||
"loss_percent": 0,
|
||||
"snt": 1,
|
||||
"last_ms": 20,
|
||||
"avg_ms": 20,
|
||||
"best_ms": 20,
|
||||
"wrst_ms": 20,
|
||||
"stdev_ms": 0,
|
||||
"received": 1
|
||||
},
|
||||
{
|
||||
"ttl": 2,
|
||||
"host": "core-b.example",
|
||||
"ip": "198.51.100.2",
|
||||
"loss_percent": 0,
|
||||
"snt": 1,
|
||||
"last_ms": 30,
|
||||
"avg_ms": 30,
|
||||
"best_ms": 30,
|
||||
"wrst_ms": 30,
|
||||
"stdev_ms": 0,
|
||||
"received": 1
|
||||
},
|
||||
{
|
||||
"ttl": 2,
|
||||
"loss_percent": 100,
|
||||
"snt": 1,
|
||||
"last_ms": 0,
|
||||
"avg_ms": 0,
|
||||
"best_ms": 0,
|
||||
"wrst_ms": 0,
|
||||
"stdev_ms": 0,
|
||||
"received": 0
|
||||
},
|
||||
{
|
||||
"ttl": 3,
|
||||
"ip": "2001:db8::3",
|
||||
"loss_percent": 0,
|
||||
"snt": 1,
|
||||
"last_ms": 40,
|
||||
"avg_ms": 40,
|
||||
"best_ms": 40,
|
||||
"wrst_ms": 40,
|
||||
"stdev_ms": 0,
|
||||
"received": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
benchmarkGeoHTTPConcurrency = http.DefaultMaxIdleConnsPerHost
|
||||
benchmarkGeoHTTPClientCount = 4
|
||||
)
|
||||
|
||||
var (
|
||||
benchmarkGeoHTTPBytesSink int64
|
||||
benchmarkGeoHTTPClientSink *http.Client
|
||||
)
|
||||
|
||||
func BenchmarkNewGeoHTTPClient(b *testing.B) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = io.WriteString(w, "geo")
|
||||
}))
|
||||
b.Cleanup(server.Close)
|
||||
|
||||
b.Run("Construct", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
var client *http.Client
|
||||
for b.Loop() {
|
||||
client = NewGeoHTTPClient(5 * time.Second)
|
||||
}
|
||||
b.ReportMetric(1, "clients/op")
|
||||
benchmarkGeoHTTPClientSink = client
|
||||
})
|
||||
|
||||
b.Run("Sequential", func(b *testing.B) {
|
||||
client := NewGeoHTTPClient(5 * time.Second)
|
||||
b.Cleanup(client.CloseIdleConnections)
|
||||
|
||||
b.ReportAllocs()
|
||||
var total int64
|
||||
for b.Loop() {
|
||||
n, err := runGeoHTTPBenchmarkRequest(client, server.URL)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
total += n
|
||||
}
|
||||
benchmarkGeoHTTPBytesSink = total
|
||||
})
|
||||
|
||||
b.Run("Concurrent2", func(b *testing.B) {
|
||||
client := NewGeoHTTPClient(5 * time.Second)
|
||||
b.Cleanup(client.CloseIdleConnections)
|
||||
results := make([]int64, benchmarkGeoHTTPConcurrency)
|
||||
errs := make([]error, benchmarkGeoHTTPConcurrency)
|
||||
|
||||
b.ReportAllocs()
|
||||
var total int64
|
||||
for b.Loop() {
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(benchmarkGeoHTTPConcurrency)
|
||||
for i := 0; i < benchmarkGeoHTTPConcurrency; i++ {
|
||||
go func(index int) {
|
||||
defer wg.Done()
|
||||
results[index], errs[index] = runGeoHTTPBenchmarkRequest(client, server.URL)
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
for i, err := range errs {
|
||||
if err != nil {
|
||||
b.Fatalf("request %d: %v", i, err)
|
||||
}
|
||||
total += results[i]
|
||||
}
|
||||
}
|
||||
b.ReportMetric(benchmarkGeoHTTPConcurrency, "requests/op")
|
||||
benchmarkGeoHTTPBytesSink = total
|
||||
})
|
||||
|
||||
b.Run("MultiClientSequential", func(b *testing.B) {
|
||||
clients := newGeoHTTPBenchmarkClients(benchmarkGeoHTTPClientCount)
|
||||
b.Cleanup(func() { closeGeoHTTPBenchmarkClients(clients) })
|
||||
warmGeoHTTPBenchmarkClients(b, clients, server.URL)
|
||||
|
||||
b.ReportAllocs()
|
||||
var total int64
|
||||
clientIndex := 0
|
||||
for b.Loop() {
|
||||
n, err := runGeoHTTPBenchmarkRequest(clients[clientIndex], server.URL)
|
||||
if err != nil {
|
||||
b.Fatalf("client %d: %v", clientIndex, err)
|
||||
}
|
||||
total += n
|
||||
clientIndex++
|
||||
if clientIndex == len(clients) {
|
||||
clientIndex = 0
|
||||
}
|
||||
}
|
||||
b.ReportMetric(benchmarkGeoHTTPClientCount, "clients/set")
|
||||
b.ReportMetric(1, "requests/op")
|
||||
benchmarkGeoHTTPBytesSink = total
|
||||
})
|
||||
|
||||
b.Run("MultiClientConcurrent", func(b *testing.B) {
|
||||
clients := newGeoHTTPBenchmarkClients(benchmarkGeoHTTPClientCount)
|
||||
b.Cleanup(func() { closeGeoHTTPBenchmarkClients(clients) })
|
||||
warmGeoHTTPBenchmarkClients(b, clients, server.URL)
|
||||
results := make([]int64, benchmarkGeoHTTPClientCount)
|
||||
errs := make([]error, benchmarkGeoHTTPClientCount)
|
||||
|
||||
b.ReportAllocs()
|
||||
var total int64
|
||||
for b.Loop() {
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(benchmarkGeoHTTPClientCount)
|
||||
for i, client := range clients {
|
||||
go func(index int, requestClient *http.Client) {
|
||||
defer wg.Done()
|
||||
results[index], errs[index] = runGeoHTTPBenchmarkRequest(requestClient, server.URL)
|
||||
}(i, client)
|
||||
}
|
||||
wg.Wait()
|
||||
for i, err := range errs {
|
||||
if err != nil {
|
||||
b.Fatalf("client %d: %v", i, err)
|
||||
}
|
||||
total += results[i]
|
||||
}
|
||||
}
|
||||
b.ReportMetric(benchmarkGeoHTTPClientCount, "clients/set")
|
||||
b.ReportMetric(benchmarkGeoHTTPClientCount, "requests/op")
|
||||
benchmarkGeoHTTPBytesSink = total
|
||||
})
|
||||
}
|
||||
|
||||
func newGeoHTTPBenchmarkClients(count int) []*http.Client {
|
||||
clients := make([]*http.Client, count)
|
||||
for i := range clients {
|
||||
clients[i] = NewGeoHTTPClient(5 * time.Second)
|
||||
}
|
||||
return clients
|
||||
}
|
||||
|
||||
func closeGeoHTTPBenchmarkClients(clients []*http.Client) {
|
||||
for _, client := range clients {
|
||||
client.CloseIdleConnections()
|
||||
}
|
||||
}
|
||||
|
||||
func warmGeoHTTPBenchmarkClients(b *testing.B, clients []*http.Client, url string) {
|
||||
b.Helper()
|
||||
for i, client := range clients {
|
||||
if _, err := runGeoHTTPBenchmarkRequest(client, url); err != nil {
|
||||
b.Fatalf("warm client %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func runGeoHTTPBenchmarkRequest(client *http.Client, url string) (int64, error) {
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n, readErr := io.Copy(io.Discard, resp.Body)
|
||||
closeErr := resp.Body.Close()
|
||||
if readErr != nil {
|
||||
return 0, readErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
return 0, closeErr
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return 0, fmt.Errorf("unexpected HTTP status %s", resp.Status)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
Reference in new issue
Block a user