-
Notifications
You must be signed in to change notification settings - Fork 127
/
insertion.go
871 lines (815 loc) · 25.6 KB
/
insertion.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
package lookoutdb
import (
"fmt"
"regexp"
"sync"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
log "github.com/sirupsen/logrus"
"github.com/armadaproject/armada/internal/common/armadacontext"
"github.com/armadaproject/armada/internal/common/armadaerrors"
"github.com/armadaproject/armada/internal/common/database/lookout"
"github.com/armadaproject/armada/internal/common/ingest/metrics"
"github.com/armadaproject/armada/internal/lookoutingesterv2/model"
)
type LookoutDb struct {
db *pgxpool.Pool
metrics *metrics.Metrics
maxBackoff int
fatalErrors []*regexp.Regexp
}
func NewLookoutDb(db *pgxpool.Pool, fatalErrors []*regexp.Regexp, metrics *metrics.Metrics, maxBackoff int) *LookoutDb {
return &LookoutDb{
db: db,
metrics: metrics,
maxBackoff: maxBackoff,
fatalErrors: fatalErrors,
}
}
// Store updates the lookout database according to the supplied InstructionSet.
// The updates are applied in the following order:
// * New Job Creations
// * Job Updates, New Job Creations, New User Annotations
// * Job Run Updates
// In each case we first try to bach insert the rows using the postgres copy protocol. If this fails then we try a
// slower, serial insert and discard any rows that cannot be inserted.
func (l *LookoutDb) Store(ctx *armadacontext.Context, instructions *model.InstructionSet) error {
// We might have multiple updates for the same job or job run
// These can be conflated to help performance
jobsToUpdate := conflateJobUpdates(instructions.JobsToUpdate)
jobRunsToUpdate := conflateJobRunUpdates(instructions.JobRunsToUpdate)
// Jobs need to be ingested first as other updates may reference these
l.CreateJobs(ctx, instructions.JobsToCreate)
// Now we can job updates, annotations and new job runs
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
l.UpdateJobs(ctx, jobsToUpdate)
}()
go func() {
defer wg.Done()
l.CreateJobRuns(ctx, instructions.JobRunsToCreate)
}()
wg.Wait()
// Finally, we can update the job runs
l.UpdateJobRuns(ctx, jobRunsToUpdate)
return nil
}
func (l *LookoutDb) CreateJobs(ctx *armadacontext.Context, instructions []*model.CreateJobInstruction) {
if len(instructions) == 0 {
return
}
start := time.Now()
err := l.CreateJobsBatch(ctx, instructions)
if err != nil {
log.WithError(err).Warn("Creating jobs via batch failed, will attempt to insert serially (this might be slow).")
l.CreateJobsScalar(ctx, instructions)
}
log.Infof("Inserted %d jobs in %s", len(instructions), time.Since(start))
}
func (l *LookoutDb) UpdateJobs(ctx *armadacontext.Context, instructions []*model.UpdateJobInstruction) {
if len(instructions) == 0 {
return
}
start := time.Now()
instructions = l.filterEventsForTerminalJobs(ctx, l.db, instructions, l.metrics)
err := l.UpdateJobsBatch(ctx, instructions)
if err != nil {
log.WithError(err).Warn("Updating jobs via batch failed, will attempt to insert serially (this might be slow).")
l.UpdateJobsScalar(ctx, instructions)
}
log.Infof("Updated %d jobs in %s", len(instructions), time.Since(start))
}
func (l *LookoutDb) CreateJobRuns(ctx *armadacontext.Context, instructions []*model.CreateJobRunInstruction) {
if len(instructions) == 0 {
return
}
start := time.Now()
err := l.CreateJobRunsBatch(ctx, instructions)
if err != nil {
log.WithError(err).Warn("Creating job runs via batch failed, will attempt to insert serially (this might be slow).")
l.CreateJobRunsScalar(ctx, instructions)
}
log.Infof("Inserted %d job runs in %s", len(instructions), time.Since(start))
}
func (l *LookoutDb) UpdateJobRuns(ctx *armadacontext.Context, instructions []*model.UpdateJobRunInstruction) {
if len(instructions) == 0 {
return
}
start := time.Now()
err := l.UpdateJobRunsBatch(ctx, instructions)
if err != nil {
log.WithError(err).Warn("Updating job runs via batch failed, will attempt to insert serially (this might be slow).")
l.UpdateJobRunsScalar(ctx, instructions)
}
log.Infof("Updated %d job runs in %s", len(instructions), time.Since(start))
}
func (l *LookoutDb) CreateJobsBatch(ctx *armadacontext.Context, instructions []*model.CreateJobInstruction) error {
return l.withDatabaseRetryInsert(func() error {
tmpTable := "job_create_tmp"
createTmp := func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, fmt.Sprintf(`
CREATE TEMPORARY TABLE %s
(
job_id varchar(32),
queue varchar(512),
owner varchar(512),
namespace varchar(512),
jobset varchar(1024),
cpu bigint,
memory bigint,
ephemeral_storage bigint,
gpu bigint,
priority bigint,
submitted timestamp,
state smallint,
last_transition_time timestamp,
last_transition_time_seconds bigint,
job_spec bytea,
priority_class varchar(63),
annotations jsonb
) ON COMMIT DROP;`, tmpTable))
if err != nil {
l.metrics.RecordDBError(metrics.DBOperationCreateTempTable)
}
return err
}
insertTmp := func(tx pgx.Tx) error {
_, err := tx.CopyFrom(ctx,
pgx.Identifier{tmpTable},
[]string{
"job_id",
"queue",
"owner",
"namespace",
"jobset",
"cpu",
"memory",
"ephemeral_storage",
"gpu",
"priority",
"submitted",
"state",
"last_transition_time",
"last_transition_time_seconds",
"job_spec",
"priority_class",
"annotations",
},
pgx.CopyFromSlice(len(instructions), func(i int) ([]interface{}, error) {
return []interface{}{
instructions[i].JobId,
instructions[i].Queue,
instructions[i].Owner,
instructions[i].Namespace,
instructions[i].JobSet,
instructions[i].Cpu,
instructions[i].Memory,
instructions[i].EphemeralStorage,
instructions[i].Gpu,
instructions[i].Priority,
instructions[i].Submitted,
instructions[i].State,
instructions[i].LastTransitionTime,
instructions[i].LastTransitionTimeSeconds,
instructions[i].JobProto,
instructions[i].PriorityClass,
instructions[i].Annotations,
}, nil
}),
)
return err
}
copyToDest := func(tx pgx.Tx) error {
_, err := tx.Exec(
ctx,
fmt.Sprintf(`
INSERT INTO job (
job_id,
queue,
owner,
namespace,
jobset,
cpu,
memory,
ephemeral_storage,
gpu,
priority,
submitted,
state,
last_transition_time,
last_transition_time_seconds,
job_spec,
priority_class,
annotations
) SELECT * from %s
ON CONFLICT DO NOTHING`, tmpTable),
)
if err != nil {
l.metrics.RecordDBError(metrics.DBOperationInsert)
}
return err
}
return batchInsert(ctx, l.db, createTmp, insertTmp, copyToDest)
})
}
// CreateJobsScalar will insert jobs one by one into the database
func (l *LookoutDb) CreateJobsScalar(ctx *armadacontext.Context, instructions []*model.CreateJobInstruction) {
sqlStatement := `INSERT INTO job (
job_id,
queue,
owner,
namespace,
jobset,
cpu,
memory,
ephemeral_storage,
gpu,
priority,
submitted,
state,
last_transition_time,
last_transition_time_seconds,
job_spec,
priority_class,
annotations
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)
ON CONFLICT DO NOTHING`
for _, i := range instructions {
err := l.withDatabaseRetryInsert(func() error {
_, err := l.db.Exec(ctx, sqlStatement,
i.JobId,
i.Queue,
i.Owner,
i.Namespace,
i.JobSet,
i.Cpu,
i.Memory,
i.EphemeralStorage,
i.Gpu,
i.Priority,
i.Submitted,
i.State,
i.LastTransitionTime,
i.LastTransitionTimeSeconds,
i.JobProto,
i.PriorityClass,
i.Annotations,
)
if err != nil {
l.metrics.RecordDBError(metrics.DBOperationInsert)
}
return err
})
if err != nil {
log.WithError(err).Warnf("Create job for job %s, jobset %s failed", i.JobId, i.JobSet)
}
}
}
func (l *LookoutDb) UpdateJobsBatch(ctx *armadacontext.Context, instructions []*model.UpdateJobInstruction) error {
return l.withDatabaseRetryInsert(func() error {
tmpTable := "job_update_tmp"
createTmp := func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, fmt.Sprintf(`
CREATE TEMPORARY TABLE %s (
job_id varchar(32),
priority bigint,
state smallint,
cancelled timestamp,
last_transition_time timestamp,
last_transition_time_seconds bigint,
duplicate bool,
latest_run_id varchar(36),
cancel_reason varchar(512)
) ON COMMIT DROP;`, tmpTable))
if err != nil {
l.metrics.RecordDBError(metrics.DBOperationCreateTempTable)
}
return err
}
insertTmp := func(tx pgx.Tx) error {
_, err := tx.CopyFrom(ctx,
pgx.Identifier{tmpTable},
[]string{
"job_id",
"priority",
"state",
"cancelled",
"last_transition_time",
"last_transition_time_seconds",
"duplicate",
"latest_run_id",
"cancel_reason",
},
pgx.CopyFromSlice(len(instructions), func(i int) ([]interface{}, error) {
return []interface{}{
instructions[i].JobId,
instructions[i].Priority,
instructions[i].State,
instructions[i].Cancelled,
instructions[i].LastTransitionTime,
instructions[i].LastTransitionTimeSeconds,
instructions[i].Duplicate,
instructions[i].LatestRunId,
instructions[i].CancelReason,
}, nil
}),
)
return err
}
copyToDest := func(tx pgx.Tx) error {
_, err := tx.Exec(
ctx,
fmt.Sprintf(`UPDATE job
SET
priority = coalesce(tmp.priority, job.priority),
state = coalesce(tmp.state, job.state),
cancelled = coalesce(tmp.cancelled, job.cancelled),
last_transition_time = coalesce(tmp.last_transition_time, job.last_transition_time),
last_transition_time_seconds = coalesce(tmp.last_transition_time_seconds, job.last_transition_time_seconds),
duplicate = coalesce(tmp.duplicate, job.duplicate),
latest_run_id = coalesce(tmp.latest_run_id, job.latest_run_id),
cancel_reason = coalesce(tmp.cancel_reason, job.cancel_reason)
FROM %s as tmp WHERE tmp.job_id = job.job_id`, tmpTable),
)
if err != nil {
l.metrics.RecordDBError(metrics.DBOperationUpdate)
}
return err
}
return batchInsert(ctx, l.db, createTmp, insertTmp, copyToDest)
})
}
func (l *LookoutDb) UpdateJobsScalar(ctx *armadacontext.Context, instructions []*model.UpdateJobInstruction) {
sqlStatement := `UPDATE job
SET
priority = coalesce($2, priority),
state = coalesce($3, state),
cancelled = coalesce($4, cancelled),
last_transition_time = coalesce($5, job.last_transition_time),
last_transition_time_seconds = coalesce($6, job.last_transition_time_seconds),
duplicate = coalesce($7, duplicate),
latest_run_id = coalesce($8, job.latest_run_id),
cancel_reason = coalesce($9, job.cancel_reason)
WHERE job_id = $1`
for _, i := range instructions {
err := l.withDatabaseRetryInsert(func() error {
_, err := l.db.Exec(ctx, sqlStatement,
i.JobId,
i.Priority,
i.State,
i.Cancelled,
i.LastTransitionTime,
i.LastTransitionTimeSeconds,
i.Duplicate,
i.LatestRunId,
i.CancelReason)
if err != nil {
l.metrics.RecordDBError(metrics.DBOperationUpdate)
}
return err
})
if err != nil {
log.WithError(err).Warnf("Updating job %s failed", i.JobId)
}
}
}
func (l *LookoutDb) CreateJobRunsBatch(ctx *armadacontext.Context, instructions []*model.CreateJobRunInstruction) error {
return l.withDatabaseRetryInsert(func() error {
tmpTable := "job_run_create_tmp"
createTmp := func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, fmt.Sprintf(`
CREATE TEMPORARY TABLE %s (
run_id varchar(36),
job_id varchar(32),
cluster varchar(512),
node varchar(512),
leased timestamp,
pending timestamp,
job_run_state smallint
) ON COMMIT DROP;`, tmpTable))
if err != nil {
l.metrics.RecordDBError(metrics.DBOperationCreateTempTable)
}
return err
}
insertTmp := func(tx pgx.Tx) error {
_, err := tx.CopyFrom(ctx,
pgx.Identifier{tmpTable},
[]string{
"run_id",
"job_id",
"cluster",
"node",
"leased",
"pending",
"job_run_state",
},
pgx.CopyFromSlice(len(instructions), func(i int) ([]interface{}, error) {
return []interface{}{
instructions[i].RunId,
instructions[i].JobId,
instructions[i].Cluster,
instructions[i].Node,
instructions[i].Leased,
instructions[i].Pending,
instructions[i].JobRunState,
}, nil
}),
)
return err
}
copyToDest := func(tx pgx.Tx) error {
_, err := tx.Exec(
ctx,
fmt.Sprintf(`
INSERT INTO job_run (
run_id,
job_id,
cluster,
node,
leased,
pending,
job_run_state
) SELECT * from %s
ON CONFLICT DO NOTHING`, tmpTable))
if err != nil {
l.metrics.RecordDBError(metrics.DBOperationInsert)
}
return err
}
return batchInsert(ctx, l.db, createTmp, insertTmp, copyToDest)
})
}
func (l *LookoutDb) CreateJobRunsScalar(ctx *armadacontext.Context, instructions []*model.CreateJobRunInstruction) {
sqlStatement := `INSERT INTO job_run (
run_id,
job_id,
cluster,
node,
leased,
pending,
job_run_state)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT DO NOTHING`
for _, i := range instructions {
err := l.withDatabaseRetryInsert(func() error {
_, err := l.db.Exec(ctx, sqlStatement,
i.RunId,
i.JobId,
i.Cluster,
i.Node,
i.Leased,
i.Pending,
i.JobRunState)
if err != nil {
l.metrics.RecordDBError(metrics.DBOperationInsert)
}
return err
})
if err != nil {
log.WithError(err).Warnf("Create job run for job %s, run %s failed", i.JobId, i.RunId)
}
}
}
func (l *LookoutDb) UpdateJobRunsBatch(ctx *armadacontext.Context, instructions []*model.UpdateJobRunInstruction) error {
return l.withDatabaseRetryInsert(func() error {
tmpTable := "job_run_update_tmp"
createTmp := func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, fmt.Sprintf(`
CREATE TEMPORARY TABLE %s (
run_id varchar(36),
node varchar(512),
pending timestamp,
started timestamp,
finished timestamp,
job_run_state smallint,
error bytea,
debug bytea,
exit_code int
) ON COMMIT DROP;`, tmpTable))
if err != nil {
l.metrics.RecordDBError(metrics.DBOperationCreateTempTable)
}
return err
}
insertTmp := func(tx pgx.Tx) error {
_, err := tx.CopyFrom(ctx,
pgx.Identifier{tmpTable},
[]string{
"run_id",
"node",
"pending",
"started",
"finished",
"job_run_state",
"error",
"debug",
"exit_code",
},
pgx.CopyFromSlice(len(instructions), func(i int) ([]interface{}, error) {
return []interface{}{
instructions[i].RunId,
instructions[i].Node,
instructions[i].Pending,
instructions[i].Started,
instructions[i].Finished,
instructions[i].JobRunState,
instructions[i].Error,
instructions[i].Debug,
instructions[i].ExitCode,
}, nil
}),
)
return err
}
copyToDest := func(tx pgx.Tx) error {
_, err := tx.Exec(
ctx,
fmt.Sprintf(`UPDATE job_run
SET
node = coalesce(tmp.node, job_run.node),
pending = coalesce(tmp.pending, job_run.pending),
started = coalesce(tmp.started, job_run.started),
finished = coalesce(tmp.finished, job_run.finished),
job_run_state = coalesce(tmp.job_run_state, job_run.job_run_state),
error = coalesce(tmp.error, job_run.error),
debug = coalesce(tmp.debug, job_run.debug),
exit_code = coalesce(tmp.exit_code, job_run.exit_code)
FROM %s as tmp where tmp.run_id = job_run.run_id`, tmpTable),
)
if err != nil {
l.metrics.RecordDBError(metrics.DBOperationUpdate)
}
return err
}
return batchInsert(ctx, l.db, createTmp, insertTmp, copyToDest)
})
}
func (l *LookoutDb) UpdateJobRunsScalar(ctx *armadacontext.Context, instructions []*model.UpdateJobRunInstruction) {
sqlStatement := `UPDATE job_run
SET
node = coalesce($2, node),
started = coalesce($3, started),
finished = coalesce($4, finished),
job_run_state = coalesce($5, job_run_state),
error = coalesce($6, error),
exit_code = coalesce($7, exit_code),
pending = coalesce($8, pending),
debug = coalesce($9, debug)
WHERE run_id = $1`
for _, i := range instructions {
err := l.withDatabaseRetryInsert(func() error {
_, err := l.db.Exec(ctx, sqlStatement,
i.RunId,
i.Node,
i.Started,
i.Finished,
i.JobRunState,
i.Error,
i.ExitCode,
i.Pending,
i.Debug)
if err != nil {
l.metrics.RecordDBError(metrics.DBOperationUpdate)
}
return err
})
if err != nil {
log.WithError(err).Warnf("Updating job run %s failed", i.RunId)
}
}
}
func batchInsert(ctx *armadacontext.Context, db *pgxpool.Pool, createTmp func(pgx.Tx) error,
insertTmp func(pgx.Tx) error, copyToDest func(pgx.Tx) error,
) error {
return pgx.BeginTxFunc(ctx, db, pgx.TxOptions{
IsoLevel: pgx.ReadCommitted,
AccessMode: pgx.ReadWrite,
DeferrableMode: pgx.Deferrable,
}, func(tx pgx.Tx) error {
// Create a temporary table to hold the staging data
err := createTmp(tx)
if err != nil {
return err
}
err = insertTmp(tx)
if err != nil {
return err
}
err = copyToDest(tx)
if err != nil {
return err
}
return nil
})
}
func conflateJobUpdates(updates []*model.UpdateJobInstruction) []*model.UpdateJobInstruction {
isTerminal := func(p *int32) bool {
if p == nil {
return false
} else {
return *p == lookout.JobFailedOrdinal ||
*p == lookout.JobSucceededOrdinal ||
*p == lookout.JobCancelledOrdinal ||
*p == lookout.JobPreemptedOrdinal
}
}
updatesById := make(map[string]*model.UpdateJobInstruction)
for _, update := range updates {
existing, ok := updatesById[update.JobId]
if !ok {
updatesById[update.JobId] = update
continue
}
// Unfortunately once a job has reached a terminal state we still get state updates for it e.g. we can get an event to
// say it's now "running". We have to throw these away else we'll end up with a zombie job.
//
// Need to deal with preempted jobs separately
// We could get a JobFailed event (or another terminal event) after a JobPreempted event,
// but the job should still be marked as Preempted
if !isTerminal(existing.State) || (update.State != nil && *update.State == lookout.JobPreemptedOrdinal) {
if update.Priority != nil {
existing.Priority = update.Priority
}
if update.State != nil {
existing.State = update.State
}
if update.Cancelled != nil {
existing.Cancelled = update.Cancelled
}
if update.LastTransitionTime != nil {
existing.LastTransitionTime = update.LastTransitionTime
}
if update.LastTransitionTimeSeconds != nil {
existing.LastTransitionTimeSeconds = update.LastTransitionTimeSeconds
}
if update.Duplicate != nil {
existing.Duplicate = update.Duplicate
}
if update.LatestRunId != nil {
existing.LatestRunId = update.LatestRunId
}
}
}
conflated := make([]*model.UpdateJobInstruction, 0, len(updatesById))
// TODO: it turns out that iteration over a map in go yields a different key order each time!
// This means that that slice outputted by this function (and the one below) will have a random order
// This isn't a problem as such for the database but does mean that reproducing errors etc will be hard
for _, v := range updatesById {
conflated = append(conflated, v)
}
return conflated
}
func conflateJobRunUpdates(updates []*model.UpdateJobRunInstruction) []*model.UpdateJobRunInstruction {
updatesById := make(map[string]*model.UpdateJobRunInstruction)
for _, update := range updates {
existing, ok := updatesById[update.RunId]
if ok {
if update.Node != nil {
existing.Node = update.Node
}
if update.Started != nil {
existing.Started = update.Started
}
if update.Finished != nil {
existing.Finished = update.Finished
}
if update.Error != nil {
existing.Error = update.Error
}
if update.Debug != nil {
existing.Debug = update.Debug
}
if update.JobRunState != nil {
existing.JobRunState = update.JobRunState
}
if update.ExitCode != nil {
existing.ExitCode = update.ExitCode
}
} else {
updatesById[update.RunId] = update
}
}
conflated := make([]*model.UpdateJobRunInstruction, 0, len(updatesById))
for _, v := range updatesById {
conflated = append(conflated, v)
}
return conflated
}
// updateInstructionsForJob is used in filterEventsForTerminalJobs, and records a list of job updates for a single job,
// along with whether it contains an instruction corresponding to a JobPreempted event
type updateInstructionsForJob struct {
instructions []*model.UpdateJobInstruction
containsPreempted bool
}
// filterEventsForTerminalJobs queries the database for any jobs that are in a terminal state and removes them from the list of
// instructions. This is necessary because Armada will generate event statuses even for jobs that have reached a terminal state
// The proper solution here is to make it so once a job is terminal, no more events are generated for it, but until
// that day we have to manually filter them out here.
// NOTE: this function will retry querying the database for as long as possible in order to determine which jobs are
// in the terminal state. If, however, the database returns a non-retryable error it will give up and simply not
// filter out any events as the job state is undetermined.
func (l *LookoutDb) filterEventsForTerminalJobs(
ctx *armadacontext.Context,
db *pgxpool.Pool,
instructions []*model.UpdateJobInstruction,
m *metrics.Metrics,
) []*model.UpdateJobInstruction {
jobIds := make([]string, len(instructions))
for i, instruction := range instructions {
jobIds[i] = instruction.JobId
}
queryStart := time.Now()
rowsRaw, err := l.withDatabaseRetryQuery(func() (interface{}, error) {
terminalStates := []int{
lookout.JobSucceededOrdinal,
lookout.JobFailedOrdinal,
lookout.JobCancelledOrdinal,
lookout.JobPreemptedOrdinal,
}
return db.Query(ctx, "SELECT DISTINCT job_id, state FROM JOB where state = any($1) AND job_id = any($2)", terminalStates, jobIds)
})
if err != nil {
m.RecordDBError(metrics.DBOperationRead)
log.WithError(err).Warnf("Cannot retrieve job state from the database- Cancelled jobs may not be filtered out")
return instructions
}
rows := rowsRaw.(pgx.Rows)
terminalJobs := make(map[string]int)
for rows.Next() {
jobId := ""
var state int16
err := rows.Scan(&jobId, &state)
if err != nil {
log.WithError(err).Warnf("Cannot retrieve jobId from row. Terminal jobs will not be filtered out")
} else {
terminalJobs[jobId] = int(state)
}
}
log.Infof("Lookup of terminal states for %d jobs took %s and returned %d results", len(instructions), time.Since(queryStart), len(terminalJobs))
if len(terminalJobs) > 0 {
jobInstructionMap := make(map[string]*updateInstructionsForJob)
for _, instruction := range instructions {
data, ok := jobInstructionMap[instruction.JobId]
if !ok {
data = &updateInstructionsForJob{
instructions: []*model.UpdateJobInstruction{},
containsPreempted: false,
}
jobInstructionMap[instruction.JobId] = data
}
data.instructions = append(data.instructions, instruction)
data.containsPreempted = instruction.State != nil && *instruction.State == lookout.JobPreemptedOrdinal
}
var filtered []*model.UpdateJobInstruction
for jobId, updateInstructions := range jobInstructionMap {
state, ok := terminalJobs[jobId]
// Need to record updates if either:
// * Job is not in a terminal state
// * Job is in succeeded, failed or cancelled, but job preempted event will be recorded
if !ok || ((state == lookout.JobSucceededOrdinal ||
state == lookout.JobFailedOrdinal ||
state == lookout.JobCancelledOrdinal) && updateInstructions.containsPreempted) {
filtered = append(filtered, updateInstructions.instructions...)
}
}
return filtered
} else {
return instructions
}
}
func (l *LookoutDb) withDatabaseRetryInsert(executeDb func() error) error {
_, err := l.withDatabaseRetryQuery(func() (interface{}, error) {
return nil, executeDb()
})
return err
}
// Executes a database function, retrying until it either succeeds or encounters a non-retryable error
func (l *LookoutDb) withDatabaseRetryQuery(executeDb func() (interface{}, error)) (interface{}, error) {
// TODO: arguably this should come from config
backOff := 1
for {
res, err := executeDb()
if err == nil {
return res, nil
}
if armadaerrors.IsRetryablePostgresError(err, l.fatalErrors) {
backOff = min(2*backOff, l.maxBackoff)
log.WithError(err).Warnf("Retryable error encountered executing sql, will wait for %d seconds before retrying.", backOff)
time.Sleep(time.Duration(backOff) * time.Second)
} else {
// Non retryable error
return nil, err
}
}
}
func min(a int, b int) int {
if a < b {
return a
}
return b
}