-
Notifications
You must be signed in to change notification settings - Fork 65
/
cache-memory.go
208 lines (180 loc) · 4.59 KB
/
cache-memory.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package rdns
import (
"os"
"sync"
"time"
"github.com/miekg/dns"
"github.com/sirupsen/logrus"
)
type memoryBackend struct {
lru *lruCache
mu sync.Mutex
opt MemoryBackendOptions
}
type MemoryBackendOptions struct {
// Total capacity of the cache, default unlimited
Capacity int
// How often to run garbage collection, default 1 minute
GCPeriod time.Duration
// Load the cache from file on startup and write it on close
Filename string
// Write the file in an interval. Only write on shutdown if not set
SaveInterval time.Duration
}
var _ CacheBackend = (*memoryBackend)(nil)
func NewMemoryBackend(opt MemoryBackendOptions) *memoryBackend {
if opt.GCPeriod == 0 {
opt.GCPeriod = time.Minute
}
b := &memoryBackend{
lru: newLRUCache(opt.Capacity),
opt: opt,
}
if opt.Filename != "" {
b.loadFromFile(opt.Filename)
}
go b.startGC(opt.GCPeriod)
go b.intervalSave()
return b
}
func (b *memoryBackend) Store(query *dns.Msg, item *cacheAnswer) {
b.mu.Lock()
b.lru.add(query, item)
b.mu.Unlock()
}
func (b *memoryBackend) Lookup(q *dns.Msg) (*dns.Msg, bool, bool) {
var answer *dns.Msg
var timestamp time.Time
var prefetchEligible bool
var expiry time.Time
b.mu.Lock()
if a := b.lru.get(q); a != nil {
answer = a.Msg.Copy()
timestamp = a.Timestamp
prefetchEligible = a.PrefetchEligible
expiry = a.Expiry
}
b.mu.Unlock()
// Return a cache-miss if there's no answer record in the map
if answer == nil {
return nil, false, false
}
// Check if item has expired from the cache
if time.Now().After(expiry) {
b.Evict(q)
return nil, false, false
}
// Make a copy of the response before returning it. Some later
// elements might make changes.
answer = answer.Copy()
answer.Id = q.Id
// Calculate the time the record spent in the cache. We need to
// subtract that from the TTL of each answer record.
age := uint32(time.Since(timestamp).Seconds())
// Go through all the answers, NS, and Extra and adjust the TTL (subtract the time
// it's spent in the cache). If the record is too old, evict it from the cache
// and return a cache-miss. OPT records have a TTL of 0 and are ignored.
for _, rr := range [][]dns.RR{answer.Answer, answer.Ns, answer.Extra} {
for _, a := range rr {
if _, ok := a.(*dns.OPT); ok {
continue
}
h := a.Header()
if age >= h.Ttl {
b.Evict(q)
return nil, false, false
}
h.Ttl -= age
}
}
return answer, prefetchEligible, true
}
func (b *memoryBackend) Evict(queries ...*dns.Msg) {
b.mu.Lock()
for _, query := range queries {
b.lru.delete(query)
}
b.mu.Unlock()
}
func (b *memoryBackend) Flush() {
b.mu.Lock()
defer b.mu.Unlock()
b.lru.reset()
}
// Runs every period time and evicts all items from the cache that are
// older than max, regardless of TTL. Note that the cache can hold old
// records that are no longer valid. These will only be evicted once
// a new query for them is made (and TTL is too old) or when they are
// older than max.
func (b *memoryBackend) startGC(period time.Duration) {
for {
time.Sleep(period)
now := time.Now()
var total, removed int
b.mu.Lock()
b.lru.deleteFunc(func(a *cacheAnswer) bool {
if now.After(a.Expiry) {
removed++
return true
}
return false
})
total = b.lru.size()
b.mu.Unlock()
Log.WithFields(logrus.Fields{"total": total, "removed": removed}).Trace("cache garbage collection")
}
}
func (b *memoryBackend) Size() int {
b.mu.Lock()
defer b.mu.Unlock()
return b.lru.size()
}
func (b *memoryBackend) Close() error {
if b.opt.Filename != "" {
return b.writeToFile(b.opt.Filename)
}
return nil
}
func (b *memoryBackend) writeToFile(filename string) error {
b.mu.Lock()
defer b.mu.Unlock()
log := Log.WithField("filename", filename)
log.Info("writing cache file")
f, err := os.Create(filename)
if err != nil {
log.WithError(err).Warn("failed to create cache file")
return err
}
defer f.Close()
if err := b.lru.serialize(f); err != nil {
log.WithError(err).Warn("failed to persist cache to disk")
return err
}
return nil
}
func (b *memoryBackend) loadFromFile(filename string) error {
b.mu.Lock()
defer b.mu.Unlock()
log := Log.WithField("filename", filename)
log.Info("reading cache file")
f, err := os.Open(filename)
if err != nil {
log.WithError(err).Warn("failed to open cache file")
return err
}
defer f.Close()
if err := b.lru.deserialize(f); err != nil {
log.WithError(err).Warn("failed to read cache from disk")
return err
}
return nil
}
func (b *memoryBackend) intervalSave() {
if b.opt.Filename == "" || b.opt.SaveInterval == 0 {
return
}
for {
time.Sleep(b.opt.SaveInterval)
b.writeToFile(b.opt.Filename)
}
}