mirror of
https://github.com/nxtrace/NTrace-core.git
synced 2026-12-02 01:11:51 +00:00
feat: refactor flag registration functions and enhance trace map URL handling
This commit is contained in:
1 parent
d044c87441
commit
fe8f1aea75
5 files changed
+196
-26
No files matched your search
+45
-8
@@ -328,15 +328,19 @@ func registerTracerouteOutputFlags(parser *argparse.Parser) tracerouteOutputFlag
|
||||
}
|
||||
|
||||
func registerWebUIFlags(parser *argparse.Parser) webUIFlags {
|
||||
if enableWebUI {
|
||||
return registerWebUIFlagsWithAvailability(parser, enableWebUI)
|
||||
}
|
||||
|
||||
func registerWebUIFlagsWithAvailability(parser *argparse.Parser, enabled bool) webUIFlags {
|
||||
if enabled {
|
||||
return webUIFlags{
|
||||
deployListen: parser.String("", "listen", &argparse.Options{Help: "Set listen address for web console (e.g. 127.0.0.1:30080)"}),
|
||||
deploy: parser.Flag("", "deploy", &argparse.Options{Help: "Start the Gin powered web console"}),
|
||||
}
|
||||
}
|
||||
return webUIFlags{
|
||||
deployListen: ptrStr(""),
|
||||
deploy: ptrBool(false),
|
||||
deployListen: parser.String("", "listen", &argparse.Options{Help: "Set listen address for web console (full build only; unavailable in this binary)"}),
|
||||
deploy: parser.Flag("", "deploy", &argparse.Options{Help: "Start the Gin powered web console (full build only; unavailable in this binary)"}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -373,6 +377,25 @@ func buildTTLIntervalHelp() string {
|
||||
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)"
|
||||
}
|
||||
|
||||
func registerTTLIntervalFlag(parser *argparse.Parser) *int {
|
||||
return registerTTLIntervalFlagWithMTRSupport(parser, enableMTR)
|
||||
}
|
||||
|
||||
func registerTTLIntervalFlagWithMTRSupport(parser *argparse.Parser, mtrEnabled bool) *int {
|
||||
options := &argparse.Options{Help: buildTTLIntervalHelp()}
|
||||
if !mtrEnabled {
|
||||
options.Default = defaultTracerouteTTLIntervalMs
|
||||
}
|
||||
return parser.Int("i", "ttl-time", options)
|
||||
}
|
||||
|
||||
func applyTTLIntervalDefault(ttlInterval *int, ttlTimeExplicit, effectiveMTR bool) {
|
||||
if ttlInterval == nil || ttlTimeExplicit || effectiveMTR {
|
||||
return
|
||||
}
|
||||
*ttlInterval = defaultTracerouteTTLIntervalMs
|
||||
}
|
||||
|
||||
func registerDisableMaptraceFlag(parser *argparse.Parser) *bool {
|
||||
if !defaultMTR {
|
||||
return parser.Flag("M", "map", &argparse.Options{Help: "Disable Print Trace Map"})
|
||||
@@ -381,10 +404,14 @@ func registerDisableMaptraceFlag(parser *argparse.Parser) *bool {
|
||||
}
|
||||
|
||||
func registerGlobalpingFlag(parser *argparse.Parser) *string {
|
||||
if enableGlobalping {
|
||||
return registerGlobalpingFlagWithAvailability(parser, enableGlobalping)
|
||||
}
|
||||
|
||||
func registerGlobalpingFlagWithAvailability(parser *argparse.Parser, enabled bool) *string {
|
||||
if enabled {
|
||||
return parser.String("", "from", &argparse.Options{Help: "Run traceroute via Globalping (https://globalping.io/network) from a specified location. The location field accepts continents, countries, regions, cities, ASNs, ISPs, or cloud regions."})
|
||||
}
|
||||
return ptrStr("")
|
||||
return parser.String("", "from", &argparse.Options{Help: "Run traceroute via Globalping (full build only; unavailable in this binary)"})
|
||||
}
|
||||
|
||||
func registerMTRFlags(parser *argparse.Parser) mtrCLIFlags {
|
||||
@@ -465,6 +492,15 @@ func maybeRunDeployMode(deploy bool, deployListen string) bool {
|
||||
if !deploy {
|
||||
return false
|
||||
}
|
||||
if !enableWebUI {
|
||||
if err := runDeploy(""); err != nil {
|
||||
if util.EnvDevMode {
|
||||
panic(err)
|
||||
}
|
||||
log.Fatal(err)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
capabilitiesCheck()
|
||||
listenAddr := strings.TrimSpace(deployListen)
|
||||
@@ -967,7 +1003,7 @@ func Execute() {
|
||||
//router := parser.Flag("R", "route", &argparse.Options{Help: "Show Routing Table [Provided By BGP.Tools]"})
|
||||
// ── Send-time: hidden in ntr (always ignored in MTR mode) ──
|
||||
packetInterval := registerPacketIntervalFlag(parser)
|
||||
ttlInterval := parser.Int("i", "ttl-time", &argparse.Options{Default: defaultTracerouteTTLIntervalMs, Help: buildTTLIntervalHelp()})
|
||||
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"})
|
||||
dot := parser.Selector("", "dot-server", []string{"dnssb", "aliyun", "dnspod", "google", "cloudflare"}, &argparse.Options{
|
||||
@@ -1007,10 +1043,10 @@ func Execute() {
|
||||
"json": *jsonPrint,
|
||||
"output": *output,
|
||||
"routePath": *routePath,
|
||||
"from": *from != "",
|
||||
"from": enableGlobalping && *from != "",
|
||||
"fastTrace": *fastTraceFlag,
|
||||
"file": *file != "",
|
||||
"deploy": *deploy,
|
||||
"deploy": enableWebUI && *deploy,
|
||||
}
|
||||
if conflict, ok := checkMTRConflicts(conflictFlags); !ok {
|
||||
fmt.Printf("--mtr 不能与 %s 同时使用\n", conflict)
|
||||
@@ -1019,6 +1055,7 @@ func Execute() {
|
||||
}
|
||||
|
||||
queriesExplicit, ttlTimeExplicit := detectExplicitProbeFlags(parser)
|
||||
applyTTLIntervalDefault(ttlInterval, ttlTimeExplicit, mtrModes.mtr)
|
||||
osType := resolveOSType()
|
||||
if handleStartupModes(*noColor, *jsonPrint, mtrModes, *ver, *deploy, *deployListen, *init, osType) {
|
||||
return
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/akamensky/argparse"
|
||||
)
|
||||
|
||||
func TestRegisterGlobalpingFlagWithAvailability_DisabledStillParses(t *testing.T) {
|
||||
parser := argparse.NewParser("ntr", "")
|
||||
from := registerGlobalpingFlagWithAvailability(parser, false)
|
||||
|
||||
if err := parser.Parse([]string{"ntr", "--from", "tokyo"}); err != nil {
|
||||
t.Fatalf("Parse returned error: %v", err)
|
||||
}
|
||||
if got := strings.TrimSpace(*from); got != "tokyo" {
|
||||
t.Fatalf("--from = %q, want tokyo", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterWebUIFlagsWithAvailability_DisabledStillParses(t *testing.T) {
|
||||
parser := argparse.NewParser("ntr", "")
|
||||
flags := registerWebUIFlagsWithAvailability(parser, false)
|
||||
|
||||
if err := parser.Parse([]string{"ntr", "--deploy", "--listen", "127.0.0.1:1080"}); err != nil {
|
||||
t.Fatalf("Parse returned error: %v", err)
|
||||
}
|
||||
if !*flags.deploy {
|
||||
t.Fatal("--deploy should parse as true")
|
||||
}
|
||||
if got := strings.TrimSpace(*flags.deployListen); got != "127.0.0.1:1080" {
|
||||
t.Fatalf("--listen = %q, want 127.0.0.1:1080", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterTTLIntervalFlagWithMTRSupport_HelpOmitsTracerouteDefault(t *testing.T) {
|
||||
parser := argparse.NewParser("ntr", "")
|
||||
registerTTLIntervalFlagWithMTRSupport(parser, true)
|
||||
|
||||
usage := parser.Usage(nil)
|
||||
if strings.Contains(usage, "Default: 300") {
|
||||
t.Fatalf("usage should not advertise traceroute default in MTR mode:\n%s", usage)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyTTLIntervalDefault(t *testing.T) {
|
||||
ttlInterval := 0
|
||||
applyTTLIntervalDefault(&ttlInterval, false, false)
|
||||
if ttlInterval != defaultTracerouteTTLIntervalMs {
|
||||
t.Fatalf("ttlInterval = %d, want %d", ttlInterval, defaultTracerouteTTLIntervalMs)
|
||||
}
|
||||
|
||||
ttlInterval = 0
|
||||
applyTTLIntervalDefault(&ttlInterval, false, true)
|
||||
if ttlInterval != 0 {
|
||||
t.Fatalf("MTR ttlInterval = %d, want 0", ttlInterval)
|
||||
}
|
||||
|
||||
ttlInterval = 0
|
||||
applyTTLIntervalDefault(&ttlInterval, true, false)
|
||||
if ttlInterval != 0 {
|
||||
t.Fatalf("explicit ttlInterval = %d, want 0", ttlInterval)
|
||||
}
|
||||
}
|
||||
+35
-9
@@ -25,6 +25,10 @@ import (
|
||||
|
||||
var traceMu sync.Mutex
|
||||
var leoConnMu sync.Mutex
|
||||
var traceMapURLFn = tracemap.GetMapUrl
|
||||
var withTraceMapScopeFn = func(setup *traceExecution, callback func() (string, error)) (string, error) {
|
||||
return withTraceGeoDNSScope(setup, callback)
|
||||
}
|
||||
|
||||
type traceExecution struct {
|
||||
Req traceRequest
|
||||
@@ -282,7 +286,9 @@ func traceHandler(c *gin.Context) {
|
||||
log.Printf("[deploy] starting trace target=%s resolved=%s method=%s lang=%s queries=%d maxHops=%d", sanitizeLogParam(setup.Target), setup.IP.String(), string(setup.Method), sanitizeLogParam(configured.Lang), configured.NumMeasurements, configured.MaxHops)
|
||||
|
||||
start := time.Now()
|
||||
res, err := trace.Traceroute(setup.Method, configured)
|
||||
res, err := withTraceSetupContext(setup, func() (*trace.Result, error) {
|
||||
return traceTracerouteFn(setup.Method, configured)
|
||||
})
|
||||
duration := time.Since(start)
|
||||
if err != nil {
|
||||
log.Printf("[deploy] trace failed target=%s error=%v", sanitizeLogParam(setup.Target), err)
|
||||
@@ -290,14 +296,9 @@ func traceHandler(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
traceMapURL := ""
|
||||
if configured.Maptrace && shouldGenerateMap(setup.DataProvider) {
|
||||
if payload, err := json.Marshal(res); err == nil {
|
||||
if mapUrl, err := tracemap.GetMapUrl(string(payload)); err == nil {
|
||||
traceMapURL = mapUrl
|
||||
log.Printf("[deploy] trace map generated target=%s mapUrl=%s", sanitizeLogParam(setup.Target), traceMapURL)
|
||||
}
|
||||
}
|
||||
traceMapURL := traceMapURLForResult(setup, res)
|
||||
if traceMapURL != "" {
|
||||
log.Printf("[deploy] trace map generated target=%s mapUrl=%s", sanitizeLogParam(setup.Target), traceMapURL)
|
||||
}
|
||||
|
||||
response := traceResponse{
|
||||
@@ -419,6 +420,14 @@ func withTraceSetupContext[T any](setup *traceExecution, callback func() (T, err
|
||||
util.PowProviderParam = prevPowProvider
|
||||
}()
|
||||
|
||||
return withTraceGeoDNSScope(setup, callback)
|
||||
}
|
||||
|
||||
func withTraceGeoDNSScope[T any](setup *traceExecution, callback func() (T, error)) (T, error) {
|
||||
if callback == nil {
|
||||
var zero T
|
||||
return zero, nil
|
||||
}
|
||||
dotServer := ""
|
||||
if setup != nil {
|
||||
dotServer = strings.TrimSpace(strings.ToLower(setup.Req.DotServer))
|
||||
@@ -426,6 +435,23 @@ func withTraceSetupContext[T any](setup *traceExecution, callback func() (T, err
|
||||
return util.WithGeoDNSResolver(dotServer, callback)
|
||||
}
|
||||
|
||||
func traceMapURLForResult(setup *traceExecution, res *trace.Result) string {
|
||||
if setup == nil || res == nil || !setup.Config.Maptrace || !shouldGenerateMap(setup.DataProvider) {
|
||||
return ""
|
||||
}
|
||||
payload, err := json.Marshal(res)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
url, err := withTraceMapScopeFn(setup, func() (string, error) {
|
||||
return traceMapURLFn(string(payload))
|
||||
})
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
func convertHops(res *trace.Result, lang string) []hopResponse {
|
||||
if res == nil || len(res.Hops) == 0 {
|
||||
return nil
|
||||
|
||||
@@ -196,3 +196,51 @@ func TestExecuteMTRRaw_PerHopDoesNotMutateSessionGlobals(t *testing.T) {
|
||||
t.Fatalf("util.PowProviderParam = %q, want keep-pow", util.PowProviderParam)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTraceMapURLForResult_UsesRequestScopedMapHelper(t *testing.T) {
|
||||
oldMapFn := traceMapURLFn
|
||||
oldScopeFn := withTraceMapScopeFn
|
||||
defer func() {
|
||||
traceMapURLFn = oldMapFn
|
||||
withTraceMapScopeFn = oldScopeFn
|
||||
}()
|
||||
|
||||
scopeCalled := false
|
||||
traceMapCalled := false
|
||||
|
||||
withTraceMapScopeFn = func(setup *traceExecution, callback func() (string, error)) (string, error) {
|
||||
scopeCalled = true
|
||||
if setup == nil {
|
||||
t.Fatal("setup should not be nil")
|
||||
}
|
||||
if strings.TrimSpace(setup.Req.DotServer) != "cloudflare" {
|
||||
t.Fatalf("DotServer = %q, want cloudflare", setup.Req.DotServer)
|
||||
}
|
||||
return callback()
|
||||
}
|
||||
traceMapURLFn = func(payload string) (string, error) {
|
||||
traceMapCalled = true
|
||||
if payload == "" {
|
||||
t.Fatal("payload should not be empty")
|
||||
}
|
||||
return "https://map.example.test", nil
|
||||
}
|
||||
|
||||
got := traceMapURLForResult(&traceExecution{
|
||||
Req: traceRequest{DotServer: "cloudflare"},
|
||||
DataProvider: "IPInfo",
|
||||
Config: trace.Config{Maptrace: true},
|
||||
}, &trace.Result{
|
||||
Hops: [][]trace.Hop{{{TTL: 1}}},
|
||||
})
|
||||
|
||||
if got != "https://map.example.test" {
|
||||
t.Fatalf("traceMapURLForResult() = %q, want https://map.example.test", got)
|
||||
}
|
||||
if !scopeCalled {
|
||||
t.Fatal("expected request-scoped map helper to be used")
|
||||
}
|
||||
if !traceMapCalled {
|
||||
t.Fatal("expected traceMapURLFn to be called")
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,6 @@ import (
|
||||
"github.com/gorilla/websocket"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/trace"
|
||||
"github.com/nxtrace/NTrace-core/tracemap"
|
||||
)
|
||||
|
||||
var traceUpgrader = websocket.Upgrader{
|
||||
@@ -284,14 +283,9 @@ func runSingleTrace(session *wsTraceSession, setup *traceExecution) {
|
||||
return
|
||||
}
|
||||
|
||||
traceMapURL := ""
|
||||
if setup.Config.Maptrace && shouldGenerateMap(setup.DataProvider) {
|
||||
if payload, err := json.Marshal(res); err == nil {
|
||||
if url, err := tracemap.GetMapUrl(string(payload)); err == nil {
|
||||
traceMapURL = url
|
||||
log.Printf("[deploy] (ws) trace map generated target=%s url=%s", sanitizeLogParam(setup.Target), traceMapURL)
|
||||
}
|
||||
}
|
||||
traceMapURL := traceMapURLForResult(setup, res)
|
||||
if traceMapURL != "" {
|
||||
log.Printf("[deploy] (ws) trace map generated target=%s url=%s", sanitizeLogParam(setup.Target), traceMapURL)
|
||||
}
|
||||
|
||||
final := traceResponse{
|
||||
|
||||
Reference in new issue
Block a user