autorestic/internal/lock/lock.go

73 lines
1.3 KiB
Go
Raw Normal View History

2021-04-09 01:55:10 +02:00
package lock
import (
2021-04-17 20:51:40 +02:00
"os"
2021-04-09 01:55:10 +02:00
"path"
"sync"
2021-04-17 20:51:40 +02:00
"github.com/cupcakearmy/autorestic/internal/colors"
2022-02-16 21:42:54 +01:00
"github.com/cupcakearmy/autorestic/internal/flags"
2021-04-09 01:55:10 +02:00
"github.com/spf13/viper"
)
var lock *viper.Viper
var file string
var once sync.Once
func getLock() *viper.Viper {
if lock == nil {
once.Do(func() {
lock = viper.New()
lock.SetDefault("running", false)
2021-11-23 12:32:35 +01:00
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")
2022-02-16 21:42:54 +01:00
if !flags.CRON_LEAN {
colors.Faint.Println("Using lock:\t", file)
}
2021-04-09 01:55:10 +02:00
lock.SetConfigFile(file)
lock.SetConfigType("yml")
lock.ReadInConfig()
})
}
return lock
}
2021-04-11 15:02:27 +02:00
func setLock(locked bool) error {
2021-04-09 01:55:10 +02:00
lock := getLock()
if locked {
running := lock.GetBool("running")
if running {
2021-04-17 20:51:40 +02:00
colors.Error.Println("an instance is already running. exiting")
os.Exit(1)
2021-04-09 01:55:10 +02:00
}
}
lock.Set("running", locked)
if err := lock.WriteConfigAs(file); err != nil {
return err
}
return nil
}
2021-04-11 15:02:27 +02:00
func GetCron(location string) int64 {
lock := getLock()
return lock.GetInt64("cron." + location)
}
func SetCron(location string, value int64) {
lock.Set("cron."+location, value)
lock.WriteConfigAs(file)
}
2021-04-09 01:55:10 +02:00
func Lock() error {
2021-04-11 15:02:27 +02:00
return setLock(true)
2021-04-09 01:55:10 +02:00
}
func Unlock() error {
2021-04-11 15:02:27 +02:00
return setLock(false)
2021-04-09 01:55:10 +02:00
}