/
postgres_store.go
1385 lines (1209 loc) · 35.7 KB
/
postgres_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
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
package jobs
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/opentracing/opentracing-go"
log "github.com/sirupsen/logrus"
// postgres sql driver
_ "github.com/lib/pq"
)
type postgreSQLStore struct {
connection *sql.DB
jobStatusSubscribers map[string]([]chan<- Job)
jobStatusSubscribersLock sync.Mutex
}
// Sort options
const (
sortByID = "job_id"
sortByName = "job_name"
sortByStatus = "status"
sortByLastUpdated = "last_updated"
sortByStoppedAt = "stopped_at"
)
// parseSortColumn parses a string into a valid sorting value
// Accepts: id, name, status and last_updated (default: last_updated)
func parseSortColumn(input string) string {
switch input {
case "id":
return sortByID
case "name":
return sortByName
case "status":
return sortByStatus
case "stopped_at":
return sortByStoppedAt
default:
return sortByLastUpdated
}
}
func searchEscape(search string) string {
/* Escape characters so they won't be interpreted as search special
* characters */
/* Percent sign, underscore and backslash are in this group. The string is
* otherwise escaped normally by SQL so this won't result in SQL injection
* attacks, but I suppose if we didn't escape search might crash. */
return strings.Replace(strings.Replace(strings.Replace(search, "\\", "\\\\", -1), "%", "\\%", -1), "_", "\\_", -1)
}
func (pq *postgreSQLStore) Find(opts *Options) ([]*Job, error) {
span := opentracing.StartSpan("PG.Find")
defer span.Finish()
var sortDirection string
if opts.SortAsc {
sortDirection = "ASC"
} else {
sortDirection = "DESC"
}
query := `
SELECT job_id,
job_name,
status,
job_definition,
last_updated,
job_queue,
image,
created_at,
stopped_at,
vcpus,
memory,
timeout,
command_line,
status_reason,
run_started_at,
exitcode,
log_stream_name,
termination_requested,
task_arn
FROM jobs
`
var whereClausesPr = []string{}
var whereClausesScan = []string{}
args := make([]interface{}, 0)
args = append(args, opts.Limit)
args = append(args, opts.Offset)
whereClausesScan = append(whereClausesScan, "last_updated > (now() - interval '30 days')")
if opts.Search != "" {
glob_search := "%" + searchEscape(opts.Search) + "%"
args = append(args, glob_search)
index := strconv.Itoa(len(args))
whereClausesScan = append(whereClausesScan, fmt.Sprintf(`
(job_id || job_name || job_queue || image) LIKE $%s
`, index))
}
var statusBuffer bytes.Buffer
var queuesBuffer bytes.Buffer
if len(opts.Status) > 0 {
statusBuffer.WriteString("status IN (")
for i, item := range opts.Status {
args = append(args, item)
statusBuffer.WriteString("$" + strconv.Itoa(len(args)))
if i < len(opts.Status)-1 {
statusBuffer.WriteString(",")
}
}
statusBuffer.WriteString(")")
whereClausesPr = append(whereClausesPr, statusBuffer.String())
}
if len(opts.Queues) > 0 {
queuesBuffer.WriteString("job_queue IN (")
for i, item := range opts.Queues {
args = append(args, item)
queuesBuffer.WriteString("$" + strconv.Itoa(len(args)))
if i < len(opts.Queues)-1 {
queuesBuffer.WriteString(",")
}
}
queuesBuffer.WriteString(")")
whereClausesPr = append(whereClausesPr, queuesBuffer.String())
}
unconditional_filters := strings.Join(whereClausesPr, " AND ")
scanner := strings.Join(whereClausesScan, " AND ")
if len(unconditional_filters) > 0 || len(scanner) > 0 {
query += " WHERE "
if len(unconditional_filters) > 0 {
query += "(" + unconditional_filters + ")"
}
if len(scanner) > 0 && len(unconditional_filters) > 0 {
query += " AND ("
}
if len(scanner) > 0 {
query += "(" + scanner + ")"
}
if len(scanner) > 0 && len(unconditional_filters) > 0 {
query += ")"
}
}
query += fmt.Sprintf(" ORDER BY %s %s LIMIT $1 OFFSET $2", parseSortColumn(opts.SortBy), sortDirection)
rows, err := pq.connection.Query(
query,
args...)
if err != nil {
log.Error("Find failed with error: ", err)
return nil, err
}
defer rows.Close()
allJobs := make([]*Job, 0)
for rows.Next() {
var job Job
if err := rows.Scan(&job.Id, &job.Name, &job.Status, &job.Description, &job.LastUpdated, &job.JobQueue, &job.Image, &job.CreatedAt, &job.StoppedAt, &job.VCpus, &job.Memory, &job.Timeout, &job.CommandLine, &job.StatusReason, &job.RunStartTime, &job.ExitCode, &job.LogStreamName, &job.TerminationRequested, &job.TaskARN); err != nil {
log.Warning(err)
return nil, err
}
allJobs = append(allJobs, &job)
}
return allJobs, nil
}
func (pq *postgreSQLStore) FindTimedoutJobs() ([]string, error) {
span := opentracing.StartSpan("PG.FindTimedoutJobs")
defer span.Finish()
query := `
SELECT job_id
FROM jobs
WHERE created_at + interval '1 second' * timeout < now()
AND timeout != -1 AND status != 'SUCCEEDED' AND status != 'GONE' AND status != 'FAILED' AND termination_requested = 'f'`
rows, err := pq.connection.Query(query)
if err != nil {
log.Warning("Cannot find timed out jobs from database: ", err)
return nil, err
}
defer rows.Close()
job_ids := make([]string, 0)
for rows.Next() {
var job_id string
if err := rows.Scan(&job_id); err != nil {
log.Error("Cannot scan rows in finding jobs that have timed out: ", err)
return nil, err
}
job_ids = append(job_ids, job_id)
}
return job_ids, nil
}
func (pq *postgreSQLStore) FindOne(index string) (*Job, error) {
span := opentracing.StartSpan("PG.FindOne")
defer span.Finish()
query := `
SELECT job_id,
job_name,
status,
job_definition,
last_updated,
job_queue,
image,
created_at,
stopped_at,
vcpus,
memory,
timeout,
command_line,
status_reason,
run_started_at,
exitcode,
log_stream_name,
termination_requested,
jobs.task_arn,
ta.instance_id,
ta.public_ip,
ta.private_ip
FROM jobs
LEFT OUTER JOIN task_arns_to_instance_info ta ON
ta.task_arn = jobs.task_arn
WHERE jobs.job_id = $1
`
rows, err := pq.connection.Query(query, index)
if err != nil {
return nil, err
}
defer rows.Close()
var job Job
rows.Next()
if job.StatusReason == nil {
sr := ""
job.StatusReason = &sr
}
if err := rows.Scan(&job.Id, &job.Name, &job.Status, &job.Description, &job.LastUpdated, &job.JobQueue, &job.Image, &job.CreatedAt, &job.StoppedAt, &job.VCpus, &job.Memory, &job.Timeout, &job.CommandLine, &job.StatusReason, &job.RunStartTime, &job.ExitCode, &job.LogStreamName, &job.TerminationRequested, &job.TaskARN, &job.InstanceID, &job.PublicIP, &job.PrivateIP); err != nil {
log.Warning(err)
return nil, err
}
return &job, nil
}
func (pq *postgreSQLStore) StaleOldJobs(job_ids map[string]bool) error {
span := opentracing.StartSpan("PG.StaleOldJobs")
defer span.Finish()
/*
What happens in this function is that we take all jobs we currently know
about and then mark all jobs that are not either SUCCESS or FAILED as GONE.
Sometimes batchiepatchie misses or AWS Batch forgets about jobs and this
can cause a job to be perpetually in RUNNING or RUNNABLE state in the
database. This function marks them so user knows they are no longer
available.
*/
err := func() error {
transaction, err := pq.connection.Begin()
if err != nil {
log.Warning(err)
return err
}
should_commit := false
final := func() error {
if should_commit {
err := transaction.Commit()
if err != nil {
log.Warning("Cannot commit transaction: ", err)
return err
}
} else {
err := transaction.Rollback()
if err != nil {
log.Warning("Cannot roll back transaction: ", err)
return err
}
}
return nil
}
defer final()
query := `create temporary table jobs_known_about ( job_id text primary key ) on commit drop`
_, err = transaction.Exec(query)
if err != nil {
log.Warning("Cannot create temporary table in StaleOldJobs: ", err)
return err
}
for job_id := range job_ids {
query := `insert into jobs_known_about ( job_id ) values ( $1 )`
_, err = transaction.Exec(query, job_id)
if err != nil {
log.Warning("Cannot insert into jobs_known_about in StaleOldJobs: ", err)
return err
}
}
where_clause := `WHERE j.status NOT IN ('GONE', 'SUCCEEDED', 'FAILED') ` +
`AND j.job_id NOT IN (SELECT jka.job_id FROM jobs_known_about jka) ` +
`AND AGE(CURRENT_TIMESTAMP, j.last_updated) > INTERVAL '300 sec'`
query = `UPDATE jobs j SET status = 'GONE' ` + where_clause
_, err = transaction.Exec(query)
if err != nil {
log.Warning("Cannot update GONE status: ", err)
return err
}
should_commit = true
// Note: transaction commit errors are silenced (but they are logged)
return nil
}()
if err != nil {
return err
}
return pq.flushJobStatusSubscriptions()
}
func (pq *postgreSQLStore) Store(jobs []*Job) error {
span := opentracing.StartSpan("PG.Store")
defer span.Finish()
/* Don't bother going to database to insert 0 jobs */
if len(jobs) == 0 {
return nil
}
err := func() error {
transaction, err := pq.connection.Begin()
if err != nil {
log.Warning(err)
return err
}
should_commit := false
final := func() error {
if should_commit {
err := transaction.Commit()
if err != nil {
log.Warning("Cannot commit transaction: ", err)
return err
}
log.Info("Committed ", len(jobs), " jobs to database.")
} else {
err := transaction.Rollback()
if err != nil {
log.Warning("Cannot roll back transaction: ", err)
return err
}
}
return nil
}
defer final()
for _, job := range jobs {
var err error
if job.StoppedAt == nil {
query := `insert into jobs (
job_id,
job_name,
job_definition,
job_queue,
image,
status,
created_at,
vcpus,
memory,
timeout,
command_line,
last_updated,
status_reason,
run_started_at,
exitcode,
log_stream_name,
task_arn)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)
on conflict (job_id) do update set status = $6, last_updated = $12, status_reason = $13, run_started_at = $14, exitcode = $15, log_stream_name = $16, task_arn = $17
where jobs.status <> $6 or jobs.status_reason <> $13 or jobs.exitcode <> $15 or jobs.log_stream_name <> $16 or jobs.task_arn <> $17 or (jobs.task_arn is null and $17 is not null) or (jobs.log_stream_name is null and $16 is not null) or (jobs.status_reason is null and $13 is not null) or (jobs.exitcode is null and $15 is not null)`
_, err = transaction.Exec(
query,
job.Id,
job.Name,
job.Description,
job.JobQueue,
job.Image,
job.Status,
job.CreatedAt.Format("2006-01-02 15:04:05"),
job.VCpus,
job.Memory,
job.Timeout,
job.CommandLine,
job.LastUpdated.Format("2006-01-02 15:04:05"),
job.StatusReason,
job.RunStartTime,
job.ExitCode,
job.LogStreamName,
job.TaskARN)
} else {
query := `insert into jobs (
job_id,
job_name,
job_definition,
job_queue,
image,
status,
created_at,
stopped_at,
vcpus,
memory,
timeout,
command_line,
last_updated,
status_reason,
run_started_at,
exitcode,
log_stream_name,
task_arn)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)
on conflict (job_id) do update set status = $6, last_updated = $13, stopped_at = $8, status_reason = $14, run_started_at = $15, exitcode = $16, log_stream_name = $17, task_arn = $18
where jobs.status <> $6 or jobs.status_reason <> $14 or jobs.exitcode <> $16 or jobs.log_stream_name <> $17 or jobs.task_arn <> $18 or (jobs.task_arn is null and $18 is not null) or (jobs.log_stream_name is null and $17 is not null) or (jobs.status_reason is null and $14 is not null) or (jobs.exitcode is null and $16 is not null)`
_, err = transaction.Exec(
query,
job.Id,
job.Name,
job.Description,
job.JobQueue,
job.Image,
job.Status,
job.CreatedAt.Format("2006-01-02 15:04:05"),
job.StoppedAt.Format("2006-01-02 15:04:05"),
job.VCpus,
job.Memory,
job.Timeout,
job.CommandLine,
job.LastUpdated.Format("2006-01-02 15:04:05"),
job.StatusReason,
job.RunStartTime,
job.ExitCode,
job.LogStreamName,
job.TaskARN)
}
if err != nil {
log.Warning(err, ": ", job)
return err
}
}
should_commit = true
return nil
}()
if err != nil {
return err
}
return pq.flushJobStatusSubscriptions()
}
func (pq *postgreSQLStore) EstimateRunningLoadByJobQueue(queues []string) (map[string]RunningLoad, error) {
span := opentracing.StartSpan("PG.EstimateRunningLoadByJobQueue")
defer span.Finish()
query := `
SELECT job_queue,SUM(vcpus),SUM(memory) FROM jobs WHERE
status = 'SUBMITTED' OR
status = 'PENDING' OR
status = 'RUNNABLE' OR
status = 'STARTING' OR
status = 'RUNNING'
GROUP BY job_queue`
rows, err := pq.connection.Query(query)
if err != nil {
log.Error("EstimateRunningLoadByJobQueue failed to query database: ", err)
return nil, err
}
defer rows.Close()
mapping := make(map[string]RunningLoad)
for rows.Next() {
var job_queue string
var vcpus int64
var memory int64
if err := rows.Scan(&job_queue, &vcpus, &memory); err != nil {
log.Error("Cannot scan rows in EstimateRunningLoadByJobQueue: ", err)
return nil, err
}
mapping[job_queue] = RunningLoad{WantedVCpus: vcpus, WantedMemory: memory}
}
/* The SQL query doesn't catch cases where no jobs are running (they will be missing from map).
Manually fill out the missing job_queues to the load estimate map
before we return from this function */
for _, queue := range queues {
if _, ok := mapping[queue]; !ok {
mapping[queue] = RunningLoad{WantedVCpus: 0, WantedMemory: 0}
}
}
return mapping, nil
}
func (pq *postgreSQLStore) UpdateJobSummaryLog(job_summaries []JobSummary) error {
span := opentracing.StartSpan("PG.UpdateJobSummaryLog")
defer span.Finish()
ctx_timeout, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
transaction, err := pq.connection.BeginTx(ctx_timeout, &sql.TxOptions{Isolation: sql.LevelSerializable})
if err != nil {
log.Warning(err)
return err
}
should_commit := false
final := func() error {
if should_commit {
err := transaction.Commit()
if err != nil {
log.Warning("Cannot commit transaction: ", err)
return err
}
} else {
err := transaction.Rollback()
if err != nil {
log.Warning("Cannot roll back transaction: ", err)
return err
}
}
return nil
}
defer final()
for _, job_summary := range job_summaries {
err := func() error {
existing_summary := JobSummary{}
rows, err := transaction.QueryContext(ctx_timeout, `
SELECT job_queue,
submitted,
pending,
runnable,
starting,
running
FROM job_summary_event_log
WHERE job_queue = $1
ORDER BY timestamp DESC LIMIT 1
`, job_summary.JobQueue)
if err != nil {
log.Error("Cannot select from database: ", err)
return err
}
defer rows.Close()
ok_to_insert := true
for rows.Next() {
err := rows.Scan(&existing_summary.JobQueue, &existing_summary.Submitted, &existing_summary.Pending, &existing_summary.Runnable, &existing_summary.Starting, &existing_summary.Running)
if err != nil {
log.Error("Cannot scan from database: ", err)
return err
}
if existing_summary.JobQueue != job_summary.JobQueue {
ok_to_insert = false
}
if existing_summary.Submitted == job_summary.Submitted &&
existing_summary.Pending == job_summary.Pending &&
existing_summary.Runnable == job_summary.Runnable &&
existing_summary.Starting == job_summary.Starting &&
existing_summary.Running == job_summary.Running {
ok_to_insert = false
}
}
if ok_to_insert {
_, err = transaction.ExecContext(ctx_timeout, `
INSERT INTO job_summary_event_log
( timestamp,
job_queue,
submitted,
pending,
runnable,
starting,
running )
VALUES ( now(), $1, $2, $3, $4, $5, $6 )`,
job_summary.JobQueue,
job_summary.Submitted,
job_summary.Pending,
job_summary.Runnable,
job_summary.Starting,
job_summary.Running)
if err != nil {
log.Error("Cannot insert into job_summary_event_log: ", err)
return err
}
}
return nil
}()
if err != nil {
return err
}
}
should_commit = true
return nil
}
func (pq *postgreSQLStore) UpdateJobLogTerminationRequested(jobID string) error {
span := opentracing.StartSpan("PG.UpdateJobLogTerminationRequested")
defer span.Finish()
_, err := pq.connection.Exec(`UPDATE jobs SET termination_requested = 't' WHERE job_id = $1`, jobID)
if err != nil {
log.Warning("Cannot update job termination requested status: ", err)
}
return err
}
func getRowsAsList(rows *sql.Rows) ([]string, error) {
lst := make([]string, 0)
for rows.Next() {
var item string
if err := rows.Scan(&item); err != nil {
log.Error("Cannot scan rows: ", err)
return nil, err
}
lst = append(lst, item)
}
return lst, nil
}
func (pq *postgreSQLStore) GetStartingStateStuckEC2Instances() ([]string, error) {
span := opentracing.StartSpan("PG.GetStartingStateStuckEC2Instances")
defer span.Finish()
query := `SELECT DISTINCT ta.instance_id FROM jobs j JOIN task_arns_to_instance_info ta ON ta.task_arn = j.task_arn WHERE instance_id is not null AND (now() - last_updated) > '600 seconds' AND status = 'STARTING' AND j.task_arn is not null`
rows, err := pq.connection.Query(query)
if err != nil {
log.Warning("Cannot select jobs that are stuck in STARTING state: ", err)
return nil, err
}
defer rows.Close()
instances, err := getRowsAsList(rows)
if err != nil {
return nil, err
}
return instances, nil
}
func (pq *postgreSQLStore) GetAliveEC2Instances() ([]string, error) {
span := opentracing.StartSpan("PG.GetAliveEC2Instances")
defer span.Finish()
query := `SELECT DISTINCT instance_id FROM instances WHERE disappeared_at is null`
rows, err := pq.connection.Query(query)
if err != nil {
log.Warning("Cannot select alive EC2 instances from database: ", err)
return nil, err
}
defer rows.Close()
instances, err := getRowsAsList(rows)
if err != nil {
return nil, err
}
return instances, nil
}
func (pq *postgreSQLStore) UpdateECSInstances(ec2info map[string]Ec2Info, tasks_per_ec2instance map[string][]string) error {
span := opentracing.StartSpan("PG.UpdateECSInstances")
defer span.Finish()
alive_instances, err := pq.GetAliveEC2Instances()
if err != nil {
return err
}
alive_instances_set := make(map[string]bool)
for _, instance_id := range alive_instances {
alive_instances_set[instance_id] = true
}
transaction, err := pq.connection.Begin()
if err != nil {
log.Warning(err)
return err
}
should_commit := false
final := func() error {
if should_commit {
err := transaction.Commit()
if err != nil {
log.Warning("Cannot commit transaction: ", err)
return err
}
} else {
err := transaction.Rollback()
if err != nil {
log.Warning("Cannot roll back transaction: ", err)
return err
}
}
return nil
}
defer final()
query := `insert into instances
( appeared_at
, disappeared_at
, launched_at
, ami
, instance_id
, instance_type
, compute_environment_arn
, ecs_cluster_arn
, availability_zone
, spot_instance_request_id
, private_ip_address
, public_ip_address )
values ( now(), null, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10 )
on conflict (instance_id)
do update set
disappeared_at = null,
launched_at = $1,
appeared_at = least( now(), instances.appeared_at ),
ami = $2,
instance_type = $4,
compute_environment_arn = $5,
ecs_cluster_arn = $6,
availability_zone = $7,
spot_instance_request_id = $8,
private_ip_address = $9,
public_ip_address = $10
`
for instance_id, instance_info := range ec2info {
delete(alive_instances_set, instance_id)
_, err := transaction.Exec(query,
instance_info.LaunchedAt,
instance_info.AMI,
instance_id,
instance_info.InstanceType,
instance_info.ComputeEnvironmentARN,
instance_info.ECSClusterARN,
instance_info.AvailabilityZone,
instance_info.SpotInstanceRequestID,
instance_info.PrivateIP,
instance_info.PublicIP)
if err != nil {
log.Warning("Cannot insert: ", err)
return err
}
}
for instance_id, tasks := range tasks_per_ec2instance {
task_json, err := json.Marshal(tasks)
if err != nil {
log.Warning("Cannot marshal some JSON: ", tasks)
return err
}
query := `insert into instance_event_log
( timestamp
, instance_id
, active_jobs )
values
( now(), $1, $2 )
on conflict do nothing`
_, err = transaction.Exec(query, instance_id, task_json)
if err != nil {
log.Warning("Cannot insert into instance_event_log: ", err)
return err
}
}
for alive_instance_id, _ := range alive_instances_set {
query := `update instances set disappeared_at = now() WHERE instance_id = $1`
_, err := transaction.Exec(query, alive_instance_id)
if err != nil {
log.Warning("Cannot update: ", err)
return err
}
}
should_commit = true
return nil
}
func (pq *postgreSQLStore) UpdateTaskArnsInstanceIDs(ec2info map[string]Ec2Info, task_ec2_mapping map[string]string) error {
span := opentracing.StartSpan("PG.UpdateTaskArnsInstanceIDs")
defer span.Finish()
transaction, err := pq.connection.Begin()
if err != nil {
log.Warning(err)
return err
}
should_commit := false
final := func() error {
if should_commit {
err := transaction.Commit()
if err != nil {
log.Warning("Cannot commit transaction: ", err)
return err
}
} else {
err := transaction.Rollback()
if err != nil {
log.Warning("Cannot roll back transaction: ", err)
return err
}
}
return nil
}
defer final()
for task_arn, ec2instance := range task_ec2_mapping {
ec2_info, ok := ec2info[ec2instance]
if !ok {
continue
}
query := `
INSERT INTO task_arns_to_instance_info
( task_arn, instance_id, public_ip, private_ip )
VALUES ( $1, $2, $3, $4 )
ON CONFLICT DO NOTHING
`
_, err = transaction.Exec(query, task_arn, ec2instance, ec2_info.PublicIP, ec2_info.PrivateIP)
if err != nil {
log.Error("Cannot insert into task_arns_to_instance_info: ", err)
return err
}
}
should_commit = true
return nil
}
func (pq *postgreSQLStore) GetStatus(jobid string) (*JobStatus, error) {
span := opentracing.StartSpan("PG.GetStatus")
defer span.Finish()
rows, err := pq.connection.Query("SELECT status,job_id FROM jobs WHERE job_id = $1", jobid)
if err != nil {
return nil, err
}
defer rows.Close()
found_row := false
job_status := JobStatus{}
for rows.Next() {
err := rows.Scan(&job_status.Status, &job_status.Id)
if err != nil {
return nil, err
}
found_row = true
}
if found_row {
return &job_status, nil
} else {
return nil, nil
}
}
func (pq *postgreSQLStore) UpdateComputeEnvironmentsLog(ce_lst []ComputeEnvironment) error {
span := opentracing.StartSpan("PG.UpdateComputeEnvironmentsLog")
defer span.Finish()
transaction, err := pq.connection.Begin()
if err != nil {
log.Warning(err)
return err
}
should_commit := false
final := func() error {
if should_commit {
err := transaction.Commit()
if err != nil {
log.Warning("Cannot commit transaction: ", err)
return err
}
} else {
err := transaction.Rollback()
if err != nil {
log.Warning("Cannot roll back transaction: ", err)
return err
}
}
return nil
}
defer final()
_, err = transaction.Exec(`set session characteristics as transaction isolation level serializable`)
if err != nil {
log.Error("UpdateComputeEnvironmentsLog: cannot set transaction to serializable.", err)
return err
}
for _, ce := range ce_lst {
err := func() error {
rows, err := transaction.Query(`
SELECT
compute_environment,
desired_vcpus,
max_vcpus,
min_vcpus,
state,
service_role
FROM compute_environment_event_log WHERE compute_environment = $1 ORDER BY timestamp DESC LIMIT 1`,
ce.Name)
if err != nil {
log.Warning(err)
return err
}
defer rows.Close()
ok_to_insert := true
for rows.Next() {
ce_existing := ComputeEnvironment{}
err := rows.Scan(&ce_existing.Name, &ce_existing.WantedvCpus, &ce_existing.MaxvCpus, &ce_existing.MinvCpus, &ce_existing.State, &ce_existing.ServiceRole)
if err != nil {
log.Warning(err)
return err
}
if ce_existing.WantedvCpus == ce.WantedvCpus &&
ce_existing.MaxvCpus == ce.MaxvCpus &&
ce_existing.MinvCpus == ce.MinvCpus &&
ce_existing.State == ce.State &&
ce_existing.ServiceRole == ce.ServiceRole {
ok_to_insert = false
}
}
if ok_to_insert {
log.Info("Updating compute environment ", ce.Name)
_, err = transaction.Exec(`
INSERT INTO compute_environment_event_log
( timestamp,
compute_environment,
desired_vcpus,
max_vcpus,
min_vcpus,
state,
service_role )
VALUES ( now(), $1, $2, $3, $4, $5, $6 )`,
ce.Name, ce.WantedvCpus, ce.MaxvCpus, ce.MinvCpus, ce.State, ce.ServiceRole)
if err != nil {
log.Warning(err)
rows.Close()
return err
}
}
return nil
}()
if err != nil {
return err
}