From cb02ef92d11409b14c2cc7cb1a8aafc134ac741e Mon Sep 17 00:00:00 2001 From: tsosunchia <59512455+tsosunchia@users.noreply.github.com> Date: Tue, 8 Sep 2026 14:48:38 +0800 Subject: [PATCH] =?UTF-8?q?fix(mtr):=20=E4=BF=9D=E7=95=99=E5=9B=A0?= =?UTF-8?q?=E6=9E=9C=E4=BA=8B=E4=BB=B6=E9=A1=BA=E5=BA=8F=E4=B8=8E=E9=A6=96?= =?UTF-8?q?=E4=B8=AA=E5=BD=95=E5=88=B6=E9=94=99=E8=AF=AF=E5=B9=B6=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E9=9A=8F=E6=9C=BA=E6=BA=90=E7=AB=AF=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/mtr_json_run.go | 19 ++++++------- cmd/mtr_json_test.go | 62 +++++++++++++++++++++++++++++++++++++++++- cmd/mtr_record.go | 4 +-- cmd/mtr_record_test.go | 29 ++++++++++++++++++++ 4 files changed, 101 insertions(+), 13 deletions(-) diff --git a/cmd/mtr_json_run.go b/cmd/mtr_json_run.go index 43e8b30..78e4581 100644 --- a/cmd/mtr_json_run.go +++ b/cmd/mtr_json_run.go @@ -129,7 +129,7 @@ func runMTRJSON(parent context.Context, opts mtrJSONOptions, stdout, stderr io.W if err == nil { display.sourceIP = resolveSrcIP(opts.Config) } - if startErr := recording.start(out, display); startErr != nil { + if startErr := recording.start(out, display); startErr != nil && err == nil { err, stage = startErr, "record" } } @@ -158,7 +158,7 @@ func runMTRJSON(parent context.Context, opts mtrJSONOptions, stdout, stderr io.W cleanup() } if recording != nil { - if recordErr := recording.finish(err, stage); recordErr != nil { + if recordErr := recording.finish(err, stage); recordErr != nil && err == nil { err, stage = recordErr, "record" } } @@ -187,8 +187,11 @@ func runMTRJSONStream(ctx context.Context, opts mtrJSONOptions, out *mtrJSONOutp out.probe(record) flushPath() }) - // A max-hops conclusion can be emitted after the last probe callback. - flushPath() + // Only max-hops can conclude without a following probe callback. A recording + // failure may drop the causal probe for any other pending path change. + if pending != nil && pending.Reason == trace.StopReasonMaxHops { + flushPath() + } return err } @@ -238,12 +241,8 @@ func normalizeMTRJSONOptions(opts *mtrJSONOptions, stderr io.Writer) error { cfg.ParallelRequests = 1 } applyDefaultPort(&cfg.DstPort, opts.Method == trace.UDPTrace) - minimumSourcePort := 0 - if opts.HumanOutput { - minimumSourcePort = -1 - } - if opts.Method != trace.ICMPTrace && (cfg.SrcPort < minimumSourcePort || cfg.SrcPort > 65535 || cfg.DstPort < 1 || cfg.DstPort > 65535) { - return errors.New("probe ports must be between 1 and 65535 (source port 0 selects automatically)") + if opts.Method != trace.ICMPTrace && (cfg.SrcPort < -1 || cfg.SrcPort > 65535 || cfg.DstPort < 1 || cfg.DstPort > 65535) { + return errors.New("probe ports must be between 1 and 65535 (source port 0 selects automatically, -1 selects randomly per probe)") } if cfg.ICMPMode <= 0 && util.EnvICMPMode > 0 { cfg.ICMPMode = util.EnvICMPMode diff --git a/cmd/mtr_json_test.go b/cmd/mtr_json_test.go index 78347fc..bb80100 100644 --- a/cmd/mtr_json_test.go +++ b/cmd/mtr_json_test.go @@ -309,8 +309,8 @@ func TestMTRJSONRunnerUsesFullConfigAndPreservesSnapshot(t *testing.T) { } runMTRJSONRawFn = func(ctx context.Context, _ trace.Method, _ trace.Config, opts trace.MTRRawOptions, callback trace.MTRRawOnRecord) error { - callback(trace.MTRRawRecord{TTL: 1, Success: true, IP: "192.0.2.1"}) opts.OnPathEnd(nil) + callback(trace.MTRRawRecord{TTL: 1, Success: true, IP: "192.0.2.1"}) return &mtrJSONSignal{syscall.SIGTERM} } stdout.Reset() @@ -493,3 +493,63 @@ func TestMTRJSONCLIProcess(t *testing.T) { }) } } + +func TestMTRJSONStreamDropsPathWithoutCausalProbe(t *testing.T) { + oldRaw := runMTRJSONRawFn + t.Cleanup(func() { runMTRJSONRawFn = oldRaw }) + for _, reason := range []string{trace.StopReasonDestination, trace.StopReasonUnreachable, trace.StopReasonMaxHops} { + t.Run(reason, func(t *testing.T) { + ctx, cancel := context.WithCancelCause(t.Context()) + defer cancel(nil) + var stdout bytes.Buffer + out := newMTRJSONOutput(&stdout, true, "target", trace.ICMPTrace, cancel) + out.startStream() + recordErr := errors.New("recording failed") + runMTRJSONRawFn = func(_ context.Context, _ trace.Method, _ trace.Config, opts trace.MTRRawOptions, cb trace.MTRRawOnRecord) error { + cb(trace.MTRRawRecord{TTL: 1, IP: "192.0.2.1"}) + opts.OnPathEnd(&trace.StopReason{Hop: 2, Reason: reason}) + return recordErr + } + err := runMTRJSONStream(ctx, testMTRJSONOptions(), out) + if !errors.Is(err, recordErr) { + t.Fatal(err) + } + out.finish(err, "probe", io.Discard) + events := decodeMTRJSON(t, stdout.Bytes()) + paths := 0 + for _, event := range events { + if string(event["type"]) == `"path_end"` { + paths++ + } + } + want := 0 + if reason == trace.StopReasonMaxHops { + want = 1 + } + if paths != want { + t.Fatalf("paths=%d want=%d: %s", paths, want, stdout.String()) + } + if want == 0 && string(events[len(events)-1]["path_end"]) != "null" { + t.Fatalf("dropped path leaked into end: %s", stdout.String()) + } + }) + } +} + +func TestMTRJSONSourcePortRange(t *testing.T) { + for _, method := range []trace.Method{trace.TCPTrace, trace.UDPTrace} { + for _, port := range []int{-2, -1, 0, 1, 65535, 65536} { + for _, human := range []bool{false, true} { + opts := testMTRJSONOptions() + opts.Method, opts.Config.SrcPort, opts.HumanOutput = method, port, human + err := normalizeMTRJSONOptions(&opts, io.Discard) + if (err == nil) != (port >= -1 && port <= 65535) { + t.Fatalf("method=%s port=%d human=%v: %v", method, port, human, err) + } + if opts.Config.SrcPort != port { + t.Fatal("source port changed") + } + } + } + } +} diff --git a/cmd/mtr_record.go b/cmd/mtr_record.go index c3d31ec..13c7c77 100644 --- a/cmd/mtr_record.go +++ b/cmd/mtr_record.go @@ -157,7 +157,7 @@ func runMTRRecorded(ctx context.Context, opts mtrJSONOptions, modes effectiveMTR if err == nil { display.sourceIP = resolveSrcIP(opts.Config) } - if startErr := recording.start(out, display); startErr != nil { + if startErr := recording.start(out, display); startErr != nil && err == nil { err, stage = startErr, "record" } if err == nil { @@ -180,7 +180,7 @@ func runMTRRecorded(ctx context.Context, opts mtrJSONOptions, modes effectiveMTR if cleanup != nil { cleanup() } - if finishErr := recording.finish(err, stage); finishErr != nil { + if finishErr := recording.finish(err, stage); finishErr != nil && err == nil { err = fmt.Errorf("write MTR recording: %w", finishErr) } var interrupted *mtrJSONSignal diff --git a/cmd/mtr_record_test.go b/cmd/mtr_record_test.go index cdb6ef8..5770b6d 100644 --- a/cmd/mtr_record_test.go +++ b/cmd/mtr_record_test.go @@ -246,3 +246,32 @@ func TestMTRRecordCLIRejectsModesBeforeNetwork(t *testing.T) { } } } + +func TestMTRRecordKeepsResolutionErrorWhenStartFails(t *testing.T) { + old := domainLookupFn + t.Cleanup(func() { domainLookupFn = old }) + domainLookupFn = func(context.Context, string, string, string, bool) (net.IP, error) { + return nil, errors.New("original resolution failure") + } + for _, human := range []bool{false, true} { + opts := testMTRJSONOptions() + opts.Target = strings.Repeat("x", mtrsession.MaxLineBytes+1) + opts.RecordPath = filepath.Join(t.TempDir(), "failed.jsonl") + var stdout, stderr bytes.Buffer + var code int + if human { + code = runMTRRecorded(t.Context(), opts, effectiveMTRModes{mtr: true}, false, 0, "", nil, &stderr) + } else { + code = runMTRJSON(t.Context(), opts, &stdout, &stderr) + } + if code != 1 || !strings.Contains(stderr.String(), "original resolution failure") { + t.Fatalf("human=%v code=%d stderr=%s", human, code, stderr.String()) + } + if !human { + events := decodeMTRJSON(t, stdout.Bytes()) + if !bytes.Contains(events[len(events)-1]["error"], []byte(`"stage":"resolve"`)) { + t.Fatal("original error stage lost") + } + } + } +}