/
apecs_runner.go
1069 lines (998 loc) · 26.8 KB
/
apecs_runner.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package apecs
import (
"context"
"errors"
"fmt"
"runtime/debug"
"strconv"
"time"
"github.com/rs/zerolog/log"
"go.opentelemetry.io/otel/attribute"
otel_codes "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
"gopkg.in/confluentinc/confluent-kafka-go.v1/kafka"
"github.com/lachlanorr/rocketcycle/pkg/jsonutils"
"github.com/lachlanorr/rocketcycle/pkg/mgmt"
"github.com/lachlanorr/rocketcycle/pkg/platform"
"github.com/lachlanorr/rocketcycle/pkg/rkcy"
"github.com/lachlanorr/rocketcycle/pkg/rkcypb"
"github.com/lachlanorr/rocketcycle/pkg/telem"
"github.com/lachlanorr/rocketcycle/version"
)
func produceApecsTxnError(
ctx context.Context,
plat *platform.Platform,
span trace.Span,
rtxn *rkcy.RtApecsTxn,
step *rkcypb.ApecsTxn_Step,
code rkcypb.Code,
logToResult bool,
format string,
args ...interface{},
) rkcypb.Code {
logMsg := fmt.Sprintf(format, args...)
log.Error().
Str("TxnId", rtxn.Txn.Id).
Msg(logMsg)
span.SetStatus(otel_codes.Error, logMsg)
if logToResult {
span.RecordError(errors.New(logMsg))
}
err := ProduceError(
ctx,
plat,
rtxn,
step,
code,
logToResult,
logMsg,
)
if err != nil {
log.Error().
Err(err).
Str("TxnId", rtxn.Txn.Id).
Msg("produceApecsTxnError: Failed to produce error message")
}
return code
}
func produceNextStep(
ctx context.Context,
plat *platform.Platform,
span trace.Span,
rtxn *rkcy.RtApecsTxn,
step *rkcypb.ApecsTxn_Step,
cmpdOffset *rkcypb.CompoundOffset,
) {
if rtxn.AdvanceStepIdx() {
nextStep := rtxn.CurrentStep()
// payload from last step should be passed to next step
if nextStep.Payload == nil && rkcy.IsPlatformCommand(nextStep.Command) {
nextStep.Payload = step.Result.Payload
}
if nextStep.System == rkcypb.System_STORAGE && nextStep.CmpdOffset == nil {
// STORAGE steps always need the value PROCESS Offset
if step.CmpdOffset != nil {
// if current step has an offset, set that one
// This allows multiple STORAGE steps in a row, and the same
// PROCESS offset will get set on all of them.
nextStep.CmpdOffset = step.CmpdOffset
} else {
// step has no offset, it's likely a PROCESS step, and we
// default to the argument, which is the most recent offset
// read from kafka
nextStep.CmpdOffset = cmpdOffset
}
}
err := ProduceCurrentStep(ctx, plat.WaitGroup(), plat.ApecsProducer, rtxn.Txn, rtxn.TraceParent)
if err != nil {
produceApecsTxnError(
ctx,
plat,
span,
rtxn,
nextStep,
rkcypb.Code_INTERNAL,
true,
"produceNextStep error=\"%s\": Failed produceCurrentStep for next step",
err.Error(),
)
return
}
} else { // txn is complete
// search for instance updates and create new storage txn to update storage
if rtxn.Txn.Direction == rkcypb.Direction_FORWARD {
for _, step := range rtxn.Txn.ForwardSteps {
if step.System == rkcypb.System_STORAGE {
// generate secondary storage steps
if step.Command == rkcy.CREATE || step.Command == rkcy.UPDATE || step.Command == rkcy.DELETE {
storageStep := &rkcypb.ApecsTxn_Step{
System: rkcypb.System_STORAGE_SCND,
Concern: step.Concern,
Command: step.Command,
Key: step.Result.Key,
Payload: step.Result.Payload,
CmpdOffset: step.CmpdOffset,
}
storageSteps := []*rkcypb.ApecsTxn_Step{storageStep}
storageTxnId := rkcy.NewTraceId()
rtxn.Txn.AssocTxns = append(rtxn.Txn.AssocTxns, &rkcypb.AssocTxn{Id: storageTxnId, Type: rkcypb.AssocTxn_SECONDARY_STORAGE})
err := executeTxn(
ctx,
plat,
storageTxnId,
&rkcypb.AssocTxn{Id: rtxn.Txn.Id, Type: rkcypb.AssocTxn_PARENT},
rtxn.TraceParent,
rkcypb.UponError_BAILOUT,
storageSteps,
nil,
)
if err != nil {
produceApecsTxnError(
ctx,
plat,
span,
rtxn,
step,
rkcypb.Code_INTERNAL,
true,
"produceNextStep error=\"%s\" Key=%s: Failed to apply secondary storage steps",
err.Error(), step.Key,
)
// This should be extremely rare, maybe impossible
// assuming we can produce at all. Without proper
// storage messages going through, we are better
// off failing very loudly.
log.Fatal().
Msgf("produceNextStep error=\"%s\" Key=%s: Failed to generate secondar storage steps", err.Error(), step.Key)
}
}
}
}
// Generate update steps for any changed instances
storageStepsMap := make(map[string]*rkcypb.ApecsTxn_Step)
for _, step := range rtxn.Txn.ForwardSteps {
if step.System == rkcypb.System_PROCESS &&
(step.Result.Instance != nil || step.Command == rkcy.REQUEST_RELATED || step.Command == rkcy.REFRESH_RELATED) {
var stepInst []byte
stepKey := fmt.Sprintf("%s_%s", step.Concern, step.Key)
if step.Result.Instance != nil {
stepInst = rkcy.PackPayloads(step.Result.Instance, plat.InstanceStore.GetRelated(step.Key))
} else if step.Command == rkcy.REQUEST_RELATED {
relRsp := &rkcypb.RelatedResponse{}
err := proto.Unmarshal(step.Result.Payload, relRsp)
if err != nil {
log.Error().
Err(err).
Msgf("UPDATE_ASYNC ERROR: failed to decode RelatedResponse")
} else {
stepInst = relRsp.Payload
}
} else if step.Command == rkcy.REFRESH_RELATED {
stepInst = step.Result.Payload
}
if stepInst == nil {
log.Error().
Msgf("UPDATE_ASYNC ERROR: Empty stepInst, stepKey=%s", stepKey)
} else {
storageStepsMap[stepKey] = &rkcypb.ApecsTxn_Step{
System: rkcypb.System_STORAGE,
Concern: step.Concern,
Command: rkcy.UPDATE_ASYNC,
Key: step.Key,
Payload: stepInst,
CmpdOffset: step.CmpdOffset,
EffectiveTime: step.EffectiveTime,
}
}
}
}
// generate a distinct storage transaction with a single
// UPDATE_ASYNC storage step for every instance modified
for _, step := range storageStepsMap {
storageSteps := []*rkcypb.ApecsTxn_Step{step}
storageTxnId := rkcy.NewTraceId()
rtxn.Txn.AssocTxns = append(rtxn.Txn.AssocTxns, &rkcypb.AssocTxn{Id: storageTxnId, Type: rkcypb.AssocTxn_GENERATED_STORAGE})
err := executeTxn(
ctx,
plat,
storageTxnId,
&rkcypb.AssocTxn{Id: rtxn.Txn.Id, Type: rkcypb.AssocTxn_PARENT},
rtxn.TraceParent,
rkcypb.UponError_BAILOUT,
storageSteps,
nil,
)
if err != nil {
produceApecsTxnError(
ctx,
plat,
span,
rtxn,
step,
rkcypb.Code_INTERNAL,
true,
"produceNextStep error=\"%s\" Key=%s: Failed to update storage",
err.Error(),
step.Key,
)
// This should be extremely rare, maybe impossible
// assuming we can produce at all. Without proper
// storage messages going through, we are better
// off failing very loudly.
log.Fatal().
Msgf("produceNextStep error=\"%s\" Key=%s: Failed to update storage", err.Error(), step.Key)
} else {
// also execute secondary storage txn
storageSteps[0].System = rkcypb.System_STORAGE_SCND
storageScndTxnId := rkcy.NewTraceId()
rtxn.Txn.AssocTxns = append(rtxn.Txn.AssocTxns, &rkcypb.AssocTxn{Id: storageTxnId, Type: rkcypb.AssocTxn_GENERATED_STORAGE})
err := executeTxn(
ctx,
plat,
storageScndTxnId,
&rkcypb.AssocTxn{Id: rtxn.Txn.Id, Type: rkcypb.AssocTxn_PARENT},
rtxn.TraceParent,
rkcypb.UponError_BAILOUT,
storageSteps,
nil,
)
if err != nil {
produceApecsTxnError(
ctx,
plat,
span,
rtxn,
step,
rkcypb.Code_INTERNAL,
true,
"produceNextStep error=\"%s\" Key=%s: Failed to update secondary storage",
err.Error(),
step.Key,
)
// This should be extremely rare, maybe impossible
// assuming we can produce at all. Without proper
// storage messages going through, we are better
// off failing very loudly.
log.Fatal().
Msgf("produceNextStep error=\"%s\" Key=%s: Failed to update secondary storage", err.Error(), step.Key)
}
}
}
}
err := ProduceComplete(ctx, plat, rtxn)
if err != nil {
produceApecsTxnError(
ctx,
plat,
span,
rtxn,
step,
rkcypb.Code_INTERNAL,
true,
"produceNextStep error=\"%s\": Failed to ProduceComplete",
err.Error(),
)
return
}
}
}
func jsonNoErr(msg proto.Message) string {
j, err := protojson.Marshal(msg)
if err != nil {
j = []byte(fmt.Sprintf(`{"err":%s}`, jsonutils.EncodeString(nil, err.Error())))
}
return string(j)
}
func cancelApecsTxn(
ctx context.Context,
plat *platform.Platform,
rtxn *rkcy.RtApecsTxn,
tp *rkcy.TopicParts,
cmpdOffset *rkcypb.CompoundOffset,
) {
ctx = telem.InjectTraceParent(ctx, rtxn.TraceParent)
ctx, span, step := telem.StartStep(ctx, rtxn)
defer span.End()
produceApecsTxnError(
ctx,
plat,
span,
rtxn,
step,
rkcypb.Code_CANCELLED,
true,
"Txn Cancelled",
)
}
func isBailoutableCode(code rkcypb.Code) bool {
return code != rkcypb.Code_OK &&
code != rkcypb.Code_STEP_ALREADY_COMPLETE &&
code != rkcypb.Code_MISMATCHED_CONCERN &&
code != rkcypb.Code_MISMATCHED_SYSTEM &&
code != rkcypb.Code_KEY_NOT_PRESENT
}
func advanceApecsTxn(
ctx context.Context,
plat *platform.Platform,
storageTarget string,
rtxn *rkcy.RtApecsTxn,
tp *rkcy.TopicParts,
cmpdOffset *rkcypb.CompoundOffset,
) rkcypb.Code {
ctx = telem.InjectTraceParent(ctx, rtxn.TraceParent)
ctx, span, step := telem.StartStep(ctx, rtxn)
defer span.End()
log.Debug().
Str("TxnId", rtxn.Txn.Id).
Msgf("Advancing ApecsTxn: %s %d %s", rkcypb.Direction_name[int32(rtxn.Txn.Direction)], rtxn.Txn.CurrentStepIdx, jsonNoErr(step))
if step.Result != nil {
return produceApecsTxnError(
ctx,
plat,
span,
rtxn,
step,
rkcypb.Code_STEP_ALREADY_COMPLETE,
true,
"advanceApecsTxn Result=%+v: Current step already has Result, %s",
step.Result,
jsonNoErr(step),
)
}
if step.Concern != tp.Concern {
return produceApecsTxnError(
ctx,
plat,
span,
rtxn,
step,
rkcypb.Code_MISMATCHED_CONCERN,
true,
"advanceApecsTxn: Mismatched concern, expected=%s actual=%s, %s",
tp.Concern,
step.Concern,
jsonNoErr(step),
)
}
if step.System != tp.System {
return produceApecsTxnError(
ctx,
plat,
span,
rtxn,
step,
rkcypb.Code_MISMATCHED_SYSTEM,
true,
"advanceApecsTxn: Mismatched system, expected=%d actual=%d, %s",
tp.System,
step.System,
jsonNoErr(step),
)
}
// Special case, only storage CREATE and process VALIDATE_CREATE can have empty key
if step.Key == "" && !rkcy.IsKeylessStep(step) {
prevStep := rtxn.PreviousStep()
if prevStep != nil && prevStep.Result != nil && prevStep.Result.Key != "" {
step.Key = prevStep.Result.Key
} else {
return produceApecsTxnError(
ctx,
plat,
span,
rtxn,
step,
rkcypb.Code_KEY_NOT_PRESENT,
true,
"advanceApecsTxn: No key in step: %s %s, %s",
step.System.String(),
step.Command,
jsonNoErr(step),
)
}
}
// Grab current timestamp, which will be used in a couple places below
now := timestamppb.Now()
// Read instance from InstanceStore
var inst []byte
if step.System == rkcypb.System_PROCESS {
step.CmpdOffset = cmpdOffset
if !rkcy.IsKeylessStep(step) && !rkcy.IsInstanceStoreStep(step) {
inst = plat.InstanceStore.GetInstance(step.Key)
}
if inst == nil && !rkcy.IsKeylessStep(step) && !rkcy.IsInstanceStoreStep(step) {
// We should attempt to get the value from the DB, and we
// do this by inserting a Storage READ step before this
// one and sending things through again
log.Debug().
Str("TxnId", rtxn.Txn.Id).
Str("Key", step.Key).
Msg("Instance not found, injecting STORAGE READ")
var err error
if step.System == rkcypb.System_PROCESS && step.Command == rkcy.READ {
// If we are doing a PROCESS READ, we can just substitute a STORAGE READ
// The STORAGE READ, if successful, will inject a REFRESH_INSTANCE which
// can safely stand in for the original PROCESS READ
err = rtxn.ReplaceStep(
rtxn.Txn.CurrentStepIdx,
&rkcypb.ApecsTxn_Step{
System: rkcypb.System_STORAGE,
Concern: step.Concern,
Command: rkcy.READ,
Key: step.Key,
CmpdOffset: cmpdOffset, // provide our PROCESS offset to the STORAGE step so it is recorded in the DB
},
)
} else {
// If not a PROCESS READ, we insert the STORAGE READ but preseve the original
// command to run after the STORAGE READ runs
err = rtxn.InsertSteps(
rtxn.Txn.CurrentStepIdx,
&rkcypb.ApecsTxn_Step{
System: rkcypb.System_STORAGE,
Concern: step.Concern,
Command: rkcy.READ,
Key: step.Key,
CmpdOffset: cmpdOffset, // provide our PROCESS offset to the STORAGE step so it is recorded in the DB
},
)
}
if err != nil {
log.Error().Err(err).Msg("error in InsertSteps")
return produceApecsTxnError(
ctx,
plat,
span,
rtxn,
nil,
rkcypb.Code_INTERNAL,
true,
"advanceApecsTxn Key=%s: Unable to insert Storage READ implicit steps",
step.Key,
)
}
err = ProduceCurrentStep(ctx, plat.WaitGroup(), plat.ApecsProducer, rtxn.Txn, rtxn.TraceParent)
if err != nil {
return produceApecsTxnError(
ctx,
plat,
span,
rtxn,
nil,
rkcypb.Code_INTERNAL,
true,
"advanceApecsTxn error=\"%s\": Failed produceCurrentStep for next step",
err.Error(),
)
}
return rkcypb.Code_OK
} else if inst != nil && step.Command == rkcy.CREATE {
return produceApecsTxnError(
ctx,
plat,
span,
rtxn,
step,
rkcypb.Code_INTERNAL,
true,
"advanceApecsTxn Key=%s: Instance already exists in store in CREATE command",
step.Key,
)
}
}
if step.CmpdOffset == nil {
return produceApecsTxnError(
ctx,
plat,
span,
rtxn,
step,
rkcypb.Code_INTERNAL,
true,
"advanceApecsTxn: Nil offset",
)
}
args := &rkcy.StepArgs{
TxnId: rtxn.Txn.Id,
Key: step.Key,
Instance: inst,
Payload: step.Payload,
EffectiveTime: step.EffectiveTime.AsTime(),
CmpdOffset: step.CmpdOffset,
}
var addSteps []*rkcypb.ApecsTxn_Step
step.Result, addSteps = handleCommand(
ctx,
plat,
storageTarget,
step.Concern,
step.System,
step.Command,
rtxn.Txn.Direction,
args,
)
if (step.Result == nil || isBailoutableCode(step.Result.Code)) &&
rtxn.Txn.UponError == rkcypb.UponError_BAILOUT {
// We'll bailout up the chain, but down here we can at least
// log any info we have about the result.
var code rkcypb.Code
if step.Result != nil {
code = step.Result.Code
for _, logEvt := range step.Result.LogEvents {
log.Error().
Str("TxnId", args.TxnId).
Str("Concern", step.Concern).
Str("System", step.System.String()).
Str("Command", step.Command).
Str("Direction", rtxn.Txn.Direction.String()).
Msgf("BAILOUT LogEvent: %s %s", rkcypb.Severity_name[int32(logEvt.Sev)], logEvt.Msg)
}
} else {
code = rkcypb.Code_NIL_RESULT
}
return produceApecsTxnError(
ctx,
plat,
span,
rtxn,
step,
code,
true,
"advanceApecsTxn Key=%s: BAILOUT, %s",
step.Key,
jsonNoErr(step),
)
}
if step.Result == nil {
return produceApecsTxnError(
ctx,
plat,
span,
rtxn,
step,
rkcypb.Code_INTERNAL,
true,
"advanceApecsTxn Key=%s: nil result from step handler, %s",
step.Key,
jsonNoErr(step),
)
}
step.Result.ProcessedTime = now
if step.Result.LogEvents != nil {
for _, logEvt := range step.Result.LogEvents {
sevMsg := fmt.Sprintf("%s %s", rkcypb.Severity_name[int32(logEvt.Sev)], logEvt.Msg)
if logEvt.Sev == rkcypb.Severity_ERR {
span.RecordError(errors.New(sevMsg))
} else {
span.AddEvent(sevMsg)
}
}
}
span.SetAttributes(
attribute.String("rkcy.code", strconv.Itoa(int(step.Result.Code))),
)
if step.Result.Code != rkcypb.Code_OK {
return produceApecsTxnError(
ctx,
plat,
span,
rtxn,
step,
step.Result.Code,
false,
"advanceApecsTxn Key=%s: Step failed with non OK result, %s",
step.Key,
jsonNoErr(step),
)
}
// Unless explcitly set by the handler, always assume we should
// pass step payload in result to next step
if step.Result.Payload == nil {
step.Result.Payload = step.Payload
}
// Record orignal instance in step if result has changed the instance
if tp.System == rkcypb.System_PROCESS && step.Result.Instance != nil {
step.Instance = inst
}
// if we have additional steps from handleCommand we should place
// them in the transaction
if addSteps != nil && len(addSteps) > 0 {
err := rtxn.InsertSteps(rtxn.Txn.CurrentStepIdx+1, addSteps...)
if err != nil {
return produceApecsTxnError(
ctx,
plat,
span,
rtxn,
step,
rkcypb.Code_INTERNAL,
true,
"InsertSteps failure: %s",
err.Error(),
)
}
}
produceNextStep(ctx, plat, span, rtxn, step, cmpdOffset)
return step.Result.Code
}
func consumeApecsTopic(
ctx context.Context,
plat *platform.Platform,
storageTarget string,
consumerBrokers string,
tp *rkcy.TopicParts,
partition int32,
bailoutCh chan<- bool,
) {
defer plat.WaitGroup().Done()
platCh := make(chan *mgmt.PlatformMessage)
mgmt.ConsumePlatformTopic(
ctx,
plat.WaitGroup(),
plat.StreamProvider(),
plat.Args.Platform,
plat.Args.Environment,
plat.Args.AdminBrokers,
platCh,
nil,
)
platMsg := <-platCh
if rkcy.IsStorageSystem(tp.System) {
plat.UpdateStorageTargets(platMsg)
}
cncAdminReadyCh := make(chan bool)
cncAdminCh := make(chan *mgmt.ConcernAdminMessage)
mgmt.ConsumeConcernAdminTopic(
ctx,
plat.WaitGroup(),
plat.StreamProvider(),
plat.Args.Platform,
plat.Args.Environment,
plat.Args.AdminBrokers,
cncAdminCh,
tp.Concern,
cncAdminReadyCh,
)
var groupName string
if tp.System == rkcypb.System_STORAGE {
groupName = fmt.Sprintf("rkcy_apecs_%s_%s", tp.FullTopic, storageTarget)
} else {
groupName = fmt.Sprintf("rkcy_apecs_%s", tp.FullTopic)
}
kafkaLogCh := make(chan kafka.LogEvent)
go rkcy.PrintKafkaLogs(ctx, kafkaLogCh)
cons, err := plat.StreamProvider().NewConsumer(consumerBrokers, groupName, kafkaLogCh)
if err != nil {
log.Fatal().
Err(err).
Msg("failed to plat.NewConsumer")
}
shouldCommit := false
defer func() {
log.Trace().
Str("Topic", tp.FullTopic).
Msgf("CONSUMER Closing...")
// make sure we don't have pending values on cncAdminReadyCh
select {
case <-cncAdminReadyCh:
log.Warn().
Str("Topic", tp.FullTopic).
Msgf("Pending cncAdminReadyCh during close")
default:
}
if shouldCommit {
_, err = cons.Commit()
shouldCommit = false
if err != nil {
log.Error().
Err(err).
Msgf("Unable to commit")
}
}
err := cons.Close()
if err != nil {
log.Error().
Err(err).
Str("Topic", tp.FullTopic).
Msgf("Error during consumer.Close()")
}
log.Trace().
Str("Topic", tp.FullTopic).
Msgf("CONSUMER CLOSED")
}()
err = cons.Assign([]kafka.TopicPartition{
{
Topic: &tp.FullTopic,
Partition: partition,
Offset: kafka.OffsetStored,
},
})
if err != nil {
log.Fatal().
Err(err).
Msg("Failed to Assign")
}
txnsToCancel := make(map[string]time.Time)
// cncAdminReady := false
firstMessage := true
commitTicker := time.NewTicker(5 * time.Second)
for {
select {
case <-ctx.Done():
log.Trace().
Msg("consumeStorage exiting, ctx.Done()")
return
case <-commitTicker.C:
if shouldCommit {
_, err = cons.Commit()
shouldCommit = false
if err != nil {
log.Fatal().
Err(err).
Msgf("Unable to commit")
}
}
case platMsg := <-platCh:
if rkcy.IsStorageSystem(tp.System) {
plat.UpdateStorageTargets(platMsg)
}
case <-cncAdminReadyCh:
// cncAdminReady = true
case cncAdminMsg := <-cncAdminCh:
if cncAdminMsg.Directive == rkcypb.Directive_CONCERN_ADMIN_CANCEL_TXN {
log.Info().Msgf("CANCEL TXN %s", cncAdminMsg.ConcernAdminDirective.TxnId)
txnsToCancel[cncAdminMsg.ConcernAdminDirective.TxnId] = time.Now()
}
default:
msg, err := cons.ReadMessage(100 * time.Millisecond)
timedOut := err != nil && err.(kafka.Error).Code() == kafka.ErrTimedOut
if err != nil && !timedOut {
log.Fatal().
Err(err).
Msg("Error during ReadMessage")
} else if !timedOut && msg != nil {
// If this is the first message read, commit the
// offset to current to ensure we have an offset in
// kafka, and if we blow up and start again we will
// not default to latest.
if firstMessage {
firstMessage = false
log.Debug().
Str("Topic", tp.FullTopic).
Int32("Partition", partition).
Int64("Offset", int64(msg.TopicPartition.Offset)).
Msg("Initial commit to current offset")
comOffs, err := cons.CommitOffsets([]kafka.TopicPartition{
{
Topic: &tp.FullTopic,
Partition: partition,
Offset: msg.TopicPartition.Offset,
},
})
if err != nil {
log.Fatal().
Err(err).
Str("Topic", tp.FullTopic).
Int32("Partition", partition).
Int64("Offset", int64(msg.TopicPartition.Offset)).
Msgf("Unable to commit initial offset")
}
log.Debug().
Str("Topic", tp.FullTopic).
Int32("Partition", partition).
Int64("Offset", int64(msg.TopicPartition.Offset)).
Msgf("Initial offset committed: %+v", comOffs)
}
directive := rkcy.GetDirective(msg)
if directive == rkcypb.Directive_APECS_TXN {
txn := rkcypb.ApecsTxn{}
err := proto.Unmarshal(msg.Value, &txn)
if err != nil {
log.Error().
Err(err).
Msg("Failed to Unmarshal ApecsTxn")
} else {
offset := &rkcypb.CompoundOffset{
Generation: tp.Generation,
Partition: partition,
Offset: int64(msg.TopicPartition.Offset),
}
rtxn, err := rkcy.NewRtApecsTxn(&txn, rkcy.GetTraceParent(msg))
if err != nil {
log.Error().
Err(err).
Msg("Failed to create RtApecsTxnf")
} else {
_, shouldCancel := txnsToCancel[rtxn.Txn.Id]
if shouldCancel {
delete(txnsToCancel, rtxn.Txn.Id)
cancelApecsTxn(ctx, plat, rtxn, tp, offset)
} else {
code := advanceApecsTxn(ctx, plat, storageTarget, rtxn, tp, offset)
// Bailout is necessary when a storage step fails.
// Those must be retried indefinitely until success.
// So... we force commit the offset to current and
// kill ourselves, and we'll pick up where we left
// off when we are restarted.
if rtxn.Txn.UponError == rkcypb.UponError_BAILOUT && isBailoutableCode(code) {
log.Error().
Int("Code", int(code)).
Str("TxnId", rtxn.Txn.Id).
Str("Txn", jsonNoErr(proto.Message(rtxn.Txn))).
Str("Topic", tp.FullTopic).
Int32("Partition", partition).
Int64("Offset", int64(msg.TopicPartition.Offset)).
Msgf("BAILOUT")
_, err := cons.CommitOffsets([]kafka.TopicPartition{
{
Topic: &tp.FullTopic,
Partition: partition,
Offset: msg.TopicPartition.Offset,
},
})
if err != nil {
log.Error().
Err(err).
Str("Topic", tp.FullTopic).
Int32("Partition", partition).
Int64("Offset", int64(msg.TopicPartition.Offset)).
Msgf("BAILOUT commit error")
}
bailoutCh <- true
return
}
}
}
}
} else {
log.Warn().
Int("Directive", int(directive)).
Msg("Invalid directive on ApecsTxn topic")
}
_, err = cons.StoreOffsets([]kafka.TopicPartition{
{
Topic: &tp.FullTopic,
Partition: partition,
Offset: msg.TopicPartition.Offset + 1,
},
})
if err != nil {
log.Fatal().
Err(err).
Msgf("Unable to store offsets %s/%d/%d", tp.FullTopic, partition, msg.TopicPartition.Offset+1)
}
shouldCommit = true
}
}
}
}
func handleCommand(
ctx context.Context,
plat *platform.Platform,
storageTarget string,
concern string,
system rkcypb.System,
command string,
direction rkcypb.Direction,
args *rkcy.StepArgs,
) (*rkcypb.ApecsTxn_Step_Result, []*rkcypb.ApecsTxn_Step) {
defer func() {
if r := recover(); r != nil {
log.Error().
Str("TxnId", args.TxnId).
Str("Concern", concern).
Str("System", system.String()).
Str("Command", command).
Str("Direction", direction.String()).
Msgf("panic during handleCommand, %s, args: %+v", r, args)
debug.PrintStack()
}
}()
cncHdlr, ok := plat.ClientCode.ConcernHandlers[concern]
if !ok {
rslt := &rkcypb.ApecsTxn_Step_Result{}
SetStepResult(rslt, fmt.Errorf("No handler for concern: '%s'", concern))
return rslt, nil
}
switch system {
case rkcypb.System_PROCESS:
return cncHdlr.HandleLogicCommand(
ctx,
system,
command,
direction,
args,
plat.InstanceStore,
plat.ConfigRdr(),
)
case rkcypb.System_STORAGE:
fallthrough
case rkcypb.System_STORAGE_SCND:
return cncHdlr.HandleCrudCommand(
ctx,
plat.WaitGroup(),
system,
command,
direction,
args,
storageTarget,
)
default:
rslt := &rkcypb.ApecsTxn_Step_Result{}
SetStepResult(rslt, fmt.Errorf("Invalid system: %s", system.String()))
return rslt, nil
}
}
func StartApecsRunner(
ctx context.Context,
plat *platform.Platform,
storageTarget string,
consumerBrokers string,
tp *rkcy.TopicParts,