Add a lock to the states file

This commit is contained in:
Matthew Penner 2020-04-10 16:37:10 -06:00
parent 1e12b7b37c
commit acf425b705

View File

@ -4,12 +4,19 @@ import (
"encoding/json"
"github.com/pkg/errors"
"os"
"sync"
)
var statesFile = "data/states.json"
var (
statesLock sync.Mutex
statesFile = "data/states.json"
)
// DoesStatesFileExist .
func DoesStatesFileExist() (bool, error) {
statesLock.Lock()
defer statesLock.Unlock()
if _, err := os.Stat(statesFile); err != nil {
if !os.IsNotExist(err) {
return false, errors.WithStack(err)
@ -29,6 +36,10 @@ func FetchServerStates() (map[string]string, error) {
return nil, errors.WithStack(err)
}
// Request a lock after we check if the file exists.
statesLock.Lock()
defer statesLock.Unlock()
// Return an empty map if the file does not exist.
if !exists {
return map[string]string{}, nil
@ -70,6 +81,10 @@ func SaveServerStates() error {
return errors.WithStack(err)
}
// Request a lock after we check if the file exists.
statesLock.Lock()
defer statesLock.Unlock()
// Create the file if it doesn't exist or open it if it already does.
var f *os.File
if !exists {