forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.go
93 lines (74 loc) · 2.14 KB
/
storage.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package dnscache
import (
"net"
"time"
"fmt"
cache "github.com/pmylund/go-cache"
"github.com/sirupsen/logrus"
)
// DnsCacheItem represents single record in cache
type DnsCacheItem struct {
Addrs []string
}
// DnsCacheStorage is an in-memory cache of auto-purged dns query ip responses
type DnsCacheStorage struct {
cache *cache.Cache
}
func NewDnsCacheStorage(expiration, checkInterval time.Duration) *DnsCacheStorage {
storage := DnsCacheStorage{cache.New(expiration, checkInterval)}
return &storage
}
// Items returns map of non expired dns cache items
func (dc *DnsCacheStorage) Items(includeExpired bool) map[string]DnsCacheItem {
var allItems = dc.cache.Items()
nonExpiredItems := map[string]DnsCacheItem{}
for k, v := range allItems {
if !includeExpired && v.Expired() {
continue
}
nonExpiredItems[k] = v.Object.(DnsCacheItem)
}
return nonExpiredItems
}
// Get returns non expired item from cache
func (dc *DnsCacheStorage) Get(key string) (DnsCacheItem, bool) {
item, found := dc.cache.Get(key)
if !found {
return DnsCacheItem{}, false
}
return item.(DnsCacheItem), found
}
func (dc *DnsCacheStorage) Delete(key string) {
dc.cache.Delete(key)
}
// FetchItem returns list of ips from cache or resolves them and add to cache
func (dc *DnsCacheStorage) FetchItem(hostName string) ([]string, error) {
if hostName == "" {
return nil, fmt.Errorf("hostName can't be empty. hostName=%v", hostName)
}
item, ok := dc.Get(hostName)
if ok {
logger.WithFields(logrus.Fields{
"hostName": hostName,
"addrs": item.Addrs,
}).Debug("Dns record was populated from cache")
return item.Addrs, nil
}
addrs, err := dc.resolveDNSRecord(hostName)
if err != nil {
return nil, err
}
dc.Set(hostName, addrs)
return addrs, nil
}
func (dc *DnsCacheStorage) Set(key string, addrs []string) {
logger.Debugf("Adding dns record to cache: key=%q, addrs=%q", key, addrs)
dc.cache.Set(key, DnsCacheItem{addrs}, cache.DefaultExpiration)
}
// Clear deletes all records from cache
func (dc *DnsCacheStorage) Clear() {
dc.cache.Flush()
}
func (dc *DnsCacheStorage) resolveDNSRecord(host string) ([]string, error) {
return net.LookupHost(host)
}