/
schedule.go
53 lines (45 loc) · 1.76 KB
/
schedule.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package common
import (
"fmt"
"math/rand"
"time"
)
var (
maitenanceWindowStart = time.Date(1970, 1, 1, 21, 0, 0, 0, time.UTC)
maitenanceWindowEnd = time.Date(1970, 1, 2, 5, 0, 0, 0, time.UTC)
maitenanceWindowRange = maitenanceWindowEnd.Unix() - maitenanceWindowStart.Unix()
)
// BackupScheduler can schedule backups
type BackupScheduler interface {
GetBackupSchedule() string
SetBackupSchedule(string)
}
type MaintenanceScheduler interface {
GetMaintenanceDayOfWeek() string
SetMaintenanceDayOfWeek(string)
GetMaintenanceTimeOfDay() string
SetMaintenanceTimeOfDay(string)
}
// SetRandomSchedules initializes the backup and maintenance schedules if the user did not explicitly provide a schedule.
// The maintenance will be set to a random time on Tuesday night between 21:00 and 5:00, and the backup schedule will be set to once a day between 20:00 and 4:00.
// If neither maintenance nor backup is set, the function will make sure that there will be backup scheduled one hour before the maintenance.
func SetRandomSchedules(backup BackupScheduler, maintenance MaintenanceScheduler) {
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
maintTime := time.Unix(maitenanceWindowStart.Unix()+rng.Int63n(maitenanceWindowRange), 0).In(time.UTC)
backupTime := maintTime.Add(-1 * time.Hour).In(time.UTC)
if backup.GetBackupSchedule() == "" {
newSchedule := fmt.Sprintf("%d %d * * *", backupTime.Minute(), backupTime.Hour())
backup.SetBackupSchedule(newSchedule)
}
if maintenance.GetMaintenanceTimeOfDay() == "" {
newTime := maintTime.Format(time.TimeOnly)
maintenance.SetMaintenanceTimeOfDay(newTime)
}
if maintenance.GetMaintenanceDayOfWeek() == "" {
day := "tuesday"
if maintTime.Day() > 1 {
day = "wednesday"
}
maintenance.SetMaintenanceDayOfWeek(day)
}
}