-
Notifications
You must be signed in to change notification settings - Fork 12
/
db.go
1733 lines (1554 loc) · 49.8 KB
/
db.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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright © 2016-2021 Genome Research Limited
// Author: Sendu Bala <sb10@sanger.ac.uk>.
//
// This file is part of wr.
//
// wr is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// wr is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with wr. If not, see <http://www.gnu.org/licenses/>.
package jobqueue
// This file contains functions for interacting with our database, which is
// boltdb, a simple key/val store with transactions and hot backup ability.
// We don't use a generic ORM for boltdb like Storm, because we can do custom
// queries that are multiple times faster than what Storm can do.
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"io"
"math"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
sync "github.com/sasha-s/go-deadlock"
"github.com/wtsi-ssg/wr/clog"
"github.com/VertebrateResequencing/muxfys/v4"
"github.com/VertebrateResequencing/wr/internal"
lru "github.com/hashicorp/golang-lru"
"github.com/sb10/waitgroup"
"github.com/ugorji/go/codec"
bolt "go.etcd.io/bbolt"
)
const (
dbDelimiter = "_::_"
jobStatWindowPercent = float32(5)
dbFilePermission = 0600
minimumTimeBetweenBackups = 30 * time.Second
dbRunningTransactionsWaitTime = 1 * time.Minute
)
var (
bucketJobsLive = []byte("jobslive")
bucketJobsComplete = []byte("jobscomplete")
bucketRTK = []byte("repgroupToKey")
bucketRGs = []byte("repgroups")
bucketLGs = []byte("limitgroups")
bucketDTK = []byte("depgroupToKey")
bucketRDTK = []byte("reverseDepgroupToKey")
bucketEnvs = []byte("envs")
bucketStdO = []byte("stdo")
bucketStdE = []byte("stde")
bucketJobRAM = []byte("jobRAM")
bucketJobDisk = []byte("jobDisk")
bucketJobSecs = []byte("jobSecs")
wipeDevDBOnInit = true
forceBackups = false
)
// Rec* variables are only exported for testing purposes (*** though they should
// probably be user configurable somewhere...).
var (
RecMBRound = 100 // when we recommend amount of memory to reserve for a job, we round up to the nearest RecMBRound MBs
RecSecRound = 1 // when we recommend time to reserve for a job, we round up to the nearest RecSecRound seconds
)
// sobsd ('slice of byte slice doublets') implements sort interface so we can
// sort a slice of []byte doublets, sorting on the first byte slice, needed for
// efficient Puts in to the database.
type sobsd [][2][]byte
func (s sobsd) Len() int {
return len(s)
}
func (s sobsd) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s sobsd) Less(i, j int) bool {
cmp := bytes.Compare(s[i][0], s[j][0])
return cmp == -1
}
// sobsdStorer is the kind of function that stores the contents of a sobsd in
// a particular bucket
type sobsdStorer func(bucket []byte, encodes sobsd) (err error)
type db struct {
backupLast time.Time
backupPath string
backupPathTmp string
ch codec.Handle
backupStopWait chan bool
backupMount *muxfys.MuxFys
backupNotification chan bool
backupWait time.Duration
bolt *bolt.DB
envcache *lru.ARCCache
updatingAfterJobExit int
wg *waitgroup.WaitGroup
wgMutex sync.Mutex // protects wg since we want to call Wait() while another goroutine might call Add()
sync.RWMutex
backingUp bool
backupFinal bool
backupQueued bool
backupsEnabled bool
s3accessor *muxfys.S3Accessor
closed bool
slowBackups bool // just for testing purposes
}
// initDB opens/creates our database and sets things up for use. If dbFile
// doesn't exist or seems corrupted, we copy it from backup if that exists,
// otherwise we start fresh.
//
// dbBkFile can be an S3 url specified like: s3://[profile@]bucket/path/file
// which will cause that s3 path to be mounted in the same directory as dbFile
// and backups will be written there.
//
// In development we delete any existing db and force a fresh start. Backups
// are also not carried out, so dbBkFile is ignored.
func initDB(ctx context.Context, dbFile string, dbBkFile string, deployment string) (*db, string, error) {
var backupsEnabled bool
var accessor *muxfys.S3Accessor
backupPathTmp := dbBkFile + ".tmp"
var msg string
if deployment == internal.Production || forceBackups {
backupsEnabled = true
if internal.InS3(dbBkFile) {
if deployment == internal.Development {
dbBkFile += "." + deployment
}
path := strings.TrimPrefix(dbBkFile, internal.S3Prefix)
pp := strings.Split(path, "@")
profile := "default"
if len(pp) == 2 {
profile = pp[0]
path = pp[1]
}
path = filepath.Dir(path)
accessorConfig, err := muxfys.S3ConfigFromEnvironment(profile, path)
if err != nil {
return nil, "", err
}
accessor, err = muxfys.NewS3Accessor(accessorConfig)
if err != nil {
return nil, "", err
}
dbBkFile = filepath.Join(path, filepath.Base(dbBkFile))
dbBkFile, err = stripBucketFromS3Path(dbBkFile)
if err != nil {
return nil, "", err
}
backupPathTmp = dbFile + ".s3backup_tmp"
if _, err = os.Stat(dbFile); os.IsNotExist(err) {
err = accessor.DownloadFile(dbBkFile, dbFile)
if err == nil {
msg = "recreated missing db file " + dbFile + " from s3 backup file " + dbBkFile
}
}
}
}
if wipeDevDBOnInit && deployment == internal.Development {
errr := os.Remove(dbFile)
if errr != nil && !os.IsNotExist(errr) {
clog.Warn(ctx, "Failed to remove database file", "path", dbFile, "err", errr)
}
if accessor != nil {
errr = accessor.DeleteFile(dbBkFile)
} else {
errr = os.Remove(dbBkFile)
}
if errr != nil && !os.IsNotExist(errr) {
clog.Warn(ctx, "Failed to remove database backup file", "path", dbBkFile, "err", errr)
}
}
var boltdb *bolt.DB
var err error
if _, err = os.Stat(dbFile); os.IsNotExist(err) {
if _, err = os.Stat(dbBkFile); os.IsNotExist(err) {
boltdb, err = bolt.Open(dbFile, dbFilePermission, nil)
msg = "created new empty db file " + dbFile
} else {
err = copyFile(dbBkFile, dbFile)
if err != nil {
return nil, msg, err
}
boltdb, err = bolt.Open(dbFile, dbFilePermission, nil)
msg = "recreated missing db file " + dbFile + " from backup file " + dbBkFile
}
} else {
boltdb, err = bolt.Open(dbFile, dbFilePermission, nil)
if err != nil {
// try the backup
bkPath := dbBkFile
if accessor != nil {
bkPath = backupPathTmp
errdl := accessor.DownloadFile(dbBkFile, bkPath)
if errdl != nil {
msg = fmt.Sprintf("tried to recreate corrupt (?) db file %s "+
"from s3 backup file %s (error with original db file was: %s)",
dbFile, dbBkFile, err)
return nil, msg, errdl
}
defer func() {
errr := os.Remove(bkPath)
if errr != nil {
clog.Warn(ctx, "failed to remove temporary s3 download of database backup", "err", errr)
}
}()
}
if _, errbk := os.Stat(bkPath); errbk == nil {
boltdb, errbk = bolt.Open(bkPath, dbFilePermission, nil)
if errbk == nil {
origerr := err
msg = fmt.Sprintf("tried to recreate corrupt (?) db file %s from backup file %s (error with original db file was: %s)", dbFile, dbBkFile, err)
err = os.Remove(dbFile)
if err != nil {
return nil, msg, err
}
err = copyFile(bkPath, dbFile)
if err != nil {
return nil, msg, err
}
boltdb, err = bolt.Open(dbFile, dbFilePermission, nil)
msg = fmt.Sprintf("recreated corrupt (?) db file %s from backup file %s (error with original db file was: %s)", dbFile, dbBkFile, origerr)
}
}
}
}
if err != nil {
return nil, msg, err
}
// ensure our buckets are in place
err = boltdb.Update(func(tx *bolt.Tx) error {
_, errf := tx.CreateBucketIfNotExists(bucketJobsLive)
if errf != nil {
return fmt.Errorf("create bucket %s: %s", bucketJobsLive, errf)
}
_, errf = tx.CreateBucketIfNotExists(bucketJobsComplete)
if errf != nil {
return fmt.Errorf("create bucket %s: %s", bucketJobsComplete, errf)
}
_, errf = tx.CreateBucketIfNotExists(bucketRTK)
if errf != nil {
return fmt.Errorf("create bucket %s: %s", bucketRTK, errf)
}
_, errf = tx.CreateBucketIfNotExists(bucketRGs)
if errf != nil {
return fmt.Errorf("create bucket %s: %s", bucketRGs, errf)
}
_, errf = tx.CreateBucketIfNotExists(bucketLGs)
if errf != nil {
return fmt.Errorf("create bucket %s: %s", bucketLGs, errf)
}
_, errf = tx.CreateBucketIfNotExists(bucketDTK)
if errf != nil {
return fmt.Errorf("create bucket %s: %s", bucketDTK, errf)
}
_, errf = tx.CreateBucketIfNotExists(bucketRDTK)
if errf != nil {
return fmt.Errorf("create bucket %s: %s", bucketRDTK, errf)
}
_, errf = tx.CreateBucketIfNotExists(bucketEnvs)
if errf != nil {
return fmt.Errorf("create bucket %s: %s", bucketEnvs, errf)
}
_, errf = tx.CreateBucketIfNotExists(bucketStdO)
if errf != nil {
return fmt.Errorf("create bucket %s: %s", bucketStdO, errf)
}
_, errf = tx.CreateBucketIfNotExists(bucketStdE)
if errf != nil {
return fmt.Errorf("create bucket %s: %s", bucketStdE, errf)
}
_, errf = tx.CreateBucketIfNotExists(bucketJobRAM)
if errf != nil {
return fmt.Errorf("create bucket %s: %s", bucketJobRAM, errf)
}
_, errf = tx.CreateBucketIfNotExists(bucketJobDisk)
if errf != nil {
return fmt.Errorf("create bucket %s: %s", bucketJobDisk, errf)
}
_, errf = tx.CreateBucketIfNotExists(bucketJobSecs)
if errf != nil {
return fmt.Errorf("create bucket %s: %s", bucketJobSecs, errf)
}
return nil
})
if err != nil {
return nil, msg, err
}
// we will cache frequently used things to avoid actual db (disk) access
envcache, err := lru.NewARC(12) // we don't expect that many different ENVs to be in use at once
if err != nil {
return nil, msg, err
}
dbstruct := &db{
bolt: boltdb,
envcache: envcache,
ch: new(codec.BincHandle),
backupsEnabled: backupsEnabled,
backupPath: dbBkFile,
backupPathTmp: backupPathTmp,
backupNotification: make(chan bool),
backupWait: minimumTimeBetweenBackups,
backupStopWait: make(chan bool),
s3accessor: accessor,
wg: waitgroup.New(),
}
return dbstruct, msg, err
}
// storeLimitGroups stores a mapping of group names to unsigned ints in a
// dedicated bucket. If a group was already in the database, and it had a
// different value, that group name will be returned in the changed slice. If
// the group is given with a value less than 0, it is not stored in the
// database; any existing entry is removed and the name is returned in the
// removed slice.
func (db *db) storeLimitGroups(limitGroups map[string]int) (changed []string, removed []string, err error) {
err = db.bolt.Batch(func(tx *bolt.Tx) error {
b := tx.Bucket(bucketLGs)
for group, limit := range limitGroups {
key := []byte(group)
v := b.Get(key)
if v != nil {
if limit < 0 {
errd := b.Delete(key)
if errd != nil {
return errd
}
removed = append(removed, group)
continue
}
if binary.BigEndian.Uint64(v) == uint64(limit) {
continue
}
changed = append(changed, group)
} else if limit < 0 {
continue
}
v = make([]byte, 8)
binary.BigEndian.PutUint64(v, uint64(limit))
errp := b.Put(key, v)
if errp != nil {
return errp
}
}
return nil
})
return changed, removed, err
}
// retrieveLimitGroup gets a value for a particular group from the db that was
// stored with storeLimitGroups(). If the group wasn't stored, returns -1.
func (db *db) retrieveLimitGroup(ctx context.Context, group string) int {
v := db.retrieve(ctx, bucketLGs, group)
if v == nil {
return -1
}
return int(binary.BigEndian.Uint64(v))
}
// storeNewJobs stores jobs in the live bucket, where they will only be used for
// disaster recovery. It also stores a lookup from the Job.RepGroup to the Job's
// key, and since this is independent, and we call this prior to checking for
// dups, we allow the same job to be looked up by multiple RepGroups. Likewise,
// we store a lookup for the Job.DepGroups and .Dependencies.DepGroups().
//
// If ignoreAdded is true, jobs that have already completed will be ignored
// along with those that have been added and the returned alreadyAdded value
// will increase.
//
// While storing it also checks if any previously stored jobs depend on a dep
// group that an input job is a member of. If not, jobsToQueue return value will
// be identical to the input job slice (minus any jobs ignored due to being
// complete). Otherwise, if the affected job was Archive()d (and not currently
// being re-run), then it will be appended to (a copy of) the input job slice
// and returned in jobsToQueue. If the affected job was in the live bucket
// (currently queued), it will be returned in the jobsToUpdate slice: you should
// use queue methods to update the job in the queue.
//
// Finally, it triggers a background database backup.
func (db *db) storeNewJobs(ctx context.Context, jobs []*Job, ignoreAdded bool) (jobsToQueue []*Job, jobsToUpdate []*Job, alreadyAdded int, err error) {
encodedJobs, rgLookups, dgLookups, rdgLookups, rgs, jobsToQueue, jobsToUpdate, alreadyAdded, err := db.prepareNewJobs(jobs, ignoreAdded)
if err != nil {
return jobsToQueue, jobsToUpdate, alreadyAdded, err
}
if len(encodedJobs) > 0 {
// now go ahead and store the lookups and jobs
numStores := 2
if len(rgs) > 0 {
numStores++
}
if len(dgLookups) > 0 {
numStores++
}
if len(rdgLookups) > 0 {
numStores++
}
errors := make(chan error, numStores)
db.wgMutex.Lock()
wgk := db.wg.Add(1)
go func() {
defer internal.LogPanic(ctx, "jobqueue database storeNewJobs rglookups", true)
defer db.wg.Done(wgk)
sort.Sort(rgLookups)
errors <- db.storeBatched(bucketRTK, rgLookups, db.storeLookups)
}()
if len(rgs) > 0 {
wgk2 := db.wg.Add(1)
go func() {
defer internal.LogPanic(ctx, "jobqueue database storeNewJobs repGroups", true)
defer db.wg.Done(wgk2)
sort.Sort(rgs)
errors <- db.storeBatched(bucketRGs, rgs, db.storeLookups)
}()
}
if len(dgLookups) > 0 {
wgk3 := db.wg.Add(1)
go func() {
defer internal.LogPanic(ctx, "jobqueue database dgLookups", true)
defer db.wg.Done(wgk3)
sort.Sort(dgLookups)
errors <- db.storeBatched(bucketDTK, dgLookups, db.storeLookups)
}()
}
if len(rdgLookups) > 0 {
wgk4 := db.wg.Add(1)
go func() {
defer internal.LogPanic(ctx, "jobqueue database storeNewJobs rdgLookups", true)
defer db.wg.Done(wgk4)
sort.Sort(rdgLookups)
errors <- db.storeBatched(bucketRDTK, rdgLookups, db.storeLookups)
}()
}
wgk5 := db.wg.Add(1)
go func() {
defer internal.LogPanic(ctx, "jobqueue database storeNewJobs encodedJobs", true)
defer db.wg.Done(wgk5)
sort.Sort(encodedJobs)
errors <- db.storeBatched(bucketJobsLive, encodedJobs, db.storeEncodedJobs)
}()
db.wgMutex.Unlock()
seen := 0
for thisErr := range errors {
if thisErr != nil {
err = thisErr
}
seen++
if seen == numStores {
close(errors)
break
}
}
}
// *** on error, because we were batching, and doing lookups separately to
// each other and jobs, we should go through and remove anything we did
// manage to add... (but this isn't so critical, since on failure here,
// they are not added to the in-memory queue and user gets an error and they
// would try to add everything back again; conversely, if we try to retrieve
// non-existent jobs based on lookups that shouldn't be there, they are
// silently skipped)
if err == nil && alreadyAdded != len(jobs) {
db.backgroundBackup(ctx)
}
return jobsToQueue, jobsToUpdate, alreadyAdded, err
}
func (db *db) prepareNewJobs(jobs []*Job, ignoreAdded bool) (encodedJobs, rgLookups, dgLookups, rdgLookups, rgs sobsd, jobsToQueue []*Job, jobsToUpdate []*Job, alreadyAdded int, err error) {
// turn the jobs in to sobsd and sort by their keys, likewise for the
// lookups
repGroups := make(map[string]bool)
depGroups := make(map[string]bool)
newJobKeys := make(map[string]bool)
var keptJobs []*Job
for _, job := range jobs {
keyStr := job.Key()
if ignoreAdded {
var added bool
added, err = db.checkIfAdded(keyStr)
if err != nil {
return encodedJobs, rgLookups, dgLookups, rdgLookups, rgs, jobsToQueue, jobsToUpdate, alreadyAdded, err
}
if added {
alreadyAdded++
continue
}
keptJobs = append(keptJobs, job)
}
newJobKeys[keyStr] = true
key := []byte(keyStr)
job.RLock()
rgLookups = append(rgLookups, [2][]byte{db.generateLookupKey(job.RepGroup, key), nil})
repGroups[job.RepGroup] = true
for _, depGroup := range job.DepGroups {
if depGroup != "" {
dgLookups = append(dgLookups, [2][]byte{db.generateLookupKey(depGroup, key), nil})
depGroups[depGroup] = true
}
}
for _, depGroup := range job.Dependencies.DepGroups() {
rdgLookups = append(rdgLookups, [2][]byte{db.generateLookupKey(depGroup, key), nil})
}
job.RUnlock()
var encoded []byte
enc := codec.NewEncoderBytes(&encoded, db.ch)
job.RLock()
err = enc.Encode(job)
job.RUnlock()
if err != nil {
return encodedJobs, rgLookups, dgLookups, rdgLookups, rgs, jobsToQueue, jobsToUpdate, alreadyAdded, err
}
encodedJobs = append(encodedJobs, [2][]byte{key, encoded})
}
if len(encodedJobs) > 0 {
if !ignoreAdded {
keptJobs = jobs
}
// first determine if any of these new jobs are the parent of previously
// stored jobs
if len(depGroups) > 0 {
jobsToQueue, jobsToUpdate, err = db.retrieveDependentJobs(depGroups, newJobKeys)
// arrange to have resurrected complete jobs stored in the live
// bucket again
for _, job := range jobsToQueue {
key := []byte(job.Key())
var encoded []byte
enc := codec.NewEncoderBytes(&encoded, db.ch)
job.RLock()
err = enc.Encode(job)
job.RUnlock()
if err != nil {
return encodedJobs, rgLookups, dgLookups, rdgLookups, rgs, jobsToQueue, jobsToUpdate, alreadyAdded, err
}
encodedJobs = append(encodedJobs, [2][]byte{key, encoded})
}
if len(jobsToQueue) > 0 {
jobsToQueue = append(jobsToQueue, jobs...)
} else {
jobsToQueue = keptJobs
}
} else {
jobsToQueue = keptJobs
}
for rg := range repGroups {
rgs = append(rgs, [2][]byte{[]byte(rg), nil})
}
}
return encodedJobs, rgLookups, dgLookups, rdgLookups, rgs, jobsToQueue, jobsToUpdate, alreadyAdded, err
}
// generateLookupKey creates a lookup key understood by the retrieval methods,
// concatenating prefix with a delimiter and the job key.
func (db *db) generateLookupKey(prefix string, jobKey []byte) []byte {
key := append([]byte(prefix), []byte(dbDelimiter)...)
return append(key, jobKey...)
}
// checkIfLive tells you if a job with the given key is currently in the live
// bucket.
func (db *db) checkIfLive(key string) (bool, error) {
var isLive bool
err := db.bolt.View(func(tx *bolt.Tx) error {
newJobBucket := tx.Bucket(bucketJobsLive)
if newJobBucket.Get([]byte(key)) != nil {
isLive = true
}
return nil
})
return isLive, err
}
// checkIfAdded tells you if a job with the given key is currently in the
// complete bucket or the live bucket.
func (db *db) checkIfAdded(key string) (bool, error) {
var isInDB bool
err := db.bolt.View(func(tx *bolt.Tx) error {
newJobBucket := tx.Bucket(bucketJobsLive)
completeJobBucket := tx.Bucket(bucketJobsComplete)
if newJobBucket.Get([]byte(key)) != nil || completeJobBucket.Get([]byte(key)) != nil {
isInDB = true
}
return nil
})
return isInDB, err
}
// archiveJob deletes a job from the live bucket, and adds a new version of it
// (with different properties) to the complete bucket.
//
// Also does what updateJobAfterExit does, except for the storage of any new
// stdout/err.
//
// The key you supply must be the key of the job you supply, or bad things will
// happen - no checking is done! A backgroundBackup() is triggered afterwards.
func (db *db) archiveJob(ctx context.Context, key string, job *Job) error {
var encoded []byte
enc := codec.NewEncoderBytes(&encoded, db.ch)
job.RLock()
err := enc.Encode(job)
job.RUnlock()
if err != nil {
return err
}
err = db.bolt.Batch(func(tx *bolt.Tx) error {
bo := tx.Bucket(bucketStdO)
be := tx.Bucket(bucketStdE)
key := []byte(key)
errf := bo.Delete(key)
if errf != nil {
return errf
}
errf = be.Delete(key)
if errf != nil {
return errf
}
b := tx.Bucket(bucketJobsLive)
errf = b.Delete(key)
if errf != nil {
return errf
}
b = tx.Bucket(bucketJobsComplete)
errf = b.Put(key, encoded)
if errf != nil {
return errf
}
b = tx.Bucket(bucketJobRAM)
errf = b.Put([]byte(fmt.Sprintf("%s%s%20d", job.ReqGroup, dbDelimiter, job.PeakRAM)), []byte(strconv.Itoa(job.PeakRAM)))
if errf != nil {
return errf
}
b = tx.Bucket(bucketJobDisk)
errf = b.Put([]byte(fmt.Sprintf("%s%s%20d", job.ReqGroup, dbDelimiter, job.PeakDisk)), []byte(strconv.Itoa(int(job.PeakDisk))))
if errf != nil {
return errf
}
b = tx.Bucket(bucketJobSecs)
secs := int(math.Ceil(job.EndTime.Sub(job.StartTime).Seconds()))
return b.Put([]byte(fmt.Sprintf("%s%s%20d", job.ReqGroup, dbDelimiter, secs)), []byte(strconv.Itoa(secs)))
})
db.backgroundBackup(ctx)
return err
}
// deleteLiveJob remove a job from the live bucket, for use when jobs were
// added in error.
func (db *db) deleteLiveJob(ctx context.Context, key string) {
db.remove(ctx, bucketJobsLive, key)
db.backgroundBackup(ctx)
//*** we're not removing the lookup entries from the bucket*TK buckets...
}
// deleteLiveJobs remove multiple jobs from the live bucket.
func (db *db) deleteLiveJobs(ctx context.Context, keys []string) error {
err := db.bolt.Batch(func(tx *bolt.Tx) error {
b := tx.Bucket(bucketJobsLive)
for _, key := range keys {
errd := b.Delete([]byte(key))
if errd != nil {
return errd
}
}
return nil
})
if err != nil {
return err
}
db.backgroundBackup(ctx)
//*** we're not removing the lookup entries from the bucket*TK buckets...
return nil
}
// recoverIncompleteJobs returns all jobs in the live bucket, for use when
// restarting the server, allowing you start working on any jobs that were
// stored with storeNewJobs() but not yet archived with archiveJob().
//
// Note that you will get back the job as it was in its last recorded state.
// The state is recorded when a job starts to run, when it exits, and when it
// is kicked.
func (db *db) recoverIncompleteJobs() ([]*Job, error) {
var jobs []*Job
err := db.bolt.View(func(tx *bolt.Tx) error {
b := tx.Bucket(bucketJobsLive)
return b.ForEach(func(key, encoded []byte) error {
if encoded != nil {
dec := codec.NewDecoderBytes(encoded, db.ch)
job := &Job{}
errf := dec.Decode(job)
if errf != nil {
return errf
}
jobs = append(jobs, job)
}
return nil
})
})
return jobs, err
}
// retrieveCompleteJobsByKeys gets jobs with the given keys from the completed
// jobs bucket (ie. those that have gone through the queue and been Remove()d).
func (db *db) retrieveCompleteJobsByKeys(keys []string) ([]*Job, error) {
var jobs []*Job
err := db.bolt.View(func(tx *bolt.Tx) error {
b := tx.Bucket(bucketJobsComplete)
for _, key := range keys {
encoded := b.Get([]byte(key))
if encoded != nil {
dec := codec.NewDecoderBytes(encoded, db.ch)
job := &Job{}
err := dec.Decode(job)
if err == nil {
jobs = append(jobs, job)
}
}
}
return nil
})
return jobs, err
}
// retrieveRepGroups gets the rep groups of all jobs that have ever been added.
func (db *db) retrieveRepGroups() ([]string, error) {
var rgs []string
err := db.bolt.View(func(tx *bolt.Tx) error {
b := tx.Bucket(bucketRGs)
return b.ForEach(func(k, v []byte) error {
rgs = append(rgs, string(k))
return nil
})
})
return rgs, err
}
// retrieveCompleteJobsByRepGroup gets jobs with the given RepGroup from the
// completed jobs bucket (ie. those that have gone through the queue and been
// Archive()d), but not those that are also currently live (ie. are being
// re-run).
func (db *db) retrieveCompleteJobsByRepGroup(repgroup string) ([]*Job, error) {
var jobs []*Job
err := db.bolt.View(func(tx *bolt.Tx) error {
newJobBucket := tx.Bucket(bucketJobsLive)
completeJobBucket := tx.Bucket(bucketJobsComplete)
lookupBucket := tx.Bucket(bucketRTK).Cursor()
prefix := []byte(repgroup + dbDelimiter)
for k, _ := lookupBucket.Seek(prefix); bytes.HasPrefix(k, prefix); k, _ = lookupBucket.Next() {
key := bytes.TrimPrefix(k, prefix)
encoded := completeJobBucket.Get(key)
if len(encoded) > 0 && newJobBucket.Get(key) == nil {
dec := codec.NewDecoderBytes(encoded, db.ch)
job := &Job{}
err := dec.Decode(job)
if err != nil {
return err
}
jobs = append(jobs, job)
}
}
return nil
})
return jobs, err
}
// retrieveDependentJobs gets previously stored jobs that had a dependency on
// one for the input depGroups. If the job is found in the live bucket, then it
// is returned in the jobsToUpdate return value. If it is found in the complete
// bucket, and is not true in the supplied newJobKeys map, then it is returned
// in the jobsToQueue return value.
func (db *db) retrieveDependentJobs(depGroups map[string]bool, newJobKeys map[string]bool) (jobsToQueue []*Job, jobsToUpdate []*Job, err error) {
// first convert the depGroups in to sorted prefixes, for linear searching
prefixes := make(sobsd, 0, len(depGroups))
for depGroup := range depGroups {
prefixes = append(prefixes, [2][]byte{[]byte(depGroup + dbDelimiter), nil})
}
sort.Sort(prefixes)
err = db.bolt.View(func(tx *bolt.Tx) error {
newJobBucket := tx.Bucket(bucketJobsLive)
completeJobBucket := tx.Bucket(bucketJobsComplete)
lookupBucket := tx.Bucket(bucketRDTK).Cursor()
doneKeys := make(map[string]bool)
for {
newDepGroups := make(map[string]bool)
for _, bsd := range prefixes {
for k, _ := lookupBucket.Seek(bsd[0]); bytes.HasPrefix(k, bsd[0]); k, _ = lookupBucket.Next() {
key := bytes.TrimPrefix(k, bsd[0])
keyStr := string(key)
if doneKeys[keyStr] {
continue
}
encoded := newJobBucket.Get(key)
live := false
if len(encoded) > 0 {
live = true
} else if !newJobKeys[keyStr] {
encoded = completeJobBucket.Get(key)
}
if len(encoded) > 0 {
dec := codec.NewDecoderBytes(encoded, db.ch)
job := &Job{}
errf := dec.Decode(job)
if errf != nil {
return errf
}
// since we're going to add this job, we also need to
// check its DepGroups and repeat this loop on any new
// ones
for _, depGroup := range job.DepGroups {
if depGroup != "" && !depGroups[depGroup] {
newDepGroups[depGroup] = true
}
}
if live {
jobsToUpdate = append(jobsToUpdate, job)
} else {
jobsToQueue = append(jobsToQueue, job)
}
}
doneKeys[keyStr] = true
}
}
if len(newDepGroups) > 0 {
var newPrefixes sobsd
for depGroup := range newDepGroups {
newPrefixes = append(newPrefixes, [2][]byte{[]byte(depGroup + dbDelimiter), nil})
depGroups[depGroup] = true
}
sort.Sort(newPrefixes)
prefixes = newPrefixes
} else {
break
}
}
return nil
})
return jobsToQueue, jobsToUpdate, err
}
// retrieveIncompleteJobKeysByDepGroup gets jobs with the given DepGroup from
// the live bucket (ie. those that have been added to the queue and not yet
// Archive()d - even if they've been added and archived in the past).
func (db *db) retrieveIncompleteJobKeysByDepGroup(depgroup string) ([]string, error) {
var jobKeys []string
err := db.bolt.View(func(tx *bolt.Tx) error {
newJobBucket := tx.Bucket(bucketJobsLive)
lookupBucket := tx.Bucket(bucketDTK).Cursor()
prefix := []byte(depgroup + dbDelimiter)
for k, _ := lookupBucket.Seek(prefix); bytes.HasPrefix(k, prefix); k, _ = lookupBucket.Next() {
key := bytes.TrimPrefix(k, prefix)
if newJobBucket.Get(key) != nil {
jobKeys = append(jobKeys, string(key))
}
}
return nil
})
return jobKeys, err
}
// storeEnv stores a clientRequest.Env in db unless cached, which means it must
// already be there. Returns a key by which the stored Env can be retrieved.
func (db *db) storeEnv(env []byte) (string, error) {
envkey := byteKey(env)
if !db.envcache.Contains(envkey) {
err := db.store(bucketEnvs, envkey, env)
if err != nil {
return envkey, err
}
db.envcache.Add(envkey, env)
}
return envkey, nil
}
// retrieveEnv gets a value from the db that was stored with storeEnv(). The
// value may come from the cache, avoiding db access.
func (db *db) retrieveEnv(ctx context.Context, envkey string) []byte {
cached, got := db.envcache.Get(envkey)
if got {
return cached.([]byte)
}
envc := db.retrieve(ctx, bucketEnvs, envkey)
db.envcache.Add(envkey, envc)
return envc
}
// updateJobAfterExit stores the Job's peak RAM usage and wall time against the
// Job's ReqGroup, but only if the job failed for using too much RAM or time,
// allowing recommendedReqGroup*(ReqGroup) to work.
//
// So that state can be restored if the server crashes and is restarted, the
// job is rewritten in its current state in to the live bucket.
//
// It also updates the stdout/err associated with a job. We don't want to store
// these in the job, since that would waste a lot of the queue's memory; we
// store in db instead, and only retrieve when a client needs to see these. To
// stop the db file becoming enormous, we only store these if the cmd failed (or
// if forceStorage is true: used when the job got buried) and also delete these
// from db when the cmd completes successfully.
//
// By doing the deletion upfront, we also ensure we have the latest std, which
// may be nil even on cmd failure. Since it is not critical to the running of
// jobs and workflows that this works 100% of the time, we ignore errors and
// write to bolt in a goroutine, giving us a significant speed boost.
func (db *db) updateJobAfterExit(ctx context.Context, job *Job, stdo []byte, stde []byte, forceStorage bool) {
var encoded []byte
enc := codec.NewEncoderBytes(&encoded, db.ch)
db.Lock()
defer db.Unlock()
if db.closed {
return
}
jobkey := job.Key()
job.RLock()
secs := int(math.Ceil(job.EndTime.Sub(job.StartTime).Seconds()))
jrg := job.ReqGroup
jpr := job.PeakRAM