From f507bc8f9ee4e63cfe5c5bc6dfc95642df736600 Mon Sep 17 00:00:00 2001 From: Cuong Manh Le Date: Mon, 23 Sep 2024 21:51:10 +0700 Subject: [PATCH] cmd/cli: cache query from self result So we don't waste time to compute a result which is not likely to be changed. --- cmd/cli/dns_proxy.go | 9 +++++++-- cmd/cli/prog.go | 1 + 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/cmd/cli/dns_proxy.go b/cmd/cli/dns_proxy.go index 81be1d0..370d8de 100644 --- a/cmd/cli/dns_proxy.go +++ b/cmd/cli/dns_proxy.go @@ -838,7 +838,7 @@ func (p *prog) getClientInfo(remoteIP string, msg *dns.Msg) *ctrld.ClientInfo { } else { ci.Hostname = p.ciTable.LookupHostname(ci.IP, ci.Mac) } - ci.Self = queryFromSelf(ci.IP) + ci.Self = p.queryFromSelf(ci.IP) // If this is a query from self, but ci.IP is not loopback IP, // try using hostname mapping for lookback IP if presents. if ci.Self { @@ -956,7 +956,10 @@ func timeDurationOrDefault(n *int, defaultN int) time.Duration { } // queryFromSelf reports whether the input IP is from device running ctrld. -func queryFromSelf(ip string) bool { +func (p *prog) queryFromSelf(ip string) bool { + if val, ok := p.queryFromSelfMap.Load(ip); ok { + return val.(bool) + } netIP := netip.MustParseAddr(ip) ifaces, err := netmon.GetInterfaceList() if err != nil { @@ -973,11 +976,13 @@ func queryFromSelf(ip string) bool { switch v := a.(type) { case *net.IPNet: if pfx, ok := netaddr.FromStdIPNet(v); ok && pfx.Addr().Compare(netIP) == 0 { + p.queryFromSelfMap.Store(ip, true) return true } } } } + p.queryFromSelfMap.Store(ip, false) return false } diff --git a/cmd/cli/prog.go b/cmd/cli/prog.go index 54ea194..bca8bfb 100644 --- a/cmd/cli/prog.go +++ b/cmd/cli/prog.go @@ -98,6 +98,7 @@ type prog struct { ptrLoopGuard *loopGuard lanLoopGuard *loopGuard metricsQueryStats atomic.Bool + queryFromSelfMap sync.Map selfUninstallMu sync.Mutex refusedQueryCount int