This repository has been archived by the owner on Feb 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 102
/
metadataReconciler.go
1203 lines (1052 loc) · 45 KB
/
metadataReconciler.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
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package replicator
import (
"errors"
"strings"
"sync/atomic"
"time"
"github.com/uber-common/bark"
"github.com/uber/tchannel-go/thrift"
"github.com/uber/cherami-server/common"
"github.com/uber/cherami-server/common/metrics"
"github.com/uber/cherami-thrift/.generated/go/metadata"
"github.com/uber/cherami-thrift/.generated/go/shared"
"github.com/uber/cherami-thrift/.generated/go/store"
)
type (
// MetadataReconciler periodically queries metadata and
// compare with the metadata from remote replicator and try
// to reconcile the states
MetadataReconciler interface {
common.Daemon
}
// metadataReconciler is an implementation of MetadataReconciler.
metadataReconciler struct {
replicator *Replicator
localZone string
suspectMissingExtents map[string]missingExtentInfo
mClient metadata.TChanMetadataService
logger bark.Logger
m3Client metrics.Client
closeChannel chan struct{}
ticker *time.Ticker
running int64
}
missingExtentInfo struct {
missingSince time.Time
destUUID string
}
)
const (
// runInterval determines how often the reconciler will run
runInterval = time.Duration(10 * time.Minute)
metadataListRequestPageSize = 50
storeCallTimeout = 10 * time.Second
extentMissingDurationThreshold = time.Duration(1 * time.Hour)
)
// NewMetadataReconciler returns an instance of MetadataReconciler
func NewMetadataReconciler(mClient metadata.TChanMetadataService, replicator *Replicator, localZone string, logger bark.Logger, m3client metrics.Client) MetadataReconciler {
return &metadataReconciler{
replicator: replicator,
localZone: localZone,
suspectMissingExtents: make(map[string]missingExtentInfo),
mClient: mClient,
logger: logger,
m3Client: m3client,
ticker: time.NewTicker(runInterval),
running: 0,
}
}
func (r *metadataReconciler) Start() {
r.logger.Info("MetadataReconciler: started")
r.closeChannel = make(chan struct{})
go r.run()
go r.houseKeep()
}
func (r *metadataReconciler) Stop() {
close(r.closeChannel)
r.logger.Info("MetadataReconciler: stopped")
}
func (r *metadataReconciler) run() {
primaryHost, err := r.replicator.GetRingpopMonitor().FindHostForKey(common.ReplicatorServiceName, common.ReplicatorServiceName)
if err != nil {
r.logger.WithField(common.TagErr, err).Error(`Error getting primary replicator from ringpop`)
return
}
// reconciler only needs to run on primary replicator
if primaryHost.UUID != r.replicator.GetHostUUID() {
return
}
if !atomic.CompareAndSwapInt64(&r.running, 0, 1) {
r.logger.Warn("Prev run is still ongoing...")
return
}
// destination/cg metadata reconciliation is only needed if this is a non-authoritative zone
var localCgs []*shared.ConsumerGroupDescription
if r.localZone != r.replicator.getAuthoritativeZone() {
r.m3Client.UpdateGauge(metrics.ReplicatorReconcileScope, metrics.ReplicatorReconcileDestRun, 1)
localDests, remoteDests, err2 := r.reconcileDestMetadata()
if err2 != nil {
r.m3Client.UpdateGauge(metrics.ReplicatorReconcileScope, metrics.ReplicatorReconcileDestFail, 1)
return
}
r.m3Client.UpdateGauge(metrics.ReplicatorReconcileScope, metrics.ReplicatorReconcileCgRun, 1)
localCgs, err = r.reconcileCgMetadata(localDests, remoteDests)
if err != nil {
r.m3Client.UpdateGauge(metrics.ReplicatorReconcileScope, metrics.ReplicatorReconcileCgFail, 1)
return
}
}
// reconcile destination extents
r.m3Client.UpdateGauge(metrics.ReplicatorReconcileScope, metrics.ReplicatorReconcileDestExtentRun, 1)
err = r.reconcileDestExtentMetadata()
if err != nil {
r.m3Client.UpdateGauge(metrics.ReplicatorReconcileScope, metrics.ReplicatorReconcileDestExtentFail, 1)
}
// reconcile cg extents
r.m3Client.UpdateGauge(metrics.ReplicatorReconcileScope, metrics.ReplicatorReconcileCgExtentRun, 1)
err = r.reconcileCgExtentMetadata(localCgs)
if err != nil {
r.m3Client.UpdateGauge(metrics.ReplicatorReconcileScope, metrics.ReplicatorReconcileCgExtentFail, 1)
}
atomic.StoreInt64(&r.running, 0)
}
func (r *metadataReconciler) reconcileDestMetadata() ([]*shared.DestinationDescription, []*shared.DestinationDescription, error) {
localDests, err := r.getAllMultiZoneDestInLocalZone()
if err != nil {
return nil, nil, err
}
remoteDests, err := r.getAllMultiZoneDestInAuthoritativeZone()
if err != nil {
return nil, nil, err
}
r.reconcileDest(localDests, remoteDests)
return localDests, remoteDests, nil
}
func (r *metadataReconciler) reconcileCgMetadata(localDests []*shared.DestinationDescription, remoteDests []*shared.DestinationDescription) ([]*shared.ConsumerGroupDescription, error) {
localCgs, err := r.getAllMultiZoneCgInLocalZone(localDests)
if err != nil {
return nil, err
}
remoteCgs, err := r.getAllMultiZoneCgInAuthoritativeZone(remoteDests)
if err != nil {
return nil, err
}
r.reconcileCg(localCgs, remoteCgs)
return localCgs, nil
}
func (r *metadataReconciler) reconcileDest(localDests []*shared.DestinationDescription, remoteDests []*shared.DestinationDescription) {
var replicatorReconcileDestFoundMissingCount int64
localDestsSet := make(map[string]*shared.DestinationDescription, len(localDests))
for _, dest := range localDests {
localDestsSet[dest.GetDestinationUUID()] = dest
}
for _, remoteDest := range remoteDests {
localDest, ok := localDestsSet[remoteDest.GetDestinationUUID()]
if ok {
if remoteDest.GetStatus() == shared.DestinationStatus_DELETING || remoteDest.GetStatus() == shared.DestinationStatus_DELETED {
// case #1: destination gets deleted in remote, but not deleted in local. Delete the destination locally
if !(localDest.GetStatus() == shared.DestinationStatus_DELETING || localDest.GetStatus() == shared.DestinationStatus_DELETED) {
r.logger.WithField(common.TagDst, common.FmtDst(remoteDest.GetDestinationUUID())).Info(`Found deleted/deleting destination from remote but not deleted/deleting locally`)
deleteRequest := &shared.DeleteDestinationRequest{
Path: common.StringPtr(remoteDest.GetPath()),
}
ctx, cancel := thrift.NewContext(localReplicatorCallTimeOut)
defer cancel()
err := r.replicator.DeleteDestination(ctx, deleteRequest)
if err != nil {
r.logger.WithFields(bark.Fields{
common.TagErr: err,
common.TagDst: common.FmtDst(remoteDest.GetDestinationUUID()),
}).Error(`Failed to delete destination in local zone for reconciliation`)
continue
}
} else {
r.logger.WithField(common.TagDst, common.FmtDst(remoteDest.GetDestinationUUID())).Info(`Found destination is deleted/deleting in both remote and local`)
continue
}
continue
}
// case #2: destination exists in both remote and local, try to compare the property to see if anything gets updated
updateRequest := &shared.UpdateDestinationRequest{
DestinationUUID: common.StringPtr(remoteDest.GetDestinationUUID()),
}
destUpdated := false
// TODO: Do we need to support updating retention?
//if localDest.GetConsumedMessagesRetention() != remoteDest.GetConsumedMessagesRetention() {
// updateRequest.ConsumedMessagesRetention = common.Int32Ptr(remoteDest.GetConsumedMessagesRetention())
// destUpdated = true
//}
//if localDest.GetUnconsumedMessagesRetention() != remoteDest.GetUnconsumedMessagesRetention() {
// updateRequest.UnconsumedMessagesRetention = common.Int32Ptr(remoteDest.GetUnconsumedMessagesRetention())
// destUpdated = true
//}
if localDest.GetOwnerEmail() != remoteDest.GetOwnerEmail() {
updateRequest.OwnerEmail = common.StringPtr(remoteDest.GetOwnerEmail())
destUpdated = true
}
if localDest.GetChecksumOption() != remoteDest.GetChecksumOption() {
updateRequest.ChecksumOption = common.InternalChecksumOptionPtr(remoteDest.GetChecksumOption())
destUpdated = true
}
if destUpdated {
r.logger.WithField(common.TagDst, common.FmtDst(remoteDest.GetDestinationUUID())).Info(`Found destination gets updated in remote but not in local`)
ctx, cancel := thrift.NewContext(localReplicatorCallTimeOut)
defer cancel()
_, err := r.replicator.UpdateDestination(ctx, updateRequest)
if err != nil {
r.logger.WithFields(bark.Fields{
common.TagErr: err,
common.TagDst: common.FmtDst(remoteDest.GetDestinationUUID()),
}).Error(`Failed to update destination in local zone for reconciliation`)
continue
}
}
} else {
// case #3: destination exists in remote, but not in local. Create the destination locally
r.logger.WithField(common.TagDst, common.FmtDst(remoteDest.GetDestinationUUID())).Warn(`Found missing destination from remote!`)
replicatorReconcileDestFoundMissingCount = replicatorReconcileDestFoundMissingCount + 1
// If the missing destination is in deleting/deleted status, we don't need to create the destination locally
if remoteDest.GetStatus() == shared.DestinationStatus_DELETING || remoteDest.GetStatus() == shared.DestinationStatus_DELETED {
r.logger.WithField(common.TagDst, common.FmtDst(remoteDest.GetDestinationUUID())).Info(`Found missing destination from remote but in deleted/deleting state`)
continue
}
createRequest := &shared.CreateDestinationUUIDRequest{
Request: &shared.CreateDestinationRequest{
Path: common.StringPtr(remoteDest.GetPath()),
Type: common.InternalDestinationTypePtr(remoteDest.GetType()),
ConsumedMessagesRetention: common.Int32Ptr(remoteDest.GetConsumedMessagesRetention()),
UnconsumedMessagesRetention: common.Int32Ptr(remoteDest.GetUnconsumedMessagesRetention()),
OwnerEmail: common.StringPtr(remoteDest.GetOwnerEmail()),
ChecksumOption: common.InternalChecksumOptionPtr(remoteDest.GetChecksumOption()),
IsMultiZone: common.BoolPtr(remoteDest.GetIsMultiZone()),
ZoneConfigs: remoteDest.GetZoneConfigs(),
SchemaInfo: remoteDest.GetSchemaInfo(),
},
DestinationUUID: common.StringPtr(remoteDest.GetDestinationUUID()),
}
ctx, cancel := thrift.NewContext(localReplicatorCallTimeOut)
defer cancel()
_, err := r.replicator.CreateDestinationUUID(ctx, createRequest)
if err != nil {
r.logger.WithFields(bark.Fields{
common.TagErr: err,
common.TagDst: common.FmtDst(remoteDest.GetDestinationUUID()),
}).Error(`Failed to create destination in local zone for reconciliation`)
continue
}
}
}
// case 4: destination missing in remote but exists locally.
// We don't need to handle this because deleted destination will still be in the uuid table for 30 days, so it should be covered by case #1
r.m3Client.UpdateGauge(metrics.ReplicatorReconcileScope, metrics.ReplicatorReconcileDestFoundMissing, replicatorReconcileDestFoundMissingCount)
}
func (r *metadataReconciler) reconcileCg(localCgs []*shared.ConsumerGroupDescription, remoteCgs []*shared.ConsumerGroupDescription) {
var replicatorReconcileCgFoundMissingCount int64
var replicatorReconcileCgFoundUpdatedCount int64
localCgsSet := make(map[string]*shared.ConsumerGroupDescription, len(localCgs))
for _, cg := range localCgs {
localCgsSet[cg.GetConsumerGroupUUID()] = cg
}
for _, remoteCg := range remoteCgs {
lclLg := r.logger.WithFields(bark.Fields{
common.TagCnsm: common.FmtCnsm(remoteCg.GetConsumerGroupUUID()),
common.TagDst: common.FmtDst(remoteCg.GetDestinationUUID()),
})
localCg, ok := localCgsSet[remoteCg.GetConsumerGroupUUID()]
if ok {
if remoteCg.GetStatus() == shared.ConsumerGroupStatus_DELETED {
// case #1: cg gets deleted in remote, but not deleted in local. Delete the cg locally
if !(localCg.GetStatus() == shared.ConsumerGroupStatus_DELETED) {
lclLg.Info(`Found deleted cg from remote but not deleted locally`)
deleteRequest := &shared.DeleteConsumerGroupRequest{
DestinationUUID: common.StringPtr(remoteCg.GetDestinationUUID()),
ConsumerGroupName: common.StringPtr(remoteCg.GetConsumerGroupName()),
}
ctx, cancel := thrift.NewContext(localReplicatorCallTimeOut)
defer cancel()
err := r.replicator.DeleteConsumerGroup(ctx, deleteRequest)
if err != nil {
lclLg.Error(`Failed to delete ConsumerGroup in local zone for reconciliation`)
continue
}
} else {
lclLg.Info(`Found ConsumerGroup is deleted in both remote and local`)
continue
}
continue
}
// case #2: cg exists in both remote and local, try to compare and update cg
r.compareAndUpdateCg(remoteCg, localCg, lclLg, &replicatorReconcileCgFoundUpdatedCount)
} else {
// case #3: cg exists in remote, but not in local. Create the cg locally
lclLg.Warn(`Found missing ConsumerGroup from remote!`)
replicatorReconcileCgFoundMissingCount = replicatorReconcileCgFoundMissingCount + 1
// If the missing ConsumerGroup is in deleted status, we don't need to create the ConsumerGroup locally
if remoteCg.GetStatus() == shared.ConsumerGroupStatus_DELETED {
lclLg.Info(`Found missing ConsumerGroup from remote but in deleted state`)
continue
}
destDesc, err := r.readDestinationInAuthoritativeZone(remoteCg.GetDestinationUUID())
if err != nil {
lclLg.WithFields(bark.Fields{
common.TagErr: err,
}).Error(`Failed to create ConsumerGroup in local zone because read destination failed in remote zone`)
continue
}
createRequest := &shared.CreateConsumerGroupUUIDRequest{
Request: &shared.CreateConsumerGroupRequest{
DestinationPath: common.StringPtr(destDesc.GetPath()),
ConsumerGroupName: common.StringPtr(remoteCg.GetConsumerGroupName()),
StartFrom: common.Int64Ptr(remoteCg.GetStartFrom()),
LockTimeoutSeconds: common.Int32Ptr(remoteCg.GetLockTimeoutSeconds()),
MaxDeliveryCount: common.Int32Ptr(remoteCg.GetMaxDeliveryCount()),
SkipOlderMessagesSeconds: common.Int32Ptr(remoteCg.GetSkipOlderMessagesSeconds()),
OwnerEmail: common.StringPtr(remoteCg.GetOwnerEmail()),
IsMultiZone: common.BoolPtr(remoteCg.GetIsMultiZone()),
ActiveZone: common.StringPtr(remoteCg.GetActiveZone()),
ZoneConfigs: remoteCg.GetZoneConfigs(),
},
ConsumerGroupUUID: common.StringPtr(remoteCg.GetConsumerGroupUUID()),
}
ctx, cancel := thrift.NewContext(localReplicatorCallTimeOut)
defer cancel()
_, err = r.replicator.CreateConsumerGroupUUID(ctx, createRequest)
if err != nil {
r.logger.WithFields(bark.Fields{
common.TagErr: err,
}).Error(`Failed to create ConsumerGroup in local zone for reconciliation`)
continue
}
continue
}
}
// case 4: cg missing in remote but exists locally.
// We don't need to handle this because deleted cg will still be in the uuid table for 30 days, so it should be covered by case #1
r.m3Client.UpdateGauge(metrics.ReplicatorReconcileScope, metrics.ReplicatorReconcileCgFoundMissing, replicatorReconcileCgFoundMissingCount)
r.m3Client.UpdateGauge(metrics.ReplicatorReconcileScope, metrics.ReplicatorReconcileCgFoundUpdated, replicatorReconcileCgFoundUpdatedCount)
}
func (r *metadataReconciler) compareAndUpdateCg(remoteCg *shared.ConsumerGroupDescription, localCg *shared.ConsumerGroupDescription, logger bark.Logger, replicatorReconcileCgFoundUpdatedCount *int64) {
updateRequest := &shared.UpdateConsumerGroupRequest{}
cgUpdated := false
if localCg.GetLockTimeoutSeconds() != remoteCg.GetLockTimeoutSeconds() {
updateRequest.LockTimeoutSeconds = common.Int32Ptr(remoteCg.GetLockTimeoutSeconds())
cgUpdated = true
}
if localCg.GetMaxDeliveryCount() != remoteCg.GetMaxDeliveryCount() {
updateRequest.MaxDeliveryCount = common.Int32Ptr(remoteCg.GetMaxDeliveryCount())
cgUpdated = true
}
if localCg.GetSkipOlderMessagesSeconds() != remoteCg.GetSkipOlderMessagesSeconds() {
updateRequest.SkipOlderMessagesSeconds = common.Int32Ptr(remoteCg.GetSkipOlderMessagesSeconds())
cgUpdated = true
}
if localCg.GetStatus() != remoteCg.GetStatus() {
updateRequest.Status = common.InternalConsumerGroupStatusPtr(remoteCg.GetStatus())
cgUpdated = true
}
if localCg.GetOwnerEmail() != remoteCg.GetOwnerEmail() {
updateRequest.OwnerEmail = common.StringPtr(remoteCg.GetOwnerEmail())
cgUpdated = true
}
if localCg.GetActiveZone() != remoteCg.GetActiveZone() {
updateRequest.ActiveZone = common.StringPtr(remoteCg.GetActiveZone())
cgUpdated = true
}
if cgUpdated {
logger.Info(`Found cg gets updated in remote but not in local`)
*replicatorReconcileCgFoundUpdatedCount = *replicatorReconcileCgFoundUpdatedCount + 1
destDesc, err := r.readDestinationInAuthoritativeZone(remoteCg.GetDestinationUUID())
if err != nil {
logger.WithFields(bark.Fields{
common.TagErr: err,
}).Error(`Failed to update ConsumerGroup in local zone because read destination failed in remote zone`)
return
}
updateRequest.DestinationPath = common.StringPtr(destDesc.GetPath())
updateRequest.ConsumerGroupName = common.StringPtr(remoteCg.GetConsumerGroupName())
ctx, cancel := thrift.NewContext(localReplicatorCallTimeOut)
defer cancel()
_, err = r.replicator.UpdateConsumerGroup(ctx, updateRequest)
if err != nil {
logger.WithField(common.TagErr, err).Error(`Failed to update cg in local zone for reconciliation`)
}
}
}
func (r *metadataReconciler) readDestinationInAuthoritativeZone(destUUID string) (*shared.DestinationDescription, error) {
var err error
authoritativeZone := r.replicator.getAuthoritativeZone()
remoteReplicator, err := r.replicator.replicatorclientFactory.GetReplicatorClient(authoritativeZone)
if err != nil {
r.logger.WithFields(bark.Fields{
common.TagErr: err,
common.TagZoneName: common.FmtZoneName(authoritativeZone),
}).Error(`Failed to get remote replicator client`)
return nil, err
}
readReq := &shared.ReadDestinationRequest{
DestinationUUID: common.StringPtr(destUUID),
}
ctx, cancel := thrift.NewContext(remoteReplicatorCallTimeOut)
defer cancel()
res, err := remoteReplicator.ReadDestination(ctx, readReq)
if err != nil {
r.logger.WithField(common.TagErr, err).Error(`Remote replicator call ReadDestination failed`)
return nil, err
}
return res, nil
}
func (r *metadataReconciler) getAllMultiZoneDestInLocalZone() ([]*shared.DestinationDescription, error) {
listReq := &shared.ListDestinationsByUUIDRequest{
MultiZoneOnly: common.BoolPtr(true),
ValidateAgainstPathTable: common.BoolPtr(true),
Limit: common.Int64Ptr(metadataListRequestPageSize),
}
var dests []*shared.DestinationDescription
for {
res, err := r.mClient.ListDestinationsByUUID(nil, listReq)
if err != nil {
r.logger.WithField(common.TagErr, err).Error(`Metadata call ListDestinationsByUUID failed`)
return nil, err
}
dests = append(dests, res.GetDestinations()...)
if len(res.GetNextPageToken()) == 0 {
break
}
listReq.PageToken = res.GetNextPageToken()
}
return dests, nil
}
func (r *metadataReconciler) getAllMultiZoneDestInAuthoritativeZone() ([]*shared.DestinationDescription, error) {
var err error
authoritativeZone := r.replicator.getAuthoritativeZone()
remoteReplicator, err := r.replicator.replicatorclientFactory.GetReplicatorClient(authoritativeZone)
if err != nil {
r.logger.WithFields(bark.Fields{
common.TagErr: err,
common.TagZoneName: common.FmtZoneName(authoritativeZone),
}).Error(`Failed to get remote replicator client`)
return nil, err
}
listReq := &shared.ListDestinationsByUUIDRequest{
MultiZoneOnly: common.BoolPtr(true),
ValidateAgainstPathTable: common.BoolPtr(true),
Limit: common.Int64Ptr(metadataListRequestPageSize),
}
var dests []*shared.DestinationDescription
for {
ctx, cancel := thrift.NewContext(remoteReplicatorCallTimeOut)
defer cancel()
res, err := remoteReplicator.ListDestinationsByUUID(ctx, listReq)
if err != nil {
r.logger.WithField(common.TagErr, err).Error(`Remote replicator call ListDestinationsByUUID failed`)
return nil, err
}
dests = append(dests, res.GetDestinations()...)
if len(res.GetNextPageToken()) == 0 {
break
}
listReq.PageToken = res.GetNextPageToken()
}
return dests, nil
}
func (r *metadataReconciler) getAllMultiZoneCgInLocalZone(dests []*shared.DestinationDescription) ([]*shared.ConsumerGroupDescription, error) {
var cgs []*shared.ConsumerGroupDescription
for _, dest := range dests {
listCgReq := &shared.ListConsumerGroupRequest{
DestinationUUID: common.StringPtr(dest.GetDestinationUUID()),
Limit: common.Int64Ptr(metadataListRequestPageSize),
}
for {
cgRes, err := r.mClient.ListConsumerGroups(nil, listCgReq)
if err != nil {
r.logger.WithField(common.TagErr, err).Error(`Metadata call ListConsumerGroups failed`)
return nil, err
}
for _, cg := range cgRes.GetConsumerGroups() {
if cg.GetIsMultiZone() {
cgs = append(cgs, cg)
}
}
if len(cgRes.GetNextPageToken()) == 0 {
break
}
listCgReq.PageToken = cgRes.GetNextPageToken()
}
}
return cgs, nil
}
func (r *metadataReconciler) getAllMultiZoneCgInAuthoritativeZone(dests []*shared.DestinationDescription) ([]*shared.ConsumerGroupDescription, error) {
var err error
authoritativeZone := r.replicator.getAuthoritativeZone()
remoteReplicator, err := r.replicator.replicatorclientFactory.GetReplicatorClient(authoritativeZone)
if err != nil {
r.logger.WithFields(bark.Fields{
common.TagErr: err,
common.TagZoneName: common.FmtZoneName(authoritativeZone),
}).Error(`Failed to get remote replicator client`)
return nil, err
}
var cgs []*shared.ConsumerGroupDescription
for _, dest := range dests {
listCgReq := &shared.ListConsumerGroupRequest{
DestinationUUID: common.StringPtr(dest.GetDestinationUUID()),
Limit: common.Int64Ptr(metadataListRequestPageSize),
}
for {
ctx, cancel := thrift.NewContext(remoteReplicatorCallTimeOut)
defer cancel()
cgRes, err := remoteReplicator.ListConsumerGroups(ctx, listCgReq)
if err != nil {
r.logger.WithField(common.TagErr, err).Error(`Remote replicator call ListConsumerGroups failed`)
return nil, err
}
for _, cg := range cgRes.GetConsumerGroups() {
if cg.GetIsMultiZone() {
cgs = append(cgs, cg)
}
}
if len(cgRes.GetNextPageToken()) == 0 {
break
}
listCgReq.PageToken = cgRes.GetNextPageToken()
}
}
return cgs, nil
}
func (r *metadataReconciler) reconcileDestExtentMetadata() error {
dests, err := r.getAllMultiZoneDestInLocalZone()
if err != nil {
return err
}
for _, dest := range dests {
localExtentsPerZone, errCur := r.getAllDestExtentInCurrentZone(dest.GetDestinationUUID())
if errCur != nil {
continue
}
for _, zoneConfig := range dest.GetZoneConfigs() {
// skip local zone
if strings.EqualFold(zoneConfig.GetZone(), r.localZone) {
continue
}
if zoneConfig.GetAllowPublish() {
remoteExtents, errRemote := r.getAllDestExtentInRemoteZone(zoneConfig.GetZone(), dest.GetDestinationUUID())
if errRemote != nil {
continue
}
// only need to reconcile for extents that are originated from the remote zone
localExtents := localExtentsPerZone[zoneConfig.GetZone()]
r.reconcileDestExtent(dest.GetDestinationUUID(), localExtents, remoteExtents, zoneConfig.GetZone())
}
}
}
return nil
}
func (r *metadataReconciler) reconcileCgExtentMetadata(localCgs []*shared.ConsumerGroupDescription) error {
for _, cg := range localCgs {
localExtents, err := r.getAllCgExtentInCurrentZone(cg.GetDestinationUUID(), cg.GetConsumerGroupUUID())
if err != nil {
continue
}
for _, zoneConfig := range cg.GetZoneConfigs() {
// skip local zone
if strings.EqualFold(zoneConfig.GetZone(), r.localZone) {
continue
}
if zoneConfig.GetVisible() {
remoteExtents, err := r.getAllCgExtentInRemoteZone(zoneConfig.GetZone(), cg.GetDestinationUUID(), cg.GetConsumerGroupUUID())
if err != nil {
continue
}
r.reconcileCgExtent(cg.GetDestinationUUID(), cg.GetConsumerGroupUUID(), localExtents, remoteExtents, zoneConfig.GetZone())
}
}
}
return nil
}
func (r *metadataReconciler) getAllDestExtentInRemoteZone(zone string, destUUID string) (map[string]*shared.ExtentStats, error) {
var err error
remoteReplicator, err := r.replicator.replicatorclientFactory.GetReplicatorClient(zone)
if err != nil {
r.logger.WithFields(bark.Fields{
common.TagErr: err,
common.TagZoneName: common.FmtZoneName(zone),
}).Error(`Failed to get remote replicator client`)
return nil, err
}
listReq := &shared.ListExtentsStatsRequest{
DestinationUUID: common.StringPtr(destUUID),
LocalExtentsOnly: common.BoolPtr(true),
Limit: common.Int64Ptr(metadataListRequestPageSize),
}
extents := make(map[string]*shared.ExtentStats)
for {
ctx, cancel := thrift.NewContext(remoteReplicatorCallTimeOut)
defer cancel()
res, err := remoteReplicator.ListExtentsStats(ctx, listReq)
if err != nil {
r.logger.WithField(common.TagErr, err).Error(`Remote replicator call ListExtentsStats failed`)
return nil, err
}
for _, ext := range res.GetExtentStatsList() {
extents[ext.GetExtent().GetExtentUUID()] = ext
}
if len(res.GetNextPageToken()) == 0 {
break
}
listReq.PageToken = res.GetNextPageToken()
}
return extents, nil
}
func (r *metadataReconciler) getAllDestExtentInCurrentZone(destUUID string) (map[string]map[string]*shared.ExtentStats, error) {
listReq := &shared.ListExtentsStatsRequest{
DestinationUUID: common.StringPtr(destUUID),
LocalExtentsOnly: common.BoolPtr(false),
Limit: common.Int64Ptr(metadataListRequestPageSize),
}
perZoneExtents := make(map[string]map[string]*shared.ExtentStats)
for {
res, err := r.mClient.ListExtentsStats(nil, listReq)
if err != nil {
r.logger.WithField(common.TagErr, err).Error(`Metadata call ListExtentsStats failed`)
return nil, err
}
for _, ext := range res.GetExtentStatsList() {
zone := ext.GetExtent().GetOriginZone()
if _, ok := perZoneExtents[zone]; !ok {
perZoneExtents[zone] = make(map[string]*shared.ExtentStats)
}
perZoneExtents[zone][ext.GetExtent().GetExtentUUID()] = ext
}
if len(res.GetNextPageToken()) == 0 {
break
}
listReq.PageToken = res.GetNextPageToken()
}
return perZoneExtents, nil
}
func (r *metadataReconciler) getAllCgExtentInRemoteZone(zone string, destUUID string, cgUUID string) (map[string]*shared.ConsumerGroupExtent, error) {
lclLg := r.logger.WithFields(bark.Fields{
common.TagDst: common.FmtDst(destUUID),
common.TagCnsm: common.FmtCnsm(cgUUID),
common.TagZoneName: common.FmtZoneName(zone),
})
var err error
remoteReplicator, err := r.replicator.replicatorclientFactory.GetReplicatorClient(zone)
if err != nil {
lclLg.WithField(common.TagErr, err).Error(`getAllCgExtentInRemoteZone: Failed to get remote replicator client`)
return nil, err
}
listReq := &shared.ReadConsumerGroupExtentsRequest{
DestinationUUID: common.StringPtr(destUUID),
ConsumerGroupUUID: common.StringPtr(cgUUID),
MaxResults: common.Int32Ptr(metadataListRequestPageSize),
}
res := make(map[string]*shared.ConsumerGroupExtent)
for {
ctx, cancel := thrift.NewContext(remoteReplicatorCallTimeOut)
defer cancel()
listRes, err := remoteReplicator.ReadConsumerGroupExtents(ctx, listReq)
if err != nil {
lclLg.WithField(common.TagErr, err).Error(`getAllCgExtentInRemoteZone: Remote replicator call ReadConsumerGroupExtents failed`)
return nil, err
}
for _, cgExt := range listRes.GetExtents() {
res[cgExt.GetExtentUUID()] = cgExt
}
if len(listRes.GetNextPageToken()) == 0 {
break
}
listReq.PageToken = listRes.GetNextPageToken()
}
return res, nil
}
func (r *metadataReconciler) getAllCgExtentInCurrentZone(destUUID string, cgUUID string) (map[string]*shared.ConsumerGroupExtent, error) {
lclLg := r.logger.WithFields(bark.Fields{
common.TagDst: common.FmtDst(destUUID),
common.TagCnsm: common.FmtCnsm(cgUUID),
})
listReq := &shared.ReadConsumerGroupExtentsRequest{
DestinationUUID: common.StringPtr(destUUID),
ConsumerGroupUUID: common.StringPtr(cgUUID),
MaxResults: common.Int32Ptr(metadataListRequestPageSize),
}
cgExtents := make(map[string]*shared.ConsumerGroupExtent)
for {
res, err := r.mClient.ReadConsumerGroupExtents(nil, listReq)
if err != nil {
lclLg.WithField(common.TagErr, err).Error(`getAllCgExtentInCurrentZone: Metadata call ReadConsumerGroupExtents failed`)
return nil, err
}
for _, cgExt := range res.GetExtents() {
cgExtents[cgExt.GetExtentUUID()] = cgExt
}
if len(res.GetNextPageToken()) == 0 {
break
}
listReq.PageToken = res.GetNextPageToken()
}
return cgExtents, nil
}
func (r *metadataReconciler) reconcileDestExtent(destUUID string, localExtents map[string]*shared.ExtentStats, remoteExtents map[string]*shared.ExtentStats, remoteZone string) {
var remoteDeletedLocalNotCount int64
var remoteConsumedLocalMissingCount int64
var remoteDeletedLocalMissingCount int64
var foundMissingCount int64
for remoteExtentUUID, remoteExtentStats := range remoteExtents {
remoteExtentStatus := remoteExtentStats.GetStatus()
localExtentStats, ok := localExtents[remoteExtentUUID]
if !ok {
r.logger.WithFields(bark.Fields{
common.TagDst: common.FmtDst(destUUID),
common.TagExt: common.FmtExt(remoteExtentUUID),
common.TagZoneName: common.FmtZoneName(remoteZone),
common.TagExtentStatus: common.FmtExtentStatus(remoteExtentStatus),
}).Warn(`Found missing extent from remote!`)
// if the extent is already in consumed/deleted state on remote side, don't bother to create the extent locally because all data is gone on remote side already
if remoteExtentStatus == shared.ExtentStatus_CONSUMED {
remoteConsumedLocalMissingCount = remoteConsumedLocalMissingCount + 1
continue
}
if remoteExtentStatus == shared.ExtentStatus_DELETED {
remoteDeletedLocalMissingCount = remoteDeletedLocalMissingCount + 1
continue
}
createRequest := &shared.CreateExtentRequest{
Extent: &shared.Extent{
ExtentUUID: common.StringPtr(remoteExtentUUID),
DestinationUUID: common.StringPtr(destUUID),
InputHostUUID: common.StringPtr(common.InputHostForRemoteExtent),
StoreUUIDs: []string{},
OriginZone: common.StringPtr(remoteZone),
},
}
// If the remote extent has cg visibility set (a merged dlq extent), only create the extent if
// the cg exists in local (i.e. if the cg is a local only cg from remote, we don't need to replicate this extent)
if remoteExtentStats.IsSetConsumerGroupVisibility() {
exist, err := r.cgExistInLocal(remoteExtentStats.GetConsumerGroupVisibility())
if err != nil {
r.logger.WithFields(bark.Fields{
common.TagErr: err,
common.TagDst: common.FmtDst(destUUID),
common.TagCnsm: common.FmtCnsm(remoteExtentStats.GetConsumerGroupVisibility()),
common.TagExt: common.FmtExt(remoteExtentUUID),
common.TagZoneName: common.FmtZoneName(remoteZone),
}).Error(`Failed to decide whether cg exist in local for dlq extent`)
continue
}
if !exist {
r.logger.WithFields(bark.Fields{
common.TagErr: err,
common.TagDst: common.FmtDst(destUUID),
common.TagCnsm: common.FmtCnsm(remoteExtentStats.GetConsumerGroupVisibility()),
common.TagExt: common.FmtExt(remoteExtentUUID),
common.TagZoneName: common.FmtZoneName(remoteZone),
}).Info(`Found missing dlq extent but cg doesn't exist in local`)
continue
}
createRequest.ConsumerGroupVisibility = common.StringPtr(remoteExtentStats.GetConsumerGroupVisibility())
}
foundMissingCount = foundMissingCount + 1
ctx, cancel := thrift.NewContext(localReplicatorCallTimeOut)
defer cancel()
_, err := r.replicator.CreateExtent(ctx, createRequest)
if err != nil {
r.logger.WithFields(bark.Fields{
common.TagErr: err,
common.TagDst: common.FmtDst(destUUID),
common.TagExt: common.FmtExt(remoteExtentUUID),
common.TagZoneName: common.FmtZoneName(remoteZone),
}).Error(`Failed to create extent in local zone for reconciliation`)
continue
}
} else {
localExtentStatus := localExtentStats.GetStatus()
if (remoteExtentStatus == shared.ExtentStatus_SEALED || remoteExtentStatus == shared.ExtentStatus_CONSUMED) && localExtentStatus == shared.ExtentStatus_OPEN {
r.sealExtentInMetadata(destUUID, remoteExtentUUID)
}
if remoteExtentStatus == shared.ExtentStatus_DELETED {
r.handleExtentDeletedOrMissingInRemote(destUUID, remoteExtentUUID, localExtentStatus, &remoteDeletedLocalNotCount)
}
}
}
// now try to find all the orphaned extents(extent already gone in remote zone but not in local zone), and try to seal them
// note we're not 100% sure if the extent is really gone even if cassandra doesn't return that extent because of
// the eventual consistency nature of cassandra
// so we maintain a timestamp to track how long the extent has been missing
// we act on it only after it has been missing for a certain period of time
remoteMissingExtents := make(map[string]struct{})
for localExtentUUID, localExtentStats := range localExtents {
// we're going to delete this extent soon locally so no need to act on it
if localExtentStats.GetStatus() == shared.ExtentStatus_CONSUMED || localExtentStats.GetStatus() == shared.ExtentStatus_DELETED {
continue
}
if _, ok := remoteExtents[localExtentUUID]; !ok {
// extent exists in local but not in remote
remoteMissingExtents[localExtentUUID] = struct{}{}
}
}
for suspectExtent, suspectExtentInfo := range r.suspectMissingExtents {
if suspectExtentInfo.destUUID != destUUID {
continue
}
if _, ok := remoteMissingExtents[suspectExtent]; !ok {
// re-appeared in remote, remove it from suspect list
delete(r.suspectMissingExtents, suspectExtent)
} else {
if time.Since(suspectExtentInfo.missingSince) > extentMissingDurationThreshold {
localStats, ok := localExtents[suspectExtent]
if !ok {
r.logger.WithFields(bark.Fields{
common.TagDst: common.FmtDst(suspectExtentInfo.destUUID),
common.TagExt: common.FmtExt(suspectExtent),
}).Error(`code bug!! suspect extent should in local extent map!!`)
continue
}
r.handleExtentDeletedOrMissingInRemote(suspectExtentInfo.destUUID, suspectExtent, localStats.GetStatus(), &remoteDeletedLocalNotCount)
}
}
}
// now add new suspect if there's any
for missingExtent := range remoteMissingExtents {
if _, ok := r.suspectMissingExtents[missingExtent]; !ok {
r.suspectMissingExtents[missingExtent] = missingExtentInfo{
destUUID: destUUID,
missingSince: time.Now(),
}
}
}
r.m3Client.UpdateGauge(metrics.ReplicatorReconcileScope, metrics.ReplicatorReconcileDestExtentFoundMissing, foundMissingCount)
r.m3Client.UpdateGauge(metrics.ReplicatorReconcileScope, metrics.ReplicatorReconcileDestExtentRemoteConsumedLocalMissing, remoteConsumedLocalMissingCount)
r.m3Client.UpdateGauge(metrics.ReplicatorReconcileScope, metrics.ReplicatorReconcileDestExtentRemoteDeletedLocalMissing, remoteDeletedLocalMissingCount)
r.m3Client.UpdateGauge(metrics.ReplicatorReconcileScope, metrics.ReplicatorReconcileDestExtentRemoteDeletedLocalNot, remoteDeletedLocalNotCount)
r.m3Client.UpdateGauge(metrics.ReplicatorReconcileScope, metrics.ReplicatorReconcileDestExtentSuspectMissingExtents, int64(len(r.suspectMissingExtents)))
}
func (r *metadataReconciler) reconcileCgExtent(destUUID string, cgUUID string, localExtents map[string]*shared.ConsumerGroupExtent, remoteExtents map[string]*shared.ConsumerGroupExtent, remoteZone string) {
lclLg := r.logger.WithFields(bark.Fields{
common.TagDst: common.FmtDst(destUUID),
common.TagCnsm: common.FmtCnsm(cgUUID),
common.TagZoneName: common.FmtZoneName(remoteZone),
})
var remoteConsumedLocalMissingCount int64
var remoteDeletedLocalMissingCount int64
var foundMissingCount int64
for remoteExtentUUID, remoteExtent := range remoteExtents {
remoteExtentStatus := remoteExtent.GetStatus()
localExtent, ok := localExtents[remoteExtentUUID]
if !ok {
lclLg.WithFields(bark.Fields{
common.TagExt: common.FmtExt(remoteExtentUUID),
common.TagCGExtentStatus: common.FmtCGExtentStatus(remoteExtentStatus),
}).Warn(`reconcileCgExtent: Found missing cg extent from remote!`)
// if the extent is already in consumed/deleted state on remote side, don't bother to create the extent locally
if remoteExtentStatus == shared.ConsumerGroupExtentStatus_CONSUMED {
remoteConsumedLocalMissingCount = remoteConsumedLocalMissingCount + 1
continue
}
if remoteExtentStatus == shared.ConsumerGroupExtentStatus_DELETED {
remoteDeletedLocalMissingCount = remoteDeletedLocalMissingCount + 1
continue
}