-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcrontinuous.go
406 lines (341 loc) · 10 KB
/
crontinuous.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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*
Copyright 2020 Adevinta
*/
package crontinuous
import (
"errors"
"fmt"
"math/rand"
"strconv"
"strings"
"sync"
"github.com/manelmontilla/cron"
"github.com/sirupsen/logrus"
)
const (
MaxRandomizeCronMinuteInterval int = 59
ScanCronType CronType = iota
ReportCronType
)
var (
// ErrScheduleNotFound is returned by DeleteSchedule method if the id for the schedule is not found.
ErrScheduleNotFound = errors.New("ErrorScheduleNotFound")
// ErrMalformedSchedule indicates the given cron spec is invalid.
ErrMalformedSchedule = errors.New("ErrorMalformedSchedule")
// ErrMalformedEntry indicates the given entry is invalid.
ErrMalformedEntry = errors.New("ErrorMalformedEntry")
// ErrInvalidCronType indicates the given cron type is invalid.
ErrInvalidCronType = errors.New("ErrInvalidCronType")
// errTeamNotWhitelisted is used internally from scan and report
// cron files to indicate that entry was saved but should not be
// created because the teamID is not whitelisted.
errTeamNotWhitelisted = errors.New("ErrTeamNotWhitelisted")
)
// Config holds the information required by the Crontinuous
type Config struct {
Bucket string
EnableTeamsWhitelistScan bool
TeamsWhitelistScan []string
EnableTeamsWhitelistReport bool
TeamsWhitelistReport []string
RandomizeCronMinuteProgramSuffixes string
RandomizeCronMinuteInterval int
}
type CronType int
type CronEntry interface {
GetID() string
GetCronSpec() string
}
type cronEntryWithSchedule struct {
entry CronEntry
schedule cron.Schedule
overwriteEntry bool
}
type cronJobSchedule struct {
schedule cron.Schedule
job cron.Job
id string
}
// Crontinuous implements the logic for storing and executing programs.
type Crontinuous struct {
config Config
log *logrus.Logger
scanCreator ScanCreator
scanCronStore ScanCronStore
scanEntries map[string]ScanEntry
scanMux sync.RWMutex
reportSender ReportSender
reportCronStore ReportCronStore
reportEntries map[string]ReportEntry
reportMux sync.RWMutex
cron *cron.Cron
}
// NewCrontinuous creates a new instance of the crontinuous service.
func NewCrontinuous(cfg Config, logger *logrus.Logger,
scanCreator ScanCreator, scanCronStore ScanCronStore,
reportSender ReportSender, reportCronStore ReportCronStore) *Crontinuous {
if cfg.RandomizeCronMinuteInterval < 1 || cfg.RandomizeCronMinuteInterval > MaxRandomizeCronMinuteInterval {
logger.Infof("changing randomize-cron-minute-interval from [%d] to [%d]", cfg.RandomizeCronMinuteInterval, MaxRandomizeCronMinuteInterval)
cfg.RandomizeCronMinuteInterval = MaxRandomizeCronMinuteInterval
}
return &Crontinuous{
config: cfg,
log: logger,
scanCreator: scanCreator,
scanCronStore: scanCronStore,
scanEntries: make(map[string]ScanEntry),
reportSender: reportSender,
reportCronStore: reportCronStore,
reportEntries: make(map[string]ReportEntry),
}
}
// Start reads the cron entries from store, s3 by now, and initializes all the entries.
func (c *Crontinuous) Start() error {
c.cron = cron.New()
var cronSchedules []cronJobSchedule
// Scan Entries
scanEntries, scanSchedules, err := c.buildScanEntries()
if err != nil {
return err
}
c.scanEntries = scanEntries
cronSchedules = append(cronSchedules, scanSchedules...)
// Report Entries
reportEntries, reportSchedules, err := c.buildReportEntries()
if err != nil {
return err
}
c.reportEntries = reportEntries
cronSchedules = append(cronSchedules, reportSchedules...)
// Schedule cron jobs
for _, cs := range cronSchedules {
c.cron.Schedule(cs.schedule, cs.job, cs.id)
}
c.cron.Start()
return nil
}
func isProgramSuffixIncluded(programID, programSuffixes string) bool {
pss := strings.Split(programSuffixes, ",")
if len(pss) == 1 && pss[0] == "" {
return false
}
for _, ps := range pss {
if strings.HasSuffix(programID, strings.TrimSpace(ps)) {
return true
}
}
return false
}
func (c *Crontinuous) buildScanEntries() (map[string]ScanEntry, []cronJobSchedule, error) {
scanEntries, err := c.scanCronStore.GetScanEntries()
if err != nil {
return nil, nil, err
}
var scanSchedules []cronJobSchedule
for _, se := range scanEntries {
if !c.isTeamWhitelisted(ScanCronType, se.TeamID) {
// If team is not whitelisted, return entry
// but do not build job to be scheduled.
continue
}
cronSpec := se.CronSpec
if isProgramSuffixIncluded(se.ProgramID, c.config.RandomizeCronMinuteProgramSuffixes) {
cs := strings.Split(cronSpec, " ")
// Ensure that the first entry of the cron string is an integer.
if _, err := strconv.Atoi(cs[0]); err == nil {
cs[0] = fmt.Sprintf("%d", rand.Intn(c.config.RandomizeCronMinuteInterval))
cronSpec = strings.Join(cs, " ")
c.log.WithFields(
logrus.Fields{"programID": se.ProgramID, "teamID": se.TeamID, "originalCron": se.CronSpec, "newCron": cronSpec},
).Info("program cron schedule minute has been randomized")
}
}
s, err := cron.ParseStandard(cronSpec)
if err != nil {
// Abort start
// TODO: skip this entry and continue?
return nil, nil, err
}
jobLog := logrus.New().WithFields(logrus.Fields{"job": se.ProgramID})
scanSchedules = append(scanSchedules, cronJobSchedule{
schedule: s,
job: &scanJob{
programID: se.ProgramID,
teamID: se.TeamID,
scanCreator: c.scanCreator,
log: jobLog,
},
id: se.ProgramID,
})
}
return scanEntries, scanSchedules, nil
}
func (c *Crontinuous) buildReportEntries() (map[string]ReportEntry, []cronJobSchedule, error) {
reportEntries, err := c.reportCronStore.GetReportEntries()
if err != nil {
return nil, nil, err
}
var reportSchedules []cronJobSchedule
for _, re := range reportEntries {
if !c.isTeamWhitelisted(ReportCronType, re.TeamID) {
// If team is not whitelisted, return entry
// but do not build job to be scheduled.
continue
}
s, err := cron.ParseStandard(re.CronSpec)
if err != nil {
// Abort start
// TODO: skip this entry and continue?
return nil, nil, err
}
jobLog := logrus.New().WithFields(logrus.Fields{"job": re.TeamID})
reportSchedules = append(reportSchedules, cronJobSchedule{
schedule: s,
job: &reportJob{
teamID: re.TeamID,
reportSender: c.reportSender,
log: jobLog,
},
id: re.TeamID,
})
}
return reportEntries, reportSchedules, nil
}
func (c *Crontinuous) isTeamWhitelisted(typ CronType, teamID string) bool {
enable := false
whitelist := []string{}
if typ == ScanCronType {
enable = c.config.EnableTeamsWhitelistScan
whitelist = c.config.TeamsWhitelistScan
}
if typ == ReportCronType {
enable = c.config.EnableTeamsWhitelistReport
whitelist = c.config.TeamsWhitelistReport
}
if !enable {
return true
}
for _, t := range whitelist {
if t == teamID {
return true
}
}
return false
}
// Stop signals the command processor to stop processing commands and wait for it to exit.
func (c *Crontinuous) Stop() {
c.cron.Stop()
c.log.Info("Stopped")
}
// BulkCreate tests for each specified entry if an entry with the same programID exists.
// If it exists and overwrite setting for that entry is set to false the method does nothing.
// If it doesn't exist or overwrite setting is set to true, the method creates/overwrites the entry.
func (c *Crontinuous) BulkCreate(typ CronType, entries []CronEntry, overwriteSettings []bool) error {
parsedEntries := make(map[string]cronEntryWithSchedule)
// In order to try to reduce to the minimun the time this methods
// locks the entries, we parse the cron strings in this loop and not inside
// the loop below inside the lock-unlock block.
for i, e := range entries {
s, err := cron.ParseStandard(e.GetCronSpec())
if err != nil {
return ErrMalformedSchedule
}
parsedEntries[e.GetID()] = cronEntryWithSchedule{
entry: e,
schedule: s,
overwriteEntry: overwriteSettings[i],
}
}
var jobsWithSchedule []cronJobSchedule
var err error
switch typ {
case ScanCronType:
jobsWithSchedule, err = c.scanBulkCreate(parsedEntries)
case ReportCronType:
jobsWithSchedule, err = c.reportBulkCreate(parsedEntries)
default:
return ErrInvalidCronType
}
if err != nil {
return err
}
for _, j := range jobsWithSchedule {
j := j // Prevent gotcha with pointers and ranges.
c.cron.Schedule(j.schedule, j.job, j.id)
}
return nil
}
// SaveEntry adds a new entry to the crontab.
func (c *Crontinuous) SaveEntry(typ CronType, entry CronEntry) error {
s, err := cron.ParseStandard(entry.GetCronSpec())
if err != nil {
return ErrMalformedSchedule
}
var cronJob cron.Job
switch typ {
case ScanCronType:
cronJob, err = c.saveScanEntry(entry)
case ReportCronType:
cronJob, err = c.saveReportEntry(entry)
default:
return ErrInvalidCronType
}
if err != nil {
if errors.Is(err, errTeamNotWhitelisted) {
// If team is not whitelisted, do not
// schedule job and return.
return nil
}
return err
}
c.cron.Schedule(s, cronJob, entry.GetID())
return nil
}
// GetEntries returns a snapshot of the current entries.
func (c *Crontinuous) GetEntries(typ CronType) ([]CronEntry, error) {
var entries []CronEntry
var err error
switch typ {
case ScanCronType:
entries, err = c.getScanEntries()
case ReportCronType:
entries, err = c.getReportEntries()
default:
return nil, ErrInvalidCronType
}
return entries, err
}
// GetEntryByID returns a snapshot of the current entries.
func (c *Crontinuous) GetEntryByID(typ CronType, ID string) (CronEntry, error) {
var entry CronEntry
var err error
switch typ {
case ScanCronType:
entry, err = c.getScanEntryByID(ID)
case ReportCronType:
entry, err = c.getReportEntryByID(ID)
default:
return nil, ErrInvalidCronType
}
if err != nil {
return nil, err
}
return entry, nil
}
// RemoveEntry remove an existing entry.
func (c *Crontinuous) RemoveEntry(typ CronType, ID string) error {
var err error
switch typ {
case ScanCronType:
err = c.removeScanEntry(ID)
case ReportCronType:
err = c.removeReportEntry(ID)
default:
return ErrInvalidCronType
}
if err != nil {
return err
}
c.cron.RemoveJob(ID)
return nil
}