2020-05-04 13:21:24 +00:00
|
|
|
package discoveryutils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
2020-05-14 19:01:51 +00:00
|
|
|
|
2021-03-01 12:13:56 +00:00
|
|
|
"github.com/VictoriaMetrics/metrics"
|
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 {
|
2021-03-01 12:13:56 +00:00
|
|
|
mu sync.Mutex
|
2024-07-09 22:14:15 +00:00
|
|
|
m map[any]any
|
2021-03-01 12:13:56 +00:00
|
|
|
|
|
|
|
entriesCount *metrics.Counter
|
2020-05-04 13:21:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewConfigMap creates ConfigMap
|
|
|
|
func NewConfigMap() *ConfigMap {
|
|
|
|
return &ConfigMap{
|
2024-07-09 22:14:15 +00:00
|
|
|
m: make(map[any]any),
|
2021-03-01 12:13:56 +00:00
|
|
|
entriesCount: metrics.GetOrCreateCounter(`vm_promscrape_discoveryutils_configmap_entries_count`),
|
2020-05-04 13:21:24 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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.
|
2024-07-09 22:14:15 +00:00
|
|
|
func (cm *ConfigMap) Get(key any, newConfig func() (any, error)) (any, error) {
|
2020-05-04 13:21:24 +00:00
|
|
|
cm.mu.Lock()
|
|
|
|
defer cm.mu.Unlock()
|
|
|
|
|
2021-03-01 12:13:56 +00:00
|
|
|
cfg := cm.m[key]
|
|
|
|
if cfg != nil {
|
|
|
|
return cfg, nil
|
2020-05-04 13:21:24 +00:00
|
|
|
}
|
|
|
|
cfg, err := newConfig()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-03-01 12:13:56 +00:00
|
|
|
cm.m[key] = cfg
|
|
|
|
cm.entriesCount.Inc()
|
2020-05-04 13:21:24 +00:00
|
|
|
return cfg, nil
|
|
|
|
}
|
|
|
|
|
2021-03-01 12:13:56 +00:00
|
|
|
// Delete deletes config for the given key from cm and returns it.
|
2024-07-09 22:14:15 +00:00
|
|
|
func (cm *ConfigMap) Delete(key any) any {
|
2021-03-01 12:13:56 +00:00
|
|
|
cm.mu.Lock()
|
|
|
|
defer cm.mu.Unlock()
|
2020-05-04 13:21:24 +00:00
|
|
|
|
2021-03-01 12:13:56 +00:00
|
|
|
cfg := cm.m[key]
|
|
|
|
if cfg == nil {
|
|
|
|
// The cfg can be missing if it wasn't accessed yet.
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
cm.entriesCount.Dec()
|
|
|
|
delete(cm.m, key)
|
|
|
|
return cfg
|
2020-05-04 13:21:24 +00:00
|
|
|
}
|