-
Notifications
You must be signed in to change notification settings - Fork 157
/
controller.go
1147 lines (866 loc) · 30 KB
/
controller.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 jobscontroller
import (
"context"
"encoding/json"
"fmt"
"os"
"strconv"
"time"
"github.com/hashicorp/go-multierror"
"github.com/hatchet-dev/hatchet/internal/datautils"
"github.com/hatchet-dev/hatchet/internal/repository"
"github.com/hatchet-dev/hatchet/internal/repository/prisma/db"
"github.com/hatchet-dev/hatchet/internal/services/shared/tasktypes"
"github.com/hatchet-dev/hatchet/internal/taskqueue"
"github.com/rs/zerolog"
"github.com/steebchen/prisma-client-go/runtime/types"
)
type JobsController interface {
Start(ctx context.Context) error
}
type JobsControllerImpl struct {
tq taskqueue.TaskQueue
l *zerolog.Logger
repo repository.Repository
dv datautils.DataDecoderValidator
}
type JobsControllerOpt func(*JobsControllerOpts)
type JobsControllerOpts struct {
tq taskqueue.TaskQueue
l *zerolog.Logger
repo repository.Repository
dv datautils.DataDecoderValidator
}
func defaultJobsControllerOpts() *JobsControllerOpts {
logger := zerolog.New(os.Stderr)
return &JobsControllerOpts{
l: &logger,
dv: datautils.NewDataDecoderValidator(),
}
}
func WithTaskQueue(tq taskqueue.TaskQueue) JobsControllerOpt {
return func(opts *JobsControllerOpts) {
opts.tq = tq
}
}
func WithLogger(l *zerolog.Logger) JobsControllerOpt {
return func(opts *JobsControllerOpts) {
opts.l = l
}
}
func WithRepository(r repository.Repository) JobsControllerOpt {
return func(opts *JobsControllerOpts) {
opts.repo = r
}
}
func WithDataDecoderValidator(dv datautils.DataDecoderValidator) JobsControllerOpt {
return func(opts *JobsControllerOpts) {
opts.dv = dv
}
}
func New(fs ...JobsControllerOpt) (*JobsControllerImpl, error) {
opts := defaultJobsControllerOpts()
for _, f := range fs {
f(opts)
}
if opts.tq == nil {
return nil, fmt.Errorf("task queue is required. use WithTaskQueue")
}
if opts.repo == nil {
return nil, fmt.Errorf("repository is required. use WithRepository")
}
return &JobsControllerImpl{
tq: opts.tq,
l: opts.l,
repo: opts.repo,
dv: opts.dv,
}, nil
}
func (jc *JobsControllerImpl) Start(ctx context.Context) error {
taskChan, err := jc.tq.Subscribe(ctx, taskqueue.JOB_PROCESSING_QUEUE)
if err != nil {
return err
}
for {
select {
case task := <-taskChan:
err = jc.handleTask(ctx, task)
if err != nil {
jc.l.Error().Err(err).Msg("could not handle job task")
}
}
}
}
func (ec *JobsControllerImpl) handleTask(ctx context.Context, task *taskqueue.Task) error {
switch task.ID {
case "job-run-queued":
return ec.handleJobRunQueued(ctx, task)
case "job-run-timed-out":
return ec.handleJobRunTimedOut(ctx, task)
case "step-run-queued":
return ec.handleStepRunQueued(ctx, task)
case "step-run-requeue-ticker":
return ec.handleStepRunRequeue(ctx, task)
case "step-run-started":
return ec.handleStepRunStarted(ctx, task)
case "step-run-finished":
return ec.handleStepRunFinished(ctx, task)
case "step-run-failed":
return ec.handleStepRunFailed(ctx, task)
case "step-run-timed-out":
return ec.handleStepRunTimedOut(ctx, task)
case "ticker-removed":
return ec.handleTickerRemoved(ctx, task)
}
return fmt.Errorf("unknown task: %s in queue %s", task.ID, string(task.Queue))
}
func (ec *JobsControllerImpl) handleJobRunQueued(ctx context.Context, task *taskqueue.Task) error {
payload := tasktypes.JobRunQueuedTaskPayload{}
metadata := tasktypes.JobRunQueuedTaskMetadata{}
err := ec.dv.DecodeAndValidate(task.Payload, &payload)
if err != nil {
return fmt.Errorf("could not decode job task payload: %w", err)
}
err = ec.dv.DecodeAndValidate(task.Metadata, &metadata)
if err != nil {
return fmt.Errorf("could not decode job task metadata: %w", err)
}
// get the job run in the database
jobRun, err := ec.repo.JobRun().GetJobRunById(metadata.TenantId, payload.JobRunId)
if err != nil {
return fmt.Errorf("could not get job run: %w", err)
}
// schedule the first step in the job run
stepRuns := jobRun.StepRuns()
if len(stepRuns) == 0 {
return fmt.Errorf("job run has no step runs")
}
stepRun := jobRun.StepRuns()[0]
// find the step run without a previous
for _, sr := range stepRuns {
if prev, ok := sr.Step().Prev(); !ok || prev == nil {
stepRun = sr
break
}
}
// send a task to the taskqueue
err = ec.tq.AddTask(
ctx,
taskqueue.JOB_PROCESSING_QUEUE,
tasktypes.StepRunQueuedToTask(
jobRun.Job(),
&stepRun,
),
)
if err != nil {
return fmt.Errorf("could not add job queued task to task queue: %w", err)
}
// send a task to schedule the job run's timeout
tickers, err := ec.getValidTickers()
if err != nil {
return err
}
ticker := &tickers[0]
ticker, err = ec.repo.Ticker().AddJobRun(ticker.ID, jobRun)
if err != nil {
return fmt.Errorf("could not add job run to ticker: %w", err)
}
scheduleTimeoutTask, err := scheduleJobRunTimeoutTask(ticker, jobRun)
if err != nil {
return fmt.Errorf("could not schedule job run timeout task: %w", err)
}
err = ec.tq.AddTask(
ctx,
taskqueue.QueueTypeFromTicker(ticker),
scheduleTimeoutTask,
)
if err != nil {
return fmt.Errorf("could not add schedule job run timeout task to task queue: %w", err)
}
// // update the job run
// _, err = ec.repo.JobRun().UpdateJobRun(metadata.TenantId, jobRun.ID, &repository.UpdateJobRunOpts{
// Status: repository.JobRunStatusPtr(db.JobRunStatusRUNNING),
// })
return nil
}
func (ec *JobsControllerImpl) handleJobRunTimedOut(ctx context.Context, task *taskqueue.Task) error {
payload := tasktypes.JobRunTimedOutTaskPayload{}
metadata := tasktypes.JobRunTimedOutTaskMetadata{}
err := ec.dv.DecodeAndValidate(task.Payload, &payload)
if err != nil {
return fmt.Errorf("could not decode job task payload: %w", err)
}
err = ec.dv.DecodeAndValidate(task.Metadata, &metadata)
if err != nil {
return fmt.Errorf("could not decode job task metadata: %w", err)
}
// get the job run in the database
jobRun, err := ec.repo.JobRun().GetJobRunById(metadata.TenantId, payload.JobRunId)
if err != nil {
return fmt.Errorf("could not get job run: %w", err)
}
stepRuns, err := ec.repo.StepRun().ListStepRuns(metadata.TenantId, &repository.ListStepRunsOpts{
JobRunId: &jobRun.ID,
Status: repository.StepRunStatusPtr(db.StepRunStatusRunning),
})
if err != nil {
return fmt.Errorf("could not list step runs: %w", err)
}
if len(stepRuns) > 1 {
return fmt.Errorf("job run has multiple running step runs")
}
if len(stepRuns) == 1 {
currStepRun := stepRuns[0]
// cancel current step run
now := time.Now().UTC()
// cancel current step run
stepRun, err := ec.repo.StepRun().UpdateStepRun(metadata.TenantId, currStepRun.ID, &repository.UpdateStepRunOpts{
CancelledAt: &now,
CancelledReason: repository.StringPtr("JOB_RUN_TIMED_OUT"),
Status: repository.StepRunStatusPtr(db.StepRunStatusCancelled),
})
if err != nil {
return fmt.Errorf("could not update step run: %w", err)
}
workerId, ok := stepRun.WorkerID()
if !ok {
return fmt.Errorf("step run has no worker id")
}
worker, err := ec.repo.Worker().GetWorkerById(workerId)
if err != nil {
return fmt.Errorf("could not get worker: %w", err)
}
// send a task to the taskqueue
err = ec.tq.AddTask(
ctx,
taskqueue.QueueTypeFromDispatcher(worker.Dispatcher()),
stepRunCancelledTask(metadata.TenantId, currStepRun.ID, "JOB_RUN_TIMED_OUT", worker),
)
if err != nil {
return fmt.Errorf("could not add job assigned task to task queue: %w", err)
}
// cancel the ticker for the step run
stepRunTicker, ok := stepRun.Ticker()
if ok {
err = ec.tq.AddTask(
ctx,
taskqueue.QueueTypeFromTicker(stepRunTicker),
cancelStepRunTimeoutTask(stepRunTicker, stepRun),
)
if err != nil {
return fmt.Errorf("could not add cancel step run timeout task to task queue: %w", err)
}
}
}
// // cancel all step runs
// err = ec.repo.StepRun().CancelPendingStepRuns(metadata.TenantId, jobRun.ID, "JOB_RUN_TIMED_OUT")
// if err != nil {
// return fmt.Errorf("could not cancel pending step runs: %w", err)
// }
// // update the job run in the database
// _, err = ec.repo.JobRun().UpdateJobRun(metadata.TenantId, jobRun.ID, &repository.UpdateJobRunOpts{
// Status: repository.JobRunStatusPtr(db.JobRunStatusCANCELLED),
// })
// if err != nil {
// return fmt.Errorf("could not update job run: %w", err)
// }
return nil
}
func (ec *JobsControllerImpl) handleStepRunQueued(ctx context.Context, task *taskqueue.Task) error {
payload := tasktypes.StepRunTaskPayload{}
metadata := tasktypes.StepRunTaskMetadata{}
err := ec.dv.DecodeAndValidate(task.Payload, &payload)
if err != nil {
return fmt.Errorf("could not decode job task payload: %w", err)
}
err = ec.dv.DecodeAndValidate(task.Metadata, &metadata)
if err != nil {
return fmt.Errorf("could not decode job task metadata: %w", err)
}
return ec.queueStepRun(ctx, metadata.TenantId, metadata.StepId, payload.StepRunId)
}
// handleStepRunRequeue looks for any step runs that haven't been assigned that are past their requeue time
func (ec *JobsControllerImpl) handleStepRunRequeue(ctx context.Context, task *taskqueue.Task) error {
payload := tasktypes.StepRunRequeueTaskPayload{}
metadata := tasktypes.StepRunRequeueTaskMetadata{}
err := ec.dv.DecodeAndValidate(task.Payload, &payload)
if err != nil {
return fmt.Errorf("could not decode step run requeue task payload: %w", err)
}
err = ec.dv.DecodeAndValidate(task.Metadata, &metadata)
if err != nil {
return fmt.Errorf("could not decode step run requeue task metadata: %w", err)
}
stepRuns, err := ec.repo.StepRun().ListStepRuns(payload.TenantId, &repository.ListStepRunsOpts{
Requeuable: repository.BoolPtr(true),
})
if err != nil {
return fmt.Errorf("could not list step runs: %w", err)
}
var allErrs error
for _, stepRun := range stepRuns {
ec.l.Debug().Msgf("requeueing step run %s", stepRun.ID)
stepRunCp := stepRun
now := time.Now().UTC().UTC()
// if the current time is after the scheduleTimeoutAt, then mark this as timed out
if scheduleTimeoutAt, ok := stepRun.ScheduleTimeoutAt(); ok && scheduleTimeoutAt.Before(now) {
_, err = ec.repo.StepRun().UpdateStepRun(payload.TenantId, stepRunCp.ID, &repository.UpdateStepRunOpts{
CancelledAt: &now,
CancelledReason: repository.StringPtr("SCHEDULING_TIMED_OUT"),
Status: repository.StepRunStatusPtr(db.StepRunStatusCancelled),
})
if err != nil {
allErrs = multierror.Append(allErrs, fmt.Errorf("could not update step run %s: %w", stepRun.ID, err))
}
break
}
requeueAfter := time.Now().UTC().Add(time.Second * 5)
_, err = ec.repo.StepRun().UpdateStepRun(payload.TenantId, stepRunCp.ID, &repository.UpdateStepRunOpts{
RequeueAfter: &requeueAfter,
})
if err != nil {
allErrs = multierror.Append(allErrs, fmt.Errorf("could not update step run %s: %w", stepRun.ID, err))
}
err = ec.tq.AddTask(
ctx,
taskqueue.JOB_PROCESSING_QUEUE,
tasktypes.StepRunQueuedToTask(
stepRunCp.JobRun().Job(),
&stepRunCp,
),
)
if err != nil {
allErrs = multierror.Append(allErrs, fmt.Errorf("could not add job queued task to task queue: %w", err))
}
}
return allErrs
}
func (ec *JobsControllerImpl) queueStepRun(ctx context.Context, tenantId, stepId, stepRunId string) error {
// add the rendered data to the step run
stepRun, err := ec.repo.StepRun().GetStepRunById(tenantId, stepRunId)
if err != nil {
return fmt.Errorf("could not get step run: %w", err)
}
updateStepOpts := &repository.UpdateStepRunOpts{}
// default scheduling timeout
if scheduleTimeoutAt, ok := stepRun.ScheduleTimeoutAt(); !ok || scheduleTimeoutAt.IsZero() {
scheduleTimeoutAt := time.Now().UTC().Add(time.Second * 30)
updateStepOpts.ScheduleTimeoutAt = &scheduleTimeoutAt
}
lookupDataModel, ok := stepRun.JobRun().LookupData()
if ok && lookupDataModel != nil {
data, ok := lookupDataModel.Data()
lookupDataMap := map[string]interface{}{}
inputDataMap := map[string]interface{}{}
err := datautils.FromJSONType(&data, &lookupDataMap)
if err != nil {
return fmt.Errorf("could not get job run lookup data: %w", err)
}
// input data is the step data
inputData, ok := stepRun.Step().Inputs()
if ok {
ec.l.Debug().Msgf("rendering template fields for step run %s", stepRun.ID)
err := datautils.FromJSONType(&inputData, &inputDataMap)
if err != nil {
return fmt.Errorf("could not get step inputs: %w", err)
}
inputDataMap, err = datautils.RenderTemplateFields(lookupDataMap, inputDataMap)
if err != nil {
return fmt.Errorf("could not render template fields: %w", err)
}
newInput, err := datautils.ToJSONType(inputDataMap)
if err != nil {
return fmt.Errorf("could not convert input data to json: %w", err)
}
updateStepOpts.Input = newInput
}
}
// update the step's input data
_, err = ec.repo.StepRun().UpdateStepRun(tenantId, stepRunId, updateStepOpts)
if err != nil {
return fmt.Errorf("could not update step run: %w", err)
}
return ec.scheduleStepRun(ctx, tenantId, stepId, stepRunId)
}
func (ec *JobsControllerImpl) scheduleStepRun(ctx context.Context, tenantId, stepId, stepRunId string) error {
// indicate that the step run is pending assignment
stepRun, err := ec.repo.StepRun().UpdateStepRun(tenantId, stepRunId, &repository.UpdateStepRunOpts{
Status: repository.StepRunStatusPtr(db.StepRunStatusPendingAssignment),
})
if err != nil {
return fmt.Errorf("could not update step run: %w", err)
}
// Assign the step run to a worker.
//
// 1. Get a list of workers that can run this step. If there are no workers available, then simply return with
// no additional transactions and this step run will be requeued.
// 2. Pick a worker to run the step and get the dispatcher currently connected to this worker.
// 3. Update the step run's designated worker.
//
// After creating the worker, send a task to the taskqueue, which will be picked up by the dispatcher.
workers, err := ec.repo.Worker().ListWorkers(tenantId, &repository.ListWorkersOpts{
Action: &stepRun.Step().ActionID,
})
if err != nil {
return fmt.Errorf("could not list workers for step: %w", err)
}
if len(workers) == 0 {
ec.l.Info().Msgf("no workers available for step %s; requeuing", stepId)
return nil
}
// pick the worker with the least jobs currently assigned (this heuristic can and should change)
selectedWorker := workers[0]
for _, worker := range workers {
if worker.StepRunCount < selectedWorker.StepRunCount {
selectedWorker = worker
}
}
// update the job run's designated worker
err = ec.repo.Worker().AddStepRun(tenantId, selectedWorker.Worker.ID, stepRunId)
if err != nil {
return fmt.Errorf("could not add step run to worker: %w", err)
}
// pick a ticker to use for timeout
tickers, err := ec.getValidTickers()
if err != nil {
return err
}
ticker := &tickers[0]
ticker, err = ec.repo.Ticker().AddStepRun(ticker.ID, stepRunId)
if err != nil {
return fmt.Errorf("could not add step run to ticker: %w", err)
}
scheduleTimeoutTask, err := scheduleStepRunTimeoutTask(ticker, stepRun)
if err != nil {
return fmt.Errorf("could not schedule step run timeout task: %w", err)
}
// send a task to the dispatcher
err = ec.tq.AddTask(
ctx,
taskqueue.QueueTypeFromDispatcher(selectedWorker.Worker.Dispatcher()),
stepRunAssignedTask(tenantId, stepRunId, selectedWorker.Worker),
)
if err != nil {
return fmt.Errorf("could not add job assigned task to task queue: %w", err)
}
// send a task to the ticker
err = ec.tq.AddTask(
ctx,
taskqueue.QueueTypeFromTicker(ticker),
scheduleTimeoutTask,
)
if err != nil {
return fmt.Errorf("could not add schedule step run timeout task to task queue: %w", err)
}
return nil
}
func (ec *JobsControllerImpl) handleStepRunStarted(ctx context.Context, task *taskqueue.Task) error {
payload := tasktypes.StepRunStartedTaskPayload{}
metadata := tasktypes.StepRunStartedTaskMetadata{}
err := ec.dv.DecodeAndValidate(task.Payload, &payload)
if err != nil {
return fmt.Errorf("could not decode step run started task payload: %w", err)
}
err = ec.dv.DecodeAndValidate(task.Metadata, &metadata)
if err != nil {
return fmt.Errorf("could not decode step run started task metadata: %w", err)
}
// update the step run in the database
startedAt, err := time.Parse(time.RFC3339, payload.StartedAt)
if err != nil {
return fmt.Errorf("could not parse started at: %w", err)
}
_, err = ec.repo.StepRun().UpdateStepRun(metadata.TenantId, payload.StepRunId, &repository.UpdateStepRunOpts{
StartedAt: &startedAt,
Status: repository.StepRunStatusPtr(db.StepRunStatusRunning),
})
return err
}
func (ec *JobsControllerImpl) handleStepRunFinished(ctx context.Context, task *taskqueue.Task) error {
payload := tasktypes.StepRunFinishedTaskPayload{}
metadata := tasktypes.StepRunFinishedTaskMetadata{}
err := ec.dv.DecodeAndValidate(task.Payload, &payload)
if err != nil {
return fmt.Errorf("could not decode step run started task payload: %w", err)
}
err = ec.dv.DecodeAndValidate(task.Metadata, &metadata)
if err != nil {
return fmt.Errorf("could not decode step run started task metadata: %w", err)
}
// update the step run in the database
finishedAt, err := time.Parse(time.RFC3339, payload.FinishedAt)
if err != nil {
return fmt.Errorf("could not parse started at: %w", err)
}
var stepOutput string
stepOutput, err = strconv.Unquote(payload.StepOutputData)
if err != nil {
stepOutput = payload.StepOutputData
}
outputJSON := types.JSON(json.RawMessage(stepOutput))
stepRun, err := ec.repo.StepRun().UpdateStepRun(metadata.TenantId, payload.StepRunId, &repository.UpdateStepRunOpts{
FinishedAt: &finishedAt,
Status: repository.StepRunStatusPtr(db.StepRunStatusSucceeded),
Output: &outputJSON,
})
if err != nil {
return fmt.Errorf("could not update step run: %w", err)
}
jobRun, err := ec.repo.JobRun().GetJobRunById(metadata.TenantId, stepRun.JobRunID)
if err != nil {
return fmt.Errorf("could not get job run: %w", err)
}
lookupData, ok := jobRun.LookupData()
if !ok {
return fmt.Errorf("job run has no lookup data")
}
stepReadableId, ok := stepRun.Step().ReadableID()
// only update the job lookup data if the step has a readable id to key
if ok && stepReadableId != "" {
data, _ := lookupData.Data()
newData, err := datautils.AddStepOutput(&data, stepReadableId, []byte(payload.StepOutputData))
if err != nil {
return fmt.Errorf("could not add step output to lookup data: %w", err)
}
// update the job run lookup data
_, err = ec.repo.JobRun().UpdateJobRunLookupData(metadata.TenantId, stepRun.JobRunID, &repository.UpdateJobRunLookupDataOpts{
LookupData: newData,
})
if err != nil {
return fmt.Errorf("could not update job run lookup data: %w", err)
}
}
// queue the next step run if there is one
if next, ok := stepRun.Next(); ok && next != nil {
err := ec.queueStepRun(ctx, metadata.TenantId, next.StepID, next.ID)
if err != nil {
return fmt.Errorf("could not queue next step run: %w", err)
}
}
// else {
// ec.l.Debug().Msgf("no next step for step run %s", stepRun.ID)
// // if there is no next step, then the job run is complete
// _, err := ec.repo.JobRun().UpdateJobRun(metadata.TenantId, stepRun.JobRunID, &repository.UpdateJobRunOpts{
// Status: repository.RunStatusPtr(db.RunStatusFINISHED),
// })
// if err != nil {
// return fmt.Errorf("could not update job run: %w", err)
// }
// }
// cancel the timeout task
stepRunTicker, ok := stepRun.Ticker()
if ok {
err = ec.tq.AddTask(
ctx,
taskqueue.QueueTypeFromTicker(stepRunTicker),
cancelStepRunTimeoutTask(stepRunTicker, stepRun),
)
if err != nil {
return fmt.Errorf("could not add cancel step run timeout task to task queue: %w", err)
}
}
return nil
}
func (ec *JobsControllerImpl) handleStepRunFailed(ctx context.Context, task *taskqueue.Task) error {
payload := tasktypes.StepRunFailedTaskPayload{}
metadata := tasktypes.StepRunFailedTaskMetadata{}
err := ec.dv.DecodeAndValidate(task.Payload, &payload)
if err != nil {
return fmt.Errorf("could not decode step run started task payload: %w", err)
}
err = ec.dv.DecodeAndValidate(task.Metadata, &metadata)
if err != nil {
return fmt.Errorf("could not decode step run started task metadata: %w", err)
}
// update the step run in the database
failedAt, err := time.Parse(time.RFC3339, payload.FailedAt)
stepRun, err := ec.repo.StepRun().UpdateStepRun(metadata.TenantId, payload.StepRunId, &repository.UpdateStepRunOpts{
FinishedAt: &failedAt,
Error: &payload.Error,
Status: repository.StepRunStatusPtr(db.StepRunStatusFailed),
})
if err != nil {
return fmt.Errorf("could not update step run: %w", err)
}
// cancel the ticker for the step run
stepRunTicker, ok := stepRun.Ticker()
if ok {
err = ec.tq.AddTask(
ctx,
taskqueue.QueueTypeFromTicker(stepRunTicker),
cancelStepRunTimeoutTask(stepRunTicker, stepRun),
)
if err != nil {
return fmt.Errorf("could not add cancel step run timeout task to task queue: %w", err)
}
}
// // cancel any pending steps for this job run in the database
// err = ec.repo.StepRun().CancelPendingStepRuns(metadata.TenantId, stepRun.JobRunID, "PREVIOUS_STEP_FAILED")
// if err != nil {
// return fmt.Errorf("could not cancel pending step runs: %w", err)
// }
// // update the job run in the database
// _, err = ec.repo.JobRun().UpdateJobRun(metadata.TenantId, stepRun.JobRunID, &repository.UpdateJobRunOpts{
// Status: repository.JobRunStatusPtr(db.JobRunStatusFAILED),
// })
// if err != nil {
// return fmt.Errorf("could not update job run: %w", err)
// }
return nil
}
func (ec *JobsControllerImpl) handleStepRunTimedOut(ctx context.Context, task *taskqueue.Task) error {
payload := tasktypes.StepRunTimedOutTaskPayload{}
metadata := tasktypes.StepRunTimedOutTaskMetadata{}
err := ec.dv.DecodeAndValidate(task.Payload, &payload)
if err != nil {
return fmt.Errorf("could not decode step run started task payload: %w", err)
}
err = ec.dv.DecodeAndValidate(task.Metadata, &metadata)
if err != nil {
return fmt.Errorf("could not decode step run started task metadata: %w", err)
}
now := time.Now().UTC()
// cancel current step run
stepRun, err := ec.repo.StepRun().UpdateStepRun(metadata.TenantId, payload.StepRunId, &repository.UpdateStepRunOpts{
CancelledAt: &now,
CancelledReason: repository.StringPtr("TIMED_OUT"),
Status: repository.StepRunStatusPtr(db.StepRunStatusCancelled),
})
if err != nil {
return fmt.Errorf("could not update step run: %w", err)
}
workerId, ok := stepRun.WorkerID()
if !ok {
return fmt.Errorf("step run has no worker id")
}
worker, err := ec.repo.Worker().GetWorkerById(workerId)
if err != nil {
return fmt.Errorf("could not get worker: %w", err)
}
// send a task to the taskqueue
err = ec.tq.AddTask(
ctx,
taskqueue.QueueTypeFromDispatcher(worker.Dispatcher()),
stepRunCancelledTask(metadata.TenantId, payload.StepRunId, "TIMED_OUT", worker),
)
if err != nil {
return fmt.Errorf("could not add job assigned task to task queue: %w", err)
}
// // cancel any pending steps for this job run in the database
// err = ec.repo.StepRun().CancelPendingStepRuns(metadata.TenantId, payload.JobRunId, "PREVIOUS_STEP_TIMED_OUT")
// if err != nil {
// return fmt.Errorf("could not cancel pending step runs: %w", err)
// }
return nil
}
func (ec *JobsControllerImpl) handleTickerRemoved(ctx context.Context, task *taskqueue.Task) error {
payload := tasktypes.RemoveTickerTaskPayload{}
metadata := tasktypes.RemoveTickerTaskMetadata{}
err := ec.dv.DecodeAndValidate(task.Payload, &payload)
if err != nil {
return fmt.Errorf("could not decode ticker removed task payload: %w", err)
}
err = ec.dv.DecodeAndValidate(task.Metadata, &metadata)
if err != nil {
return fmt.Errorf("could not decode ticker removed task metadata: %w", err)
}
// reassign all step runs to a different ticker
tickers, err := ec.getValidTickers()
if err != nil {
return err
}
// reassign all step runs randomly to tickers
numTickers := len(tickers)
// get all step runs assigned to the ticker
stepRuns, err := ec.repo.StepRun().ListAllStepRuns(&repository.ListAllStepRunsOpts{
NoTickerId: repository.BoolPtr(true),
Status: repository.StepRunStatusPtr(db.StepRunStatusRunning),
})
if err != nil {
return fmt.Errorf("could not list step runs: %w", err)
}
for i, stepRun := range stepRuns {
stepRunCp := stepRun
ticker := tickers[i%numTickers]
_, err = ec.repo.Ticker().AddStepRun(ticker.ID, stepRun.ID)
if err != nil {
return fmt.Errorf("could not update step run: %w", err)
}
scheduleTimeoutTask, err := scheduleStepRunTimeoutTask(&ticker, &stepRunCp)
if err != nil {
return fmt.Errorf("could not schedule step run timeout task: %w", err)
}
// send a task to the ticker
err = ec.tq.AddTask(
ctx,
taskqueue.QueueTypeFromTicker(&ticker),
scheduleTimeoutTask,
)
if err != nil {
return fmt.Errorf("could not add schedule step run timeout task to task queue: %w", err)
}
}
// get all step runs assigned to the ticker
jobRuns, err := ec.repo.JobRun().ListAllJobRuns(&repository.ListAllJobRunsOpts{
NoTickerId: repository.BoolPtr(true),
Status: repository.JobRunStatusPtr(db.JobRunStatusRunning),
})
if err != nil {
return fmt.Errorf("could not list step runs: %w", err)
}
for i, jobRun := range jobRuns {
jobRunCp := jobRun
ticker := tickers[i%numTickers]
_, err = ec.repo.Ticker().AddJobRun(ticker.ID, &jobRunCp)
if err != nil {
return fmt.Errorf("could not update step run: %w", err)
}
scheduleTimeoutTask, err := scheduleJobRunTimeoutTask(&ticker, &jobRunCp)
if err != nil {
return fmt.Errorf("could not schedule step run timeout task: %w", err)
}
// send a task to the ticker
err = ec.tq.AddTask(
ctx,
taskqueue.QueueTypeFromTicker(&ticker),
scheduleTimeoutTask,
)
if err != nil {
return fmt.Errorf("could not add schedule step run timeout task to task queue: %w", err)
}
}
return nil
}
func (ec *JobsControllerImpl) getValidTickers() ([]db.TickerModel, error) {
within := time.Now().UTC().Add(-6 * time.Second)
tickers, err := ec.repo.Ticker().ListTickers(&repository.ListTickerOpts{
LatestHeartbeatAt: &within,
})
if err != nil {
return nil, fmt.Errorf("could not list tickers: %w", err)
}
if len(tickers) == 0 {
return nil, fmt.Errorf("no tickers available")
}
return tickers, nil
}
func stepRunAssignedTask(tenantId, stepRunId string, worker *db.WorkerModel) *taskqueue.Task {
dispatcher := worker.Dispatcher()
payload, _ := datautils.ToJSONMap(tasktypes.StepRunAssignedTaskPayload{