forked from blind-oracle/dnstap-bgp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
87 lines (74 loc) · 1.19 KB
/
cache.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
package main
import (
"net"
"sync"
"time"
)
type cacheEntry struct {
IP net.IP
Domain string
TS time.Time
}
type expireFunc func(*cacheEntry)
type cache struct {
m map[string]*cacheEntry
ttl time.Duration
expireCb expireFunc
sync.RWMutex
}
func (c *cache) cleanupScheduler() {
for {
c.cleanup()
time.Sleep(time.Minute)
}
}
func (c *cache) cleanup() {
now := time.Now()
c.Lock()
for k, v := range c.m {
if now.Sub(v.TS) >= c.ttl {
delete(c.m, k)
if c.expireCb != nil {
c.expireCb(v)
}
}
}
c.Unlock()
}
func (c *cache) exists(ip net.IP, update bool) bool {
c.Lock()
e, ok := c.m[string(ip)]
if ok && update {
e.TS = time.Now()
}
c.Unlock()
return ok
}
func (c *cache) add(e *cacheEntry) {
c.Lock()
c.m[string(e.IP)] = e
c.Unlock()
return
}
func (c *cache) getAll() (es []*cacheEntry) {
c.RLock()
for _, e := range c.m {
es = append(es, e)
}
c.RUnlock()
return
}
func (c *cache) count() int {
c.Lock()
defer c.Unlock()
return len(c.m)
}
func newCache(ttl time.Duration, expireCb expireFunc) (c *cache) {
c = &cache{
m: map[string]*cacheEntry{},
expireCb: expireCb,
ttl: ttl,
}
go c.cleanupScheduler()
return
}