Don't delete cached server IP addresses

If we can't update an entry, keep the previous one.
This commit is contained in:
Frank Denis 2019-11-01 22:55:06 +01:00
parent 3db3de0a91
commit e028f4d483
1 changed files with 17 additions and 12 deletions

View File

@ -97,21 +97,21 @@ func (xTransport *XTransport) saveCachedIP(host string, ip net.IP, ttl time.Dura
xTransport.cachedIPs.Unlock() xTransport.cachedIPs.Unlock()
} }
func (xTransport *XTransport) loadCachedIP(host string, deleteIfExpired bool) (net.IP, bool) { func (xTransport *XTransport) loadCachedIP(host string) (ip net.IP, expired bool) {
ip = nil
expired = false
xTransport.cachedIPs.RLock() xTransport.cachedIPs.RLock()
item, ok := xTransport.cachedIPs.cache[host] item, ok := xTransport.cachedIPs.cache[host]
xTransport.cachedIPs.RUnlock() xTransport.cachedIPs.RUnlock()
if !ok { if !ok {
return nil, false return
} }
ip = item.ip
expiration := item.expiration expiration := item.expiration
if deleteIfExpired && expiration != nil && time.Until(*expiration) < 0 { if expiration != nil && time.Until(*expiration) < 0 {
xTransport.cachedIPs.Lock() expired = true
delete(xTransport.cachedIPs.cache, host)
xTransport.cachedIPs.Unlock()
return nil, false
} }
return item.ip, ok return
} }
func (xTransport *XTransport) rebuildTransport() { func (xTransport *XTransport) rebuildTransport() {
@ -131,8 +131,8 @@ func (xTransport *XTransport) rebuildTransport() {
DialContext: func(ctx context.Context, network, addrStr string) (net.Conn, error) { DialContext: func(ctx context.Context, network, addrStr string) (net.Conn, error) {
host, port := ExtractHostAndPort(addrStr, stamps.DefaultPort) host, port := ExtractHostAndPort(addrStr, stamps.DefaultPort)
ipOnly := host ipOnly := host
cachedIP, ok := xTransport.loadCachedIP(host, false) cachedIP, _ := xTransport.loadCachedIP(host)
if ok { if cachedIP == nil {
if ipv4 := cachedIP.To4(); ipv4 != nil { if ipv4 := cachedIP.To4(); ipv4 != nil {
ipOnly = ipv4.String() ipOnly = ipv4.String()
} else { } else {
@ -249,7 +249,8 @@ func (xTransport *XTransport) resolveHost(host string) (err error) {
if ParseIP(host) != nil { if ParseIP(host) != nil {
return return
} }
if _, ok := xTransport.loadCachedIP(host, true); ok { cachedIP, expired := xTransport.loadCachedIP(host)
if !expired {
return return
} }
var foundIP net.IP var foundIP net.IP
@ -275,8 +276,12 @@ func (xTransport *XTransport) resolveHost(host string) (err error) {
} }
} }
if err != nil { if err != nil {
if cachedIP != nil {
foundIP = cachedIP
} else {
return return
} }
}
xTransport.saveCachedIP(host, foundIP, ttl) xTransport.saveCachedIP(host, foundIP, ttl)
dlog.Debugf("[%s] IP address [%s] added to the cache, valid until %v", host, foundIP, ttl) dlog.Debugf("[%s] IP address [%s] added to the cache, valid until %v", host, foundIP, ttl)
return return