Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 868d5f0

Browse files
committedOct 13, 2015
cache interface addresses
I frequently see a lot of goroutines stuck in a syscall trying to get addresses from the kernel. No idea why they hang, but i figure theres no harm in caching them for a few seconds. License: MIT Signed-off-by: Jeromy <jeromyj@gmail.com>
1 parent b610b8f commit 868d5f0

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
 

‎p2p/net/swarm/addr/addr.go

+20
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ package addrutil
22

33
import (
44
"fmt"
5+
"sync"
6+
"time"
57

68
logging "github.com/ipfs/go-ipfs/vendor/QmXJkcEXB6C9h6Ytb6rrUTFU56Ro62zxgrbxTT3dgjQGA8/go-log"
79

@@ -188,10 +190,25 @@ func ResolveUnspecifiedAddresses(unspecAddrs, ifaceAddrs []ma.Multiaddr) ([]ma.M
188190
return outputAddrs, nil
189191
}
190192

193+
const interfaceAddrCacheLife = time.Second * 5
194+
195+
var interfaceAddrLastCache time.Time
196+
var interfaceAddrCache []ma.Multiaddr
197+
var interfaceAddrLock sync.Mutex
198+
191199
// InterfaceAddresses returns a list of addresses associated with local machine
192200
// Note: we do not return link local addresses. IP loopback is ok, because we
193201
// may be connecting to other nodes in the same machine.
202+
// Addresses are cached for a short time as this method may be called very frequently
203+
// and syscalls can get expensive.
194204
func InterfaceAddresses() ([]ma.Multiaddr, error) {
205+
interfaceAddrLock.Lock()
206+
defer interfaceAddrLock.Unlock()
207+
cacheAge := time.Now().Sub(interfaceAddrLastCache)
208+
if interfaceAddrCache != nil && cacheAge < interfaceAddrCacheLife {
209+
return interfaceAddrCache, nil
210+
}
211+
195212
maddrs, err := manet.InterfaceMultiaddrs()
196213
if err != nil {
197214
return nil, err
@@ -209,6 +226,9 @@ func InterfaceAddresses() ([]ma.Multiaddr, error) {
209226
}
210227

211228
log.Debug("InterfaceAddresses: usable:", out)
229+
230+
interfaceAddrCache = out
231+
interfaceAddrLastCache = time.Now()
212232
return out, nil
213233
}
214234

0 commit comments

Comments
 (0)
Please sign in to comment.