-
Notifications
You must be signed in to change notification settings - Fork 0
/
scheduler.go
162 lines (135 loc) · 4.84 KB
/
scheduler.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package agent
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/joaquinrovira/upv-oos-reservations/lib/logging"
"github.com/joaquinrovira/upv-oos-reservations/lib/model/daytime"
"github.com/joaquinrovira/upv-oos-reservations/lib/model/timerange"
"github.com/joaquinrovira/upv-oos-reservations/lib/util"
"github.com/joaquinrovira/upv-oos-reservations/lib/vars"
"github.com/reugn/go-quartz/quartz"
)
var lock sync.Mutex
var triggers []*util.CronTrigger
func registerCron(cron string) {
if triggers == nil {
triggers = make([]*util.CronTrigger, 0)
}
if trigger, err := util.NewCronTrigger(strings.TrimSpace(cron)); err != nil {
logging.Out().Fatal().Msgf("'%s' %v", cron, err)
} else {
triggers = append(triggers, trigger)
logging.Out().Info().Msgf("registered job trigger %-20v", fmt.Sprintf("(%v)", trigger.Expression()))
logging.Out().Info().Msgf("description: \"%v\"", trigger.Description())
}
}
func init() {
logging.Out().Info().Msg("+-----------------------+")
logging.Out().Info().Msg("| Registering CRON jobs |")
logging.Out().Info().Msg("+-----------------------+")
tz, _ := time.Now().Zone()
logging.Out().Debug().Msgf("TZ=%v", tz)
// Parse and validate Crons
// Split by ',' and trim
var split = strings.FieldsFunc(vars.Get(vars.DefaultCron), func(r rune) bool { return r == ',' })
for _, cron := range split {
logging.Out().Info().Msgf("env.%-15s adding default cron '%s'", vars.DefaultCron, cron)
registerCron(cron)
}
// Parse and validate CustomCron
if vars.Has(vars.CustomCron) {
cron := vars.Get(vars.CustomCron)
logging.Out().Info().Msgf("env.%-15s adding custom cron '%s'", vars.CustomCron, cron)
registerCron(cron)
}
// Add high-frequency job when DEBUG env var is present
if vars.Has(vars.HighFqTrigger) {
var cron string = "*/10 * * * * *" // Every 10 seconds
logging.Out().Info().Msgf("env.%-15s enabled adding debug cron '%s'", vars.HighFqTrigger, cron)
registerCron(cron)
}
}
func runJobScheduleWrapper(a *Agent, trigger *util.CronTrigger) quartz.Job {
return quartz.NewFunctionJob(func(context.Context) (int, error) {
logging.Out().Debug().Msgf("👀 \t %s", trigger.Expression())
lock.Lock()
logging.Out().Debug().Msgf("🔒 \t %s", trigger.Expression())
defer lock.Unlock()
defer logging.Out().Debug().Msgf("🔓 \t %s", trigger.Expression())
logging.Out().Info().Msg("+------------------------------------------+")
logging.Out().Info().Msgf("| Reservation trigger %20s |", trigger.Expression())
logging.Out().Info().Msg("+------------------------------------------+")
next, _ := trigger.NextFireTime(time.Now().UnixNano())
defer logging.Out().Debug().Msgf("next execution in %v", time.Until(time.Unix(0, next)).Round(time.Second))
return 0, a.Run()
})
}
func (a *Agent) RunWithScheduler() (err error) {
sched := quartz.NewStdScheduler()
sched.Start(context.TODO())
for _, trigger := range triggers {
job := runJobScheduleWrapper(a, trigger)
sched.ScheduleJob(context.TODO(), job, trigger)
}
<-a.ctx.Done()
sched.Stop()
return
}
func (a *Agent) Run() (err error) {
a.Login()
targets := a.target.Clone()
value, err := a.GetReservationsData()
if err != nil {
return err
}
// Remove targets that have already been fulfilled
reservations := value.GetReservations()
for day := range reservations {
logging.Out().Info().Msgf("%-10v (skipping) already fulfilled in time slot %v", day.String(), reservations[day].At)
delete(targets, day)
}
// Remove targets for today or the days before
today := time.Now().Weekday()
if today != time.Saturday {
for day := range targets {
if day <= today {
logging.Out().Info().Msgf("%-10v (skipping) avoiding past days", day.String())
delete(targets, day)
}
}
}
// Minimum 24hr buffer
logging.Out().Debug().Msg("ensuring 24hr buffer")
tomorrow := time.Now().Add(time.Hour * 24).Weekday()
now, _ := daytime.FromTime(time.Now())
var newTargetValue []timerange.TimeRange
for _, rnge := range targets[tomorrow] {
if rnge.End.Value() < now.Value() {
logging.Out().Info().Msgf("%-10v (avoiding) range %v with less than 24h reservation margin", tomorrow, rnge)
continue
}
if rnge.Start.Value() < now.Value() {
logging.Out().Info().Msgf("%-10v (modifying) range %v to range %v-%v to ensure 24h reservation margin", tomorrow, rnge, now, rnge.End)
rnge.Start = now
}
newTargetValue = append(newTargetValue, rnge)
}
targets[tomorrow] = newTargetValue
// Handle valid targets
for day, target := range targets {
if len(target) < 1 {
continue
}
targetErr := a.handleTargetList(value, day, target)
if targetErr != nil {
logging.Out().Err(targetErr).Msgf("%-10v (failure) unable to fulfill request for %v", day.String(), target)
} else {
logging.Out().Info().Msgf("%-10v (success) %v fullfilled", day.String(), target)
}
}
logging.Out().Info().Msg("finished reservation attempt!")
return err
}