2020-05-04 13:21:24 +00:00
|
|
|
package discoveryutils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"time"
|
2020-05-14 19:01:51 +00:00
|
|
|
|
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/fasttime"
|
2020-05-04 13:21:24 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// ConfigMap is a map for storing discovery api configs.
|
|
|
|
//
|
|
|
|
// It automatically removes old configs which weren't accessed recently.
|
|
|
|
type ConfigMap struct {
|
|
|
|
mu sync.Mutex
|
|
|
|
m map[interface{}]*configMapEntry
|
|
|
|
hasCleaner bool
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewConfigMap creates ConfigMap
|
|
|
|
func NewConfigMap() *ConfigMap {
|
|
|
|
return &ConfigMap{
|
|
|
|
m: make(map[interface{}]*configMapEntry),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get returns config for the given key.
|
|
|
|
//
|
|
|
|
// Key must be a pointer.
|
|
|
|
//
|
|
|
|
// It creates new config map with newConfig() call if cm doesn't contain config under the given key.
|
|
|
|
func (cm *ConfigMap) Get(key interface{}, newConfig func() (interface{}, error)) (interface{}, error) {
|
|
|
|
cm.mu.Lock()
|
|
|
|
defer cm.mu.Unlock()
|
|
|
|
|
|
|
|
if !cm.hasCleaner {
|
|
|
|
cm.hasCleaner = true
|
|
|
|
go cm.cleaner()
|
|
|
|
}
|
|
|
|
|
|
|
|
e := cm.m[key]
|
|
|
|
if e != nil {
|
2020-05-14 19:01:51 +00:00
|
|
|
e.lastAccessTime = fasttime.UnixTimestamp()
|
2020-05-04 13:21:24 +00:00
|
|
|
return e.cfg, nil
|
|
|
|
}
|
|
|
|
cfg, err := newConfig()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
cm.m[key] = &configMapEntry{
|
|
|
|
cfg: cfg,
|
2020-05-14 19:01:51 +00:00
|
|
|
lastAccessTime: fasttime.UnixTimestamp(),
|
2020-05-04 13:21:24 +00:00
|
|
|
}
|
|
|
|
return cfg, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cm *ConfigMap) cleaner() {
|
|
|
|
tc := time.NewTicker(15 * time.Minute)
|
2020-05-14 19:01:51 +00:00
|
|
|
for range tc.C {
|
|
|
|
currentTime := fasttime.UnixTimestamp()
|
2020-05-04 13:21:24 +00:00
|
|
|
cm.mu.Lock()
|
|
|
|
for k, e := range cm.m {
|
2020-05-14 19:01:51 +00:00
|
|
|
if currentTime-e.lastAccessTime > 10*60 {
|
2020-05-04 13:21:24 +00:00
|
|
|
delete(cm.m, k)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
cm.mu.Unlock()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type configMapEntry struct {
|
|
|
|
cfg interface{}
|
2020-05-14 19:01:51 +00:00
|
|
|
lastAccessTime uint64
|
2020-05-04 13:21:24 +00:00
|
|
|
}
|