bugfix: Race condition in stringvariables (#311)

This commit is contained in:
James Read 2024-05-13 15:10:44 +01:00 committed by GitHub
parent 1ab35fdb36
commit 80083fedab
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 28 additions and 8 deletions

View File

@ -30,14 +30,6 @@ func ReplaceEntityVars(prefix string, source string) string {
return source
}
func RemoveKeysThatStartWith(search string) {
for k, _ := range contents {
if strings.HasPrefix(k, search) {
delete(contents, k)
}
}
}
func GetEntities(entityTitle string) []string {
var ret []string

View File

@ -12,6 +12,8 @@ package stringvariables
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"strings"
"sync"
)
var (
@ -21,15 +23,25 @@ var (
Name: "olivetin_sv_count",
Help: "The number entries in the sv map",
})
rwmutex = sync.RWMutex{}
)
func init() {
rwmutex.Lock()
contents = make(map[string]string)
rwmutex.Unlock()
}
func Get(key string) string {
rwmutex.RLock()
v, ok := contents[key]
rwmutex.RUnlock()
if !ok {
return ""
} else {
@ -42,7 +54,23 @@ func GetAll() map[string]string {
}
func Set(key string, value string) {
rwmutex.Lock()
contents[key] = value
metricSvCount.Set(float64(len(contents)))
rwmutex.Unlock()
}
func RemoveKeysThatStartWith(search string) {
rwmutex.Lock()
for k, _ := range contents {
if strings.HasPrefix(k, search) {
delete(contents, k)
}
}
rwmutex.Unlock()
}