/
replication_manager.go
1307 lines (1116 loc) · 52 KB
/
replication_manager.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) 2013-2020 Couchbase, Inc.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
// replication manager.
package replication_manager
import (
"bufio"
"encoding/json"
"errors"
"expvar"
"fmt"
"io"
"os"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"time"
mcc "github.com/couchbase/gomemcached/client"
"github.com/couchbase/goxdcr/backfill_manager"
"github.com/couchbase/goxdcr/base"
"github.com/couchbase/goxdcr/common"
"github.com/couchbase/goxdcr/factory"
"github.com/couchbase/goxdcr/log"
"github.com/couchbase/goxdcr/metadata"
"github.com/couchbase/goxdcr/pipeline"
"github.com/couchbase/goxdcr/pipeline_manager"
"github.com/couchbase/goxdcr/pipeline_svc"
"github.com/couchbase/goxdcr/resource_manager"
"github.com/couchbase/goxdcr/service_def"
"github.com/couchbase/goxdcr/supervisor"
utilities "github.com/couchbase/goxdcr/utils"
)
var logger_rm *log.CommonLogger = log.NewLogger("ReplMgr", log.DefaultLoggerContext)
var StatsUpdateIntervalForPausedReplications = 60 * time.Second
var GoXDCROptions struct {
SourceKVAdminPort uint64 //source kv admin port
XdcrRestPort uint64 // port number of XDCR rest server
SslProxyUpstreamPort uint64
IsEnterprise bool // whether couchbase is of enterprise edition
IsConvert bool // whether xdcr is running in conversion/upgrade mode
// logging related parameters
LogFileDir string
MaxLogFileSize uint64
MaxNumberOfLogFiles uint64
}
/************************************
/* ReplicationManager Interface
*************************************/
type ReplicationManagerIf interface {
OnError(s common.Supervisor, errMap base.ErrorMap)
}
/************************************
/* struct ReplicationManager
*************************************/
type replicationManager struct {
// supervises the livesness of adminport
supervisor.GenericSupervisor
// Single instance of pipeline_mgr here instead of using a global
pipelineMgr pipeline_manager.PipelineMgrIface
resourceMgr resource_manager.ResourceMgrIface
//replication specification service handle
repl_spec_svc service_def.ReplicationSpecSvc
//remote cluster service handle
remote_cluster_svc service_def.RemoteClusterSvc
//cluster info service handle
cluster_info_svc service_def.ClusterInfoSvc
//xdcr topology service handle
xdcr_topology_svc service_def.XDCRCompTopologySvc
//replication settings service handle
replication_settings_svc service_def.ReplicationSettingsSvc
//checkpoint service handle
checkpoint_svc service_def.CheckpointsService
//capi service handle
capi_svc service_def.CAPIService
//audit service handle
audit_svc service_def.AuditSvc
//global setting service
global_setting_svc service_def.GlobalSettingsSvc
//bucket settings service
bucket_settings_svc service_def.BucketSettingsSvc
//internal settings service
internal_settings_svc service_def.InternalSettingsSvc
// Mockable utils object
utils utilities.UtilsIface
resolver_svc *service_def.ResolverSvcIface
// Collections Manifests service
collectionsManifestSvc service_def.CollectionsManifestSvc
// Backfill replication service
backfillReplSvc service_def.BackfillReplSvc
// Backfill Manager service
backfillMgr service_def.BackfillMgrIface
once sync.Once
//finish channel for adminport
adminport_finch chan bool
metadata_change_callback_cancel_ch chan struct{}
running bool
running_lock sync.RWMutex
children_waitgrp *sync.WaitGroup
status_logger_finch chan bool
mem_stats_logger_finch chan bool
}
//singleton
var replication_mgr replicationManager
func StartReplicationManager(sourceKVHost string,
xdcrRestPort uint16, sourceKVAdminPort uint16,
repl_spec_svc service_def.ReplicationSpecSvc,
remote_cluster_svc service_def.RemoteClusterSvc,
cluster_info_svc service_def.ClusterInfoSvc,
xdcr_topology_svc service_def.XDCRCompTopologySvc,
replication_settings_svc service_def.ReplicationSettingsSvc,
checkpoint_svc service_def.CheckpointsService,
capi_svc service_def.CAPIService,
audit_svc service_def.AuditSvc,
uilog_svc service_def.UILogSvc,
global_setting_svc service_def.GlobalSettingsSvc,
bucket_settings_svc service_def.BucketSettingsSvc,
internal_settings_svc service_def.InternalSettingsSvc,
throughput_throttler_svc service_def.ThroughputThrottlerSvc,
resolver_svc service_def.ResolverSvcIface,
utilitiesIn utilities.UtilsIface,
collectionsManifestSvc service_def.CollectionsManifestSvc,
backfillReplSvc service_def.BackfillReplSvc) {
replication_mgr.once.Do(func() {
// ns_server shutdown protocol: poll stdin and exit upon reciept of EOF
go pollStdin()
// initialize constants
initConstants(xdcr_topology_svc, internal_settings_svc)
// Take in utilities
replication_mgr.utils = utilitiesIn
// Start resolver_svc before the adminport and before starting any pipeline,
// since it will initialize the javascript function handler and start the resolverSvc that the pipeline needs
resolver_svc.Start(sourceKVHost, xdcrRestPort)
// initializes replication manager
replication_mgr.init(repl_spec_svc, remote_cluster_svc, cluster_info_svc,
xdcr_topology_svc, replication_settings_svc, checkpoint_svc, capi_svc,
audit_svc, uilog_svc, global_setting_svc, bucket_settings_svc, internal_settings_svc,
throughput_throttler_svc, resolver_svc, collectionsManifestSvc, backfillReplSvc)
// start replication manager supervisor
// TODO should we make heart beat settings configurable?
replication_mgr.GenericSupervisor.Start(nil)
// set ReplicationStatus for both paused and active replications
replication_mgr.initReplications()
logger_rm.Info("initReplications succeeded")
replication_mgr.running = true
replication_mgr.running_lock = sync.RWMutex{}
replication_mgr.status_logger_finch = make(chan bool, 1)
go replication_mgr.checkReplicationStatus(replication_mgr.status_logger_finch)
// periodically log mem stats to facilitate debugging of memory issues
replication_mgr.mem_stats_logger_finch = make(chan bool, 1)
go logMemStats(replication_mgr.mem_stats_logger_finch)
// upgrade remote cluster refs before initializing metadata change monitor
// and starting adminport to reduce interference
replication_mgr.upgradeRemoteClusterRefs()
replication_mgr.initMetadataChangeMonitor()
// start adminport
adminport := NewAdminport(sourceKVHost, xdcrRestPort, sourceKVAdminPort, replication_mgr.adminport_finch, replication_mgr.utils)
go adminport.Start()
logger_rm.Info("Admin port has been launched")
// add adminport as children of replication manager supervisor
replication_mgr.GenericSupervisor.AddChild(adminport)
logger_rm.Info("ReplicationManager is running")
})
}
func initConstants(xdcr_topology_svc service_def.XDCRCompTopologySvc, internal_settings_svc service_def.InternalSettingsSvc) {
// get cluster version
version, err := xdcr_topology_svc.MyClusterVersion()
if err != nil {
logger_rm.Errorf("Failed to get local cluster version. err=%v", err)
// in the unlikely event of error, an empty version will be used
}
internal_settings := internal_settings_svc.GetInternalSettings()
logger_rm.Infof("XDCR internal settings: %v\n", internal_settings.ToMap())
metadata.InitConstants(internal_settings.Values[metadata.XmemMaxIdleCountLowerBoundKey].(int),
internal_settings.Values[metadata.XmemMaxIdleCountUpperBoundKey].(int))
base.InitConstants(time.Duration(internal_settings.Values[metadata.TopologyChangeCheckIntervalKey].(int))*time.Second,
internal_settings.Values[metadata.MaxTopologyChangeCountBeforeRestartKey].(int),
internal_settings.Values[metadata.MaxTopologyStableCountBeforeRestartKey].(int),
internal_settings.Values[metadata.MaxWorkersForCheckpointingKey].(int),
time.Duration(internal_settings.Values[metadata.TimeoutCheckpointBeforeStopKey].(int))*time.Second,
internal_settings.Values[metadata.CapiDataChanSizeMultiplierKey].(int),
time.Duration(internal_settings.Values[metadata.RefreshRemoteClusterRefIntervalKey].(int))*time.Second,
version,
internal_settings.Values[metadata.CapiMaxRetryBatchUpdateDocsKey].(int),
time.Duration(internal_settings.Values[metadata.CapiBatchTimeoutKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.CapiWriteTimeoutKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.CapiReadTimeoutKey].(int))*time.Second,
internal_settings.Values[metadata.MaxCheckpointRecordsToKeepKey].(int),
internal_settings.Values[metadata.MaxCheckpointRecordsToReadKey].(int),
time.Duration(internal_settings.Values[metadata.DefaultHttpTimeoutKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.ShortHttpTimeoutKey].(int))*time.Second,
internal_settings.Values[metadata.MaxRetryForLiveUpdatePipelineKey].(int),
time.Duration(internal_settings.Values[metadata.WaitTimeForLiveUpdatePipelineKey].(int))*time.Millisecond,
time.Duration(internal_settings.Values[metadata.ReplSpecCheckIntervalKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.MemStatsLogIntervalKey].(int))*time.Second,
internal_settings.Values[metadata.MaxNumOfMetakvRetriesKey].(int),
time.Duration(internal_settings.Values[metadata.RetryIntervalMetakvKey].(int))*time.Millisecond,
internal_settings.Values[metadata.UprFeedDataChanLengthKey].(int),
internal_settings.Values[metadata.UprFeedBufferSizeKey].(int),
internal_settings.Values[metadata.XmemMaxRetryKey].(int),
time.Duration(internal_settings.Values[metadata.XmemWriteTimeoutKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.XmemReadTimeoutKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.XmemMaxReadDownTimeKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.XmemBackoffWaitTimeKey].(int))*time.Millisecond,
internal_settings.Values[metadata.XmemMaxBackoffFactorKey].(int),
internal_settings.Values[metadata.XmemMaxRetryNewConnKey].(int),
time.Duration(internal_settings.Values[metadata.XmemBackoffTimeNewConnKey].(int))*time.Millisecond,
time.Duration(internal_settings.Values[metadata.XmemSelfMonitorIntervalKey].(int))*time.Second,
internal_settings.Values[metadata.XmemMaxIdleCountKey].(int),
internal_settings.Values[metadata.XmemMaxIdleCountLowerBoundKey].(int),
internal_settings.Values[metadata.XmemMaxIdleCountUpperBoundKey].(int),
internal_settings.Values[metadata.XmemMaxDataChanSizeKey].(int),
internal_settings.Values[metadata.XmemMaxBatchSizeKey].(int),
time.Duration(internal_settings.Values[metadata.CapiRetryIntervalKey].(int))*time.Millisecond,
internal_settings.Values[metadata.MaxLengthSnapshotHistoryKey].(int),
internal_settings.Values[metadata.MaxRetryTargetStatsKey].(int),
time.Duration(internal_settings.Values[metadata.RetryIntervalTargetStatsKey].(int))*time.Millisecond,
internal_settings.Values[metadata.NumberOfSlotsForBandwidthThrottlingKey].(int),
internal_settings.Values[metadata.PercentageOfBytesToSendAsMinKey].(int),
time.Duration(internal_settings.Values[metadata.AuditWriteTimeoutKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.AuditReadTimeoutKey].(int))*time.Second,
internal_settings.Values[metadata.MaxRetryCapiServiceKey].(int),
internal_settings.Values[metadata.MaxNumberOfAsyncListenersKey].(int),
time.Duration(internal_settings.Values[metadata.XmemMaxRetryIntervalKey].(int))*time.Second,
internal_settings.Values[metadata.XmemMaxRetryMutationLockedKey].(int),
time.Duration(internal_settings.Values[metadata.XmemMaxRetryIntervalMutationLockedKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.HELOTimeoutKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.WaitTimeBetweenMetadataChangeListenersKey].(int))*time.Millisecond,
time.Duration(internal_settings.Values[metadata.KeepAlivePeriodKey].(int))*time.Second,
internal_settings.Values[metadata.ThresholdPercentageForEventChanSizeLoggingKey].(int),
time.Duration(internal_settings.Values[metadata.ThresholdForThroughSeqnoComputationKey].(int))*time.Millisecond,
time.Duration(internal_settings.Values[metadata.StatsLogIntervalKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.XmemDefaultRespTimeoutKey].(int))*time.Millisecond,
internal_settings.Values[metadata.BypassSanInCertificateCheckKey].(int),
internal_settings.Values[metadata.ReplicationSpecGCCntKey].(int),
time.Duration(internal_settings.Values[metadata.TimeoutRuntimeContextStartKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.TimeoutRuntimeContextStopKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.TimeoutPartsStartKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.TimeoutPartsStopKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.TimeoutDcpCloseUprStreamsKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.TimeoutDcpCloseUprFeedKey].(int))*time.Second,
time.Duration(internal_settings.Values[metadata.CpuCollectionIntervalKey].(int))*time.Millisecond,
time.Duration(internal_settings.Values[metadata.ResourceManagementIntervalKey].(int))*time.Millisecond,
time.Duration(internal_settings.Values[metadata.ResourceManagementStatsIntervalKey].(int))*time.Millisecond,
internal_settings.Values[metadata.ChangesLeftThresholdForOngoingReplicationKey].(int),
internal_settings.Values[metadata.ResourceManagementRatioBaseKey].(int),
internal_settings.Values[metadata.ResourceManagementRatioUpperBoundKey].(int),
internal_settings.Values[metadata.MaxCountBacklogForSetDcpPriorityKey].(int),
internal_settings.Values[metadata.MaxCountNoBacklogForResetDcpPriorityKey].(int),
internal_settings.Values[metadata.ExtraQuotaForUnderutilizedCPUKey].(int),
time.Duration(internal_settings.Values[metadata.ThroughputThrottlerLogIntervalKey].(int))*time.Millisecond,
time.Duration(internal_settings.Values[metadata.ThroughputThrottlerClearTokensIntervalKey].(int))*time.Millisecond,
internal_settings.Values[metadata.NumberOfSlotsForThroughputThrottlingKey].(int),
internal_settings.Values[metadata.IntervalForThrottlerCalibrationKey].(int),
internal_settings.Values[metadata.ThroughputSampleSizeKey].(int),
internal_settings.Values[metadata.ThroughputSampleAlphaKey].(int),
internal_settings.Values[metadata.ThresholdRatioForProcessCpuKey].(int),
internal_settings.Values[metadata.ThresholdRatioForTotalCpuKey].(int),
internal_settings.Values[metadata.MaxCountCpuNotMaxedKey].(int),
internal_settings.Values[metadata.MaxCountThroughputDropKey].(int),
internal_settings.Values[metadata.FilteringInternalKey].(string),
internal_settings.Values[metadata.FilteringInternalXattr].(string),
internal_settings.Values[metadata.RemoteClusterAlternateAddrChangeKey].(int),
internal_settings.Values[metadata.ManifestRefreshSrcIntervalKey].(int),
internal_settings.Values[metadata.ManifestRefreshTgtIntervalKey].(int),
time.Duration(internal_settings.Values[metadata.BackfillPersistIntervalKey].(int64))*time.Millisecond,
time.Duration(internal_settings.Values[metadata.TimeoutHttpsPortLookupKey].(int))*time.Second,
)
}
func (rm *replicationManager) initMetadataChangeMonitor() {
mcm := NewMetadataChangeMonitor()
// the sequence of the listener registration matters
// for example, replicationSpecChangeListener will get all active replications started
// this requires replication settings and remote cluster reference to be initialized
// that is why it needs to be registered and started after the other listeners
globalSettingChangeListener := NewGlobalSettingChangeListener(
rm.global_setting_svc,
rm.metadata_change_callback_cancel_ch,
rm.children_waitgrp,
log.DefaultLoggerContext,
rm.utils,
rm.resourceMgr)
mcm.RegisterListener(globalSettingChangeListener)
rm.global_setting_svc.SetMetadataChangeHandlerCallback(globalSettingChangeListener.globalSettingChangeHandlerCallback)
internalSettingsChangeListener := NewInternalSettingsChangeListener(
rm.internal_settings_svc,
rm.metadata_change_callback_cancel_ch,
rm.children_waitgrp,
log.DefaultLoggerContext,
rm.utils)
mcm.RegisterListener(internalSettingsChangeListener)
rm.internal_settings_svc.SetMetadataChangeHandlerCallback(internalSettingsChangeListener.internalSettingsChangeHandlerCallback)
remoteClusterChangeListener := NewRemoteClusterChangeListener(
rm.remote_cluster_svc,
rm.repl_spec_svc,
rm.metadata_change_callback_cancel_ch,
rm.children_waitgrp,
log.DefaultLoggerContext,
rm.utils)
mcm.RegisterListener(remoteClusterChangeListener)
rm.remote_cluster_svc.SetMetadataChangeHandlerCallback(remoteClusterChangeListener.remoteClusterChangeHandlerCallback)
replicationSpecChangeListener := NewReplicationSpecChangeListener(
rm.repl_spec_svc,
rm.metadata_change_callback_cancel_ch,
rm.children_waitgrp,
log.DefaultLoggerContext,
rm.utils,
rm.resourceMgr)
mcm.RegisterListener(replicationSpecChangeListener)
// ReplSpecSvc allows multiple callbacks - add the collections one first to be called first
rm.repl_spec_svc.SetMetadataChangeHandlerCallback(rm.collectionsManifestSvc.ReplicationSpecChangeCallback)
rm.repl_spec_svc.SetMetadataChangeHandlerCallback(replicationSpecChangeListener.replicationSpecChangeHandlerCallback)
rm.repl_spec_svc.SetMetadataChangeHandlerCallback(rm.backfillReplSvc.ReplicationSpecChangeCallback)
rm.repl_spec_svc.SetMetadataChangeHandlerCallback(rm.backfillMgr.ReplicationSpecChangeCallback)
rm.repl_spec_svc.SetMetadataChangeHandlerCallback(rm.checkpoint_svc.ReplicationSpecChangeCallback)
mcm.Start()
}
func (rm *replicationManager) initReplications() {
var specs map[string]*metadata.ReplicationSpecification
var err error
specs, err = rm.repl_spec_svc.AllReplicationSpecs()
if err == nil {
for _, spec := range specs {
if spec.Settings.Active {
logger_rm.Infof("Initializing active replication %v", spec.Id)
rm.pipelineMgr.UpdatePipeline(spec.Id, nil)
} else {
logger_rm.Infof("Initializing paused replication %v", spec.Id)
rm.pipelineMgr.InitiateRepStatus(spec.Id)
}
}
} else {
logger_rm.Errorf("Failed to initReplications - unable to retrieve specs from service cache.")
exitProcess(false)
}
}
func (rm *replicationManager) checkReplicationStatus(fin_chan chan bool) {
logger_rm.Infof("checkReplicationStatus started.")
defer logger_rm.Infof("checkReplicationStatus exited")
status_check_ticker := time.NewTicker(base.ReplSpecCheckInterval)
defer status_check_ticker.Stop()
stats_update_ticker := time.NewTicker(StatsUpdateIntervalForPausedReplications)
defer stats_update_ticker.Stop()
// key of outer map - bucket name
// key of inner map - kv address
// value - memcached client
bucket_kv_mem_clients := make(map[string]map[string]mcc.ClientIface)
for {
select {
case <-fin_chan:
return
case <-status_check_ticker.C:
rm.pipelineMgr.CheckPipelines()
case <-stats_update_ticker.C:
pipeline_svc.UpdateStats(ClusterInfoService(), XDCRCompTopologyService(), CheckpointService(), bucket_kv_mem_clients, logger_rm, rm.utils, rm.remote_cluster_svc, rm.backfillReplSvc)
}
}
}
func (rm *replicationManager) init(
repl_spec_svc service_def.ReplicationSpecSvc,
remote_cluster_svc service_def.RemoteClusterSvc,
cluster_info_svc service_def.ClusterInfoSvc,
xdcr_topology_svc service_def.XDCRCompTopologySvc,
replication_settings_svc service_def.ReplicationSettingsSvc,
checkpoint_svc service_def.CheckpointsService,
capi_svc service_def.CAPIService,
audit_svc service_def.AuditSvc,
uilog_svc service_def.UILogSvc,
global_setting_svc service_def.GlobalSettingsSvc,
bucket_settings_svc service_def.BucketSettingsSvc,
internal_settings_svc service_def.InternalSettingsSvc,
throughput_throttler_svc service_def.ThroughputThrottlerSvc,
resolverSvc service_def.ResolverSvcIface,
collectionsManifestSvc service_def.CollectionsManifestSvc,
backfillReplSvc service_def.BackfillReplSvc) {
rm.GenericSupervisor = *supervisor.NewGenericSupervisor(base.ReplicationManagerSupervisorId, log.DefaultLoggerContext, rm, nil, rm.utils)
rm.repl_spec_svc = repl_spec_svc
rm.remote_cluster_svc = remote_cluster_svc
rm.cluster_info_svc = cluster_info_svc
rm.xdcr_topology_svc = xdcr_topology_svc
rm.replication_settings_svc = replication_settings_svc
rm.checkpoint_svc = checkpoint_svc
rm.capi_svc = capi_svc
rm.audit_svc = audit_svc
rm.adminport_finch = make(chan bool, 1)
rm.children_waitgrp = &sync.WaitGroup{}
rm.global_setting_svc = global_setting_svc
rm.bucket_settings_svc = bucket_settings_svc
rm.internal_settings_svc = internal_settings_svc
rm.collectionsManifestSvc = collectionsManifestSvc
rm.backfillReplSvc = backfillReplSvc
fac := factory.NewXDCRFactory(repl_spec_svc, remote_cluster_svc, cluster_info_svc,
xdcr_topology_svc, checkpoint_svc, capi_svc, uilog_svc, bucket_settings_svc,
throughput_throttler_svc, log.DefaultLoggerContext, log.DefaultLoggerContext,
rm, rm.utils, resolverSvc, collectionsManifestSvc, rm.getBackfillMgr, rm.backfillReplSvc)
pipelineMgrObj := pipeline_manager.NewPipelineManager(fac, repl_spec_svc, xdcr_topology_svc, remote_cluster_svc, cluster_info_svc, checkpoint_svc, uilog_svc, log.DefaultLoggerContext, rm.utils, collectionsManifestSvc, rm.backfillReplSvc)
rm.pipelineMgr = pipelineMgrObj
rm.resourceMgr = resource_manager.NewResourceManager(rm.pipelineMgr, repl_spec_svc, xdcr_topology_svc, remote_cluster_svc, cluster_info_svc, checkpoint_svc, uilog_svc, throughput_throttler_svc, log.DefaultLoggerContext, rm.utils, rm.backfillReplSvc)
rm.resourceMgr.Start()
rm.backfillMgr = backfill_manager.NewBackfillManager(collectionsManifestSvc, repl_spec_svc, backfillReplSvc, pipelineMgrObj, cluster_info_svc, xdcr_topology_svc, checkpoint_svc)
rm.backfillMgr.Start()
rm.metadata_change_callback_cancel_ch = make(chan struct{}, 1)
logger_rm.Info("Replication manager is initialized")
}
func ReplicationSpecService() service_def.ReplicationSpecSvc {
return replication_mgr.repl_spec_svc
}
func RemoteClusterService() service_def.RemoteClusterSvc {
return replication_mgr.remote_cluster_svc
}
func ClusterInfoService() service_def.ClusterInfoSvc {
return replication_mgr.cluster_info_svc
}
func XDCRCompTopologyService() service_def.XDCRCompTopologySvc {
return replication_mgr.xdcr_topology_svc
}
func ReplicationSettingsService() service_def.ReplicationSettingsSvc {
return replication_mgr.replication_settings_svc
}
func CheckpointService() service_def.CheckpointsService {
return replication_mgr.checkpoint_svc
}
func AuditService() service_def.AuditSvc {
return replication_mgr.audit_svc
}
func GlobalSettingsService() service_def.GlobalSettingsSvc {
return replication_mgr.global_setting_svc
}
func BucketSettingsService() service_def.BucketSettingsSvc {
return replication_mgr.bucket_settings_svc
}
func InternalSettingsService() service_def.InternalSettingsSvc {
return replication_mgr.internal_settings_svc
}
//CreateReplication create the replication specification in metadata store
//and start the replication pipeline
func CreateReplication(justValidate bool, sourceBucket, targetCluster, targetBucket string, settings metadata.ReplicationSettingsMap, realUserId *service_def.RealUserId, ips *service_def.LocalRemoteIPs) (string, map[string]error, error, []string) {
logger_rm.Infof("Creating replication - justValidate=%v, sourceBucket=%s, targetCluster=%s, targetBucket=%s, settings=%v\n",
justValidate, sourceBucket, targetCluster, targetBucket, settings.CloneAndRedact())
var spec *metadata.ReplicationSpecification
spec, errorsMap, err, warnings := replication_mgr.createAndPersistReplicationSpec(justValidate, sourceBucket, targetCluster, targetBucket, settings)
if err != nil {
logger_rm.Errorf("%v\n", err)
return "", nil, err, nil
} else if len(errorsMap) != 0 {
return "", errorsMap, nil, nil
}
if justValidate {
return spec.Id, nil, nil, warnings
}
go writeCreateReplicationEvent(spec, realUserId, ips)
logger_rm.Infof("Replication specification %s is created\n", spec.Id)
return spec.Id, nil, nil, warnings
}
//DeleteReplication stops the running replication of given replicationId and
//delete the replication specification from the metadata store
func DeleteReplication(topic string, realUserId *service_def.RealUserId, ips *service_def.LocalRemoteIPs) error {
logger_rm.Infof("Deleting replication %s\n", topic)
// delete replication spec
spec, err := ReplicationSpecService().DelReplicationSpec(topic)
if err == nil {
logger_rm.Infof("Replication specification %s is deleted\n", topic)
} else {
logger_rm.Errorf("%v\n", err)
return err
}
go writeGenericReplicationEvent(service_def.CancelReplicationEventId, spec, realUserId, ips)
logger_rm.Infof("Pipeline %s is deleted\n", topic)
return nil
}
//update the replication settings and XDCR process setting
func UpdateDefaultSettings(settings metadata.ReplicationSettingsMap, realUserId *service_def.RealUserId, ips *service_def.LocalRemoteIPs) (map[string]error, error) {
logger_rm.Infof("UpdateDefaultSettings called with settings=%v\n", settings)
// Validate process setting keys
globalSettingsMap := metadata.ValidateGlobalSettingsKey(settings)
if len(globalSettingsMap) > 0 {
//First update XDCR Process specific setting
errorMap, err := GlobalSettingsService().UpdateGlobalSettings(globalSettingsMap)
if len(errorMap) > 0 || err != nil {
return errorMap, err
}
logger_rm.Infof("Updated global settings\n")
} else {
logger_rm.Infof("Did not update global settings since there are no real changes\n")
}
//validate replication settings
replicationSettingMap := metadata.ValidateReplicationSettingsKey(settings)
if len(replicationSettingMap) > 0 {
//Now update default replication setting
changedSettingsMap, errorMap, err := ReplicationSettingsService().UpdateDefaultReplicationSettings(replicationSettingMap)
if len(errorMap) > 0 || err != nil {
return errorMap, err
}
if len(changedSettingsMap) != 0 {
go writeUpdateDefaultReplicationSettingsEvent(&changedSettingsMap, realUserId, ips)
}
logger_rm.Infof("Updated default replication settings\n")
} else {
logger_rm.Infof("Did not update default replication settings since there are no real changes\n")
}
return nil, nil
}
func compressionSettingsChanged(changedSettingsMap metadata.ReplicationSettingsMap, oldCompressionType int) bool {
if compressionType, ok := changedSettingsMap[metadata.CompressionTypeKey]; ok && (base.GetCompressionType(compressionType.(int)) != base.CompressionTypeNone) &&
base.GetCompressionType(oldCompressionType) != base.GetCompressionType(compressionType.(int)) {
return true
}
return false
}
func filterSettingsChanged(changedSettingsMap metadata.ReplicationSettingsMap, oldFilterExpression string) bool {
if newFilterExpression, ok := changedSettingsMap[metadata.FilterExpressionKey]; ok {
if newFilterExpression != oldFilterExpression {
return true
}
}
return false
}
//update the per-replication settings
func UpdateReplicationSettings(topic string, settings metadata.ReplicationSettingsMap, realUserId *service_def.RealUserId, ips *service_def.LocalRemoteIPs) (map[string]error, error) {
logger_rm.Infof("Update replication settings for %v, settings=%v\n", topic, settings.CloneAndRedact())
var internalChangesTookPlace bool
// read replication spec with the specified replication id
replSpec, err := ReplicationSpecService().ReplicationSpec(topic)
if err != nil {
return nil, err
}
// Validate the spec once more with the new settings
replSpecificFields, replSpecificErr := constructReplicationSpecificFieldsFromSpec(replSpec)
if replSpecificErr != nil {
return nil, err
}
// Save some old values that we may need
filterExpression := replSpec.Settings.Values[metadata.FilterExpressionKey].(string)
oldCompressionType := replSpec.Settings.Values[metadata.CompressionTypeKey].(int)
filterVersion := replSpec.Settings.Values[metadata.FilterVersionKey].(base.FilterVersionType)
// update replication spec with input settings
changedSettingsMap, errorMap := replSpec.Settings.UpdateSettingsFromMap(settings)
// Only Re-evaluate Compression pre-requisites if it is turned on and actually switched algorithms to catch any cluster-wide compression changes
compressionType, CompressionOk := changedSettingsMap[metadata.CompressionTypeKey]
if CompressionOk && (base.GetCompressionType(compressionType.(int)) != base.CompressionTypeNone) &&
base.GetCompressionType(oldCompressionType) != base.GetCompressionType(compressionType.(int)) {
validateRoutineErrorMap, validateErr := ReplicationSpecService().ValidateReplicationSettings(replSpecificFields.SourceBucketName,
replSpecificFields.RemoteClusterName, replSpecificFields.TargetBucketName, settings)
if len(validateRoutineErrorMap) > 0 {
return validateRoutineErrorMap, nil
} else if validateErr != nil {
return nil, validateErr
}
}
// If compression is SNAPPY and is not changed, take this oppurtunity to change it to AUTO
if oldCompressionType == base.CompressionTypeSnappy && !CompressionOk {
changedSettingsMap[metadata.CompressionTypeKey] = base.CompressionTypeAuto
}
if len(errorMap) != 0 {
return errorMap, nil
}
// If nonfilter-settings invoked this change, take this opportunity to fix stale infos if there is an existing expression present
if !filterSettingsChanged(changedSettingsMap, filterExpression) && len(filterExpression) > 0 && filterVersion < base.FilterVersionAdvanced {
settings[metadata.FilterVersionKey] = base.FilterVersionAdvanced
_, errorMap = replSpec.Settings.UpdateSettingsFromMap(settings)
if len(errorMap) != 0 {
return errorMap, fmt.Errorf("Internal XDCR Error related to internal filter management: %v", errorMap)
}
internalChangesTookPlace = true
}
if len(changedSettingsMap) != 0 {
err = ReplicationSpecService().SetReplicationSpec(replSpec)
if err != nil {
return nil, err
}
logger_rm.Infof("Updated replication settings for replication %v\n", topic)
go writeUpdateReplicationSettingsEvent(replSpec, &changedSettingsMap, realUserId, ips)
// if the active flag has been changed, log Pause/ResumeReplication event
active, ok := changedSettingsMap[metadata.ActiveKey]
if ok {
if active.(bool) {
go writeGenericReplicationEvent(service_def.ResumeReplicationEventId, replSpec, realUserId, ips)
} else {
go writeGenericReplicationEvent(service_def.PauseReplicationEventId, replSpec, realUserId, ips)
}
}
logger_rm.Infof("Done with replication settings auditing for replication %v\n", topic)
} else if internalChangesTookPlace {
err = ReplicationSpecService().SetReplicationSpec(replSpec)
if err != nil {
return nil, err
}
logger_rm.Infof("Internally updated replication settings for replication %v\n", topic)
} else {
logger_rm.Infof("Did not update replication settings for replication %v since there are no real changes", topic)
}
return nil, nil
}
// get statistics for all running replications
//% returns a list of replication stats for the bucket. the format for each
//% item in the list is:
//% {ReplicationDocId, & the settings doc id for this replication
//% [{changes_left, Integer}, % amount of work remaining
//% {docs_checked, Integer}, % total number of docs checked on target, survives restarts
//% {docs_written, Integer}, % total number of docs written to target, survives restarts
//% ...
//% ]
//% }
func GetStatistics(bucket string) (*expvar.Map, error) {
repIds := replication_mgr.pipelineMgr.AllReplicationsForBucket(bucket)
logger_rm.Debugf("repIds=%v\n", repIds)
stats := new(expvar.Map).Init()
for _, repId := range repIds {
statsForPipeline := pipeline_svc.GetStatisticsForPipeline(repId)
for i, oneStats := range statsForPipeline {
if oneStats == nil {
continue
}
fullReplicationId := common.ComposeFullTopic(repId, common.PipelineType(i))
stats.Set(fullReplicationId, oneStats)
}
}
logger_rm.Debugf("stats=%v\n", stats.String())
return stats, nil
}
func GetAllStatistics() (*expvar.Map, error) {
repIds := replication_mgr.pipelineMgr.AllReplications()
stats := new(expvar.Map).Init()
for _, repId := range repIds {
statsForPipeline := pipeline_svc.GetStatisticsForPipeline(repId)
for i, oneStats := range statsForPipeline {
if oneStats == nil {
continue
}
fullReplicationId := common.ComposeFullTopic(repId, common.PipelineType(i))
stats.Set(fullReplicationId, oneStats)
}
}
return stats, nil
}
//create and persist the replication specification
func (rm *replicationManager) createAndPersistReplicationSpec(justValidate bool, sourceBucket, targetCluster, targetBucket string, settings metadata.ReplicationSettingsMap) (*metadata.ReplicationSpecification, map[string]error, error, []string) {
logger_rm.Infof("Creating replication spec - justValidate=%v, sourceBucket=%s, targetCluster=%s, targetBucket=%s, settings=%v\n",
justValidate, sourceBucket, targetCluster, targetBucket, settings.CloneAndRedact())
// validate that everything is alright with the replication configuration before actually creating it
sourceBucketUUID, targetBucketUUID, targetClusterRef, errorMap, err, warnings := replication_mgr.repl_spec_svc.ValidateNewReplicationSpec(sourceBucket, targetCluster, targetBucket, settings)
if err != nil || len(errorMap) > 0 {
return nil, errorMap, err, nil
}
spec, err := metadata.NewReplicationSpecification(sourceBucket, sourceBucketUUID, targetClusterRef.Uuid(), targetBucket, targetBucketUUID)
if err != nil {
return nil, nil, err, nil
}
replSettings, err := ReplicationSettingsService().GetDefaultReplicationSettings()
if err != nil {
return nil, nil, err, nil
}
// default isCapi to false if replication type is not explicitly specified in settings
isCapi := false
for key, value := range settings {
if key == metadata.ReplicationTypeKey {
isCapi = (value == metadata.ReplicationTypeCapi)
break
}
}
if isCapi {
// for capi replication, ensure that bandwith limit is 0 regardless of the default setting
replSettings.BandwidthLimit = 0
}
_, errorMap = replSettings.UpdateSettingsFromMap(settings)
if len(errorMap) != 0 {
return nil, errorMap, nil, nil
}
spec.Settings = replSettings
if justValidate {
return spec, nil, nil, warnings
}
//persist it
err = replication_mgr.repl_spec_svc.AddReplicationSpec(spec, base.FlattenStringArray(warnings))
if err == nil {
logger_rm.Infof("Success adding replication specification %s\n", spec.Id)
return spec, nil, nil, warnings
} else {
logger_rm.Errorf("Error adding replication specification %s. err=%v\n", spec.Id, err)
return nil, nil, err, nil
}
}
/**
* Certain errors are still considered errors but should not be raised to the UI level.
* Returns true if the error is to be hidden from the web GUI.
*/
func bypassUIErrorCodes(errStr string) bool {
if strings.Contains(errStr, base.ErrorNoSourceNozzle.Error()) {
return true
} else if strings.Contains(errStr, base.ErrorMasterNegativeIndex.Error()) {
return true
}
return false
}
func processErrorMsgForUI(errStr string) string {
// For pipeline start timeouts, return a more friendly error msg
if (strings.Contains(errStr, pipeline.PipelineContextStart) || strings.Contains(errStr, pipeline.PipelinePartStart)) &&
strings.Contains(errStr, base.ErrorExecutionTimedOut.Error()) {
errStr = base.ErrorPipelineStartTimedOutUI.Error()
}
//prepend current node name, if not empty, to the error message to make it more helpful
cur_node, err := XDCRCompTopologyService().MyHost()
if err != nil {
cur_node = ""
}
if cur_node != "" {
errStr = cur_node + ":" + errStr
}
return errStr
}
// get info of all running replications - serves back to consumers who call the REST end point, i.e. UI
func GetReplicationInfos() ([]base.ReplicationInfo, error) {
combinedRepls := make([]base.ReplicationInfo, 0)
replIds := replication_mgr.pipelineMgr.AllReplications()
for _, replId := range replIds {
var replInfos []base.ReplicationInfo
rep_status, _ := replication_mgr.pipelineMgr.ReplicationStatus(replId)
if rep_status != nil {
replInfos = populateReplInfos(replId, rep_status)
}
// set maxVBReps stats to 0 when replication has never been run or has been paused to ensure that ns_server gets the correct replication status
if rep_status == nil || rep_status.RuntimeStatus(true) == pipeline.Paused {
for _, replInfo := range replInfos {
replInfo.StatsMap[base.MaxVBReps] = 0
}
}
combinedRepls = append(combinedRepls, replInfos...)
}
return combinedRepls, nil
}
func populateReplInfos(replId string, rep_status *pipeline.ReplicationStatus) (replInfos []base.ReplicationInfo) {
// set stats map
expvarMaps := pipeline_svc.GetStatisticsForPipeline(replId)
for i, expvarMap := range expvarMaps {
if expvarMap == nil {
continue
}
fullReplId := common.ComposeFullTopic(replId, common.PipelineType(i))
var brokenMap metadata.CollectionNamespaceMapping
var brokenMapDoneFunc func()
var brokenExternalMap map[string][]string
if rep_status.Pipeline() != nil {
brokenMap, brokenMapDoneFunc = rep_status.Pipeline().GetBrokenMapRO()
brokenExternalMap = brokenMap.ToExternalMap()
}
replInfo := base.ReplicationInfo{
Id: fullReplId,
StatsMap: replication_mgr.utils.GetMapFromExpvarMap(expvarMap),
BrokenCollectionMapping: brokenExternalMap,
ErrorList: make([]base.ErrorInfo, 0),
}
if brokenMapDoneFunc != nil {
brokenMapDoneFunc()
}
validateStatsMap(replInfo.StatsMap)
if common.PipelineType(i) == common.MainPipeline {
// set error list
fillReplInfoWithErr(rep_status, replInfo)
}
replInfos = append(replInfos, replInfo)
}
return replInfos
}
func fillReplInfoWithErr(rep_status *pipeline.ReplicationStatus, replInfo base.ReplicationInfo) {
errs := rep_status.Errors()
if len(errs) == 0 {
return
}
for _, pipeline_error := range errs {
if bypassUIErrorCodes(pipeline_error.ErrMsg) {
continue
}
err_msg := processErrorMsgForUI(pipeline_error.ErrMsg)
errInfo := base.ErrorInfo{pipeline_error.Timestamp.UnixNano(), err_msg}
replInfo.ErrorList = append(replInfo.ErrorList, errInfo)
}
}
func validateStatsMap(statsMap map[string]interface{}) {
missingStats := make([]string, 0)
if _, ok := statsMap[service_def.CHANGES_LEFT_METRIC]; !ok {
missingStats = append(missingStats, service_def.CHANGES_LEFT_METRIC)
}
if len(missingStats) > 0 {
logger_rm.Errorf("Stats missing when constructing replication infos: %v", missingStats)
}
}
//error handler
func (rm *replicationManager) OnError(s common.Supervisor, errMap map[string]error) {
logger_rm.Infof("Supervisor %v of type %v reported errors %v\n", s.Id(), reflect.TypeOf(s), errMap)
if s.Id() == base.ReplicationManagerSupervisorId {
// the errors came from the replication manager supervisor because adminport is not longer alive.
// there is nothing we can do except to abort xdcr. ns_server will restart xdcr while later
exitProcess(false)
} else {
// the errors came from a pipeline supervisor because some parts are not longer alive.
pipeline, err := rm.getPipelineFromPipelineSupevisor(s)
if err == nil {
// try to fix the pipeline
var errMsg string
if len(errMap) == 0 {
// errMap is empty, which should not have happened. use predefined error message
logger_rm.Warnf("Supervisor %v of type %v reported empty error map\n", s.Id(), reflect.TypeOf(s))
errMsg = "pipeline failed"
} else {
errMsg = base.FlattenErrorMap(errMap)
}
// NOTE because we flatten the error map here, any error checked should not be exact match
rm.pipelineMgr.UpdatePipeline(pipeline.Topic(), errors.New(errMsg))
}
}
}
//lauch the repairer for a pipeline
//in asynchronous fashion
func (rm *replicationManager) getPipelineFromPipelineSupevisor(s common.Supervisor) (common.Pipeline, error) {
supervisorId := s.Id()
if strings.HasPrefix(supervisorId, base.PipelineSupervisorIdPrefix) {
pipelineId := supervisorId[len(base.PipelineSupervisorIdPrefix):]
rep_status, _ := rm.pipelineMgr.ReplicationStatus(pipelineId)
if rep_status != nil {
pipeline := rep_status.Pipeline()
if pipeline != nil {
return pipeline, nil
} else {
// should never get here
return nil, errors.New(fmt.Sprintf("Internal error. Pipeline, %v, is not found", pipelineId))
}
} else {
logger_rm.Errorf("Replication %v no longer exists", pipelineId)
return nil, errors.New(fmt.Sprintf("Internal error. Replication %v, is not found", pipelineId))
}
} else {
// should never get here
return nil, errors.New(fmt.Sprintf("Internal error. Supervisor, %v, is not a pipeline supervisor.", supervisorId))
}
}
func validatePipelineExists(topic, action string, exist bool) error {
_, err := replication_mgr.repl_spec_svc.ReplicationSpec(topic)
pipelineExist := (err == nil)
if pipelineExist != exist {
state := "already exists"
if exist {
state = "does not exist"
}
return errors.New(fmt.Sprintf("Error %v replication with id, %v, since it %v.\n", action, topic, state))
}
return nil
}
// ns_server shutdown protocol: poll stdin and exit upon reciept of EOF
func pollStdin() {
reader := bufio.NewReader(os.Stdin)
logger_rm.Infof("pollEOF: About to start stdin polling")
for {
ch, err := reader.ReadByte()
logger_rm.Infof("received byte %v\n", ch)