/
store.go
729 lines (619 loc) · 18.3 KB
/
store.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
package dkron
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"sort"
"strconv"
"strings"
"sync"
"time"
dkronpb "github.com/distribworks/dkron/v3/plugin/types"
"github.com/sirupsen/logrus"
"github.com/tidwall/buntdb"
"google.golang.org/protobuf/proto"
)
const (
// MaxExecutions to maintain in the storage
MaxExecutions = 100
jobsPrefix = "jobs"
executionsPrefix = "executions"
)
var (
// ErrDependentJobs is returned when deleting a job that has dependent jobs
ErrDependentJobs = errors.New("store: could not delete job with dependent jobs, delete childs first")
)
// Store is the local implementation of the Storage interface.
// It gives dkron the ability to manipulate its embedded storage
// BuntDB.
type Store struct {
db *buntdb.DB
lock *sync.Mutex // for
logger *logrus.Entry
}
// JobOptions additional options to apply when loading a Job.
type JobOptions struct {
Metadata map[string]string `json:"tags"`
Sort string
Order string
Query string
Status string
Disabled string
}
// ExecutionOptions additional options like "Sort" will be ready for JSON marshall
type ExecutionOptions struct {
Sort string
Order string
Timezone *time.Location
}
type kv struct {
Key string
Value []byte
}
// NewStore creates a new Storage instance.
func NewStore(logger *logrus.Entry) (*Store, error) {
db, err := buntdb.Open(":memory:")
if err != nil {
return nil, err
}
_ = db.CreateIndex("name", jobsPrefix+":*", buntdb.IndexJSON("name"))
_ = db.CreateIndex("started_at", executionsPrefix+":*", buntdb.IndexJSON("started_at"))
_ = db.CreateIndex("finished_at", executionsPrefix+":*", buntdb.IndexJSON("finished_at"))
_ = db.CreateIndex("attempt", executionsPrefix+":*", buntdb.IndexJSON("attempt"))
_ = db.CreateIndex("displayname", jobsPrefix+":*", buntdb.IndexJSON("displayname"))
_ = db.CreateIndex("schedule", jobsPrefix+":*", buntdb.IndexJSON("schedule"))
_ = db.CreateIndex("success_count", jobsPrefix+":*", buntdb.IndexJSON("success_count"))
_ = db.CreateIndex("error_count", jobsPrefix+":*", buntdb.IndexJSON("error_count"))
_ = db.CreateIndex("last_success", jobsPrefix+":*", buntdb.IndexJSON("last_success"))
_ = db.CreateIndex("last_error", jobsPrefix+":*", buntdb.IndexJSON("last_error"))
_ = db.CreateIndex("next", jobsPrefix+":*", buntdb.IndexJSON("next"))
store := &Store{
db: db,
lock: &sync.Mutex{},
logger: logger,
}
return store, nil
}
func (s *Store) setJobTxFunc(pbj *dkronpb.Job) func(tx *buntdb.Tx) error {
return func(tx *buntdb.Tx) error {
jobKey := fmt.Sprintf("%s:%s", jobsPrefix, pbj.Name)
jb, err := json.Marshal(pbj)
if err != nil {
return err
}
s.logger.WithField("job", pbj.Name).Debug("store: Setting job")
if _, _, err := tx.Set(jobKey, string(jb), nil); err != nil {
return err
}
return nil
}
}
// DB is the getter for the BuntDB instance
func (s *Store) DB() *buntdb.DB {
return s.db
}
// SetJob stores a job in the storage
func (s *Store) SetJob(job *Job, copyDependentJobs bool) error {
var pbej dkronpb.Job
var ej *Job
if err := job.Validate(); err != nil {
return err
}
// Abort if parent not found before committing job to the store
if job.ParentJob != "" {
if j, _ := s.GetJob(job.ParentJob, nil); j == nil {
return ErrParentJobNotFound
}
}
err := s.db.Update(func(tx *buntdb.Tx) error {
// Get if the requested job already exist
err := s.getJobTxFunc(job.Name, &pbej)(tx)
if err != nil && err != buntdb.ErrNotFound {
return err
}
ej = NewJobFromProto(&pbej, s.logger)
if ej.Name != "" {
// When the job runs, these status vars are updated
// otherwise use the ones that are stored
if ej.LastError.After(job.LastError) {
job.LastError = ej.LastError
}
if ej.LastSuccess.After(job.LastSuccess) {
job.LastSuccess = ej.LastSuccess
}
if ej.SuccessCount > job.SuccessCount {
job.SuccessCount = ej.SuccessCount
}
if ej.ErrorCount > job.ErrorCount {
job.ErrorCount = ej.ErrorCount
}
if len(ej.DependentJobs) != 0 && copyDependentJobs {
job.DependentJobs = ej.DependentJobs
}
if ej.Status != "" {
job.Status = ej.Status
}
}
if job.Schedule != ej.Schedule {
job.Next, err = job.GetNext()
if err != nil {
return err
}
} else {
// If coming from a backup us the previous value, don't allow overwriting this
if job.Next.Before(ej.Next) {
job.Next = ej.Next
}
}
pbj := job.ToProto()
if err := s.setJobTxFunc(pbj)(tx); err != nil {
return err
}
return nil
})
if err != nil {
return err
}
// If the parent job changed update the parents of the old (if any) and new jobs
if job.ParentJob != ej.ParentJob {
if err := s.removeFromParent(ej); err != nil {
return err
}
if err := s.addToParent(job); err != nil {
return err
}
}
return nil
}
// Removes the given job from its parent.
// Does nothing if nil is passed as child.
func (s *Store) removeFromParent(child *Job) error {
// Do nothing if no job was given or job has no parent
if child == nil || child.ParentJob == "" {
return nil
}
parent, err := child.GetParent(s)
if err != nil {
return err
}
// Remove all occurrences from the parent, not just one.
// Due to an old bug (in v1), a parent can have the same child more than once.
djs := []string{}
for _, djn := range parent.DependentJobs {
if djn != child.Name {
djs = append(djs, djn)
}
}
parent.DependentJobs = djs
if err := s.SetJob(parent, false); err != nil {
return err
}
return nil
}
// Adds the given job to its parent.
func (s *Store) addToParent(child *Job) error {
// Do nothing if job has no parent
if child.ParentJob == "" {
return nil
}
parent, err := child.GetParent(s)
if err != nil {
return err
}
parent.DependentJobs = append(parent.DependentJobs, child.Name)
if err := s.SetJob(parent, false); err != nil {
return err
}
return nil
}
// SetExecutionDone saves the execution and updates the job with the corresponding
// results
func (s *Store) SetExecutionDone(execution *Execution) (bool, error) {
err := s.db.Update(func(tx *buntdb.Tx) error {
// Load the job from the store
var pbj dkronpb.Job
if err := s.getJobTxFunc(execution.JobName, &pbj)(tx); err != nil {
if err == buntdb.ErrNotFound {
s.logger.Warn(ErrExecutionDoneForDeletedJob)
return ErrExecutionDoneForDeletedJob
}
s.logger.WithError(err).Fatal(err)
return err
}
key := fmt.Sprintf("%s:%s:%s", executionsPrefix, execution.JobName, execution.Key())
// Save the execution to store
pbe := execution.ToProto()
if err := s.setExecutionTxFunc(key, pbe)(tx); err != nil {
return err
}
if pbe.Success {
pbj.LastSuccess.HasValue = true
pbj.LastSuccess.Time = pbe.FinishedAt
pbj.SuccessCount++
} else {
pbj.LastError.HasValue = true
pbj.LastError.Time = pbe.FinishedAt
pbj.ErrorCount++
}
status, err := s.computeStatus(pbj.Name, pbe.Group, tx)
if err != nil {
return err
}
pbj.Status = status
if err := s.setJobTxFunc(&pbj)(tx); err != nil {
return err
}
return nil
})
if err != nil {
s.logger.WithError(err).Error("store: Error in SetExecutionDone")
return false, err
}
return true, nil
}
func (s *Store) jobHasMetadata(job *Job, metadata map[string]string) bool {
if job == nil || job.Metadata == nil || len(job.Metadata) == 0 {
return false
}
for k, v := range metadata {
if val, ok := job.Metadata[k]; !ok || v != val {
return false
}
}
return true
}
// GetJobs returns all jobs
func (s *Store) GetJobs(options *JobOptions) ([]*Job, error) {
if options == nil {
options = &JobOptions{
Sort: "name",
}
}
jobs := make([]*Job, 0)
jobsFn := func(key, item string) bool {
var pbj dkronpb.Job
// [TODO] This condition is temporary while we migrate to JSON marshalling for jobs
// so we can use BuntDb indexes. To be removed in future versions.
if err := proto.Unmarshal([]byte(item), &pbj); err != nil {
if err := json.Unmarshal([]byte(item), &pbj); err != nil {
return false
}
}
job := NewJobFromProto(&pbj, s.logger)
job.logger = s.logger
if options == nil ||
(options.Metadata == nil || len(options.Metadata) == 0 || s.jobHasMetadata(job, options.Metadata)) &&
(options.Query == "" || strings.Contains(job.Name, options.Query) || strings.Contains(job.DisplayName, options.Query)) &&
(options.Disabled == "" || strconv.FormatBool(job.Disabled) == options.Disabled) &&
((options.Status == "untriggered" && job.Status == "") || (options.Status == "" || job.Status == options.Status)) {
jobs = append(jobs, job)
}
return true
}
err := s.db.View(func(tx *buntdb.Tx) error {
var err error
if options.Order == "DESC" {
err = tx.Descend(options.Sort, jobsFn)
} else {
err = tx.Ascend(options.Sort, jobsFn)
}
return err
})
return jobs, err
}
// GetJob finds and return a Job from the store
func (s *Store) GetJob(name string, options *JobOptions) (*Job, error) {
var pbj dkronpb.Job
err := s.db.View(s.getJobTxFunc(name, &pbj))
if err != nil {
return nil, err
}
job := NewJobFromProto(&pbj, s.logger)
job.logger = s.logger
return job, nil
}
// This will allow reuse this code to avoid nesting transactions
func (s *Store) getJobTxFunc(name string, pbj *dkronpb.Job) func(tx *buntdb.Tx) error {
return func(tx *buntdb.Tx) error {
item, err := tx.Get(fmt.Sprintf("%s:%s", jobsPrefix, name))
if err != nil {
return err
}
// [TODO] This condition is temporary while we migrate to JSON marshalling for jobs
// so we can use BuntDb indexes. To be removed in future versions.
if err := proto.Unmarshal([]byte(item), pbj); err != nil {
if err := json.Unmarshal([]byte(item), pbj); err != nil {
return err
}
}
s.logger.WithFields(logrus.Fields{
"job": pbj.Name,
}).Debug("store: Retrieved job from datastore")
return nil
}
}
// DeleteJob deletes the given job from the store, along with
// all its executions and references to it.
func (s *Store) DeleteJob(name string) (*Job, error) {
var job *Job
err := s.db.Update(func(tx *buntdb.Tx) error {
// Get the job
var pbj dkronpb.Job
if err := s.getJobTxFunc(name, &pbj)(tx); err != nil {
return err
}
// Check if the job has dependent jobs
// and return an error indicating to remove childs
// first.
if len(pbj.DependentJobs) > 0 {
return ErrDependentJobs
}
job = NewJobFromProto(&pbj, s.logger)
if err := s.deleteExecutionsTxFunc(name)(tx); err != nil {
return err
}
_, err := tx.Delete(fmt.Sprintf("%s:%s", jobsPrefix, name))
return err
})
if err != nil {
return nil, err
}
// If the transaction succeeded, remove from parent
if job.ParentJob != "" {
if err := s.removeFromParent(job); err != nil {
return nil, err
}
}
return job, nil
}
// GetExecutions returns the executions given a Job name.
func (s *Store) GetExecutions(jobName string, opts *ExecutionOptions) ([]*Execution, error) {
prefix := fmt.Sprintf("%s:%s:", executionsPrefix, jobName)
kvs, err := s.list(prefix, true, opts)
if err != nil {
return nil, err
}
return s.unmarshalExecutions(kvs, opts.Timezone)
}
func (s *Store) list(prefix string, checkRoot bool, opts *ExecutionOptions) ([]kv, error) {
var found bool
kvs := []kv{}
err := s.db.View(s.listTxFunc(prefix, &kvs, &found, opts))
if err == nil && !found && checkRoot {
return nil, buntdb.ErrNotFound
}
return kvs, err
}
func (*Store) listTxFunc(prefix string, kvs *[]kv, found *bool, opts *ExecutionOptions) func(tx *buntdb.Tx) error {
fnc := func(key, value string) bool {
if strings.HasPrefix(key, prefix) {
*found = true
// ignore self in listing
if !bytes.Equal(trimDirectoryKey([]byte(key)), []byte(prefix)) {
kv := kv{Key: key, Value: []byte(value)}
*kvs = append(*kvs, kv)
}
}
return true
}
return func(tx *buntdb.Tx) (err error) {
if opts.Order == "DESC" {
err = tx.Descend(opts.Sort, fnc)
} else {
err = tx.Ascend(opts.Sort, fnc)
}
return err
}
}
// GetExecutionGroup returns all executions in the same group of a given execution
func (s *Store) GetExecutionGroup(execution *Execution, opts *ExecutionOptions) ([]*Execution, error) {
res, err := s.GetExecutions(execution.JobName, opts)
if err != nil {
return nil, err
}
var executions []*Execution
for _, ex := range res {
if ex.Group == execution.Group {
executions = append(executions, ex)
}
}
return executions, nil
}
// GetGroupedExecutions returns executions for a job grouped and with an ordered index
// to facilitate access.
func (s *Store) GetGroupedExecutions(jobName string, opts *ExecutionOptions) (map[int64][]*Execution, []int64, error) {
execs, err := s.GetExecutions(jobName, opts)
if err != nil {
return nil, nil, err
}
groups := make(map[int64][]*Execution)
for _, exec := range execs {
groups[exec.Group] = append(groups[exec.Group], exec)
}
// Build a separate data structure to show in order
var byGroup int64arr
for key := range groups {
byGroup = append(byGroup, key)
}
sort.Sort(sort.Reverse(byGroup))
return groups, byGroup, nil
}
func (*Store) setExecutionTxFunc(key string, pbe *dkronpb.Execution) func(tx *buntdb.Tx) error {
return func(tx *buntdb.Tx) error {
// Get previous execution
i, err := tx.Get(key)
if err != nil && err != buntdb.ErrNotFound {
return err
}
// Do nothing if a previous execution exists and is
// more recent, avoiding non ordered execution set
if i != "" {
var p dkronpb.Execution
// [TODO] This condition is temporary while we migrate to JSON marshalling for executions
// so we can use BuntDb indexes. To be removed in future versions.
if err := proto.Unmarshal([]byte(i), &p); err != nil {
if err := json.Unmarshal([]byte(i), &p); err != nil {
return err
}
}
// Compare existing execution
if p.GetFinishedAt().Seconds > pbe.GetFinishedAt().Seconds {
return nil
}
}
eb, err := json.Marshal(pbe)
if err != nil {
return err
}
_, _, err = tx.Set(key, string(eb), nil)
return err
}
}
// SetExecution Save a new execution and returns the key of the new saved item or an error.
func (s *Store) SetExecution(execution *Execution) (string, error) {
pbe := execution.ToProto()
key := fmt.Sprintf("%s:%s:%s", executionsPrefix, execution.JobName, execution.Key())
s.logger.WithFields(logrus.Fields{
"job": execution.JobName,
"execution": key,
"finished": execution.FinishedAt.String(),
}).Debug("store: Setting key")
err := s.db.Update(s.setExecutionTxFunc(key, pbe))
if err != nil {
s.logger.WithError(err).WithFields(logrus.Fields{
"job": execution.JobName,
"execution": key,
}).Debug("store: Failed to set key")
return "", err
}
execs, err := s.GetExecutions(execution.JobName, &ExecutionOptions{})
if err != nil && err != buntdb.ErrNotFound {
s.logger.WithError(err).
WithField("job", execution.JobName).
Error("store: Error getting executions for job")
}
// Delete all execution results over the limit, starting from olders
if len(execs) > MaxExecutions {
//sort the array of all execution groups by StartedAt time
sort.Slice(execs, func(i, j int) bool {
return execs[i].StartedAt.Before(execs[j].StartedAt)
})
for i := 0; i < len(execs)-MaxExecutions; i++ {
s.logger.WithFields(logrus.Fields{
"job": execs[i].JobName,
"execution": execs[i].Key(),
}).Debug("store: to delete key")
err = s.db.Update(func(tx *buntdb.Tx) error {
k := fmt.Sprintf("%s:%s:%s", executionsPrefix, execs[i].JobName, execs[i].Key())
_, err := tx.Delete(k)
return err
})
if err != nil {
s.logger.WithError(err).
WithField("execution", execs[i].Key()).
Error("store: Error trying to delete overflowed execution")
}
}
}
return key, nil
}
// DeleteExecutions removes all executions of a job
func (s *Store) deleteExecutionsTxFunc(jobName string) func(tx *buntdb.Tx) error {
return func(tx *buntdb.Tx) error {
var delkeys []string
prefix := fmt.Sprintf("%s:%s", executionsPrefix, jobName)
if err := tx.Ascend("", func(key, value string) bool {
if strings.HasPrefix(key, prefix) {
delkeys = append(delkeys, key)
}
return true
}); err != nil {
return err
}
for _, k := range delkeys {
_, _ = tx.Delete(k)
}
return nil
}
}
// Shutdown close the KV store
func (s *Store) Shutdown() error {
return s.db.Close()
}
// Snapshot creates a backup of the data stored in BuntDB
func (s *Store) Snapshot(w io.WriteCloser) error {
return s.db.Save(w)
}
// Restore load data created with backup in to Bunt
func (s *Store) Restore(r io.ReadCloser) error {
return s.db.Load(r)
}
func (s *Store) unmarshalExecutions(items []kv, timezone *time.Location) ([]*Execution, error) {
var executions []*Execution
for _, item := range items {
var pbe dkronpb.Execution
// [TODO] This condition is temporary while we migrate to JSON marshalling for jobs
// so we can use BuntDb indexes. To be removed in future versions.
if err := proto.Unmarshal([]byte(item.Value), &pbe); err != nil {
if err := json.Unmarshal(item.Value, &pbe); err != nil {
s.logger.WithError(err).WithField("key", item.Key).Debug("error unmarshaling JSON")
return nil, err
}
}
execution := NewExecutionFromProto(&pbe)
if timezone != nil {
execution.FinishedAt = execution.FinishedAt.In(timezone)
execution.StartedAt = execution.StartedAt.In(timezone)
}
executions = append(executions, execution)
}
return executions, nil
}
func (s *Store) computeStatus(jobName string, exGroup int64, tx *buntdb.Tx) (string, error) {
// compute job status based on execution group
kvs := []kv{}
found := false
prefix := fmt.Sprintf("%s:%s:", executionsPrefix, jobName)
if err := s.listTxFunc(prefix, &kvs, &found, &ExecutionOptions{})(tx); err != nil {
return "", err
}
execs, err := s.unmarshalExecutions(kvs, nil)
if err != nil {
return "", err
}
var executions []*Execution
for _, ex := range execs {
if ex.Group == exGroup {
executions = append(executions, ex)
}
}
success := 0
failed := 0
var status string
for _, ex := range executions {
if ex.Success {
success = success + 1
} else {
failed = failed + 1
}
}
if failed == 0 {
status = StatusSuccess
} else if failed > 0 && success == 0 {
status = StatusFailed
} else if failed > 0 && success > 0 {
status = StatusPartiallyFailed
}
return status, nil
}
func trimDirectoryKey(key []byte) []byte {
if isDirectoryKey(key) {
return key[:len(key)-1]
}
return key
}
func isDirectoryKey(key []byte) bool {
return len(key) > 0 && key[len(key)-1] == ':'
}