genericize ip cache

This commit is contained in:
Daniel Smith
2015-01-09 14:06:30 -08:00
parent f2b82c6c2b
commit 6e70853e83
3 changed files with 150 additions and 32 deletions

View File

@@ -17,7 +17,6 @@ limitations under the License.
package master
import (
"sync"
"time"
"github.com/GoogleCloudPlatform/kubernetes/pkg/cloudprovider"
@@ -26,19 +25,6 @@ import (
"github.com/golang/glog"
)
type ipCacheEntry struct {
ip string
lastUpdate time.Time
}
type ipCache struct {
clock util.Clock
cloudProvider cloudprovider.Interface
cache map[string]ipCacheEntry
lock sync.Mutex
ttl time.Duration
}
// NewIPCache makes a new ip caching layer, which will get IP addresses from cp,
// and use clock for deciding when to re-get an IP address.
// Thread-safe.
@@ -47,30 +33,24 @@ type ipCache struct {
// that could be produced from a template and a type via `go generate`.
func NewIPCache(cp cloudprovider.Interface, clock util.Clock, ttl time.Duration) *ipCache {
return &ipCache{
clock: clock,
cloudProvider: cp,
cache: map[string]ipCacheEntry{},
ttl: ttl,
cache: util.NewTimeCache(
clock,
ttl,
func(host string) util.T {
return getInstanceIPFromCloud(cp, host)
},
),
}
}
type ipCache struct {
cache util.TimeCache
}
// GetInstanceIP returns the IP address of host, from the cache
// if possible, otherwise it asks the cloud provider.
func (c *ipCache) GetInstanceIP(host string) string {
c.lock.Lock()
defer c.lock.Unlock()
data, ok := c.cache[host]
now := c.clock.Now()
if !ok || now.Sub(data.lastUpdate) > c.ttl {
ip := getInstanceIPFromCloud(c.cloudProvider, host)
data = ipCacheEntry{
ip: ip,
lastUpdate: now,
}
c.cache[host] = data
}
return data.ip
return c.cache.Get(host).(string)
}
func getInstanceIPFromCloud(cloud cloudprovider.Interface, host string) string {