/
xdcrnewbasetests.py
4133 lines (3732 loc) · 175 KB
/
xdcrnewbasetests.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 copy
import json
import logging
import random
import re
import time
import unittest
import logger
from collection.collections_rest_client import CollectionsRest
from couchbase_cli import CouchbaseCLI
from couchbase_helper.cluster import Cluster
from couchbase_helper.document import View
from couchbase_helper.documentgenerator import BlobGenerator, DocumentGenerator, SDKDataLoader
from membase.api.exception import ServerUnavailableException
from membase.api.rest_client import RestConnection, Bucket
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 security.auditmain import audit
from security.ntonencryptionBase import ntonencryptionBase
from security.rbac_base import RbacBase
from security.x509_multiple_CA_util import x509main
from testconstants import STANDARD_BUCKET_PORT, WIN_COUCHBASE_LOGS_PATH
from TestInput import TestInputSingleton
from lib.Cb_constants.CBServer import CbServer
from lib.membase.api.exception import XDCRException
from lib.SystemEventLogLib.Events import EventHelper
from lib.SystemEventLogLib.xdcr_events import XDCRServiceEvents
from lib import global_vars
from scripts import collect_data_files
from scripts.collect_server_info import cbcollectRunner
from scripts.java_sdk_setup import JavaSdkSetup
class RenameNodeException(XDCRException):
"""Exception thrown when converting ip to hostname failed
"""
def __init__(self, msg=''):
XDCRException.__init__(self, msg)
class RebalanceNotStopException(XDCRException):
"""Exception thrown when stopping rebalance failed
"""
def __init__(self, msg=''):
XDCRException.__init__(self, msg)
def raise_if(cond, ex):
"""Raise Exception if condition is True
"""
if cond:
raise ex
class TOPOLOGY:
CHAIN = "chain"
STAR = "star"
RING = "ring"
HYBRID = "hybrid"
class REPLICATION_DIRECTION:
UNIDIRECTION = "unidirection"
BIDIRECTION = "bidirection"
class REPLICATION_TYPE:
CONTINUOUS = "continuous"
class REPLICATION_PROTOCOL:
CAPI = "capi"
XMEM = "xmem"
class INPUT:
REPLICATION_DIRECTION = "rdirection"
CLUSTER_TOPOLOGY = "ctopology"
SEED_DATA = "sdata"
SEED_DATA_MODE = "sdata_mode"
SEED_DATA_OPERATION = "sdata_op"
POLL_INTERVAL = "poll_interval" # in seconds
POLL_TIMEOUT = "poll_timeout" # in seconds
SEED_DATA_MODE_SYNC = "sync"
class OPS:
CREATE = "create"
UPDATE = "update"
DELETE = "delete"
APPEND = "append"
class EVICTION_POLICY:
VALUE_ONLY = "valueOnly"
FULL_EVICTION = "fullEviction"
NO_EVICTION = "noEviction"
NRU_EVICTION = "nruEviction"
CB = [VALUE_ONLY, FULL_EVICTION]
EPH = [NO_EVICTION, NRU_EVICTION]
class BUCKET_PRIORITY:
HIGH = "high"
class BUCKET_NAME:
DEFAULT = "default"
class OS:
WINDOWS = "windows"
LINUX = "linux"
OSX = "osx"
class COMMAND:
SHUTDOWN = "shutdown"
REBOOT = "reboot"
class STATE:
RUNNING = "running"
class REPL_PARAM:
FAILURE_RESTART = "failureRestartInterval"
CHECKPOINT_INTERVAL = "checkpointInterval"
OPTIMISTIC_THRESHOLD = "optimisticReplicationThreshold"
FILTER_EXP = "filterExpression"
FILTER_SKIP_RESTREAM = "filterSkipRestream"
SOURCE_NOZZLES = "sourceNozzlePerNode"
TARGET_NOZZLES = "targetNozzlePerNode"
BATCH_COUNT = "workerBatchSize"
BATCH_SIZE = "docBatchSizeKb"
LOG_LEVEL = "logLevel"
MAX_REPLICATION_LAG = "maxExpectedReplicationLag"
TIMEOUT_PERC = "timeoutPercentageCap"
PAUSE_REQUESTED = "pauseRequested"
PRIORITY = "priority"
DESIRED_LATENCY = "desiredLatency"
COMPRESSION_TYPE = "compressionType"
EXPLICIT_MAPPING = "collectionsExplicitMapping"
MAPPING_RULES = "colMappingRules"
MIGRATION_MODE = "collectionsMigrationMode"
MIRRORING_MODE = "collectionsMirroringMode"
class TEST_XDCR_PARAM:
FAILURE_RESTART = "failure_restart_interval"
CHECKPOINT_INTERVAL = "checkpoint_interval"
OPTIMISTIC_THRESHOLD = "optimistic_threshold"
FILTER_EXP = "filter_expression"
FILTER_SKIP_RESTREAM = "filter_skip_restream"
SOURCE_NOZZLES = "source_nozzles"
TARGET_NOZZLES = "target_nozzles"
BATCH_COUNT = "batch_count"
BATCH_SIZE = "batch_size"
LOG_LEVEL = "log_level"
MAX_REPLICATION_LAG = "max_replication_lag"
TIMEOUT_PERC = "timeout_percentage"
PRIORITY = "priority"
DESIRED_LATENCY = "desired_latency"
COMPRESSION_TYPE = "compression_type"
EXPLICIT_MAPPING = "explicit_mapping"
MAPPING_RULES = "colmapping_rules"
MIGRATION_MODE = "migration_mode"
MIRRORING_MODE = "mirroring_mode"
@staticmethod
def get_test_to_create_repl_param_map():
return {
TEST_XDCR_PARAM.FAILURE_RESTART: REPL_PARAM.FAILURE_RESTART,
TEST_XDCR_PARAM.CHECKPOINT_INTERVAL: REPL_PARAM.CHECKPOINT_INTERVAL,
TEST_XDCR_PARAM.OPTIMISTIC_THRESHOLD: REPL_PARAM.OPTIMISTIC_THRESHOLD,
TEST_XDCR_PARAM.FILTER_EXP: REPL_PARAM.FILTER_EXP,
TEST_XDCR_PARAM.FILTER_SKIP_RESTREAM: REPL_PARAM.FILTER_SKIP_RESTREAM,
TEST_XDCR_PARAM.SOURCE_NOZZLES: REPL_PARAM.SOURCE_NOZZLES,
TEST_XDCR_PARAM.TARGET_NOZZLES: REPL_PARAM.TARGET_NOZZLES,
TEST_XDCR_PARAM.BATCH_COUNT: REPL_PARAM.BATCH_COUNT,
TEST_XDCR_PARAM.BATCH_SIZE: REPL_PARAM.BATCH_SIZE,
TEST_XDCR_PARAM.MAX_REPLICATION_LAG: REPL_PARAM.MAX_REPLICATION_LAG,
TEST_XDCR_PARAM.TIMEOUT_PERC: REPL_PARAM.TIMEOUT_PERC,
TEST_XDCR_PARAM.LOG_LEVEL: REPL_PARAM.LOG_LEVEL,
TEST_XDCR_PARAM.PRIORITY: REPL_PARAM.PRIORITY,
TEST_XDCR_PARAM.DESIRED_LATENCY: REPL_PARAM.DESIRED_LATENCY,
TEST_XDCR_PARAM.COMPRESSION_TYPE: REPL_PARAM.COMPRESSION_TYPE,
TEST_XDCR_PARAM.EXPLICIT_MAPPING: REPL_PARAM.EXPLICIT_MAPPING,
TEST_XDCR_PARAM.MAPPING_RULES: REPL_PARAM.MAPPING_RULES,
TEST_XDCR_PARAM.MIGRATION_MODE: REPL_PARAM.MIGRATION_MODE,
TEST_XDCR_PARAM.MIRRORING_MODE: REPL_PARAM.MIRRORING_MODE
}
class XDCR_PARAM:
# Per-replication params (input)
XDCR_FAILURE_RESTART = "xdcrFailureRestartInterval"
XDCR_CHECKPOINT_INTERVAL = "xdcrCheckpointInterval"
XDCR_OPTIMISTIC_THRESHOLD = "xdcrOptimisticReplicationThreshold"
XDCR_FILTER_EXP = "xdcrFilterExpression"
XDCR_FILTER_SKIP_RESTREAM = "xdcrfilterSkipRestream"
XDCR_SOURCE_NOZZLES = "xdcrSourceNozzlePerNode"
XDCR_TARGET_NOZZLES = "xdcrTargetNozzlePerNode"
XDCR_BATCH_COUNT = "xdcrWorkerBatchSize"
XDCR_BATCH_SIZE = "xdcrDocBatchSizeKb"
XDCR_LOG_LEVEL = "xdcrLogLevel"
XDCR_MAX_REPLICATION_LAG = "xdcrMaxExpectedReplicationLag"
XDCR_TIMEOUT_PERC = "xdcrTimeoutPercentageCap"
XDCR_PRIORITY = "xdcrPriority"
XDCR_DESIRED_LATENCY = "xdcrDesiredLatency"
XDCR_COMPRESSION_TYPE = "xdcrCompressionType"
class CHECK_AUDIT_EVENT:
CHECK = False
# Event Definition:
# https://github.com/couchbase/goxdcr/blob/master/etc/audit_descriptor.json
class GO_XDCR_AUDIT_EVENT_ID:
CREATE_CLUSTER = 16384
MOD_CLUSTER = 16385
RM_CLUSTER = 16386
CREATE_REPL = 16387
PAUSE_REPL = 16388
RESUME_REPL = 16389
CAN_REPL = 16390
DEFAULT_SETT = 16391
IND_SETT = 16392
class BUCKET_COLLECTIONS_DENSITY:
def __init__(self, density):
self.density_map = {
"low": {"num_scopes": 1, "num_collections_per_scope": 1, "num_docs_per_collection": 1000},
"medium": {"num_scopes": 5, "num_collections_per_scope": 10, "num_docs_per_collection": 1000},
"high": {"num_scopes": 10, "num_collections_per_scope": 20, "num_docs_per_collection": 1000}
}
self.density = density
self.num_scopes = 0
self.num_collections = 0
self.num_docs = 0
if self.density == "random":
self.num_scopes = random.randint(1, 99)
max_collections = int(1000 / self.num_scopes) - 1
self.num_collections = random.randint(1, max_collections)
while self.num_scopes*self.num_collections > 1000:
self.num_scopes //= 10
self.num_collections //= 10
self.num_docs = random.randint(100, 10000)
else:
self.num_scopes = self.density_map[self.density]["num_scopes"]
self.num_collections = self.density_map[self.density]["num_collections_per_scope"]
self.num_docs = self.density_map[self.density]["num_docs_per_collection"]
class NodeHelper:
_log = logger.Logger.get_logger()
@staticmethod
def disable_firewall(
server, rep_direction=REPLICATION_DIRECTION.UNIDIRECTION):
"""Disable firewall to put restriction to replicate items in XDCR.
@param server: server object to disable firewall
@param rep_direction: replication direction unidirection/bidirection
"""
shell = RemoteMachineShellConnection(server)
shell.info = shell.extract_remote_info()
if shell.info.type.lower() == "windows":
output, error = shell.execute_command('netsh advfirewall set publicprofile state off')
shell.log_command_output(output, error)
output, error = shell.execute_command('netsh advfirewall set privateprofile state off')
shell.log_command_output(output, error)
# for details see RemoteUtilHelper.enable_firewall for windows
output, error = shell.execute_command('netsh advfirewall firewall delete rule name="block erl.exe in"')
shell.log_command_output(output, error)
output, error = shell.execute_command('netsh advfirewall firewall delete rule name="block erl.exe out"')
shell.log_command_output(output, error)
else:
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 rep_direction == REPLICATION_DIRECTION.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()
@staticmethod
def reboot_server(server, test_case, wait_timeout=60):
remote_client = RemoteMachineShellConnection(server)
remote_client.reboot_node()
# wait for restart and warmup on all node
ClusterOperationHelper.wait_for_ns_servers_or_assert([server], test_case, wait_if_warmup=True)
# disable firewall on these nodes
remote_client.disable_firewall()
remote_client.disconnect()
@staticmethod
def enable_firewall(
server, rep_direction=REPLICATION_DIRECTION.UNIDIRECTION):
"""Enable firewall
@param server: server object to enable firewall
@param rep_direction: replication direction unidirection/bidirection
"""
is_bidirectional = rep_direction == REPLICATION_DIRECTION.BIDIRECTION
RemoteUtilHelper.enable_firewall(
server,
bidirectional=is_bidirectional,
xdcr=True)
@staticmethod
def do_a_warm_up(server):
"""Warmp up server
"""
shell = RemoteMachineShellConnection(server)
shell.restart_couchbase()
shell.disconnect()
@staticmethod
def wait_service_started(server, wait_time=120):
"""Function will wait for Couchbase service to be in
running phase.
"""
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, _ = shell.execute_command(cmd)
if str(output).lower().find("running") != -1:
# self.log.info("Couchbase service is running")
return
time.sleep(10)
raise Exception(
"Couchbase service is not running after {0} seconds".format(
wait_time))
@staticmethod
def wait_warmup_completed(warmupnodes, bucket_names=["default"]):
if isinstance(bucket_names, str):
bucket_names = [bucket_names]
start = time.time()
for server in warmupnodes:
for bucket in bucket_names:
while time.time() - start < 150:
try:
mc = MemcachedClientHelper.direct_client(server, bucket)
if mc.stats()["ep_warmup_thread"] == "complete":
NodeHelper._log.info(
"Warmed up: %s items on %s on %s" %
(mc.stats("warmup")["ep_warmup_key_count"], bucket, server))
time.sleep(10)
break
elif mc.stats()["ep_warmup_thread"] == "running":
NodeHelper._log.info(
"Still warming up .. ep_warmup_key_count : %s" % (mc.stats("warmup")["ep_warmup_key_count"]))
continue
else:
NodeHelper._log.info(
"Value of ep_warmup_thread does not exist, exiting from this server")
break
except Exception as e:
NodeHelper._log.info(e)
time.sleep(10)
if mc.stats()["ep_warmup_thread"] == "running":
NodeHelper._log.info(
"ERROR: ep_warmup_thread's status not complete")
mc.close()
@staticmethod
def wait_node_restarted(
server, test_case, wait_time=120, wait_if_warmup=False,
check_service=False):
"""Wait server to be re-started
"""
now = time.time()
if check_service:
NodeHelper.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], test_case, wait_time=wait_time - num * 10,
wait_if_warmup=wait_if_warmup)
break
except ServerUnavailableException:
num += 1
time.sleep(10)
@staticmethod
def kill_erlang(server):
"""Kill erlang process running on server.
"""
NodeHelper._log.info("Killing erlang on server: {0}".format(server))
shell = RemoteMachineShellConnection(server)
os_info = shell.extract_remote_info()
shell.kill_erlang(os_info)
shell.disconnect()
@staticmethod
def kill_memcached(server):
"""Kill memcached process running on server.
"""
shell = RemoteMachineShellConnection(server)
shell.kill_erlang()
shell.disconnect()
@staticmethod
def kill_goxdcr(server):
"""Kill goxdcr process running on server.
"""
shell = RemoteMachineShellConnection(server)
shell.kill_goxdcr()
shell.disconnect()
@staticmethod
def get_goxdcr_log_dir(node):
"""Gets couchbase log directory, even for cluster_run
"""
_, dir = RestConnection(node).diag_eval('filename:absname(element(2, application:get_env(ns_server,error_logger_mf_dir))).')
return str(dir).replace('"', '')
@staticmethod
def check_goxdcr_log(server, search_str, goxdcr_log=None, print_matches=None, log_name=None, timeout=0):
""" Checks if a string 'str' is present in 'log_name' on 'server'
and returns the number of occurances
@param goxdcr_log: goxdcr log location on the server
@timeout: search every 10 seconds until timeout
"""
if not log_name:
log_name = "goxdcr.log"
shell = RemoteMachineShellConnection(server)
info = shell.extract_remote_info().type.lower()
if info == "windows":
goxdcr_log = WIN_COUCHBASE_LOGS_PATH + log_name + '*'
cmd = "grep "
else:
if not goxdcr_log:
goxdcr_log = NodeHelper.get_goxdcr_log_dir(server) \
+ '/' + log_name + '*'
cmd = "zgrep "
cmd += "\"{0}\" {1}".format(search_str, goxdcr_log)
iter = 0
count = 0
matches = []
# Search 5 times with a break of timeout sec
while iter < 5:
matches, err = shell.execute_command(cmd)
count = len(matches)
if count > 0 or timeout == 0:
break
else:
NodeHelper._log.info("Waiting {0}s for {1} to appear in {2} ..".format(timeout, search_str, log_name))
time.sleep(timeout)
iter += 1
shell.disconnect()
NodeHelper._log.info(count)
if print_matches:
NodeHelper._log.info(matches)
return matches, count
@staticmethod
def rename_nodes(servers):
"""Rename server name from ip to their hostname
@param servers: list of server objects.
@return: dictionary whose key is server and value is hostname
"""
hostnames = {}
for server in servers:
shell = RemoteMachineShellConnection(server)
try:
if "ec2" in str(server.ip):
hostname = shell.get_aws_public_hostname()
elif "azure" in str(server.ip):
hostname = str(server.ip)
else:
hostname = shell.get_full_hostname()
rest = RestConnection(server)
renamed, content = rest.rename_node(
hostname, username=server.rest_username,
password=server.rest_password)
raise_if(
not renamed,
RenameNodeException(
"Server %s is not renamed! Hostname %s. Error %s" % (
server, hostname, content)
)
)
hostnames[server] = hostname
server.hostname = hostname
finally:
shell.disconnect()
return hostnames
# Returns version like "x.x.x" after removing build number
@staticmethod
def get_cb_version(node):
rest = RestConnection(node)
version = rest.get_nodes_self().version
return version[:version.rfind('-')]
@staticmethod
def set_wall_clock_time(node, date_str):
shell = RemoteMachineShellConnection(node)
# os_info = shell.extract_remote_info()
# if os_info == OS.LINUX:
# date command works on linux and windows cygwin as well.
shell.execute_command(
"sudo date -s '%s'" %
time.ctime(
date_str.tx_time))
# elif os_info == OS.WINDOWS:
# raise "NEED To SETUP DATE COMMAND FOR WINDOWS"
@staticmethod
def get_cbcollect_info(servers):
"""Collect cbcollectinfo logs for all the servers in the cluster.
"""
path = TestInputSingleton.input.param("logs_folder", "/tmp")
path = path or "."
runner = cbcollectRunner(servers, path)
runner.run()
if len(runner.succ) > 0:
TestInputSingleton.input.test_params[
"get-cbcollect-info"] = False
for (server, e) in runner.fail:
NodeHelper._log.error(
"IMPOSSIBLE TO GRAB CBCOLLECT FROM {0}: {1}".format(
server.ip,
e))
@staticmethod
def collect_data_files(server):
"""Collect bucket data files for all the servers in the cluster.
Data files are collected only if data is not verified on the cluster.
"""
path = TestInputSingleton.input.param("logs_folder", "/tmp")
collect_data_files.cbdatacollectRunner(server, path).run()
@staticmethod
def collect_logs(servers, cluster_run=False):
"""Grab cbcollect before we cleanup
"""
NodeHelper.get_cbcollect_info(servers)
if not cluster_run:
for server in servers:
NodeHelper.collect_data_files(server)
class ValidateAuditEvent:
@staticmethod
def validate_audit_event(event_id, master_node, expected_results):
if CHECK_AUDIT_EVENT.CHECK:
audit_obj = audit(event_id, master_node)
field_verified, value_verified = audit_obj.validateEvents(
expected_results)
raise_if(
not field_verified,
XDCRException("One of the fields is not matching"))
raise_if(
not value_verified,
XDCRException("Values for one of the fields is not matching"))
class FloatingServers:
"""Keep Track of free servers, For Rebalance-in
or swap-rebalance operations.
"""
_serverlist = []
class XDCRRemoteClusterRef:
"""Class keep the information related to Remote Cluster References.
"""
def __init__(self, src_cluster, dest_cluster, name, encryption=False, replicator_target_role=False,
multiple_ca=False, client_certificate=None, client_key=None, systemeventlog=None):
"""
@param src_cluster: source couchbase cluster object.
@param dest_cluster: destination couchbase cluster object:
@param name: remote cluster reference name.
@param encryption: True to enable SSL encryption for replication else
False
"""
self.__src_cluster = src_cluster
self.__dest_cluster = dest_cluster
self.__name = name
self.__encryption = encryption
self.__multiple_ca = multiple_ca
self.__client_certificate = client_certificate
self.__client_key = client_key
self.__systemeventlog = systemeventlog
self.__rest_info = {}
self.__replicator_target_role = replicator_target_role
self.__use_scramsha = TestInputSingleton.input.param("use_scramsha", False)
# List of XDCReplication objects
self.__replications = []
def __str__(self):
return "{0} -> {1}, Name: {2}".format(
self.__src_cluster.get_name(), self.__dest_cluster.get_name(),
self.__name)
def get_cb_clusters(self):
return self.__cb_clusters
def get_src_cluster(self):
return self.__src_cluster
def get_dest_cluster(self):
return self.__dest_cluster
def get_name(self):
return self.__name
def get_replications(self):
return self.__replications
def get_rest_info(self):
return self.__rest_info
def get_systemeventlog(self):
return self.__systemeventlog
def get_replication_for_bucket(self, bucket):
for replication in self.__replications:
if replication.get_src_bucket().name == bucket.name:
return replication
return None
def __get_event_expected_results(self):
expected_results = {
"real_userid:source": "ns_server",
"real_userid:user": self.__src_cluster.get_master_node().rest_username,
"cluster_name": self.__name,
"cluster_hostname": "%s:%s" % (self.__dest_cluster.get_master_node().ip, self.__dest_cluster.get_master_node().port),
"is_encrypted": self.__encryption,
"encryption_type": ""}
return expected_results
def __validate_create_event(self):
ValidateAuditEvent.validate_audit_event(
GO_XDCR_AUDIT_EVENT_ID.CREATE_CLUSTER,
self.__src_cluster.get_master_node(),
self.__get_event_expected_results())
self.__systemeventlog.add_event(
XDCRServiceEvents.create_remote_cluster_ref(self.__src_cluster.get_master_node().ip,
self.__dest_cluster.get_master_node().ip
+ ':' + self.__dest_cluster.get_master_node().port,
self.__rest_info['uuid'],
"plain",
self.__name
))
def _extract_certs(self, raw_content):
certs = ""
for ca_dict in raw_content:
certs += ca_dict["pem"]
return certs
def add(self):
"""create cluster reference- add remote cluster
"""
rest_conn_src = RestConnection(self.__src_cluster.get_master_node())
certificate = None
dest_master = self.__dest_cluster.get_master_node()
if self.__encryption:
rest_conn_dest = RestConnection(dest_master)
if self.__multiple_ca:
raw_content = rest_conn_dest.get_trusted_CAs()
certificate = self._extract_certs(raw_content)
else:
certificate = rest_conn_dest.get_cluster_ceritificate()
if self.__replicator_target_role:
self.dest_user = "replicator_user"
self.dest_pass = "password"
else:
self.dest_user = dest_master.rest_username
self.dest_pass = dest_master.rest_password
if not self.__use_scramsha:
self.__rest_info = rest_conn_src.add_remote_cluster(
dest_master.cluster_ip, dest_master.port,
self.dest_user,
self.dest_pass, self.__name,
demandEncryption=self.__encryption,
certificate=certificate,
clientCertificate=self.__client_certificate,
clientKey=self.__client_key
)
else:
print("Using scram-sha authentication")
self.__rest_info = rest_conn_src.add_remote_cluster(
dest_master.cluster_ip, dest_master.port,
self.dest_user,
self.dest_pass, self.__name,
demandEncryption=self.__encryption,
encryptionType="half"
)
self.__validate_create_event()
def __validate_modify_event(self):
ValidateAuditEvent.validate_audit_event(
GO_XDCR_AUDIT_EVENT_ID.MOD_CLUSTER,
self.__src_cluster.get_master_node(),
self.__get_event_expected_results())
self.__systemeventlog.add_event(
XDCRServiceEvents.update_remote_cluster_ref(self.__src_cluster.get_master_node(),
self.__dest_cluster.get_master_node().ip,
self.__rest_info['uuid'],
self.__encryption,
self.__name
))
def use_scram_sha_auth(self):
self.__use_scramsha = True
self.__encryption = True
self.modify()
def modify(self, encryption=True):
dest_master = self.__dest_cluster.get_master_node()
rest_conn_src = RestConnection(self.__src_cluster.get_master_node())
if encryption:
rest_conn_dest = RestConnection(dest_master)
if not self.__use_scramsha:
if self.__multiple_ca:
raw_content = rest_conn_dest.get_trusted_CAs()
certificate = self._extract_certs(raw_content)
else:
certificate = rest_conn_dest.get_cluster_ceritificate()
self.__rest_info = rest_conn_src.modify_remote_cluster(
dest_master.ip, dest_master.port,
self.dest_user,
self.dest_pass, self.__name,
demandEncryption=encryption,
certificate=certificate,
clientCertificate=self.__client_certificate,
clientKey=self.__client_key
)
else:
print("Using scram-sha authentication")
self.__rest_info = rest_conn_src.modify_remote_cluster(
dest_master.ip, dest_master.port,
self.dest_user,
self.dest_pass, self.__name,
demandEncryption=encryption,
encryptionType="half")
self.__encryption = encryption
self.__validate_modify_event()
def __validate_remove_event(self):
ValidateAuditEvent.validate_audit_event(
GO_XDCR_AUDIT_EVENT_ID.RM_CLUSTER,
self.__src_cluster.get_master_node(),
self.__get_event_expected_results())
self.__systemeventlog.add_event(
XDCRServiceEvents.delete_remote_cluster_ref(self.__src_cluster.get_master_node(),
self.__dest_cluster.get_master_node().ip,
self.__rest_info['uuid'],
self.__encryption,
self.__name
))
def remove(self):
RestConnection(
self.__src_cluster.get_master_node()).remove_remote_cluster(
self.__name)
self.__validate_remove_event()
def create_replication(
self, fromBucket,
rep_type=REPLICATION_PROTOCOL.XMEM,
toBucket=None):
"""Create replication objects, but replication will not get
started here.
"""
self.__replications.append(
XDCReplication(
self,
fromBucket,
rep_type,
toBucket))
def clear_all_replications(self):
self.__replications = []
def start_all_replications(self):
"""Start all created replication
"""
[repl.start() for repl in self.__replications]
def pause_all_replications(self, verify=False):
"""Pause all created replication
"""
[repl.pause(verify=verify) for repl in self.__replications]
def pause_all_replications_by_id(self, verify=False):
[repl.pause(repl_id=repl.get_repl_id(), verify=verify) for repl in self.__replications]
def resume_all_replications(self, verify=False):
"""Resume all created replication
"""
[repl.resume(verify=verify) for repl in self.__replications]
def resume_all_replications_by_id(self, verify=False):
[repl.resume(repl_id=repl.get_repl_id(), verify=verify) for repl in self.__replications]
def stop_all_replications(self):
rest = RestConnection(self.__src_cluster.get_master_node())
rest_all_repls = rest.get_replications()
for repl in self.__replications:
for rest_all_repl in rest_all_repls:
if repl.get_repl_id() == rest_all_repl['id']:
repl.cancel(rest, rest_all_repl)
self.clear_all_replications()
class XDCReplication:
def __init__(self, remote_cluster_ref, from_bucket, rep_type, to_bucket):
"""
@param remote_cluster_ref: XDCRRemoteClusterRef object
@param from_bucket: Source bucket (Bucket object)
@param rep_type: replication protocol REPLICATION_PROTOCOL.CAPI/XMEM
@param to_bucket: Destination bucket (Bucket object)
"""
self.__input = TestInputSingleton.input
self.__remote_cluster_ref = remote_cluster_ref
self.__from_bucket = from_bucket
self.__to_bucket = to_bucket or from_bucket
self.__src_cluster = self.__remote_cluster_ref.get_src_cluster()
self.__dest_cluster = self.__remote_cluster_ref.get_dest_cluster()
self.__src_cluster_name = self.__src_cluster.get_name()
self.__rep_type = rep_type
self.__test_xdcr_params = {}
self.__updated_params = {}
self.__parse_test_xdcr_params()
self.log = logger.Logger.get_logger()
# Response from REST API
self.__rep_id = None
def __str__(self):
return "Replication {0}:{1} -> {2}:{3}".format(
self.__src_cluster.get_name(),
self.__from_bucket.name, self.__dest_cluster.get_name(),
self.__to_bucket.name)
def __get_random_filter(self, filter_type):
from scripts.edgyjson.main import JSONDoc
obj = JSONDoc(template="query.json", filter=True, load=False)
filter_type = filter_type.split("-")[1]
if filter_type == "random":
filter_type = random.choice(obj.filters_json_objs_dict.keys())
num_exps = random.randint(0, 5)
ex = ""
while num_exps:
nesting_level = random.randint(0, 5)
ex_no_brackets = random.choice(obj.filters_json_objs_dict[filter_type])
ex_with_brackets = '( ' + ex_no_brackets + ' )'
# Generate nested exps: for eg ((exp1 AND exp2) OR exp3)
for _ in range(nesting_level):
ex += '( ' + random.choice([ex_no_brackets, ex_with_brackets]) \
+ ' )' + random.choice([" AND ", " OR "])
num_exps -= 1
# Enclose keys having '_' in quotes (eg:'string_long')
if '_' in ex:
ex = ("'%s_%s'") % ex
ex += random.choice(obj.filters_json_objs_dict[filter_type])
return ex
# get per replication params specified as from_bucket@cluster_name=<setting>:<value>
# eg. default@C1=filter_expression:loadOne,failure_restart_interval:20
def __parse_test_xdcr_params(self):
param_str = self.__input.param(
"%s@%s" %
(self.__from_bucket, self.__src_cluster_name), None)
if param_str:
argument_split = re.split('[:,]', param_str)
self.__test_xdcr_params.update(
dict(list(zip(argument_split[::2], argument_split[1::2])))
)
if 'filter_expression' in self.__test_xdcr_params:
ex = self.__test_xdcr_params['filter_expression']
if len(ex) > 0:
if ex.startswith("random"):
self.__test_xdcr_params['filter_expression'] = self.__get_random_filter(ex)
masked_input = {"comma": ',', "star": '*', "dot": '.', "equals": '=', "{": '', "}": '', "colon": ':'}
for _ in masked_input:
self.__test_xdcr_params['filter_expression'] = self.__test_xdcr_params['filter_expression'].replace(
_, masked_input[_])
if "colmapping_rules" in self.__test_xdcr_params:
masked_input = {"comma": ',', "colon": ':', "dot": '.'}
for _ in masked_input:
self.__test_xdcr_params['colmapping_rules'] = self.__test_xdcr_params[
'colmapping_rules'].replace(
_, masked_input[_])
def __convert_test_to_xdcr_params(self):
xdcr_params = {}
xdcr_param_map = TEST_XDCR_PARAM.get_test_to_create_repl_param_map()
for test_param, value in self.__test_xdcr_params.items():
xdcr_params[xdcr_param_map[test_param]] = value
return xdcr_params
def get_filter_exp(self):
if TEST_XDCR_PARAM.FILTER_EXP in self.__test_xdcr_params:
return self.__test_xdcr_params[TEST_XDCR_PARAM.FILTER_EXP]
return None
def get_src_bucket(self):
return self.__from_bucket
def get_dest_bucket(self):
return self.__to_bucket
def get_src_cluster(self):
return self.__src_cluster
def get_dest_cluster(self):
return self.__dest_cluster
def get_repl_id(self):
return self.__rep_id
def get_remote_cluster_ref(self):
return self.__remote_cluster_ref
def __get_event_expected_results(self):
expected_results = {
"real_userid:source": "ns_server",
"real_userid:user": self.__src_cluster.get_master_node().rest_username,
"local_cluster_name": "%s:%s" % (self.__src_cluster.get_master_node().ip, self.__src_cluster.get_master_node().port),
"source_bucket_name": self.__from_bucket.name,
"remote_cluster_name": self.__remote_cluster_ref.get_name(),
"target_bucket_name": self.__to_bucket.name
}
# optional audit param
if self.get_filter_exp():
expected_results["filter_expression"] = self.get_filter_exp()
return expected_results
def __validate_update_repl_event(self):
expected_results = {
"settings": {
"continuous": 'true',
"target": self.__to_bucket.name,
"source": self.__from_bucket.name,
"type": "xdc-%s" % self.__rep_type
},
"id": self.__rep_id,
"real_userid:source": "ns_server",
"real_userid:user": self.__src_cluster.get_master_node().rest_username,
}
expected_results["settings"].update(self.__updated_params)
def __validate_set_param_event(self):
expected_results = self.__get_event_expected_results()
expected_results["updated_settings"] = self.__updated_params
ValidateAuditEvent.validate_audit_event(
GO_XDCR_AUDIT_EVENT_ID.IND_SETT,
self.get_src_cluster().get_master_node(), expected_results)
self.get_remote_cluster_ref().get_systemeventlog().add_event(
XDCRServiceEvents.update_replication(self.get_src_cluster().get_master_node(),
self.get_src_bucket().name,
self.get_dest_bucket().name,
self.get_repl_id(),
self.get_remote_cluster_ref().get_name(),
self.get_filter_exp()
))
def get_xdcr_setting(self, param):
"""Get a replication setting value
"""
src_master = self.__src_cluster.get_master_node()