/
xdcrbasetests.py
1454 lines (1299 loc) · 75.3 KB
/
xdcrbasetests.py
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
import sys
import time
import datetime
import unittest
import logger
import logging
import copy
import string
import random
from threading import Thread
from membase.api.rest_client import RestConnection, Bucket
from couchbase_helper.cluster import Cluster
from couchbase_helper.document import View
from TestInput import TestInputSingleton
from membase.helper.bucket_helper import BucketOperationHelper
from membase.helper.cluster_helper import ClusterOperationHelper
from memcached.helper.data_helper import MemcachedClientHelper
from remote.remote_util import RemoteMachineShellConnection
from remote.remote_util import RemoteUtilHelper
from couchbase_helper.stats_tools import StatsCommon
from scripts.collect_server_info import cbcollectRunner
from tasks.future import TimeoutError
from memcached.helper.kvstore import Synchronized
from couchbase_helper.documentgenerator import BlobGenerator
from membase.api.exception import ServerUnavailableException, XDCRException
from testconstants import STANDARD_BUCKET_PORT
#===============================================================================
# class: XDCRConstants
# Constants used in XDCR application testing. It includes input parameters as well
# as internal constants used in the code.
# All string literals used in the XDCR code shall be defined in this class.
#===============================================================================
class XDCRConstants:
INPUT_PARAM_REPLICATION_DIRECTION = "rdirection"
INPUT_PARAM_CLUSTER_TOPOLOGY = "ctopology"
INPUT_PARAM_SEED_DATA = "sdata"
INPUT_PARAM_SEED_DATA_MODE = "sdata_mode"
INPUT_PARAM_SEED_DATA_OPERATION = "sdata_op"
INPUT_PARAM_POLL_INTERVAL = "poll_interval" # in seconds
INPUT_PARAM_POLL_TIMEOUT = "poll_timeout" # in seconds
# CLUSTER_TOPOLOGY_TYPE_LINE = "line"
CLUSTER_TOPOLOGY_TYPE_CHAIN = "chain"
CLUSTER_TOPOLOGY_TYPE_STAR = "star"
CLUSTER_TOPOLOGY_TYPE_RING = "ring"
REPLICATION_TYPE_CONTINUOUS = "continuous"
REPLICATION_DIRECTION_UNIDIRECTION = "unidirection"
REPLICATION_DIRECTION_BIDIRECTION = "bidirection"
SEED_DATA_MODE_SYNC = "sync"
#===============================================================================
# class: XDCRBaseTest
# This class is the base class (super class) for all the test classes written
# for XDCR. It configures the cluster as defined in the <cluster-file>.ini
# passed as an command line argument "-i" while running the test using testrunner.
# The child classes can override the following methods if required.
# - init_parameters_extended
# - setup_extendedself._input.param(XDCRConstants.INPUT_PARAM_REPLICATION_DIRECTION,
# - teardown_extended
# The reason for providing extended functions is so that inheriting classes can take advantage of
# clean_broken _setup in case an exception comes during test setUp.
# Note:B
# It assumes that the each node is physically up and running.
# In ini file , the cluster name should start with "cluster" (prefix).
#===============================================================================
class XDCRBaseTest(unittest.TestCase):
def setUp(self):
try:
self.log = logger.Logger.get_logger()
self._input = TestInputSingleton.input
if self._input.param("log_level", None):
self.log.setLevel(level=0)
for hd in self.log.handlers:
if str(hd.__class__).find('FileHandler') != -1:
hd.setLevel(level=logging.DEBUG)
else:
hd.setLevel(level=getattr(logging, self._input.param("log_level", None)))
self._init_parameters()
if not hasattr(self, 'cluster'):
self.cluster = Cluster()
# REPLICATION RATE STATS
self._local_replication_rate = {}
self._xdc_replication_ops = {}
self._xdc_replication_rate = {}
self._start_replication_time = {}
self.log.info("============== XDCRbasetests setup is started for test #{0} {1}=============="\
.format(self.case_number, self._testMethodName))
if not self._input.param("skip_cleanup", False) and str(self.__class__).find('upgradeXDCR') == -1:
self._cleanup_previous_setup()
self._init_clusters(self._disabled_consistent_view)
# XDCR global settings
# Set this by default to 1 for all tests
self.set_xdcr_param('xdcrFailureRestartInterval', 1)
if self._checkpoint_interval:
self.set_xdcr_param('xdcrCheckpointInterval', self._checkpoint_interval)
self._optimistic_xdcr_threshold = self._input.param("optimistic_xdcr_threshold", 256)
if self.src_master.ip != self.dest_master.ip: # Only if it's not a cluster_run
if self._optimistic_xdcr_threshold != 256:
self.set_xdcr_param('xdcrOptimisticReplicationThreshold', self._optimistic_xdcr_threshold)
self.setup_extended()
self.log.info("============== XDCRbasetests setup is finished for test #{0} {1} =============="\
.format(self.case_number, self._testMethodName))
# # THREADS FOR STATS KEEPING
self.__stats_threads = []
if str(self.__class__).find('upgradeXDCR') == -1 and \
str(self.__class__).find('tuq_xdcr') == -1 and self.print_stats:
self.__stats_threads.append(Thread(target=self._replication_stat_keeper, args=["replication_data_replicated", self.src_master]))
self.__stats_threads.append(Thread(target=self._replication_stat_keeper, args=["xdc_ops", self.dest_master]))
self.__stats_threads.append(Thread(target=self._replication_stat_keeper, args=["data_replicated", self.src_master]))
if self._replication_direction_str == XDCRConstants.REPLICATION_DIRECTION_BIDIRECTION:
self.__stats_threads.append(Thread(target=self._replication_stat_keeper, args=["replication_data_replicated", self.dest_master]))
self.__stats_threads.append(Thread(target=self._replication_stat_keeper, args=["xdc_ops", self.src_master]))
self.__stats_threads.append(Thread(target=self._replication_stat_keeper, args=["data_replicated", self.dest_master]))
[st_thread.setDaemon(True) for st_thread in self.__stats_threads]
[st_thread.start() for st_thread in self.__stats_threads]
self._log_start(self)
except Exception as e:
self.log.error(e.message)
self.log.error("Error while setting up clusters: %s", sys.exc_info())
self._cleanup_broken_setup()
raise
def tearDown(self):
try:
test_failed = (hasattr(self, '_resultForDoCleanups') and len(self._resultForDoCleanups.failures or self._resultForDoCleanups.errors)) \
or (hasattr(self, '_exc_info') and self._exc_info()[1] is not None)
self._end_replication_flag = 1
if str(self.__class__).find('tuq_xdcr') != -1:
self._do_cleanup()
return
# Grab cbcollect before we cleanup
if test_failed and TestInputSingleton.input.param("get-cbcollect-info", False):
self.__get_cbcollect_info()
cluster_run = len(set([server.ip for server in self._servers])) == 1
if test_failed and not cluster_run and self.collect_data_files:
self.__collect_data_files()
if test_failed and (str(self.__class__).find('upgradeXDCR') != -1 or TestInputSingleton.input.param("stop-on-failure", False)):
self.log.warn("CLEANUP WAS SKIPPED")
return
if self.print_stats:
self.log.info("============== XDCRbasetests stats for test #{0} {1} =============="\
.format(self.case_number, self._testMethodName))
[st_thread.join() for st_thread in self.__stats_threads]
self.log.info("Type of run: %s XDCR" % XDCRConstants.REPLICATION_DIRECTION_BIDIRECTION.upper())
self._print_stats(self.src_master)
if self._replication_direction_str == XDCRConstants.REPLICATION_DIRECTION_BIDIRECTION:
self._print_stats(self.dest_master)
self.log.info("============== = = = = = = = = END = = = = = = = = = = ==============")
self.log.info("============== XDCRbasetests cleanup is started for test #{0} {1} =============="\
.format(self.case_number, self._testMethodName))
self.teardown_extended()
self._do_cleanup()
self.log.info("============== XDCRbasetests cleanup is finished for test #{0} {1} =============="\
.format(self.case_number, self._testMethodName))
finally:
self.cluster.shutdown(force=True)
self._log_finish(self)
def __get_cbcollect_info(self):
self.cluster.shutdown(force=True)
self._log_finish(self)
path = self._input.param("logs_folder", "/tmp")
for server in self.src_nodes + self.dest_nodes:
print "grabbing cbcollect from {0}".format(server.ip)
path = path or "."
try:
cbcollectRunner(server, path).run()
TestInputSingleton.input.test_params["get-cbcollect-info"] = False
except:
print "IMPOSSIBLE TO GRAB CBCOLLECT FROM {0}".format(server.ip)
def __collect_data_files(self):
self.cluster.shutdown(force=True)
self._log_finish(self)
logs_folder = self._input.param("logs_folder", "/tmp")
from scripts import collect_data_files
nodes = self.src_nodes + self.dest_nodes
for server in nodes:
collect_data_files.cbdatacollectRunner(server, logs_folder).run()
def _print_stats(self, node):
if node == self.src_master:
node1 = self.dest_master
else:
node1 = self.src_master
self.log.info("STATS with source at {0} and destination at {1}".format(node.ip, node1.ip))
for the_bucket in self._get_cluster_buckets(node):
self.log.info("Bucket: {0}".format(the_bucket.name))
if node in self._local_replication_rate:
if the_bucket.name in self._local_replication_rate[node]:
if self._local_replication_rate[node][the_bucket.name] is not None:
_sum_ = 0
for _i in self._local_replication_rate[node][the_bucket.name]:
_sum_ += _i
self.log.info("\tAverage local replica creation rate for bucket '{0}': {1} KB per second"\
.format(the_bucket.name, (float)(_sum_) / (len(self._local_replication_rate[node][the_bucket.name]) * 1000)))
if node1 in self._xdc_replication_ops:
if the_bucket.name in self._xdc_replication_ops[node1]:
if self._xdc_replication_ops[node1][the_bucket.name] is not None:
_sum_ = 0
for _i in self._xdc_replication_ops[node1][the_bucket.name]:
_sum_ += _i
self._xdc_replication_ops[node1][the_bucket.name].sort()
_mid = len(self._xdc_replication_ops[node1][the_bucket.name]) / 2
if len(self._xdc_replication_ops[node1][the_bucket.name]) % 2 == 0:
_median_value_ = (float)(self._xdc_replication_ops[node1][the_bucket.name][_mid] +
self._xdc_replication_ops[node1][the_bucket.name][_mid - 1]) / 2
else:
_median_value_ = self._xdc_replication_ops[node1][the_bucket.name][_mid]
self.log.info("\tMedian XDC replication ops for bucket '{0}': {1} K ops per second"\
.format(the_bucket.name, (float)(_median_value_) / 1000))
self.log.info("\tMean XDC replication ops for bucket '{0}': {1} K ops per second"\
.format(the_bucket.name, (float)(_sum_) / (len(self._xdc_replication_ops[node1][the_bucket.name]) * 1000)))
if node in self._xdc_replication_rate:
if the_bucket.name in self._xdc_replication_rate[node]:
if self._xdc_replication_rate[node][the_bucket.name] is not None:
_sum_ = 0
for _i in self._xdc_replication_rate[node][the_bucket.name]:
_sum_ += _i
self.log.info("\tAverage XDCR data replication rate for bucket '{0}': {1} KB per second"\
.format(the_bucket.name, (float)(_sum_) / (len(self._xdc_replication_rate[node][the_bucket.name]) * 1000)))
def _cleanup_previous_setup(self):
self.teardown_extended()
self._do_cleanup()
def _init_parameters(self):
self.log.info("Initializing input parameters started...")
self._clusters_dic = self._input.clusters # clusters is declared as dic in TestInput which is unordered.
self._clusters_keys_olst = range(
len(self._clusters_dic)) # clusters are populated in the dic in testrunner such that ordinal is the key.
# orderedDic cannot be used in order to maintain the compatibility with python 2.6
self._cluster_counter_temp_int = 0
self._cluster_names_dic = self._get_cluster_names()
self._servers = self._input.servers
self._disabled_consistent_view = self._input.param("disabled_consistent_view", None)
self._floating_servers_set = self._get_floating_servers() # These are the servers defined in .ini file but not linked to any cluster.
self._cluster_counter_temp_int = 0 # TODO: fix the testrunner code to pass cluster name in params.
self.buckets = []
# max items number to verify in ValidateDataTask, None - verify all
self.max_verify = self._input.param("max_verify", None)
self._checkpoint_interval = self._input.param("checkpoint_interval", 1800)
self._default_bucket = self._input.param("default_bucket", True)
self._end_replication_flag = self._input.param("end_replication_flag", 0)
"""
ENTER: sasl_buckets=[no.] or standard_buckets=[no.]
"""
self._standard_buckets = self._input.param("standard_buckets", 0)
self._sasl_buckets = self._input.param("sasl_buckets", 0)
self._extra_buckets = self._input.param("extra_buckets", 0) # number of buckets to add inside test body
if self._default_bucket:
self.default_bucket_name = "default"
self._num_replicas = self._input.param("replicas", 1)
self._mem_quota_int = 0 # will be set in subsequent methods
self.eviction_policy = self._input.param("eviction_policy", 'valueOnly') # or 'fullEviction'
self.mixed_priority = self._input.param("mixed_priority", None)
# if mixed priority is set by user, set high priority for sasl and standard buckets
if self.mixed_priority:
self.bucket_priority = 'high'
else:
self.bucket_priority = None
self.num_items = self._input.param("items", 1000)
self._value_size = self._input.param("value_size", 256)
self._dgm_run = self._input.param("dgm_run", False)
self.active_resident_threshold = int(self._input.param("active_resident_threshold", 0))
self.rep_type = self._input.param("replication_type", "xmem")
self._poll_interval = self._input.param(XDCRConstants.INPUT_PARAM_POLL_INTERVAL, 5)
self._poll_timeout = self._input.param(XDCRConstants.INPUT_PARAM_POLL_TIMEOUT, 120)
self.init_parameters_extended()
self._doc_ops = self._input.param("doc-ops", "None")
if self._doc_ops is not None:
self._doc_ops = self._doc_ops.split("-")
self._doc_ops_dest = self._input.param("doc-ops-dest", "None")
# semi-colon separator is not accepted for some reason here
if self._doc_ops_dest is not None:
self._doc_ops_dest = self._doc_ops_dest.split("-")
self.case_number = self._input.param("case_number", 0)
self._expires = self._input.param("expires", 0)
self.wait_timeout = self._input.param("timeout", 60)
self._percent_update = self._input.param("upd", 30)
self._percent_delete = self._input.param("del", 30)
self._warmup = self._input.param("warm", None)
self._failover = self._input.param("failover", None)
self._graceful = self._input.param("graceful", False)
self._demand_encryption = self._input.param("demand_encryption", 0)
self._rebalance = self._input.param("rebalance", None)
self._use_hostanames = self._input.param("use_hostnames", False)
self.print_stats = self._input.param("print_stats", False)
self._wait_for_expiration = self._input.param("wait_for_expiration", False)
self.collect_data_files = False
if self._warmup is not None:
self._warmup = self._warmup.split("-")
if self._failover is not None:
self._failover = self._failover.split("-")
if self._rebalance is not None:
self._rebalance = self._rebalance.split("-")
self._num_rebalance = self._input.param("num_rebalance", 1)
"""
CREATE's a set of items,
UPDATE's UPD% of the items starting from 0,
DELETE's DEL% of the items starting from the end (count(items)).
"""
self.gen_create = BlobGenerator('loadOne', 'loadOne', self._value_size, end=self.num_items)
self.gen_delete = BlobGenerator('loadOne', 'loadOne-', self._value_size,
start=int((self.num_items) * (float)(100 - self._percent_delete) / 100), end=self.num_items)
self.gen_update = BlobGenerator('loadOne', 'loadOne-', self._value_size, start=0,
end=int(self.num_items * (float)(self._percent_update) / 100))
self.gen_append = BlobGenerator('loadOne', 'loadOne', self._value_size, end=self.num_items)
self.ord_keys = self._clusters_keys_olst
self.ord_keys_len = len(self.ord_keys)
self.src_nodes = copy.copy(self._clusters_dic[0])
self.dest_nodes = copy.copy(self._clusters_dic[1])
if int(self.src_nodes[0].port) in xrange(9091, 9991):
temp = self.dest_nodes
self.dest_nodes = self.src_nodes
self.src_nodes = temp
self.src_master = self.src_nodes[0]
self.dest_master = self.dest_nodes[0]
self._defaul_map_func = "function (doc) {\n emit(doc._id, doc);\n}"
self._default_view_name = "default_view"
self._default_view = View(self._default_view_name, self._defaul_map_func, None)
self._num_views = self._input.param("num_views", 5)
self._is_dev_ddoc = self._input.param("is_dev_ddoc", True)
self.fragmentation_value = self._input.param("fragmentation_value", 80)
self.disable_src_comp = self._input.param("disable_src_comp", True)
self.disable_dest_comp = self._input.param("disable_dest_comp", True)
self.log.info("Initializing input parameters completed.")
@staticmethod
def _log_start(self):
try:
msg = "{0} : {1} started ".format(datetime.datetime.now(), self._testMethodName)
RestConnection(self.src_master[0]).log_client_error(msg)
RestConnection(self.dest_master[0]).log_client_error(msg)
except:
pass
@staticmethod
def _log_finish(self):
try:
msg = "{0} : {1} finished ".format(datetime.datetime.now(), self._testMethodName)
RestConnection(self.src_master[0]).log_client_error(msg)
RestConnection(self.dest_master[0]).log_client_error(msg)
except:
pass
def sleep(self, timeout=1, message=""):
self.log.info("sleep for {0} secs. {1} ...".format(timeout, message))
time.sleep(timeout)
def _replication_stat_keeper(self, arg, node):
while not self._end_replication_flag == 1:
if node in self._clusters_dic[0]:
consider_node = self.src_master
elif node in self._clusters_dic[1]:
consider_node = self.dest_master
if arg == "replication_data_replicated":
rest = RestConnection(consider_node)
for the_bucket in self._get_cluster_buckets(consider_node):
stats = rest.fetch_bucket_stats(bucket=the_bucket.name)["op"]["samples"]
_x_ = stats[arg][-1]
if _x_ > 0:
_y_ = datetime.datetime.now()
if node not in self._local_replication_rate:
self._local_replication_rate[node] = {}
if the_bucket.name not in self._local_replication_rate[node]:
self._local_replication_rate[node][the_bucket.name] = []
self._local_replication_rate[node][the_bucket.name].append((float)(_x_) / (_y_ - self._start_replication_time[the_bucket.name]).seconds)
elif arg == "xdc_ops":
rest = RestConnection(consider_node)
for the_bucket in self._get_cluster_buckets(consider_node):
stats = rest.fetch_bucket_stats(bucket=the_bucket.name)["op"]["samples"]
_x_ = stats[arg][-1]
if _x_ > 0:
if node not in self._xdc_replication_ops:
self._xdc_replication_ops[node] = {}
if the_bucket.name not in self._xdc_replication_ops[node]:
self._xdc_replication_ops[node][the_bucket.name] = []
self._xdc_replication_ops[node][the_bucket.name].append((float)(_x_))
elif arg == "data_replicated":
rest1 = RestConnection(consider_node)
if consider_node == self.src_master:
rest2 = RestConnection(self.dest_master)
else:
rest2 = RestConnection(self.src_master)
dest_uuid = rest2.get_pools_info()["uuid"]
for the_bucket in self._get_cluster_buckets(consider_node):
argument = "{0}/{1}/{2}/{3}/{4}".format("replications", dest_uuid, the_bucket.name, the_bucket.name, arg)
stats = rest1.fetch_bucket_stats(bucket=the_bucket.name)["op"]["samples"]
_x_ = stats[argument][-1]
if _x_ > 0:
_y_ = datetime.datetime.now()
if node not in self._xdc_replication_rate:
self._xdc_replication_rate[node] = {}
if the_bucket.name not in self._xdc_replication_rate[node]:
self._xdc_replication_rate[node][the_bucket.name] = []
self._xdc_replication_rate[node][the_bucket.name].append((float)(_x_) / (_y_ - self._start_replication_time[the_bucket.name]).seconds)
def _get_floating_servers(self):
cluster_nodes = []
floating_servers = copy.copy(self._servers)
for key, node in self._clusters_dic.items():
cluster_nodes.extend(node)
for c_node in cluster_nodes:
for node in floating_servers:
if node.ip in str(c_node) and node.port in str(c_node):
floating_servers.remove(node)
return floating_servers
def _init_clusters(self, disabled_consistent_view=None):
for key in self._clusters_keys_olst:
self._setup_cluster(self._clusters_dic[key], disabled_consistent_view)
# This method shall be overridden in case there are parameters that need to be initialized.
def init_parameters_extended(self):
pass
# This method shall be overridden in case there are custom steps involved during setup.
def setup_extended(self):
pass
# This method shall be overridden in case there are custom steps involved during teardown.
def teardown_extended(self):
pass
def __stop_rebalance(self, nodes):
rest = RestConnection(nodes[0])
if rest._rebalance_progress_status() == 'running':
self.log.warning("rebalancing is still running, test should be verified")
stopped = rest.stop_rebalance()
self.assertTrue(stopped, msg="unable to stop rebalance")
def _do_cleanup(self):
for key in self._clusters_keys_olst:
nodes = self._clusters_dic[key]
self.log.info("cleanup cluster{0}: {1}".format(key + 1, nodes))
self.__stop_rebalance(nodes)
for node in nodes:
BucketOperationHelper.delete_all_buckets_or_assert([node], self)
if self._input.param("forceEject", False) and node not in [self.src_nodes[0], self.dest_nodes[0] ]:
try:
rest = RestConnection(node)
rest.force_eject_node()
except BaseException, e:
self.log.error(e)
else:
ClusterOperationHelper.cleanup_cluster([node], self)
ClusterOperationHelper.wait_for_ns_servers_or_assert([node], self)
def _cleanup_broken_setup(self):
try:
self.tearDown()
except:
self.log.info("Error while cleaning broken setup.")
def _get_cluster_names(self):
cs_names = {}
for key in self._clusters_keys_olst:
cs_names[key] = "cluster{0}".format(self._cluster_counter_temp_int)
self._cluster_counter_temp_int += 1
return cs_names
def _setup_cluster(self, nodes, disabled_consistent_view=None):
self._init_nodes(nodes, disabled_consistent_view)
self.cluster.async_rebalance(nodes, nodes[1:], [], use_hostnames=self._use_hostanames).result()
if str(self.__class__).find('upgradeXDCR') != -1:
self._create_buckets(self, nodes)
else:
self._create_buckets(nodes)
def _init_nodes(self, nodes, disabled_consistent_view=None):
_tasks = []
for node in nodes:
_tasks.append(self.cluster.async_init_node(node, disabled_consistent_view))
for task in _tasks:
mem_quota_node = task.result()
if mem_quota_node < self._mem_quota_int or self._mem_quota_int == 0:
self._mem_quota_int = mem_quota_node
if self._use_hostanames:
if not hasattr(self, 'hostnames'):
self.hostnames = {}
self.hostnames.update(self._rename_nodes(nodes))
def _rename_nodes(self, servers):
hostnames = {}
for server in servers:
shell = RemoteMachineShellConnection(server)
try:
hostname = shell.get_full_hostname()
rest = RestConnection(server)
renamed, content = rest.rename_node(hostname, username=server.rest_username, password=server.rest_password)
self.assertTrue(renamed, "Server %s is not renamed!Hostname %s. Error %s" % (
server, hostname, content))
hostnames[server] = hostname
finally:
shell.disconnect()
for i in xrange(len(servers)):
if servers[i] in hostnames:
if server and server.ip != servers[i].ip:
continue
servers[i].hostname = hostnames[servers[i]]
return hostnames
def _create_sasl_buckets(self, server, num_buckets, server_id, bucket_size):
bucket_tasks = []
for i in range(num_buckets):
name = "sasl_bucket_" + str(i + 1)
bucket_tasks.append(self.cluster.async_create_sasl_bucket(server, name, 'password',
bucket_size, self._num_replicas,
eviction_policy=self.eviction_policy,
bucket_priority=self.bucket_priority))
self.buckets.append(Bucket(name=name, authType="sasl", saslPassword="password",
num_replicas=self._num_replicas, bucket_size=bucket_size,
master_id=server_id, eviction_policy=self.eviction_policy))
for task in bucket_tasks:
task.result(self.wait_timeout * 10)
def _create_standard_buckets(self, server, num_buckets, server_id, bucket_size):
bucket_tasks = []
for i in range(num_buckets):
name = "standard_bucket_" + str(i + 1)
bucket_tasks.append(self.cluster.async_create_standard_bucket(server, name,
STANDARD_BUCKET_PORT + i,
bucket_size,
self._num_replicas,
eviction_policy=self.eviction_policy,
bucket_priority=self.bucket_priority))
self.buckets.append(Bucket(name=name, authType=None, saslPassword=None,
num_replicas=self._num_replicas, bucket_size=bucket_size,
port=STANDARD_BUCKET_PORT + i, master_id=server_id, eviction_policy=self.eviction_policy))
for task in bucket_tasks:
task.result(self.wait_timeout * 10)
def _create_buckets(self, nodes):
if self._dgm_run:
self._mem_quota_int = 256
master_node = nodes[0]
total_buckets = self._sasl_buckets + self._default_bucket + self._standard_buckets + self._extra_buckets
#to enable tests to skip creating buckets in setup and create them later
if not total_buckets:
return
bucket_size = self._get_bucket_size(self._mem_quota_int, total_buckets)
rest = RestConnection(master_node)
master_id = rest.get_nodes_self().id
if len(set([server.ip for server in self._servers])) != 1: # if not cluster run use ip addresses instead of lh
master_id = master_id.replace("127.0.0.1", master_node.ip).replace("localhost", master_node.ip)
self._create_sasl_buckets(master_node, self._sasl_buckets, master_id, bucket_size)
self._create_standard_buckets(master_node, self._standard_buckets, master_id, bucket_size)
if self._default_bucket:
self.cluster.create_default_bucket(master_node, bucket_size, self._num_replicas, eviction_policy=self.eviction_policy)
self.buckets.append(Bucket(name="default", authType="sasl", saslPassword="",
num_replicas=self._num_replicas, bucket_size=bucket_size, master_id=master_id,
eviction_policy=self.eviction_policy))
def _get_bucket_size(self, mem_quota, num_buckets):
#min size is 100MB now
return max(100, int(float(mem_quota) / float(num_buckets)))
def _get_cluster_buckets(self, master_server):
rest = RestConnection(master_server)
master_id = rest.get_nodes_self().id
if master_id.find('es') != 0:
# verify if node_ids were changed for cluster_run
for bucket in self.buckets:
if ("127.0.0.1" in bucket.master_id and "127.0.0.1" not in master_id) or \
("localhost" in bucket.master_id and "localhost" not in master_id):
new_ip = master_id[master_id.index("@") + 1:]
bucket.master_id = bucket.master_id.replace("127.0.0.1", new_ip).\
replace("localhost", new_ip)
if len(set([server.ip for server in self._servers])) != 1: # if not cluster run use ip addresses instead of lh
master_id = master_id.replace("127.0.0.1", master_server.ip).replace("localhost", master_server.ip)
buckets = filter(lambda bucket: bucket.master_id == master_id, self.buckets)
if not buckets:
self.log.warn("No bucket(s) found on the server %s" % master_server)
return buckets
def do_a_warm_up(self, node):
shell = RemoteMachineShellConnection(node)
shell.stop_couchbase()
self.sleep(5)
shell.start_couchbase()
shell.disconnect()
def adding_back_a_node(self, master, server):
rest = RestConnection(master)
nodes = rest.node_statuses()
for node in nodes:
if server.ip == node.ip and int(server.port) == int(node.port):
rest.add_back_node(node.id)
def _get_active_replica_count_from_cluster(self, master):
buckets = self._get_cluster_buckets(master)
for bucket in buckets:
keys_loaded = sum([len(kv_store) for kv_store in bucket.kvs.values() if kv_store is not None])
self.log.info("Keys loaded into bucket {0}:{1}".format(bucket.name,
keys_loaded))
self.log.info("Stat: vb_active_curr_items = {0}".
format(MemcachedClientHelper.direct_client(master,
bucket.name).stats()['vb_active_curr_items']))
self.log.info("Stat: vb_replica_curr_items = {0}".
format(MemcachedClientHelper.direct_client(master,
bucket.name).stats()['vb_replica_curr_items']))
def _async_failover(self, nodes, failover_nodes):
self.log.info("Printing pre-failover stats")
self._get_active_replica_count_from_cluster(nodes[0])
tasks = []
tasks.append(self.cluster.async_failover(nodes, failover_nodes, graceful=self._graceful))
return tasks
def _async_rebalance(self, nodes, to_add_node, to_remove_node):
tasks = []
tasks.append(self.cluster.async_rebalance(nodes, to_add_node, to_remove_node))
return tasks
# Change the master_id of buckets to new master node
def __change_masterid_buckets(self, new_master, buckets):
new_master_id = RestConnection(new_master).get_nodes_self().id
for bucket in buckets:
bucket.master_id = new_master_id
# Initiates a rebalance-out asynchronously on both clusters
def _async_rebalance_out(self, master=False):
tasks = []
if "source" in self._rebalance and self._num_rebalance < len(self.src_nodes):
src_buckets = self._get_cluster_buckets(self.src_master)
tasks += self.__async_rebalance_out_cluster(self.src_nodes, self.src_master, master=master)
if master:
self.src_master = self.src_nodes[0]
self.__change_masterid_buckets(self.src_master, src_buckets)
if "destination" in self._rebalance and self._num_rebalance < len(self.dest_nodes):
dest_buckets = self._get_cluster_buckets(self.dest_master)
tasks += self.__async_rebalance_out_cluster(self.dest_nodes, self.dest_master, master=master, cluster_type="source")
if master:
self.dest_master = self.dest_nodes[0]
self.__change_masterid_buckets(self.dest_master, dest_buckets)
return tasks
def __async_rebalance_out_cluster(self, cluster_nodes, master_node, master=False, cluster_type="source"):
remove_nodes = []
if master:
remove_nodes = [master_node]
else:
remove_nodes = cluster_nodes[len(cluster_nodes) - self._num_rebalance:]
if self._failover and cluster_type in self._failover:
tasks = self._async_failover(cluster_nodes, remove_nodes)
for task in tasks:
task.result()
tasks = self._async_rebalance(cluster_nodes, [], remove_nodes)
remove_node_ips = [remove_node.ip for remove_node in remove_nodes]
self.log.info(" Starting rebalance-out nodes:{0} at {1} cluster {2}".
format(remove_node_ips, cluster_type, master_node.ip))
map(cluster_nodes.remove, remove_nodes)
return tasks
# Initiates a rebalance-in asynchronously on both clusters
def _async_rebalance_in(self):
tasks = []
if "source" in self._rebalance:
tasks += self.__async_rebalance_in_cluster(self.src_nodes, self.src_master)
if "destination" in self._rebalance:
tasks += self.__async_rebalance_in_cluster(self.dest_nodes, self.dest_master, cluster_type="destination")
return tasks
def __async_rebalance_in_cluster(self, cluster_nodes, master_node, cluster_type="source"):
add_nodes = self._floating_servers_set[0:self._num_rebalance]
map(self._floating_servers_set.remove, add_nodes)
tasks = self._async_rebalance(cluster_nodes, add_nodes, [])
add_nodes_ips = [node.ip for node in add_nodes]
self.log.info(" Starting rebalance-in nodes:{0} at {1} cluster {2}".
format(add_nodes_ips, cluster_type, master_node.ip))
map(cluster_nodes.append, add_nodes)
return tasks
# Initiates a swap-rebalance asynchronously on both clusters
def _async_swap_rebalance(self, master=False):
tasks = []
if "source" in self._rebalance and self._num_rebalance < len(self.src_nodes):
src_buckets = self._get_cluster_buckets(self.src_master)
tasks += self.__async_swap_rebalance_cluster(self.src_nodes, self.src_master, master=master)
if master:
self.src_master = self.src_nodes[0]
self.__change_masterid_buckets(self.src_master, src_buckets)
if "destination" in self._rebalance and self._num_rebalance < len(self.dest_nodes):
dest_buckets = self._get_cluster_buckets(self.dest_master)
tasks += self.__async_swap_rebalance_cluster(self.dest_nodes, self.dest_master, master=master, cluster_type="destination")
if master:
self.dest_master = self.dest_nodes[0]
self.__change_masterid_buckets(self.dest_master, dest_buckets)
return tasks
def __async_swap_rebalance_cluster(self, cluster_nodes, master_node, master=False, cluster_type="source"):
add_node = self._floating_servers_set.pop()
if master:
remove_node = master_node
else:
remove_node = cluster_nodes[len(cluster_nodes) - 1]
tasks = self._async_rebalance(cluster_nodes, [add_node], [remove_node])
self.log.info(" Starting swap-rebalance [remove_node:{0}] -> [add_node:{1}] at {2} cluster {3}"
.format(remove_node.ip, add_node.ip, cluster_type, master_node.ip))
cluster_nodes.remove(remove_node)
cluster_nodes.append(add_node)
return tasks
def get_servers_in_cluster(self, member):
nodes = [node for node in RestConnection(member).get_nodes()]
servers = []
cluster_run = len(set([server.ip for server in self._servers])) == 1
for server in self._servers:
for node in nodes:
if ((server.hostname if server.hostname else server.ip) == str(node.ip) or cluster_run)\
and server.port == str(node.port):
servers.append(server)
return servers
def wait_warmup_completed(self, warmupnodes, bucket_names=["default"]):
if isinstance(bucket_names, str):
bucket_names = [bucket_names]
for server in warmupnodes:
for bucket in bucket_names:
mc = MemcachedClientHelper.direct_client(server, bucket)
start = time.time()
while time.time() - start < 150:
if mc.stats()["ep_warmup_thread"] == "complete":
self.log.info("Warmed up: %s items " % (mc.stats()["curr_items_tot"]))
self.sleep(10)
break
elif mc.stats()["ep_warmup_thread"] == "running":
self.log.info(
"Still warming up .. curr_items_tot : %s" % (mc.stats()["curr_items_tot"]))
continue
else:
self.log.info("Value of ep_warmup_thread does not exist, exiting from this server")
break
if mc.stats()["ep_warmup_thread"] == "running":
self.log.info("ERROR: ep_warmup_thread's status not complete")
mc.close
def wait_node_restarted(self, server, wait_time=120, wait_if_warmup=False, check_service=False):
now = time.time()
if check_service:
self.wait_service_started(server, wait_time)
wait_time = now + wait_time - time.time()
num = 0
while num < wait_time / 10:
try:
ClusterOperationHelper.wait_for_ns_servers_or_assert(
[server], self, wait_time=wait_time - num * 10, wait_if_warmup=wait_if_warmup)
break
except ServerUnavailableException:
num += 1
self.sleep(10)
def wait_service_started(self, server, wait_time=120):
shell = RemoteMachineShellConnection(server)
os_type = shell.extract_remote_info().distribution_type
if os_type.lower() == 'windows':
cmd = "sc query CouchbaseServer | grep STATE"
else:
cmd = "service couchbase-server status"
now = time.time()
while time.time() - now < wait_time:
output, error = shell.execute_command(cmd)
if str(output).lower().find("running") != -1:
self.log.info("Couchbase service is running")
return
self.sleep(10, "couchbase service is not running")
self.fail("Couchbase service is not running after {0} seconds".format(wait_time))
def _enable_firewall(self, server):
is_bidirectional = self._replication_direction_str == "bidirection"
RemoteUtilHelper.enable_firewall(server, bidirectional=is_bidirectional, xdcr=True)
def _disable_firewall(self, server):
shell = RemoteMachineShellConnection(server)
o, r = shell.execute_command("iptables -F")
shell.log_command_output(o, r)
o, r = shell.execute_command("/sbin/iptables -A INPUT -p tcp -i eth0 --dport 1000:65535 -j ACCEPT")
shell.log_command_output(o, r)
if self._replication_direction_str == "bidirection":
o, r = shell.execute_command("/sbin/iptables -A OUTPUT -p tcp -o eth0 --dport 1000:65535 -j ACCEPT")
shell.log_command_output(o, r)
o, r = shell.execute_command("/sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT")
shell.log_command_output(o, r)
self.log.info("enabled firewall on {0}".format(server))
o, r = shell.execute_command("/sbin/iptables --list")
shell.log_command_output(o, r)
shell.disconnect()
""" Reboot node, wait till nodes are warmed up """
def reboot_node(self, node):
self.log.info("Rebooting node '{0}'....".format(node.ip))
shell = RemoteMachineShellConnection(node)
if shell.extract_remote_info().type.lower() == 'windows':
o, r = shell.execute_command("shutdown -r -f -t 0")
elif shell.extract_remote_info().type.lower() == 'linux':
o, r = shell.execute_command("reboot")
shell.log_command_output(o, r)
# wait for restart and warmup on all node
self.sleep(self.wait_timeout * 5)
# disable firewall on these nodes
self._disable_firewall(node)
# wait till node is ready after warmup
ClusterOperationHelper.wait_for_ns_servers_or_assert([node], self, wait_if_warmup=True)
def disable_compaction(self, server=None, bucket="default"):
server = server or self.src_master
new_config = {"viewFragmntThresholdPercentage" : None,
"dbFragmentThresholdPercentage" : None,
"dbFragmentThreshold" : None,
"viewFragmntThreshold" : None}
self.cluster.modify_fragmentation_config(server, new_config, bucket)
def make_default_views(self, prefix, count, is_dev_ddoc=False,):
ref_view = self._default_view
ref_view.name = (prefix, ref_view.name)[prefix is None]
return [View(ref_view.name + str(i), ref_view.map_func, None, is_dev_ddoc) for i in xrange(count)]
def async_create_views(self, server, design_doc_name, views, bucket="default"):
tasks = []
if len(views):
for view in views:
t_ = self.cluster.async_create_view(server, design_doc_name, view, bucket)
tasks.append(t_)
else:
t_ = self.cluster.async_create_view(server, design_doc_name, None, bucket)
tasks.append(t_)
return tasks
def _get_num_items_ratio(self, op_type):
if op_type in ["update", "delete"]:
return self.num_items / 3
else:
return self.num_items
def _load_gen_data(self, cname, node):
for op_type in self._seed_data_ops_lst:
num_items_ratio = self._get_num_items_ratio(op_type)
load_gen = BlobGenerator(cname, cname, self._value_size, end=num_items_ratio)
self.log.info("Starting Load operation '{0}' for items (ratio) '{1}' on node '{2}'....".format(op_type,
num_items_ratio, cname))
if self._seed_data_mode_str == XDCRConstants.SEED_DATA_MODE_SYNC:
self._load_all_buckets(node, load_gen, op_type, 0)
self.log.info("Completed Load of {0}".format(op_type))
else:
self._async_load_all_buckets(node, load_gen, op_type, 0)
self.log.info("Started async Load of {0}".format(op_type))
def _async_load_bucket(self, bucket, server, kv_gen, op_type, exp, kv_store=1, flag=0, only_store_hash=True, batch_size=1000, pause_secs=1, timeout_secs=30):
gen = copy.deepcopy(kv_gen)
task = self.cluster.async_load_gen_docs(server, bucket.name, gen,
bucket.kvs[kv_store], op_type,
exp, flag, only_store_hash,
batch_size, pause_secs, timeout_secs)
return task
def _async_load_all_buckets(self, server, kv_gen, op_type, exp, kv_store=1, flag=0, only_store_hash=True, batch_size=1, pause_secs=1, timeout_secs=30):
tasks = []
buckets = self._get_cluster_buckets(server)
for bucket in buckets:
gen = copy.deepcopy(kv_gen)
tasks.append(self.cluster.async_load_gen_docs(server, bucket.name, gen,
bucket.kvs[kv_store],
op_type, exp, flag, only_store_hash,
batch_size, pause_secs, timeout_secs))
return tasks
def _load_bucket(self, bucket, server, kv_gen, op_type, exp, kv_store=1, flag=0, only_store_hash=True, batch_size=1000, pause_secs=1, timeout_secs=30):
task = self._async_load_bucket(bucket, server, kv_gen, op_type, exp, kv_store, flag, only_store_hash, batch_size, pause_secs, timeout_secs)
task.result()
def key_generator(self, size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for x in range(size))
def _load_all_buckets(self, server, kv_gen, op_type, exp, kv_store=1, flag=0, only_store_hash=True, batch_size=1000, pause_secs=1, timeout_secs=30):
tasks = self._async_load_all_buckets(server, kv_gen, op_type, exp, kv_store, flag, only_store_hash, batch_size, pause_secs, timeout_secs)
for task in tasks:
task.result()
if self.active_resident_threshold:
stats_all_buckets = {}
for bucket in self._get_cluster_buckets(server):
stats_all_buckets[bucket.name] = StatsCommon()
for bucket in self._get_cluster_buckets(server):
threshold_reached = False
while not threshold_reached:
active_resident = stats_all_buckets[bucket.name].get_stats([server], bucket, '', 'vb_active_perc_mem_resident')[server]
if int(active_resident) > self.active_resident_threshold:
self.log.info("resident ratio is %s greater than %s for %s in bucket %s. Continue loading to the cluster" %
(active_resident, self.active_resident_threshold, server.ip, bucket.name))
random_key = self.key_generator()
generate_load = BlobGenerator(random_key, '%s-' % random_key, self._value_size, end=batch_size * 50)
self._load_bucket(bucket, server, generate_load, "create", exp=0, kv_store=1, flag=0, only_store_hash=True, batch_size=batch_size, pause_secs=5, timeout_secs=60)
else:
threshold_reached = True
self.log.info("DGM state achieved for %s in bucket %s!" % (server.ip, bucket.name))
break
def _modify_src_data(self):
"""Setting up creates/updates/deletes at source nodes"""
if self._doc_ops is not None:
if "create" in self._doc_ops:
self._load_all_buckets(self.src_master, self.gen_create, "create", 0)
if "update" in self._doc_ops:
self._load_all_buckets(self.src_master, self.gen_update, "update", self._expires)
if "delete" in self._doc_ops:
self._load_all_buckets(self.src_master, self.gen_delete, "delete", 0)
self._wait_flusher_empty(self.src_master, self.src_nodes)
if self._wait_for_expiration and self._expires:
self.sleep(self._expires, "Waiting for expiration of updated items")
def _async_modify_data(self):
tasks = []
"""Setting up creates/updates/deletes at source nodes"""
if self._doc_ops is not None:
# allows multiple of them but one by one
if "update" in self._doc_ops:
tasks.extend(self._async_load_all_buckets(self.src_master, self.gen_update, "update", self._expires))
if "create" in self._doc_ops:
tasks.extend(self._async_load_all_buckets(self.src_master, self.gen_create, "create", 0))
if "delete" in self._doc_ops:
tasks.extend(self._async_load_all_buckets(self.src_master, self.gen_delete, "delete", 0))
for task in tasks:
task.result()
if self._wait_for_expiration and self._expires:
self.sleep(self._expires, "Waiting for expiration of updated items")
def _async_update_delete_data(self):
self.log.info("The tasks:-")
tasks = []
# Setting up doc-ops at source nodes and doc-ops-dest at destination nodes
if self._doc_ops is not None:
# allows multiple of them but one by one on either of the clusters
if "update" in self._doc_ops:
tasks.extend(self._async_load_all_buckets(self.src_master, self.gen_update, "update", self._expires))
if "delete" in self._doc_ops:
tasks.extend(self._async_load_all_buckets(self.src_master, self.gen_delete, "delete", 0))
self.sleep(self.wait_timeout / 6)
if self._doc_ops_dest is not None:
if "update" in self._doc_ops_dest:
tasks.extend(self._async_load_all_buckets(self.dest_master, self.gen_update2, "update", self._expires))
if "delete" in self._doc_ops_dest:
tasks.extend(self._async_load_all_buckets(self.dest_master, self.gen_delete2, "delete", 0))
self.sleep(self.wait_timeout / 6)
for task in tasks:
task.result()
if self._wait_for_expiration and self._expires:
self.sleep(self._expires, "Waiting for expiration of updated items")
#===============================================================================