backive/scheduler/scheduler.go

77 lines
1.7 KiB
Go
Raw Normal View History

2021-10-27 23:05:36 +02:00
package scheduler
import (
2021-11-02 14:36:07 +01:00
"container/list"
2021-10-27 23:05:36 +02:00
"encoding/json"
2021-11-02 14:36:07 +01:00
"fmt"
2021-10-27 23:05:36 +02:00
"time"
"github.com/qwc/backive/config"
"github.com/qwc/backive/db"
)
2021-11-02 14:36:07 +01:00
type backupRuns struct {
runlist *list.List
}
2021-10-27 23:17:18 +02:00
// Runs contains the Data for the scheduler: mapping from backups to a list of timestamps of the last 10 backups
2021-11-02 14:36:07 +01:00
type Runs map[string]backupRuns
2021-10-27 23:05:36 +02:00
var runs Runs
2021-10-27 23:17:18 +02:00
// Load loads the data from the json database
2021-10-27 23:05:36 +02:00
func Load() {
runerr := json.Unmarshal([]byte(db.Database["runs"]), &runs)
if runerr != nil {
panic(runerr)
}
}
2021-10-27 23:17:18 +02:00
// Save saves the data into the json database
2021-10-27 23:05:36 +02:00
func Save() {
str, err := json.Marshal(runs)
if err != nil {
panic(err)
}
db.Database["runs"] = string(str)
}
2021-10-27 23:17:18 +02:00
// ShouldRun Takes a backup key and returns a bool if a backup should run now.
2021-10-27 23:05:36 +02:00
func ShouldRun(backup string) bool {
2021-10-27 23:17:18 +02:00
backupdata := config.Get().Backups[backup]
freq := backupdata.Frequency
2021-10-27 23:05:36 +02:00
// calculate time difference from last run, return true if no run has taken place
2021-11-02 14:36:07 +01:00
lr, ok := LastRun(backup)
if ok == nil {
dur := time.Since(lr)
days := dur.Hours() / 24
if days > float64(freq) {
return true
}
}
if freq == 0 {
2021-10-27 23:05:36 +02:00
return true
}
return false
}
2021-11-02 14:36:07 +01:00
// RegisterRun saves a date of a backup run into the internal storage
func RegisterRun(backup string) {
nbl, ok := runs[backup]
if !ok {
nbl.runlist = list.New()
runs[backup] = nbl
}
nbl.runlist.PushFront(time.Now())
}
// LastRun returns the time.Time of the last run of the backup given.
func LastRun(backup string) (time.Time, error) {
_, ok := runs[backup]
if ok {
var t = time.Time(runs[backup].runlist.Front().Value.(time.Time))
return t, nil
}
2021-11-02 14:40:35 +01:00
return time.Unix(0, 0), fmt.Errorf("Backup name not found and therefore has never run")
2021-11-02 14:36:07 +01:00
}