You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
autorestic/internal/lock/lock.go

79 lines
1.4 KiB

4 years ago
package lock
import (
"os"
4 years ago
"path"
"sync"
"github.com/cupcakearmy/autorestic/internal/colors"
3 years ago
"github.com/cupcakearmy/autorestic/internal/flags"
4 years ago
"github.com/spf13/viper"
)
var lock *viper.Viper
var file string
var once sync.Once
const (
RUNNING = "running"
)
4 years ago
func getLock() *viper.Viper {
if lock == nil {
once.Do(func() {
lock = viper.New()
lock.SetDefault("running", false)
p := viper.ConfigFileUsed()
if p == "" {
colors.Error.Println("cannot lock before reading config location")
os.Exit(1)
}
file = path.Join(path.Dir(p), ".autorestic.lock.yml")
3 years ago
if !flags.CRON_LEAN {
colors.Faint.Println("Using lock:\t", file)
}
4 years ago
lock.SetConfigFile(file)
lock.SetConfigType("yml")
lock.ReadInConfig()
})
}
return lock
}
func setLockValue(key string, value interface{}) (*viper.Viper, error) {
4 years ago
lock := getLock()
if key == RUNNING {
value := value.(bool)
if value && lock.GetBool(key) {
colors.Error.Println("an instance is already running. exiting")
os.Exit(1)
4 years ago
}
}
lock.Set(key, value)
4 years ago
if err := lock.WriteConfigAs(file); err != nil {
return nil, err
4 years ago
}
return lock, nil
4 years ago
}
4 years ago
func GetCron(location string) int64 {
return getLock().GetInt64("cron." + location)
4 years ago
}
func SetCron(location string, value int64) {
setLockValue("cron."+location, value)
4 years ago
}
4 years ago
func Lock() error {
_, err := setLockValue(RUNNING, true)
return err
4 years ago
}
func Unlock() error {
_, err := setLockValue(RUNNING, false)
return err
4 years ago
}