Skip to content

Commit

Permalink
fix(dns): concurrent map writes
Browse files Browse the repository at this point in the history
  • Loading branch information
EkkoG committed Oct 30, 2024
1 parent dbbae6f commit bf953c8
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
6 changes: 0 additions & 6 deletions control/dns.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,7 @@ type DnsForwarder interface {
Close() error
}

var forwarderCache = make(map[string]DnsForwarder)

func newDnsForwarder(upstream *dns.Upstream, dialArgument dialArgument) (DnsForwarder, error) {
if forwarder, ok := forwarderCache[upstream.String()]; ok {
return forwarder, nil
}
forwarder, err := func() (DnsForwarder, error) {
switch dialArgument.l4proto {
case consts.L4ProtoStr_TCP:
Expand Down Expand Up @@ -65,7 +60,6 @@ func newDnsForwarder(upstream *dns.Upstream, dialArgument dialArgument) (DnsForw
if err != nil {
return nil, err
}
forwarderCache[upstream.String()] = forwarder
return forwarder, nil
}

Expand Down
18 changes: 17 additions & 1 deletion control/dns_control.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ type DnsController struct {
// mutex protects the dnsCache.
dnsCacheMu sync.Mutex
dnsCache map[string]*DnsCache
dnsForwarderCacheMu sync.Mutex
dnsForwarderCache map[string]DnsForwarder
}

func parseIpVersionPreference(prefer int) (uint16, error) {
Expand Down Expand Up @@ -114,6 +116,8 @@ func NewDnsController(routing *dns.Dns, option *DnsControllerOption) (c *DnsCont
fixedDomainTtl: option.FixedDomainTtl,
dnsCacheMu: sync.Mutex{},
dnsCache: make(map[string]*DnsCache),
dnsForwarderCacheMu: sync.Mutex{},
dnsForwarderCache: make(map[string]DnsForwarder),
}, nil
}

Expand Down Expand Up @@ -556,7 +560,19 @@ func (c *DnsController) dialSend(invokingDepth int, req *udpRequest, data []byte
ctxDial, cancel := context.WithTimeout(context.TODO(), consts.DefaultDialTimeout)
defer cancel()

forwarder, err := newDnsForwarder(upstream, *dialArgument)
// get forwarder from cache
c.dnsForwarderCacheMu.Lock()
forwarder, ok := c.dnsForwarderCache[upstreamName]
if !ok {
forwarder, err = newDnsForwarder(upstream, *dialArgument)
if err != nil {
c.dnsForwarderCacheMu.Unlock()
return err
}
c.dnsForwarderCache[upstreamName] = forwarder
}
c.dnsForwarderCacheMu.Unlock()

defer func() {
if !connClosed {
forwarder.Close()
Expand Down

0 comments on commit bf953c8

Please sign in to comment.