-
Notifications
You must be signed in to change notification settings - Fork 145
/
dispatcher.go
604 lines (460 loc) · 14.9 KB
/
dispatcher.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
package dispatcher
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/go-co-op/gocron/v2"
"github.com/google/uuid"
"github.com/hashicorp/go-multierror"
"github.com/rs/zerolog"
"github.com/hatchet-dev/hatchet/internal/datautils"
"github.com/hatchet-dev/hatchet/internal/msgqueue"
"github.com/hatchet-dev/hatchet/internal/services/dispatcher/contracts"
"github.com/hatchet-dev/hatchet/internal/services/shared/recoveryutils"
"github.com/hatchet-dev/hatchet/internal/services/shared/tasktypes"
"github.com/hatchet-dev/hatchet/internal/telemetry"
"github.com/hatchet-dev/hatchet/internal/telemetry/servertel"
"github.com/hatchet-dev/hatchet/pkg/logger"
"github.com/hatchet-dev/hatchet/pkg/repository"
"github.com/hatchet-dev/hatchet/pkg/repository/cache"
"github.com/hatchet-dev/hatchet/pkg/repository/prisma/dbsqlc"
"github.com/hatchet-dev/hatchet/pkg/repository/prisma/sqlchelpers"
"github.com/hatchet-dev/hatchet/pkg/validator"
hatcheterrors "github.com/hatchet-dev/hatchet/pkg/errors"
)
type Dispatcher interface {
contracts.DispatcherServer
Start() (func() error, error)
}
type DispatcherImpl struct {
contracts.UnimplementedDispatcherServer
s gocron.Scheduler
mq msgqueue.MessageQueue
l *zerolog.Logger
dv datautils.DataDecoderValidator
v validator.Validator
repo repository.EngineRepository
cache cache.Cacheable
entitlements repository.EntitlementsRepository
dispatcherId string
workers *workers
a *hatcheterrors.Wrapped
}
var ErrWorkerNotFound = fmt.Errorf("worker not found")
type workers struct {
innerMap sync.Map
}
func (w *workers) Range(f func(key, value interface{}) bool) {
w.innerMap.Range(f)
}
func (w *workers) Add(workerId, sessionId string, worker *subscribedWorker) {
actual, _ := w.innerMap.LoadOrStore(workerId, &sync.Map{})
actual.(*sync.Map).Store(sessionId, worker)
}
func (w *workers) GetForSession(workerId, sessionId string) (*subscribedWorker, error) {
actual, ok := w.innerMap.Load(workerId)
if !ok {
return nil, ErrWorkerNotFound
}
worker, ok := actual.(*sync.Map).Load(sessionId)
if !ok {
return nil, ErrWorkerNotFound
}
return worker.(*subscribedWorker), nil
}
func (w *workers) Get(workerId string) ([]*subscribedWorker, error) {
actual, ok := w.innerMap.Load(workerId)
if !ok {
return nil, ErrWorkerNotFound
}
workers := []*subscribedWorker{}
actual.(*sync.Map).Range(func(key, value interface{}) bool {
workers = append(workers, value.(*subscribedWorker))
return true
})
return workers, nil
}
func (w *workers) DeleteForSession(workerId, sessionId string) {
actual, ok := w.innerMap.Load(workerId)
if !ok {
return
}
actual.(*sync.Map).Delete(sessionId)
}
func (w *workers) Delete(workerId string) {
w.innerMap.Delete(workerId)
}
type DispatcherOpt func(*DispatcherOpts)
type DispatcherOpts struct {
mq msgqueue.MessageQueue
l *zerolog.Logger
dv datautils.DataDecoderValidator
repo repository.EngineRepository
entitlements repository.EntitlementsRepository
dispatcherId string
alerter hatcheterrors.Alerter
cache cache.Cacheable
}
func defaultDispatcherOpts() *DispatcherOpts {
logger := logger.NewDefaultLogger("dispatcher")
alerter := hatcheterrors.NoOpAlerter{}
return &DispatcherOpts{
l: &logger,
dv: datautils.NewDataDecoderValidator(),
dispatcherId: uuid.New().String(),
alerter: alerter,
}
}
func WithMessageQueue(mq msgqueue.MessageQueue) DispatcherOpt {
return func(opts *DispatcherOpts) {
opts.mq = mq
}
}
func WithAlerter(a hatcheterrors.Alerter) DispatcherOpt {
return func(opts *DispatcherOpts) {
opts.alerter = a
}
}
func WithRepository(r repository.EngineRepository) DispatcherOpt {
return func(opts *DispatcherOpts) {
opts.repo = r
}
}
func WithEntitlementsRepository(r repository.EntitlementsRepository) DispatcherOpt {
return func(opts *DispatcherOpts) {
opts.entitlements = r
}
}
func WithLogger(l *zerolog.Logger) DispatcherOpt {
return func(opts *DispatcherOpts) {
opts.l = l
}
}
func WithDataDecoderValidator(dv datautils.DataDecoderValidator) DispatcherOpt {
return func(opts *DispatcherOpts) {
opts.dv = dv
}
}
func WithDispatcherId(dispatcherId string) DispatcherOpt {
return func(opts *DispatcherOpts) {
opts.dispatcherId = dispatcherId
}
}
func WithCache(cache cache.Cacheable) DispatcherOpt {
return func(opts *DispatcherOpts) {
opts.cache = cache
}
}
func New(fs ...DispatcherOpt) (*DispatcherImpl, error) {
opts := defaultDispatcherOpts()
for _, f := range fs {
f(opts)
}
if opts.mq == nil {
return nil, fmt.Errorf("task queue is required. use WithMessageQueue")
}
if opts.repo == nil {
return nil, fmt.Errorf("repository is required. use WithRepository")
}
if opts.entitlements == nil {
return nil, fmt.Errorf("entitlements repository is required. use WithEntitlementsRepository")
}
if opts.cache == nil {
return nil, fmt.Errorf("cache is required. use WithCache")
}
newLogger := opts.l.With().Str("service", "dispatcher").Logger()
opts.l = &newLogger
// create a new scheduler
s, err := gocron.NewScheduler(gocron.WithLocation(time.UTC))
if err != nil {
return nil, fmt.Errorf("could not create scheduler for dispatcher: %w", err)
}
a := hatcheterrors.NewWrapped(opts.alerter)
a.WithData(map[string]interface{}{"service": "dispatcher"})
return &DispatcherImpl{
mq: opts.mq,
l: opts.l,
dv: opts.dv,
v: validator.NewDefaultValidator(),
repo: opts.repo,
entitlements: opts.entitlements,
dispatcherId: opts.dispatcherId,
workers: &workers{},
s: s,
a: a,
cache: opts.cache,
}, nil
}
func (d *DispatcherImpl) Start() (func() error, error) {
ctx, cancel := context.WithCancel(context.Background())
// register the dispatcher by creating a new dispatcher in the database
dispatcher, err := d.repo.Dispatcher().CreateNewDispatcher(ctx, &repository.CreateDispatcherOpts{
ID: d.dispatcherId,
})
if err != nil {
cancel()
return nil, err
}
_, err = d.s.NewJob(
gocron.DurationJob(time.Second*5),
gocron.NewTask(
d.runUpdateHeartbeat(ctx),
),
)
if err != nil {
cancel()
return nil, fmt.Errorf("could not schedule heartbeat update: %w", err)
}
d.s.Start()
wg := sync.WaitGroup{}
f := func(task *msgqueue.Message) error {
wg.Add(1)
defer wg.Done()
err := d.handleTask(ctx, task)
if err != nil {
d.l.Error().Err(err).Msgf("could not handle dispatcher task %s", task.ID)
return err
}
return nil
}
// subscribe to a task queue with the dispatcher id
dispatcherId := sqlchelpers.UUIDToStr(dispatcher.ID)
cleanupQueue, err := d.mq.Subscribe(msgqueue.QueueTypeFromDispatcherID(dispatcherId), f, msgqueue.NoOpHook)
if err != nil {
cancel()
return nil, err
}
cleanup := func() error {
d.l.Debug().Msgf("dispatcher is shutting down...")
cancel()
if err := cleanupQueue(); err != nil {
return fmt.Errorf("could not cleanup queue: %w", err)
}
wg.Wait()
// drain the existing connections
d.l.Debug().Msg("draining existing connections")
d.workers.Range(func(key, value interface{}) bool {
value.(*sync.Map).Range(func(key, value interface{}) bool {
w := value.(*subscribedWorker)
w.finished <- true
return true
})
return true
})
if err := d.s.Shutdown(); err != nil {
return fmt.Errorf("could not shutdown scheduler: %w", err)
}
deleteCtx, deleteCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer deleteCancel()
err = d.repo.Dispatcher().Delete(deleteCtx, dispatcherId)
if err != nil {
return fmt.Errorf("could not delete dispatcher: %w", err)
}
d.l.Debug().Msgf("deleted dispatcher %s", dispatcherId)
d.l.Debug().Msgf("dispatcher has shutdown")
return nil
}
return cleanup, nil
}
func (d *DispatcherImpl) handleTask(ctx context.Context, task *msgqueue.Message) (err error) {
defer func() {
if r := recover(); r != nil {
recoverErr := recoveryutils.RecoverWithAlert(d.l, d.a, r)
if recoverErr != nil {
err = recoverErr
}
}
}()
switch task.ID {
case "group-key-action-assigned":
err = d.a.WrapErr(d.handleGroupKeyActionAssignedTask(ctx, task), map[string]interface{}{})
case "step-run-assigned":
err = d.a.WrapErr(d.handleStepRunAssignedTask(ctx, task), map[string]interface{}{})
case "step-run-cancelled":
err = d.a.WrapErr(d.handleStepRunCancelled(ctx, task), map[string]interface{}{})
default:
err = fmt.Errorf("unknown task: %s", task.ID)
}
return err
}
func (d *DispatcherImpl) handleGroupKeyActionAssignedTask(ctx context.Context, task *msgqueue.Message) error {
ctx, span := telemetry.NewSpan(ctx, "group-key-action-assigned")
defer span.End()
payload := tasktypes.GroupKeyActionAssignedTaskPayload{}
metadata := tasktypes.GroupKeyActionAssignedTaskMetadata{}
err := d.dv.DecodeAndValidate(task.Payload, &payload)
if err != nil {
return fmt.Errorf("could not decode dispatcher task payload: %w", err)
}
err = d.dv.DecodeAndValidate(task.Metadata, &metadata)
if err != nil {
return fmt.Errorf("could not decode dispatcher task metadata: %w", err)
}
// get the worker for this task
workers, err := d.workers.Get(payload.WorkerId)
if err != nil {
return fmt.Errorf("could not get worker: %w", err)
}
// load the workflow run from the database
workflowRun, err := d.repo.WorkflowRun().GetWorkflowRunById(ctx, metadata.TenantId, payload.WorkflowRunId)
if err != nil {
return fmt.Errorf("could not get workflow run: %w", err)
}
servertel.WithWorkflowRunModel(span, workflowRun)
groupKeyRunId := sqlchelpers.UUIDToStr(workflowRun.GetGroupKeyRunId)
if groupKeyRunId == "" {
return fmt.Errorf("could not get group key run")
}
sqlcGroupKeyRun, err := d.repo.GetGroupKeyRun().GetGroupKeyRunForEngine(ctx, metadata.TenantId, groupKeyRunId)
if err != nil {
return fmt.Errorf("could not get group key run for engine: %w", err)
}
var multiErr error
var success bool
for _, w := range workers {
err = w.StartGroupKeyAction(ctx, metadata.TenantId, sqlcGroupKeyRun)
if err != nil {
multiErr = multierror.Append(multiErr, fmt.Errorf("could not send group key action to worker: %w", err))
} else {
success = true
}
}
if success {
return nil
}
return multiErr
}
func (d *DispatcherImpl) handleStepRunAssignedTask(ctx context.Context, task *msgqueue.Message) error {
ctx, span := telemetry.NewSpan(ctx, "step-run-assigned")
defer span.End()
payload := tasktypes.StepRunAssignedTaskPayload{}
metadata := tasktypes.StepRunAssignedTaskMetadata{}
err := d.dv.DecodeAndValidate(task.Payload, &payload)
if err != nil {
return fmt.Errorf("could not decode dispatcher task payload: %w", err)
}
err = d.dv.DecodeAndValidate(task.Metadata, &metadata)
if err != nil {
return fmt.Errorf("could not decode dispatcher task metadata: %w", err)
}
// get the worker for this task
workers, err := d.workers.Get(payload.WorkerId)
if err != nil {
return fmt.Errorf("could not get worker: %w", err)
}
if len(workers) == 0 {
d.l.Warn().Msgf("worker %s not found, ignoring task for step run %s", payload.WorkerId, payload.StepRunId)
return nil
}
// load the step run from the database
stepRun, err := d.repo.StepRun().GetStepRunForEngine(ctx, metadata.TenantId, payload.StepRunId)
if err != nil {
return fmt.Errorf("could not get step run: %w", err)
}
// if the step run has a job run in a non-running state, we should not send it to the worker
if stepRun.JobRunStatus != dbsqlc.JobRunStatusRUNNING {
d.l.Warn().Msgf("step run %s is not in a running state, ignoring", payload.StepRunId)
return nil
}
// if the step run is not in an assigned state, we should not send it to the worker
if stepRun.SRStatus != dbsqlc.StepRunStatusASSIGNED {
d.l.Warn().Msgf("step run %s is not in an assigned state, ignoring", payload.StepRunId)
return nil
}
data, err := d.repo.StepRun().GetStepRunDataForEngine(ctx, metadata.TenantId, payload.StepRunId)
if err != nil {
return fmt.Errorf("could not get step run data: %w", err)
}
servertel.WithStepRunModel(span, stepRun)
var multiErr error
var success bool
for i, w := range workers {
err = w.StartStepRun(ctx, metadata.TenantId, stepRun, data)
if err != nil {
multiErr = multierror.Append(multiErr, fmt.Errorf("could not send step action to worker (%d): %w", i, err))
} else {
success = true
}
}
if success {
defer d.repo.StepRun().DeferredStepRunEvent(
stepRun.SRID,
dbsqlc.StepRunEventReasonSENTTOWORKER,
dbsqlc.StepRunEventSeverityINFO,
"Sent step run to the assigned worker",
nil,
)
return nil
}
defer d.repo.StepRun().DeferredStepRunEvent(
stepRun.SRID,
dbsqlc.StepRunEventReasonREASSIGNED,
dbsqlc.StepRunEventSeverityWARNING,
"Could not send step run to assigned worker",
nil,
)
// we were unable to send the step run to any worker, revert the step run to pending assignment
err = d.repo.StepRun().UnassignStepRunFromWorker(ctx, metadata.TenantId, sqlchelpers.UUIDToStr(stepRun.SRID))
if err != nil {
multiErr = multierror.Append(multiErr, fmt.Errorf("💥 could not revert step run: %w", err))
}
return multiErr
}
func (d *DispatcherImpl) handleStepRunCancelled(ctx context.Context, task *msgqueue.Message) error {
ctx, span := telemetry.NewSpan(ctx, "step-run-cancelled")
defer span.End()
payload := tasktypes.StepRunCancelledTaskPayload{}
metadata := tasktypes.StepRunCancelledTaskMetadata{}
err := d.dv.DecodeAndValidate(task.Payload, &payload)
if err != nil {
return fmt.Errorf("could not decode dispatcher task payload: %w", err)
}
err = d.dv.DecodeAndValidate(task.Metadata, &metadata)
if err != nil {
return fmt.Errorf("could not decode dispatcher task metadata: %w", err)
}
// get the worker for this task
workers, err := d.workers.Get(payload.WorkerId)
if err != nil && !errors.Is(err, ErrWorkerNotFound) {
return fmt.Errorf("could not get worker: %w", err)
} else if errors.Is(err, ErrWorkerNotFound) {
// if the worker is not found, we can ignore this task
d.l.Debug().Msgf("worker %s not found, ignoring task", payload.WorkerId)
return nil
}
// load the step run from the database
stepRun, err := d.repo.StepRun().GetStepRunForEngine(ctx, metadata.TenantId, payload.StepRunId)
if err != nil {
return fmt.Errorf("could not get step run: %w", err)
}
servertel.WithStepRunModel(span, stepRun)
var multiErr error
var success bool
for _, w := range workers {
err = w.CancelStepRun(ctx, metadata.TenantId, stepRun)
if err != nil {
multiErr = multierror.Append(multiErr, fmt.Errorf("could not send job to worker: %w", err))
} else {
success = true
}
}
if success {
return nil
}
return multiErr
}
func (d *DispatcherImpl) runUpdateHeartbeat(ctx context.Context) func() {
return func() {
d.l.Debug().Msgf("dispatcher: updating heartbeat")
now := time.Now().UTC()
// update the heartbeat
_, err := d.repo.Dispatcher().UpdateDispatcher(ctx, d.dispatcherId, &repository.UpdateDispatcherOpts{
LastHeartbeatAt: &now,
})
if err != nil {
d.l.Err(err).Msg("dispatcher: could not update heartbeat")
}
}
}