修复 MTR 调度 goroutine 泄漏

This commit is contained in:
tsosunchia committed 2026-03-15 22:11:44 +08:00
1 parent fe8f1aea75
commit 0b0c6662e8
14 files changed
+466 -260

No files matched your search

+51 -22
View File
@@ -370,6 +370,31 @@ nexttrace --no-color 1.1.1.1
export NO_COLOR=1
```
#### Advanced tuning quick guide
| Flag | What it controls | Default / starting point | When to change it |
| --- | --- | --- | --- |
| `--queries` | Samples per hop in normal traceroute; explicit probe count per hop in MTR | traceroute: `3`; MTR report: `10` when omitted; MTR TUI/raw: unlimited when omitted | Raise to `5-10` on unstable paths |
| `--max-attempts` | Hard cap on probe packets per hop | auto-sized from `--queries` | Raise on lossy links when replies arrive slowly |
| `--parallel-requests` | Total in-flight probes across TTLs | `18` | Use `1` on multipath/load-balanced paths; keep `6-18` on stable links |
| `--send-time` | Gap between packets inside one TTL group | `50ms` | Raise to `100-200ms` on rate-limited devices; ignored in MTR |
| `--ttl-time` | Gap between TTL groups in traceroute; per-hop interval in MTR | traceroute: `300ms`; MTR: `1000ms` when omitted | Lower to speed up; raise on remote/rate-limited paths |
| `--timeout` | Per-probe timeout | `1000ms` | Raise to `2000-3000ms` for intercontinental or high-loss paths |
| `--psize` | Payload size | `52` bytes | Raise only for MTU or large-packet testing |
These probe knobs are CLI-only today; `nt_config.yaml` does not yet store them. If you want reusable profiles, keep them in shell aliases or small wrapper scripts.
```bash
# Conservative profile for multipath or ECMP networks
nexttrace --parallel-requests 1 --send-time 100 --ttl-time 500 --timeout 2000 example.com
# Faster profile for stable single-path networks
nexttrace --parallel-requests 18 --send-time 20 --ttl-time 150 example.com
# Lossy long-haul profile
nexttrace --queries 5 --max-attempts 10 --timeout 2500 example.com
```
#### `NextTrace` supports MTR (My Traceroute) continuous probing mode
```bash
@@ -630,14 +655,17 @@ Arguments:
--icmp-mode Windows ONLY: Choose the method to listen
for ICMP packets (1=Socket, 2=WinDivert;
0=Auto)
-q --queries Set the number of latency samples to
display for each hop. Default: 3
--max-attempts Set the maximum number of probe packets
per hop (instead of a fixed auto value)
--parallel-requests Set ParallelRequests number. It should be
1 when there is a multi-routing. Default:
18
-q --queries Latency samples per hop. Increase to 5-10
on unstable paths for a steadier view.
Default: 3
--max-attempts Advanced: hard cap on probe packets per
hop. Leave unset for auto sizing; raise on
lossy links if --queries is not enough
--parallel-requests Advanced: total concurrent in-flight
probes across TTLs. Use 1 on
multipath/load-balanced paths; 6-18 is a
good starting range on stable links.
Default: 18
-m --max-hops Set the max number of hops (max TTL to be
reached). Default: 30
-d --data-provider Choose IP Geograph Data Provider [IP.SB,
@@ -678,20 +706,21 @@ Arguments:
--listen Set listen address for web console (e.g.
127.0.0.1:30080)
--deploy Start the Gin powered web console
-z --send-time Set how many [milliseconds] between
sending each packet. Default: 50ms.
Ignored in MTR mode. Default: 50
-i --ttl-time Interval [ms] between TTL groups in normal
traceroute (default: 300ms). In MTR mode
(--mtr/-r/-w, including --raw), sets
per-hop probe interval: how long between
successive probes to the same hop
(default: 1000ms when omitted). Default:
300
--timeout The number of [milliseconds] to keep probe
sockets open before giving up on the
connection. Default: 1000
--psize Set the payload size. Default: 52
-z --send-time Advanced: per-packet gap [ms] inside the
same TTL group. Lower is faster; raise to
100-200ms on rate-limited links. Ignored
in MTR mode. Default: 50
-i --ttl-time Advanced: TTL-group interval [ms] in
normal traceroute. In MTR mode
(--mtr/-r/-w, including --raw), this
becomes per-hop probe interval. 500-1000ms
is a good MTR starting range
--timeout Per-probe timeout [ms]. Raise to 2000-3000
on slow intercontinental or high-loss
paths. Default: 1000
--psize Payload size in bytes. Keep 52 for normal
routing checks; raise only for MTU or
large-packet testing. Default: 52
--dot-server Use DoT Server for DNS Parse [dnssb,
aliyun, dnspod, google, cloudflare]
-g --language Choose the language for displaying [en,
+51 -22
View File
@@ -366,6 +366,31 @@ nexttrace --no-color 1.1.1.1
export NO_COLOR=1
```
#### 高级参数调优速查
| 参数 | 控制内容 | 默认值 / 起步建议 | 什么时候调 |
| --- | --- | --- | --- |
| `--queries` | 常规 traceroute 的每跳采样数;MTR 中显式指定每跳探测次数 | traceroute: `3`;MTR report: 未指定时 `10`;MTR TUI/raw: 未指定时无限 | 链路抖动大时可升到 `5-10` |
| `--max-attempts` | 每跳最大发包上限 | 默认按 `--queries` 自动推导 | 丢包严重、回包慢时增大 |
| `--parallel-requests` | 跨 TTL 的总并发 in-flight 探测数 | `18` | 多路径/负载均衡链路用 `1`;稳定链路一般 `6-18` |
| `--send-time` | 同一 TTL 组内相邻探测包间隔 | `50ms` | 设备限速时升到 `100-200ms`;MTR 下忽略 |
| `--ttl-time` | 常规 traceroute 的 TTL 组间隔;MTR 的每跳探测间隔 | traceroute: `300ms`;MTR: 未指定时 `1000ms` | 想加速就调低;远程/限速链路调高 |
| `--timeout` | 单个探测包超时 | `1000ms` | 跨洲或高丢包链路升到 `2000-3000ms` |
| `--psize` | 载荷大小 | `52` 字节 | 只在 MTU 或大包探测时增大 |
这些探测参数目前仍是 CLI 级配置,`nt_config.yaml` 还不能直接保存它们。若要复用一组调优参数,建议写成 shell alias 或小脚本。
```bash
# 适合多路径 / ECMP 的保守配置
nexttrace --parallel-requests 1 --send-time 100 --ttl-time 500 --timeout 2000 example.com
# 适合稳定单路径链路的快速配置
nexttrace --parallel-requests 18 --send-time 20 --ttl-time 150 example.com
# 适合高丢包长途链路的配置
nexttrace --queries 5 --max-attempts 10 --timeout 2500 example.com
```
#### `NextTrace` 支持 MTR(My Traceroute)连续探测模式
```bash
@@ -610,14 +635,17 @@ Arguments:
--icmp-mode Windows ONLY: Choose the method to listen
for ICMP packets (1=Socket, 2=WinDivert;
0=Auto)
-q --queries Set the number of latency samples to
display for each hop. Default: 3
--max-attempts Set the maximum number of probe packets
per hop (instead of a fixed auto value)
--parallel-requests Set ParallelRequests number. It should be
1 when there is a multi-routing. Default:
18
-q --queries Latency samples per hop. Increase to 5-10
on unstable paths for a steadier view.
Default: 3
--max-attempts Advanced: hard cap on probe packets per
hop. Leave unset for auto sizing; raise on
lossy links if --queries is not enough
--parallel-requests Advanced: total concurrent in-flight
probes across TTLs. Use 1 on
multipath/load-balanced paths; 6-18 is a
good starting range on stable links.
Default: 18
-m --max-hops Set the max number of hops (max TTL to be
reached). Default: 30
-d --data-provider Choose IP Geograph Data Provider [IP.SB,
@@ -658,20 +686,21 @@ Arguments:
--listen Set listen address for web console (e.g.
127.0.0.1:30080)
--deploy Start the Gin powered web console
-z --send-time Set how many [milliseconds] between
sending each packet. Default: 50ms.
Ignored in MTR mode. Default: 50
-i --ttl-time Interval [ms] between TTL groups in normal
traceroute (default: 300ms). In MTR mode
(--mtr/-r/-w, including --raw), sets
per-hop probe interval: how long between
successive probes to the same hop
(default: 1000ms when omitted). Default:
300
--timeout The number of [milliseconds] to keep probe
sockets open before giving up on the
connection. Default: 1000
--psize Set the payload size. Default: 52
-z --send-time Advanced: per-packet gap [ms] inside the
same TTL group. Lower is faster; raise to
100-200ms on rate-limited links. Ignored
in MTR mode. Default: 50
-i --ttl-time Advanced: TTL-group interval [ms] in
normal traceroute. In MTR mode
(--mtr/-r/-w, including --raw), this
becomes per-hop probe interval. 500-1000ms
is a good MTR starting range
--timeout Per-probe timeout [ms]. Raise to 2000-3000
on slow intercontinental or high-loss
paths. Default: 1000
--psize Payload size in bytes. Keep 52 for normal
routing checks; raise only for MTU or
large-packet testing. Default: 52
--dot-server Use DoT Server for DNS Parse [dnssb,
aliyun, dnspod, google, cloudflare]
-g --language Choose the language for displaying [en,
+34 -14
View File
@@ -303,9 +303,33 @@ func registerICMPModeFlag(parser *argparse.Parser) *int {
func buildQueriesHelp() string {
if defaultMTR {
return "Set the max number of probes per hop in MTR mode (0 = unlimited for TUI; default 10 for --report)"
return "MTR only: max probes per hop. 0 = unlimited in TUI/raw; --report defaults to 10 when omitted. Start with 10-20 on unstable paths"
}
return "Set the number of latency samples to display for each hop"
return "Latency samples per hop. Increase to 5-10 on unstable paths for a steadier view"
}
func buildMaxAttemptsHelp() string {
return "Advanced: hard cap on probe packets per hop. Leave unset for auto sizing; raise on lossy links if --queries is not enough"
}
func buildParallelRequestsHelp() string {
return "Advanced: total concurrent in-flight probes across TTLs. Use 1 on multipath/load-balanced paths; 6-18 is a good starting range on stable links"
}
func buildPacketIntervalHelp() string {
help := "Advanced: per-packet gap [ms] inside the same TTL group. Lower is faster; raise to 100-200ms on rate-limited links"
if enableMTR {
help += ". Ignored in MTR mode"
}
return help
}
func buildTimeoutHelp() string {
return "Per-probe timeout [ms]. Raise to 2000-3000 on slow intercontinental or high-loss paths"
}
func buildPayloadSizeHelp() string {
return "Payload size in bytes. Keep 52 for normal routing checks; raise only for MTU or large-packet testing"
}
func registerTracerouteOutputFlags(parser *argparse.Parser) tracerouteOutputFlags {
@@ -346,11 +370,7 @@ func registerWebUIFlagsWithAvailability(parser *argparse.Parser, enabled bool) w
func registerPacketIntervalFlag(parser *argparse.Parser) *int {
if !defaultMTR {
sendTimeHelp := "Set how many [milliseconds] between sending each packet. Default: 50ms"
if enableMTR {
sendTimeHelp += ". Ignored in MTR mode"
}
return parser.Int("z", "send-time", &argparse.Options{Default: defaultPacketIntervalMs, Help: sendTimeHelp})
return parser.Int("z", "send-time", &argparse.Options{Default: defaultPacketIntervalMs, Help: buildPacketIntervalHelp()})
}
return ptrInt(defaultPacketIntervalMs)
}
@@ -369,12 +389,12 @@ func buildRawHelp() string {
func buildTTLIntervalHelp() string {
if !enableMTR {
return "Set the interval [ms] between TTL groups for traceroute (default: 300ms)"
return "Advanced: TTL-group interval [ms] in normal traceroute. 100-300ms is usually safe; lower is faster but may trigger rate limits"
}
if defaultMTR {
return "Set the per-hop probe interval [ms] in MTR mode (default: 1000ms when omitted)"
return "Advanced: per-hop probe interval [ms] in MTR mode. 500-1000ms is a good starting point; omitted defaults to 1000ms"
}
return "Interval [ms] between TTL groups in normal traceroute (default: 300ms). In MTR mode (--mtr/-r/-w, including --raw), sets per-hop probe interval: how long between successive probes to the same hop (default: 1000ms when omitted)"
return "Advanced: TTL-group interval [ms] in normal traceroute. In MTR mode (--mtr/-r/-w, including --raw), this becomes per-hop probe interval. 500-1000ms is a good MTR starting range"
}
func registerTTLIntervalFlag(parser *argparse.Parser) *int {
@@ -971,8 +991,8 @@ func Execute() {
port := parser.Int("p", "port", &argparse.Options{Help: "Set the destination port to use. With default of 80 for \"tcp\", 33494 for \"udp\""})
icmpMode := registerICMPModeFlag(parser)
numMeasurements := parser.Int("q", "queries", &argparse.Options{Default: 3, Help: buildQueriesHelp()})
maxAttempts := parser.Int("", "max-attempts", &argparse.Options{Help: "Set the maximum number of probe packets per hop (instead of a fixed auto value)"})
parallelRequests := parser.Int("", "parallel-requests", &argparse.Options{Default: 18, Help: "Set ParallelRequests number. It should be 1 when there is a multi-routing"})
maxAttempts := parser.Int("", "max-attempts", &argparse.Options{Help: buildMaxAttemptsHelp()})
parallelRequests := parser.Int("", "parallel-requests", &argparse.Options{Default: 18, Help: buildParallelRequestsHelp()})
maxHops := parser.Int("m", "max-hops", &argparse.Options{Default: 30, Help: "Set the max number of hops (max TTL to be reached)"})
dataOrigin := parser.Selector("d", "data-provider", []string{"IP.SB", "ip.sb", "IPInfo", "ipinfo", "IPInsight", "ipinsight", "IPAPI.com", "ip-api.com", "IPInfoLocal", "ipinfolocal", "chunzhen", "LeoMoeAPI", "leomoeapi", "ipdb.one", "disable-geoip"}, &argparse.Options{Default: "LeoMoeAPI",
Help: "Choose IP Geograph Data Provider [IP.SB, IPInfo, IPInsight, IP-API.com, IPInfoLocal, CHUNZHEN, disable-geoip]"})
@@ -1004,8 +1024,8 @@ func Execute() {
// ── Send-time: hidden in ntr (always ignored in MTR mode) ──
packetInterval := registerPacketIntervalFlag(parser)
ttlInterval := registerTTLIntervalFlag(parser)
timeout := parser.Int("", "timeout", &argparse.Options{Default: 1000, Help: "The number of [milliseconds] to keep probe sockets open before giving up on the connection"})
packetSize := parser.Int("", "psize", &argparse.Options{Default: 52, Help: "Set the payload size"})
timeout := parser.Int("", "timeout", &argparse.Options{Default: 1000, Help: buildTimeoutHelp()})
packetSize := parser.Int("", "psize", &argparse.Options{Default: 52, Help: buildPayloadSizeHelp()})
dot := parser.Selector("", "dot-server", []string{"dnssb", "aliyun", "dnspod", "google", "cloudflare"}, &argparse.Options{
Help: "Use DoT Server for DNS Parse [dnssb, aliyun, dnspod, google, cloudflare]"})
lang := parser.Selector("g", "language", []string{"en", "cn"}, &argparse.Options{Default: "cn",
+21
View File
@@ -63,3 +63,24 @@ func TestApplyTTLIntervalDefault(t *testing.T) {
t.Fatalf("explicit ttlInterval = %d, want 0", ttlInterval)
}
}
func TestAdvancedHelpTextMentionsTuningGuidance(t *testing.T) {
parser := argparse.NewParser("ntr", "")
registerPacketIntervalFlag(parser)
parser.Int("", "max-attempts", &argparse.Options{Help: buildMaxAttemptsHelp()})
parser.Int("", "parallel-requests", &argparse.Options{Default: 18, Help: buildParallelRequestsHelp()})
parser.Int("", "timeout", &argparse.Options{Default: 1000, Help: buildTimeoutHelp()})
parser.Int("", "psize", &argparse.Options{Default: 52, Help: buildPayloadSizeHelp()})
usage := parser.Usage(nil)
for _, want := range []string{
"load-balanced paths",
"rate-limited links",
"intercontinental",
"MTU or large-packet",
} {
if !strings.Contains(usage, want) {
t.Fatalf("usage missing tuning guidance %q:\n%s", want, usage)
}
}
}
+27 -33
View File
@@ -110,10 +110,11 @@ func (t *ICMPTracer) launchTTL(ctx context.Context, s *internal.ICMPSpec, ttl in
}
}(ttl, i)
select {
case <-ctx.Done():
if i+1 == t.MaxAttempts {
return
}
if !waitForTraceDelay(ctx, time.Millisecond*time.Duration(t.PacketInterval)) {
return
case <-time.After(time.Millisecond * time.Duration(t.PacketInterval)):
}
}
}(ttl)
@@ -319,10 +320,8 @@ func (t *ICMPTracer) Execute() (res *Result, err error) {
for ttl := t.BeginHop + 1; ttl <= t.MaxHops; ttl++ {
// 之后按 TTLInterval 周期启动后续 TTL 组
select {
case <-ctx.Done():
if !waitForTraceDelay(ctx, time.Millisecond*time.Duration(t.TTLInterval)) {
return
case <-time.After(time.Millisecond * time.Duration(t.TTLInterval)):
}
// 如果到达最终跳,则退出
@@ -372,7 +371,7 @@ func (t *ICMPTracer) send(ctx context.Context, s *internal.ICMPSpec, ttl, i int)
return nil
}
if err := t.sem.Acquire(ctx, 1); err != nil {
if err := acquireTraceSemaphore(ctx, t.sem); err != nil {
return err
}
defer t.sem.Release(1)
@@ -413,35 +412,30 @@ func (t *ICMPTracer) send(ctx context.Context, s *internal.ICMPSpec, ttl, i int)
// 登记 pending,并启动超时守护
t.markPending(seq)
go func(seq, ttl, i int) {
select {
case <-ctx.Done():
if !waitForTraceDelay(ctx, t.Timeout) {
_ = t.clearPending(seq)
return
case <-time.After(t.Timeout):
// 仍未完成且未超出 final/未达成 ttlComp 才补位
if !t.clearPending(seq) {
return
}
if f := t.final.Load(); f != -1 && ttl > int(f) {
return
}
if t.ttlComp(ttl) {
return
}
h := Hop{
Success: false,
Address: nil,
TTL: ttl,
RTT: 0,
Error: errHopLimitTimeout,
}
_, _ = t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
t.dropSent(seq)
}
if !t.clearPending(seq) {
return
}
if f := t.final.Load(); f != -1 && ttl > int(f) {
return
}
if t.ttlComp(ttl) {
return
}
h := Hop{
Success: false,
Address: nil,
TTL: ttl,
RTT: 0,
Error: errHopLimitTimeout,
}
_, _ = t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
t.dropSent(seq)
}(seq, ttl, i)
start, err := s.SendICMP(ctx, ipHeader, icmpHeader, nil, payload)
+27 -33
View File
@@ -110,10 +110,11 @@ func (t *ICMPTracerv6) launchTTL(ctx context.Context, s *internal.ICMPSpec, ttl
}
}(ttl, i)
select {
case <-ctx.Done():
if i+1 == t.MaxAttempts {
return
}
if !waitForTraceDelay(ctx, time.Millisecond*time.Duration(t.PacketInterval)) {
return
case <-time.After(time.Millisecond * time.Duration(t.PacketInterval)):
}
}
}(ttl)
@@ -319,10 +320,8 @@ func (t *ICMPTracerv6) Execute() (res *Result, err error) {
for ttl := t.BeginHop + 1; ttl <= t.MaxHops; ttl++ {
// 之后按 TTLInterval 周期启动后续 TTL 组
select {
case <-ctx.Done():
if !waitForTraceDelay(ctx, time.Millisecond*time.Duration(t.TTLInterval)) {
return
case <-time.After(time.Millisecond * time.Duration(t.TTLInterval)):
}
// 如果到达最终跳,则退出
@@ -372,7 +371,7 @@ func (t *ICMPTracerv6) send(ctx context.Context, s *internal.ICMPSpec, ttl, i in
return nil
}
if err := t.sem.Acquire(ctx, 1); err != nil {
if err := acquireTraceSemaphore(ctx, t.sem); err != nil {
return err
}
defer t.sem.Release(1)
@@ -416,35 +415,30 @@ func (t *ICMPTracerv6) send(ctx context.Context, s *internal.ICMPSpec, ttl, i in
// 登记 pending,并启动超时守护
t.markPending(seq)
go func(seq, ttl, i int) {
select {
case <-ctx.Done():
if !waitForTraceDelay(ctx, t.Timeout) {
_ = t.clearPending(seq)
return
case <-time.After(t.Timeout):
// 仍未完成且未超出 final/未达成 ttlComp 才补位
if !t.clearPending(seq) {
return
}
if f := t.final.Load(); f != -1 && ttl > int(f) {
return
}
if t.ttlComp(ttl) {
return
}
h := Hop{
Success: false,
Address: nil,
TTL: ttl,
RTT: 0,
Error: errHopLimitTimeout,
}
_, _ = t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
t.dropSent(seq)
}
if !t.clearPending(seq) {
return
}
if f := t.final.Load(); f != -1 && ttl > int(f) {
return
}
if t.ttlComp(ttl) {
return
}
h := Hop{
Success: false,
Address: nil,
TTL: ttl,
RTT: 0,
Error: errHopLimitTimeout,
}
_, _ = t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
t.dropSent(seq)
}(seq, ttl, i)
start, err := s.SendICMP(ctx, ipHeader, icmpHeader, icmpEcho, payload)
+14 -4
View File
@@ -229,15 +229,25 @@ func (rt *mtrSchedulerRuntime) processProbeError(ttl int, err error) {
}
func (rt *mtrSchedulerRuntime) recordSyntheticTimeout(ttl int) {
rt.agg.Update(timeoutProbeResult(ttl, rt.maxHops), 1)
rt.agg.Update(rt.timeoutProbeResult(ttl), 1)
if rt.onProbe != nil {
rt.onProbe(mtrProbeResult{TTL: ttl}, rt.computeIteration())
}
rt.maybeSnapshot(false)
}
func timeoutProbeResult(ttl, maxHops int) *Result {
singleRes := &Result{Hops: make([][]Hop, maxHops)}
func (rt *mtrSchedulerRuntime) resultHopCount() int {
if n := len(rt.states) - 1; n > 0 {
return n
}
if rt.maxHops > 0 {
return rt.maxHops
}
return 0
}
func (rt *mtrSchedulerRuntime) timeoutProbeResult(ttl int) *Result {
singleRes := &Result{Hops: make([][]Hop, rt.resultHopCount())}
idx := ttl - 1
if idx >= 0 && idx < len(singleRes.Hops) {
singleRes.Hops[idx] = []Hop{{TTL: ttl, Error: errHopLimitTimeout}}
@@ -306,7 +316,7 @@ func (rt *mtrSchedulerRuntime) markProbeCompleted(ttl int) {
}
func (rt *mtrSchedulerRuntime) singleProbeResult(ttl int, result mtrProbeResult) *Result {
singleRes := &Result{Hops: make([][]Hop, rt.maxHops)}
singleRes := &Result{Hops: make([][]Hop, rt.resultHopCount())}
hop := Hop{
Success: result.Success,
Address: result.Addr,
+29
View File
@@ -55,6 +55,35 @@ func (m *mockTTLProber) getProbeCount() int {
// Tests
// ---------------------------------------------------------------------------
func TestScheduler_ResultBuildersUseBoundedHopCount(t *testing.T) {
rt, err := newMTRSchedulerRuntime(
context.Background(),
&mockTTLProber{},
NewMTRAggregator(),
mtrSchedulerConfig{
BeginHop: 1,
MaxHops: 1 << 20,
HopInterval: time.Millisecond,
ParallelRequests: 1,
},
nil,
nil,
)
if err != nil {
t.Fatalf("newMTRSchedulerRuntime returned error: %v", err)
}
if rt.maxHops != 255 {
t.Fatalf("rt.maxHops = %d, want 255", rt.maxHops)
}
if got := len(rt.timeoutProbeResult(1).Hops); got != 255 {
t.Fatalf("timeoutProbeResult hop len = %d, want 255", got)
}
if got := len(rt.singleProbeResult(1, mtrProbeResult{TTL: 1}).Hops); got != 255 {
t.Fatalf("singleProbeResult hop len = %d, want 255", got)
}
}
func TestScheduler_MaxPerHopCompletion(t *testing.T) {
dstIP := net.ParseIP("10.0.0.5")
+27 -33
View File
@@ -112,10 +112,11 @@ func (t *TCPTracer) launchTTL(ctx context.Context, s *internal.TCPSpec, ttl int)
}
}(ttl, i)
select {
case <-ctx.Done():
if i+1 == t.MaxAttempts {
return
}
if !waitForTraceDelay(ctx, time.Millisecond*time.Duration(t.PacketInterval)) {
return
case <-time.After(time.Millisecond * time.Duration(t.PacketInterval)):
}
}
}(ttl)
@@ -326,10 +327,8 @@ func (t *TCPTracer) Execute() (res *Result, err error) {
for ttl := t.BeginHop + 1; ttl <= t.MaxHops; ttl++ {
// 之后按 TTLInterval 周期启动后续 TTL 组
select {
case <-ctx.Done():
if !waitForTraceDelay(ctx, time.Millisecond*time.Duration(t.TTLInterval)) {
return
case <-time.After(time.Millisecond * time.Duration(t.TTLInterval)):
}
// 如果到达最终跳,则退出
@@ -398,7 +397,7 @@ func (t *TCPTracer) send(ctx context.Context, s *internal.TCPSpec, ttl, i int) e
return nil
}
if err := t.sem.Acquire(ctx, 1); err != nil {
if err := acquireTraceSemaphore(ctx, t.sem); err != nil {
return err
}
defer t.sem.Release(1)
@@ -453,35 +452,30 @@ func (t *TCPTracer) send(ctx context.Context, s *internal.TCPSpec, ttl, i int) e
// 登记 pending,并启动超时守护
t.markPending(seq)
go func(seq, ttl, i int) {
select {
case <-ctx.Done():
if !waitForTraceDelay(ctx, t.Timeout) {
_ = t.clearPending(seq)
return
case <-time.After(t.Timeout):
// 仍未完成且未超出 final/未达成 ttlComp 才补位
if !t.clearPending(seq) {
return
}
if f := t.final.Load(); f != -1 && ttl > int(f) {
return
}
if t.ttlComp(ttl) {
return
}
h := Hop{
Success: false,
Address: nil,
TTL: ttl,
RTT: 0,
Error: errHopLimitTimeout,
}
_, _ = t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
t.dropSent(seq)
}
if !t.clearPending(seq) {
return
}
if f := t.final.Load(); f != -1 && ttl > int(f) {
return
}
if t.ttlComp(ttl) {
return
}
h := Hop{
Success: false,
Address: nil,
TTL: ttl,
RTT: 0,
Error: errHopLimitTimeout,
}
_, _ = t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
t.dropSent(seq)
}(seq, ttl, i)
start, err := s.SendTCP(ctx, ipHeader, tcpHeader, payload)
+27 -33
View File
@@ -112,10 +112,11 @@ func (t *TCPTracerIPv6) launchTTL(ctx context.Context, s *internal.TCPSpec, ttl
}
}(ttl, i)
select {
case <-ctx.Done():
if i+1 == t.MaxAttempts {
return
}
if !waitForTraceDelay(ctx, time.Millisecond*time.Duration(t.PacketInterval)) {
return
case <-time.After(time.Millisecond * time.Duration(t.PacketInterval)):
}
}
}(ttl)
@@ -326,10 +327,8 @@ func (t *TCPTracerIPv6) Execute() (res *Result, err error) {
for ttl := t.BeginHop + 1; ttl <= t.MaxHops; ttl++ {
// 之后按 TTLInterval 周期启动后续 TTL 组
select {
case <-ctx.Done():
if !waitForTraceDelay(ctx, time.Millisecond*time.Duration(t.TTLInterval)) {
return
case <-time.After(time.Millisecond * time.Duration(t.TTLInterval)):
}
// 如果到达最终跳,则退出
@@ -398,7 +397,7 @@ func (t *TCPTracerIPv6) send(ctx context.Context, s *internal.TCPSpec, ttl, i in
return nil
}
if err := t.sem.Acquire(ctx, 1); err != nil {
if err := acquireTraceSemaphore(ctx, t.sem); err != nil {
return err
}
defer t.sem.Release(1)
@@ -453,35 +452,30 @@ func (t *TCPTracerIPv6) send(ctx context.Context, s *internal.TCPSpec, ttl, i in
// 登记 pending,并启动超时守护
t.markPending(seq)
go func(seq, ttl, i int) {
select {
case <-ctx.Done():
if !waitForTraceDelay(ctx, t.Timeout) {
_ = t.clearPending(seq)
return
case <-time.After(t.Timeout):
// 仍未完成且未超出 final/未达成 ttlComp 才补位
if !t.clearPending(seq) {
return
}
if f := t.final.Load(); f != -1 && ttl > int(f) {
return
}
if t.ttlComp(ttl) {
return
}
h := Hop{
Success: false,
Address: nil,
TTL: ttl,
RTT: 0,
Error: errHopLimitTimeout,
}
_, _ = t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
t.dropSent(seq)
}
if !t.clearPending(seq) {
return
}
if f := t.final.Load(); f != -1 && ttl > int(f) {
return
}
if t.ttlComp(ttl) {
return
}
h := Hop{
Success: false,
Address: nil,
TTL: ttl,
RTT: 0,
Error: errHopLimitTimeout,
}
_, _ = t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
t.dropSent(seq)
}(seq, ttl, i)
start, err := s.SendTCP(ctx, ipHeader, tcpHeader, payload)
+47
View File
@@ -13,6 +13,7 @@ import (
"time"
"golang.org/x/net/idna"
"golang.org/x/sync/semaphore"
"golang.org/x/sync/singleflight"
"github.com/nxtrace/NTrace-core/ipgeo"
@@ -115,6 +116,52 @@ func applyTracerouteDefaults(config *Config) {
}
}
func waitForTraceDelay(ctx context.Context, d time.Duration) bool {
if ctx == nil {
ctx = context.Background()
}
if ctx != nil && ctx.Err() != nil {
return false
}
if d <= 0 {
return true
}
timer := time.NewTimer(d)
defer stopAndDrainTimer(timer)
select {
case <-ctx.Done():
return false
case <-timer.C:
return ctx == nil || ctx.Err() == nil
}
}
func stopAndDrainTimer(timer *time.Timer) {
if timer == nil {
return
}
if timer.Stop() {
return
}
select {
case <-timer.C:
default:
}
}
func acquireTraceSemaphore(ctx context.Context, sem *semaphore.Weighted) error {
if sem == nil {
return nil
}
if ctx == nil {
ctx = context.Background()
}
if err := ctx.Err(); err != nil {
return err
}
return sem.Acquire(ctx, 1)
}
func normalizeICMPMode(config *Config) {
if config == nil {
return
+54
View File
@@ -0,0 +1,54 @@
package trace
import (
"context"
"errors"
"testing"
"time"
"golang.org/x/sync/semaphore"
)
func TestWaitForTraceDelayCanceledContextReturnsImmediately(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
start := time.Now()
if waitForTraceDelay(ctx, time.Second) {
t.Fatal("waitForTraceDelay should return false for canceled context")
}
if elapsed := time.Since(start); elapsed > 50*time.Millisecond {
t.Fatalf("waitForTraceDelay returned too slowly after cancel: %v", elapsed)
}
}
func TestWaitForTraceDelayZeroDelaySucceeds(t *testing.T) {
if !waitForTraceDelay(context.Background(), 0) {
t.Fatal("waitForTraceDelay should succeed for zero delay")
}
}
func TestAcquireTraceSemaphoreChecksCanceledContextFirst(t *testing.T) {
sem := semaphore.NewWeighted(1)
if err := sem.Acquire(context.Background(), 1); err != nil {
t.Fatalf("initial acquire failed: %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
start := time.Now()
err := acquireTraceSemaphore(ctx, sem)
if !errors.Is(err, context.Canceled) {
t.Fatalf("acquireTraceSemaphore error = %v, want context.Canceled", err)
}
if elapsed := time.Since(start); elapsed > 50*time.Millisecond {
t.Fatalf("acquireTraceSemaphore returned too slowly after cancel: %v", elapsed)
}
sem.Release(1)
if err := acquireTraceSemaphore(context.Background(), sem); err != nil {
t.Fatalf("acquireTraceSemaphore should still acquire after release: %v", err)
}
sem.Release(1)
}
+30 -33
View File
@@ -117,10 +117,11 @@ func (t *UDPTracer) launchTTL(ctx context.Context, s *internal.UDPSpec, ttl int)
}
}(ttl, i)
select {
case <-ctx.Done():
if i+1 == t.MaxAttempts {
return
}
if !waitForTraceDelay(ctx, time.Millisecond*time.Duration(t.PacketInterval)) {
return
case <-time.After(time.Millisecond * time.Duration(t.PacketInterval)):
}
}
}(ttl)
@@ -375,10 +376,8 @@ func (t *UDPTracer) Execute() (res *Result, err error) {
for ttl := t.BeginHop + 1; ttl <= t.MaxHops; ttl++ {
// 之后按 TTLInterval 周期启动后续 TTL 组
select {
case <-ctx.Done():
if !waitForTraceDelay(ctx, time.Millisecond*time.Duration(t.TTLInterval)) {
return
case <-time.After(time.Millisecond * time.Duration(t.TTLInterval)):
}
// 如果到达最终跳,则退出
@@ -452,7 +451,7 @@ func (t *UDPTracer) acquireSendPermit(ctx context.Context, ttl int) (func(), boo
if t.ttlComp(ttl) {
return nil, true, nil
}
if err := t.sem.Acquire(ctx, 1); err != nil {
if err := acquireTraceSemaphore(ctx, t.sem); err != nil {
return nil, false, err
}
release := func() { t.sem.Release(1) }
@@ -495,35 +494,33 @@ func (t *UDPTracer) buildUDPPacket(ttl, i, srcPort int) (int, *layers.IPv4, *lay
func (t *UDPTracer) startSendTimeout(ctx context.Context, ttl, i, seq int) {
t.markPending(ttl, i)
go func(seq, ttl, i int) {
select {
case <-ctx.Done():
if !waitForTraceDelay(ctx, t.Timeout) {
_ = t.clearPending(ttl, i)
return
case <-time.After(t.Timeout):
if !t.clearPending(ttl, i) {
return
}
if f := t.final.Load(); f != -1 && ttl > int(f) {
return
}
if t.ttlComp(ttl) {
return
}
h := Hop{
Success: false,
Address: nil,
TTL: ttl,
RTT: 0,
Error: errHopLimitTimeout,
}
_, _ = t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
if t.OSType != 1 {
t.dropSent(seq)
return
}
t.dropByAttempt(ttl, i)
}
if !t.clearPending(ttl, i) {
return
}
if f := t.final.Load(); f != -1 && ttl > int(f) {
return
}
if t.ttlComp(ttl) {
return
}
h := Hop{
Success: false,
Address: nil,
TTL: ttl,
RTT: 0,
Error: errHopLimitTimeout,
}
_, _ = t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
if t.OSType != 1 {
t.dropSent(seq)
return
}
t.dropByAttempt(ttl, i)
}(seq, ttl, i)
}
+27 -33
View File
@@ -112,10 +112,11 @@ func (t *UDPTracerIPv6) launchTTL(ctx context.Context, s *internal.UDPSpec, ttl
}
}(ttl, i)
select {
case <-ctx.Done():
if i+1 == t.MaxAttempts {
return
}
if !waitForTraceDelay(ctx, time.Millisecond*time.Duration(t.PacketInterval)) {
return
case <-time.After(time.Millisecond * time.Duration(t.PacketInterval)):
}
}
}(ttl)
@@ -311,10 +312,8 @@ func (t *UDPTracerIPv6) Execute() (res *Result, err error) {
for ttl := t.BeginHop + 1; ttl <= t.MaxHops; ttl++ {
// 之后按 TTLInterval 周期启动后续 TTL 组
select {
case <-ctx.Done():
if !waitForTraceDelay(ctx, time.Millisecond*time.Duration(t.TTLInterval)) {
return
case <-time.After(time.Millisecond * time.Duration(t.TTLInterval)):
}
// 如果到达最终跳,则退出
@@ -383,7 +382,7 @@ func (t *UDPTracerIPv6) send(ctx context.Context, s *internal.UDPSpec, ttl, i in
return nil
}
if err := t.sem.Acquire(ctx, 1); err != nil {
if err := acquireTraceSemaphore(ctx, t.sem); err != nil {
return err
}
defer t.sem.Release(1)
@@ -437,35 +436,30 @@ func (t *UDPTracerIPv6) send(ctx context.Context, s *internal.UDPSpec, ttl, i in
// 登记 pending,并启动超时守护
t.markPending(seq)
go func(seq, ttl, i int) {
select {
case <-ctx.Done():
if !waitForTraceDelay(ctx, t.Timeout) {
_ = t.clearPending(seq)
return
case <-time.After(t.Timeout):
// 仍未完成且未超出 final/未达成 ttlComp 才补位
if !t.clearPending(seq) {
return
}
if f := t.final.Load(); f != -1 && ttl > int(f) {
return
}
if t.ttlComp(ttl) {
return
}
h := Hop{
Success: false,
Address: nil,
TTL: ttl,
RTT: 0,
Error: errHopLimitTimeout,
}
_, _ = t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
t.dropSent(seq)
}
if !t.clearPending(seq) {
return
}
if f := t.final.Load(); f != -1 && ttl > int(f) {
return
}
if t.ttlComp(ttl) {
return
}
h := Hop{
Success: false,
Address: nil,
TTL: ttl,
RTT: 0,
Error: errHopLimitTimeout,
}
_, _ = t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
t.dropSent(seq)
}(seq, ttl, i)
start, err := s.SendUDP(ctx, ipHeader, udpHeader, payload)