forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tscache.go
65 lines (58 loc) · 1.52 KB
/
tscache.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
package vsphere
import (
"log"
"sync"
"time"
)
// TSCache is a cache of timestamps used to determine the validity of datapoints
type TSCache struct {
ttl time.Duration
table map[string]time.Time
done chan struct{}
mux sync.RWMutex
}
// NewTSCache creates a new TSCache with a specified time-to-live after which timestamps are discarded.
func NewTSCache(ttl time.Duration) *TSCache {
return &TSCache{
ttl: ttl,
table: make(map[string]time.Time),
done: make(chan struct{}),
}
}
// Purge removes timestamps that are older than the time-to-live
func (t *TSCache) Purge() {
t.mux.Lock()
defer t.mux.Unlock()
n := 0
for k, v := range t.table {
if time.Now().Sub(v) > t.ttl {
delete(t.table, k)
n++
}
}
log.Printf("D! [input.vsphere] Purged timestamp cache. %d deleted with %d remaining", n, len(t.table))
}
// IsNew returns true if the supplied timestamp for the supplied key is more recent than the
// timestamp we have on record.
func (t *TSCache) IsNew(key string, tm time.Time) bool {
t.mux.RLock()
defer t.mux.RUnlock()
v, ok := t.table[key]
if !ok {
return true // We've never seen this before, so consider everything a new sample
}
return !tm.Before(v)
}
// Get returns a timestamp (if present)
func (t *TSCache) Get(key string) (time.Time, bool) {
t.mux.RLock()
defer t.mux.RUnlock()
ts, ok := t.table[key]
return ts, ok
}
// Put updates the latest timestamp for the supplied key.
func (t *TSCache) Put(key string, time time.Time) {
t.mux.Lock()
defer t.mux.Unlock()
t.table[key] = time
}