-
Notifications
You must be signed in to change notification settings - Fork 134
/
consistency_test.py
1608 lines (1303 loc) · 67.4 KB
/
consistency_test.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 queue
import sys
import threading
import time
import pytest
import logging
from collections import OrderedDict, namedtuple
from copy import deepcopy
from cassandra import ConsistencyLevel, consistency_value_to_name
from cassandra.query import BatchStatement, BatchType, SimpleStatement
from tools.jmxutils import JolokiaAgent, make_mbean
from tools.assertions import (assert_all, assert_length_equal, assert_none,
assert_unavailable)
from dtest import MultiError, Tester, create_ks, create_cf
from tools.data import (create_c1c2_table, insert_c1c2, insert_columns,
query_c1c2, rows_to_list)
since = pytest.mark.since
ported_to_in_jvm = pytest.mark.ported_to_in_jvm
logger = logging.getLogger(__name__)
ExpectedConsistency = namedtuple('ExpectedConsistency', ('num_write_nodes', 'num_read_nodes', 'is_strong'))
class TestHelper(Tester):
def _is_local(self, cl):
return (cl == ConsistencyLevel.LOCAL_QUORUM or
cl == ConsistencyLevel.LOCAL_ONE or
cl == ConsistencyLevel.LOCAL_SERIAL)
def _is_conditional(self, cl):
return (cl == ConsistencyLevel.SERIAL or
cl == ConsistencyLevel.LOCAL_SERIAL)
def _required_nodes(self, cl, rf_factors, dc):
"""
Return the number of nodes required by this consistency level
in the current data center, specified by the dc parameter,
given a list of replication factors, one per dc.
"""
return {
ConsistencyLevel.ANY: 1,
ConsistencyLevel.ONE: 1,
ConsistencyLevel.TWO: 2,
ConsistencyLevel.THREE: 3,
ConsistencyLevel.QUORUM: sum(rf_factors) // 2 + 1,
ConsistencyLevel.ALL: sum(rf_factors),
ConsistencyLevel.LOCAL_QUORUM: rf_factors[dc] // 2 + 1,
ConsistencyLevel.EACH_QUORUM: rf_factors[dc] // 2 + 1,
ConsistencyLevel.SERIAL: sum(rf_factors) // 2 + 1,
ConsistencyLevel.LOCAL_SERIAL: rf_factors[dc] // 2 + 1,
ConsistencyLevel.LOCAL_ONE: 1,
}[cl]
def get_expected_consistency(self, idx, rf_factors, write_cl, read_cl):
"""
Given a node index, identify to which data center we are connecting and return
the expected consistency: number of nodes we write to, read from, and whether
we should have strong consistency, that is whether R + W > N
"""
nodes = [self.nodes] if isinstance(self.nodes, int) else self.nodes
def get_data_center():
"""
:return: the data center corresponding to this node
"""
dc = 0
for i in range(1, len(nodes)):
if idx < sum(nodes[:i]):
break
dc += 1
return dc
data_center = get_data_center()
if write_cl == ConsistencyLevel.EACH_QUORUM:
write_nodes = sum([self._required_nodes(write_cl, rf_factors, i) for i in range(0, len(nodes))])
else:
write_nodes = self._required_nodes(write_cl, rf_factors, data_center)
read_nodes = self._required_nodes(read_cl, rf_factors, data_center)
is_strong = read_nodes + write_nodes > sum(rf_factors)
return ExpectedConsistency(num_write_nodes=write_nodes,
num_read_nodes=read_nodes,
is_strong=is_strong)
def _should_succeed(self, cl, rf_factors, num_nodes_alive, current):
"""
Return true if the read or write operation should succeed based on
the consistency level requested, the replication factors and the
number of nodes alive in each data center.
"""
if self._is_local(cl):
return num_nodes_alive[current] >= self._required_nodes(cl, rf_factors, current)
elif cl == ConsistencyLevel.EACH_QUORUM:
for i in range(0, len(rf_factors)):
if num_nodes_alive[i] < self._required_nodes(cl, rf_factors, i):
return False
return True
else:
return sum(num_nodes_alive) >= self._required_nodes(cl, rf_factors, current)
def _start_cluster(self, save_sessions=False, requires_local_reads=False):
cluster = self.cluster
nodes = self.nodes
rf = self.rf
configuration_options = {'hinted_handoff_enabled': False}
# If we must read from the local replica first, then the dynamic snitch poses a problem
# because occasionally it may think that another replica is preferable even if the
# coordinator is a replica
if requires_local_reads:
configuration_options['dynamic_snitch'] = False
cluster.set_configuration_options(values=configuration_options)
cluster.populate(nodes)
if requires_local_reads and isinstance(nodes, int):
# Changing the snitch to PropertyFileSnitch even in the
# single dc tests ensures that StorageProxy sorts the replicas eligible
# for reading by proximity to the local host, essentially picking the
# local host for local reads, see IEndpointSnitch.sortByProximity() and
# StorageProxy.getLiveSortedEndpoints(), which is called by the AbstractReadExecutor
# to determine the target replicas. The default case, a SimpleSnitch wrapped in
# a dynamic snitch, may rarely choose a different replica.
logger.debug('Changing snitch for single dc case')
for node in cluster.nodelist():
node.data_center = 'dc1'
cluster.set_configuration_options(values={
'endpoint_snitch': 'org.apache.cassandra.locator.PropertyFileSnitch'})
cluster.start()
self.ksname = 'mytestks'
session = self.patient_exclusive_cql_connection(cluster.nodelist()[0])
create_ks(session, self.ksname, rf)
self.create_tables(session, requires_local_reads)
if save_sessions:
self.sessions = []
self.sessions.append(session)
for node in cluster.nodelist()[1:]:
self.sessions.append(self.patient_exclusive_cql_connection(node, self.ksname))
def create_tables(self, session, requires_local_reads):
self.create_users_table(session, requires_local_reads)
self.create_counters_table(session, requires_local_reads)
session.cluster.control_connection.wait_for_schema_agreement(wait_time=60)
def truncate_tables(self, session):
statement = SimpleStatement("TRUNCATE users", ConsistencyLevel.ALL)
session.execute(statement)
statement = SimpleStatement("TRUNCATE counters", ConsistencyLevel.ALL)
session.execute(statement)
def create_users_table(self, session, requires_local_reads):
create_cmd = """
CREATE TABLE users (
userid int PRIMARY KEY,
firstname text,
lastname text,
age int
)"""
if requires_local_reads:
create_cmd += " WITH " + self.get_local_reads_properties(self.cluster.version())
session.execute(create_cmd)
@staticmethod
def get_local_reads_properties(cluster_version):
"""
If we must read from the local replica first, then we should disable read repair and
speculative retry, see CASSANDRA-12092
"""
if cluster_version < '4.0':
return " dclocal_read_repair_chance = 0 AND read_repair_chance = 0 AND speculative_retry = 'NONE'"
else:
return " speculative_retry = 'NONE'"
def insert_user(self, session, userid, age, consistency, serial_consistency=None):
text = "INSERT INTO users (userid, firstname, lastname, age) VALUES ({}, 'first{}', 'last{}', {}) {}"\
.format(userid, userid, userid, age, "IF NOT EXISTS" if serial_consistency else "")
statement = SimpleStatement(text, consistency_level=consistency, serial_consistency_level=serial_consistency)
session.execute(statement)
def update_user(self, session, userid, age, consistency, serial_consistency=None, prev_age=None):
text = "UPDATE users SET age = {} WHERE userid = {}".format(age, userid)
if serial_consistency and prev_age:
text = text + " IF age = {}".format(prev_age)
statement = SimpleStatement(text, consistency_level=consistency, serial_consistency_level=serial_consistency)
session.execute(statement)
def delete_user(self, session, userid, consistency):
statement = SimpleStatement("DELETE FROM users where userid = {}".format(userid), consistency_level=consistency)
session.execute(statement)
def query_user(self, session, userid, age, consistency, check_ret=True):
statement = SimpleStatement("SELECT userid, age FROM users where userid = {}".format(userid), consistency_level=consistency)
res = session.execute(statement)
expected = [[userid, age]] if age else []
ret = rows_to_list(res) == expected
if check_ret:
assert ret, "Got {} from {}, expected {} at {}".format(rows_to_list(res), session.cluster.contact_points, expected, consistency_value_to_name(consistency))
return ret
def create_counters_table(self, session, requires_local_reads):
create_cmd = """
CREATE TABLE counters (
id int PRIMARY KEY,
c counter
)"""
if requires_local_reads:
create_cmd += " WITH " + self.get_local_reads_properties(self.cluster.version())
session.execute(create_cmd)
def update_counter(self, session, id, consistency, serial_consistency=None):
text = "UPDATE counters SET c = c + 1 WHERE id = {}".format(id)
statement = SimpleStatement(text, consistency_level=consistency, serial_consistency_level=serial_consistency)
session.execute(statement)
return statement
def query_counter(self, session, id, val, consistency, check_ret=True):
statement = SimpleStatement("SELECT * from counters WHERE id = {}".format(id), consistency_level=consistency)
ret = rows_to_list(session.execute(statement))
if check_ret:
assert ret[0][1] == val, "Got {} from {}, expected {} at {}".format(ret[0][1],
session.cluster.contact_points,
val,
consistency_value_to_name(consistency))
return ret[0][1] if ret else 0
class TestAvailability(TestHelper):
"""
Test that we can read and write depending on the number of nodes that are alive and the consistency levels.
"""
def _test_simple_strategy(self, combinations):
"""
Helper test function for a single data center: invoke _test_insert_query_from_node() for each node
and each combination, progressively stopping nodes.
"""
cluster = self.cluster
nodes = self.nodes
rf = self.rf
num_alive = nodes
for node in range(nodes):
logger.debug('Testing node {} in single dc with {} nodes alive'.format(node, num_alive))
session = self.patient_exclusive_cql_connection(cluster.nodelist()[node], self.ksname)
for combination in combinations:
self._test_insert_query_from_node(session, 0, [rf], [num_alive], *combination)
self.cluster.nodelist()[node].stop()
num_alive -= 1
def _test_network_topology_strategy(self, combinations):
"""
Helper test function for multiple data centers, invoke _test_insert_query_from_node() for each node
in each dc and each combination, progressively stopping nodes.
"""
cluster = self.cluster
nodes = self.nodes
rf = self.rf
nodes_alive = deepcopy(nodes)
rf_factors = list(rf.values())
for i in range(0, len(nodes)): # for each dc
logger.debug('Testing dc {} with rf {} and {} nodes alive'.format(i, rf_factors[i], nodes_alive))
for n in range(nodes[i]): # for each node in this dc
logger.debug('Testing node {} in dc {} with {} nodes alive'.format(n, i, nodes_alive))
node = n + sum(nodes[:i])
session = self.patient_exclusive_cql_connection(cluster.nodelist()[node], self.ksname)
for combination in combinations:
self._test_insert_query_from_node(session, i, rf_factors, nodes_alive, *combination)
self.cluster.nodelist()[node].stop(wait_other_notice=True)
nodes_alive[i] -= 1
def _test_insert_query_from_node(self, session, dc_idx, rf_factors, num_nodes_alive, write_cl, read_cl, serial_cl=None, check_ret=True):
"""
Test availability for read and write via the session passed in as a parameter.
"""
logger.debug("Connected to %s for %s/%s/%s" %
(session.cluster.contact_points, consistency_value_to_name(write_cl), consistency_value_to_name(read_cl), consistency_value_to_name(serial_cl)))
start = 0
end = 100
age = 30
if self._should_succeed(write_cl, rf_factors, num_nodes_alive, dc_idx):
for n in range(start, end):
self.insert_user(session, n, age, write_cl, serial_cl)
else:
assert_unavailable(self.insert_user, session, end, age, write_cl, serial_cl)
if self._should_succeed(read_cl, rf_factors, num_nodes_alive, dc_idx):
for n in range(start, end):
self.query_user(session, n, age, read_cl, check_ret)
else:
assert_unavailable(self.query_user, session, end, age, read_cl, check_ret)
def test_simple_strategy(self):
"""
Test for a single datacenter, using simple replication strategy.
"""
self.nodes = 3
self.rf = 3
self._start_cluster()
combinations = [
(ConsistencyLevel.ALL, ConsistencyLevel.ALL),
(ConsistencyLevel.QUORUM, ConsistencyLevel.QUORUM),
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.LOCAL_QUORUM),
(ConsistencyLevel.EACH_QUORUM, ConsistencyLevel.LOCAL_QUORUM),
(ConsistencyLevel.ONE, ConsistencyLevel.ONE, None, False),
(ConsistencyLevel.ONE, ConsistencyLevel.ALL),
(ConsistencyLevel.ALL, ConsistencyLevel.ONE),
(ConsistencyLevel.QUORUM, ConsistencyLevel.TWO),
(ConsistencyLevel.QUORUM, ConsistencyLevel.THREE),
(ConsistencyLevel.TWO, ConsistencyLevel.TWO),
(ConsistencyLevel.THREE, ConsistencyLevel.ONE),
(ConsistencyLevel.ANY, ConsistencyLevel.ONE, None, False),
(ConsistencyLevel.LOCAL_ONE, ConsistencyLevel.LOCAL_ONE, None, False),
(ConsistencyLevel.QUORUM, ConsistencyLevel.SERIAL, ConsistencyLevel.SERIAL),
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.LOCAL_SERIAL, ConsistencyLevel.LOCAL_SERIAL),
(ConsistencyLevel.QUORUM, ConsistencyLevel.LOCAL_SERIAL, ConsistencyLevel.SERIAL),
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.SERIAL, ConsistencyLevel.LOCAL_SERIAL),
]
self._test_simple_strategy(combinations)
@since("3.0")
def test_simple_strategy_each_quorum(self):
"""
@jira_ticket CASSANDRA-10584
Test for a single datacenter, using simple replication strategy, only
the each quorum reads.
"""
self.nodes = 3
self.rf = 3
self._start_cluster()
combinations = [
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.EACH_QUORUM),
(ConsistencyLevel.EACH_QUORUM, ConsistencyLevel.EACH_QUORUM),
]
self._test_simple_strategy(combinations)
@pytest.mark.resource_intensive
def test_network_topology_strategy(self):
"""
Test for multiple datacenters, using network topology replication strategy.
"""
self.nodes = [3, 3, 3]
self.rf = OrderedDict([('dc1', 3), ('dc2', 3), ('dc3', 3)])
self._start_cluster()
combinations = [
(ConsistencyLevel.ALL, ConsistencyLevel.ALL),
(ConsistencyLevel.QUORUM, ConsistencyLevel.QUORUM),
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.LOCAL_QUORUM),
(ConsistencyLevel.EACH_QUORUM, ConsistencyLevel.LOCAL_QUORUM),
(ConsistencyLevel.ONE, ConsistencyLevel.ONE, None, False),
(ConsistencyLevel.ONE, ConsistencyLevel.ALL),
(ConsistencyLevel.ALL, ConsistencyLevel.ONE),
(ConsistencyLevel.QUORUM, ConsistencyLevel.TWO),
(ConsistencyLevel.QUORUM, ConsistencyLevel.THREE),
(ConsistencyLevel.TWO, ConsistencyLevel.TWO),
(ConsistencyLevel.THREE, ConsistencyLevel.ONE),
(ConsistencyLevel.ANY, ConsistencyLevel.ONE, None, False),
(ConsistencyLevel.LOCAL_ONE, ConsistencyLevel.LOCAL_ONE, None, False),
(ConsistencyLevel.QUORUM, ConsistencyLevel.SERIAL, ConsistencyLevel.SERIAL),
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.LOCAL_SERIAL, ConsistencyLevel.LOCAL_SERIAL),
(ConsistencyLevel.QUORUM, ConsistencyLevel.LOCAL_SERIAL, ConsistencyLevel.SERIAL),
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.SERIAL, ConsistencyLevel.LOCAL_SERIAL),
]
self._test_network_topology_strategy(combinations)
@pytest.mark.resource_intensive
@since("3.0")
def test_network_topology_strategy_each_quorum(self):
"""
@jira_ticket CASSANDRA-10584
Test for multiple datacenters, using network topology strategy, only
the each quorum reads.
"""
self.nodes = [3, 3, 3]
self.rf = OrderedDict([('dc1', 3), ('dc2', 3), ('dc3', 3)])
self._start_cluster()
combinations = [
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.EACH_QUORUM),
(ConsistencyLevel.EACH_QUORUM, ConsistencyLevel.EACH_QUORUM),
]
self._test_network_topology_strategy(combinations)
class TestAccuracy(TestHelper):
"""
Test that we can consistently read back what we wrote depending on the write and read consistency levels.
"""
class Validation:
def __init__(self, outer, sessions, nodes, rf_factors, start, end, write_cl, read_cl, serial_cl=None):
self.outer = outer
self.sessions = sessions
self.nodes = nodes
self.rf_factors = rf_factors
self.start = start
self.end = end
self.write_cl = write_cl
self.read_cl = read_cl
self.serial_cl = serial_cl
logger.debug('Testing accuracy with WRITE/READ/SERIAL consistency set to {}/{}/{} (keys : {} to {})'
.format(consistency_value_to_name(write_cl), consistency_value_to_name(read_cl), consistency_value_to_name(serial_cl), start, end - 1))
def get_expected_consistency(self, idx):
return self.outer.get_expected_consistency(idx, self.rf_factors, self.write_cl, self.read_cl)
def validate_users(self):
"""
First validation function: update the users table sending different values to different sessions
and check that when strong_consistency is true (R + W > N) we read back the latest value from all sessions.
If strong_consistency is false we instead check that we read back the latest value from at least
the number of nodes we wrote to.
"""
outer = self.outer
sessions = self.sessions
start = self.start
end = self.end
write_cl = self.write_cl
read_cl = self.read_cl
serial_cl = self.serial_cl
def check_all_sessions(idx, n, val):
expected_consistency = self.get_expected_consistency(idx)
num = 0
for s in sessions:
if outer.query_user(s, n, val, read_cl, check_ret=expected_consistency.is_strong):
num += 1
assert num >= expected_consistency.num_write_nodes, "Failed to read value from sufficient number of nodes," + \
" required {} but got {} - [{}, {}]".format(expected_consistency.num_write_nodes, num, n, val)
for n in range(start, end):
age = 30
for s in range(0, len(sessions)):
outer.insert_user(sessions[s], n, age, write_cl, serial_cl)
check_all_sessions(s, n, age)
if serial_cl is None:
age += 1
for s in range(0, len(sessions)):
outer.update_user(sessions[s], n, age, write_cl, serial_cl, age - 1)
check_all_sessions(s, n, age)
age += 1
outer.delete_user(sessions[0], n, write_cl)
check_all_sessions(s, n, None)
def validate_counters(self):
"""
Second validation function: update the counters table sending different values to different sessions
and check that when strong_consistency is true (R + W > N) we read back the latest value from all sessions.
If strong_consistency is false we instead check that we read back the latest value from at least
the number of nodes we wrote to.
"""
outer = self.outer
sessions = self.sessions
start = self.start
end = self.end
write_cl = self.write_cl
read_cl = self.read_cl
serial_cl = self.serial_cl
def check_all_sessions(idx, n, val):
expected_consistency = self.get_expected_consistency(idx)
results = []
for s in sessions:
results.append(outer.query_counter(s, n, val, read_cl, check_ret=expected_consistency.is_strong))
assert results.count(val) >= expected_consistency.num_write_nodes, "Failed to read value from sufficient number of nodes, required {} nodes to have a" + \
" counter value of {} at key {}, instead got these values: {}".format(expected_consistency.num_write_nodes, val, n, results)
for n in range(start, end):
c = 1
for s in range(0, len(sessions)):
outer.update_counter(sessions[s], n, write_cl, serial_cl)
check_all_sessions(s, n, c)
# Update the counter again at CL ALL to make sure all nodes are on the same page
# since a counter update requires a read
outer.update_counter(sessions[s], n, ConsistencyLevel.ALL)
c += 2 # the counter was updated twice
def _run_test_function_in_parallel(self, valid_fcn, nodes, rf_factors, combinations):
"""
Run a test function in parallel.
"""
requires_local_reads = False
for combination in combinations:
for i, _ in enumerate(nodes):
expected_consistency = self.get_expected_consistency(i, rf_factors, combination[0], combination[1])
if not expected_consistency.is_strong:
# if at least one combination does not reach strong consistency, in order to validate weak
# consistency we require local reads, see CASSANDRA-12092 for details.
requires_local_reads = True
break
if requires_local_reads:
break
self._start_cluster(save_sessions=True, requires_local_reads=requires_local_reads)
input_queue = queue.Queue()
exceptions_queue = queue.Queue()
def run():
while not input_queue.empty():
try:
v = TestAccuracy.Validation(self, self.sessions, nodes, rf_factors, *input_queue.get(block=False))
valid_fcn(v)
except queue.Empty:
pass
except Exception:
exceptions_queue.put(sys.exc_info())
start = 0
num_keys = 50
for combination in combinations:
input_queue.put((start, start + num_keys) + combination)
start += num_keys
threads = []
for n in range(0, 8):
t = threading.Thread(target=run)
t.setDaemon(True)
t.start()
threads.append(t)
logger.debug("Waiting for workers to complete")
while exceptions_queue.empty():
time.sleep(0.1)
if len([t for t in threads if t.is_alive()]) == 0:
break
if not exceptions_queue.empty():
_, exceptions, tracebacks = list(zip(*exceptions_queue.queue))
raise MultiError(exceptions=exceptions, tracebacks=tracebacks)
@pytest.mark.resource_intensive
def test_simple_strategy_users(self):
"""
Test for a single datacenter, users table, only the each quorum reads.
"""
self.nodes = 5
self.rf = 3
combinations = [
(ConsistencyLevel.ALL, ConsistencyLevel.ALL),
(ConsistencyLevel.QUORUM, ConsistencyLevel.QUORUM),
(ConsistencyLevel.ALL, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.ALL),
(ConsistencyLevel.QUORUM, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.QUORUM),
(ConsistencyLevel.TWO, ConsistencyLevel.TWO),
(ConsistencyLevel.ONE, ConsistencyLevel.THREE),
(ConsistencyLevel.THREE, ConsistencyLevel.ONE),
(ConsistencyLevel.ANY, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.TWO),
(ConsistencyLevel.TWO, ConsistencyLevel.ONE),
# These are multi-DC consistency levels that should default to quorum calls
(ConsistencyLevel.EACH_QUORUM, ConsistencyLevel.LOCAL_QUORUM),
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.LOCAL_QUORUM),
(ConsistencyLevel.QUORUM, ConsistencyLevel.SERIAL, ConsistencyLevel.SERIAL),
(ConsistencyLevel.QUORUM, ConsistencyLevel.LOCAL_SERIAL, ConsistencyLevel.SERIAL),
]
logger.debug("Testing single dc, users")
self._run_test_function_in_parallel(TestAccuracy.Validation.validate_users, [self.nodes], [self.rf], combinations)
@pytest.mark.resource_intensive
@since("3.0")
def test_simple_strategy_each_quorum_users(self):
"""
@jira_ticket CASSANDRA-10584
Test for a single datacenter, users table, only the each quorum reads.
"""
self.nodes = 5
self.rf = 3
combinations = [
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.EACH_QUORUM),
(ConsistencyLevel.EACH_QUORUM, ConsistencyLevel.EACH_QUORUM),
]
logger.debug("Testing single dc, users, each quorum reads")
self._run_test_function_in_parallel(TestAccuracy.Validation.validate_users, [self.nodes], [self.rf], combinations)
@pytest.mark.resource_intensive
def test_network_topology_strategy_users(self):
"""
Test for multiple datacenters, users table.
"""
self.nodes = [3, 3]
self.rf = OrderedDict([('dc1', 3), ('dc2', 3)])
combinations = [
(ConsistencyLevel.ALL, ConsistencyLevel.ALL),
(ConsistencyLevel.QUORUM, ConsistencyLevel.QUORUM),
(ConsistencyLevel.EACH_QUORUM, ConsistencyLevel.LOCAL_QUORUM),
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.LOCAL_QUORUM),
(ConsistencyLevel.ALL, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.ALL),
(ConsistencyLevel.QUORUM, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.QUORUM),
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.LOCAL_QUORUM),
(ConsistencyLevel.EACH_QUORUM, ConsistencyLevel.ONE),
(ConsistencyLevel.TWO, ConsistencyLevel.TWO),
(ConsistencyLevel.ONE, ConsistencyLevel.THREE),
(ConsistencyLevel.THREE, ConsistencyLevel.ONE),
(ConsistencyLevel.ANY, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.TWO),
(ConsistencyLevel.TWO, ConsistencyLevel.ONE),
(ConsistencyLevel.QUORUM, ConsistencyLevel.SERIAL, ConsistencyLevel.SERIAL),
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.LOCAL_SERIAL, ConsistencyLevel.LOCAL_SERIAL),
(ConsistencyLevel.QUORUM, ConsistencyLevel.LOCAL_SERIAL, ConsistencyLevel.SERIAL),
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.SERIAL, ConsistencyLevel.LOCAL_SERIAL),
]
logger.debug("Testing multiple dcs, users")
self._run_test_function_in_parallel(TestAccuracy.Validation.validate_users, self.nodes, list(self.rf.values()), combinations),
@pytest.mark.resource_intensive
@since("3.0")
def test_network_topology_strategy_each_quorum_users(self):
"""
@jira_ticket CASSANDRA-10584
Test for a multiple datacenters, users table, only the each quorum
reads.
"""
self.nodes = [3, 3]
self.rf = OrderedDict([('dc1', 3), ('dc2', 3)])
combinations = [
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.EACH_QUORUM),
(ConsistencyLevel.EACH_QUORUM, ConsistencyLevel.EACH_QUORUM),
]
logger.debug("Testing multiple dcs, users, each quorum reads")
self._run_test_function_in_parallel(TestAccuracy.Validation.validate_users, self.nodes, list(self.rf.values()), combinations)
def test_simple_strategy_counters(self):
"""
Test for a single datacenter, counters table.
"""
self.nodes = 3
self.rf = 3
combinations = [
(ConsistencyLevel.ALL, ConsistencyLevel.ALL),
(ConsistencyLevel.QUORUM, ConsistencyLevel.QUORUM),
(ConsistencyLevel.ALL, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.ALL),
(ConsistencyLevel.QUORUM, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.QUORUM),
(ConsistencyLevel.TWO, ConsistencyLevel.TWO),
(ConsistencyLevel.ONE, ConsistencyLevel.THREE),
(ConsistencyLevel.THREE, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.TWO),
(ConsistencyLevel.TWO, ConsistencyLevel.ONE),
# These are multi-DC consistency levels that should default to quorum calls
(ConsistencyLevel.EACH_QUORUM, ConsistencyLevel.LOCAL_QUORUM),
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.LOCAL_QUORUM),
]
logger.debug("Testing single dc, counters")
self._run_test_function_in_parallel(TestAccuracy.Validation.validate_counters, [self.nodes], [self.rf], combinations)
@since("3.0")
def test_simple_strategy_each_quorum_counters(self):
"""
@jira_ticket CASSANDRA-10584
Test for a single datacenter, counters table, only the each quorum
reads.
"""
self.nodes = 3
self.rf = 3
combinations = [
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.EACH_QUORUM),
(ConsistencyLevel.EACH_QUORUM, ConsistencyLevel.EACH_QUORUM),
]
logger.debug("Testing single dc, counters, each quorum reads")
self._run_test_function_in_parallel(TestAccuracy.Validation.validate_counters, [self.nodes], [self.rf], combinations)
@pytest.mark.resource_intensive
def test_network_topology_strategy_counters(self):
"""
Test for multiple datacenters, counters table.
"""
self.nodes = [3, 3]
self.rf = OrderedDict([('dc1', 3), ('dc2', 3)])
combinations = [
(ConsistencyLevel.ALL, ConsistencyLevel.ALL),
(ConsistencyLevel.QUORUM, ConsistencyLevel.QUORUM),
(ConsistencyLevel.EACH_QUORUM, ConsistencyLevel.LOCAL_QUORUM),
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.LOCAL_QUORUM),
(ConsistencyLevel.ALL, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.ALL),
(ConsistencyLevel.QUORUM, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.QUORUM),
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.LOCAL_QUORUM),
(ConsistencyLevel.EACH_QUORUM, ConsistencyLevel.ONE),
(ConsistencyLevel.TWO, ConsistencyLevel.TWO),
(ConsistencyLevel.ONE, ConsistencyLevel.THREE),
(ConsistencyLevel.THREE, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.ONE),
(ConsistencyLevel.ONE, ConsistencyLevel.TWO),
(ConsistencyLevel.TWO, ConsistencyLevel.ONE),
]
logger.debug("Testing multiple dcs, counters")
self._run_test_function_in_parallel(TestAccuracy.Validation.validate_counters, self.nodes, list(self.rf.values()), combinations),
@pytest.mark.resource_intensive
@since("3.0")
def test_network_topology_strategy_each_quorum_counters(self):
"""
@jira_ticket CASSANDRA-10584
Test for multiple datacenters, counters table, only the each quorum
reads.
"""
self.nodes = [3, 3]
self.rf = OrderedDict([('dc1', 3), ('dc2', 3)])
combinations = [
(ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.EACH_QUORUM),
(ConsistencyLevel.EACH_QUORUM, ConsistencyLevel.EACH_QUORUM),
]
logger.debug("Testing multiple dcs, counters, each quorum reads")
self._run_test_function_in_parallel(TestAccuracy.Validation.validate_counters, self.nodes, list(self.rf.values()), combinations),
class TestConsistency(Tester):
@since('4.0')
def test_18766_sr(self):
"""
@jira_ticket CASSANDRA-18766
"""
cluster = self.cluster
self.cluster.populate(3).start()
node1 = cluster.nodelist()[0]
node1.stress(['write', 'n=100000', '-rate', 'threads=8', '-schema', 'replication(strategy=SimpleStrategy,replication_factor=2)'])
node1.stress(['read no-warmup duration=1m', '-rate', 'threads=8', '-errors', 'skip-read-validation'])
speculative_reads_mbean = make_mbean("metrics", type="Table", name="SpeculativeRetries", keyspace='keyspace1', scope='standard1')
coordinator_reads_mbean = make_mbean("metrics", type="Table", name="CoordinatorReadLatency", keyspace='keyspace1', scope='standard1')
for node in cluster.nodelist():
with JolokiaAgent(node) as jmx:
sr = jmx.read_attribute(speculative_reads_mbean, "Count")
cr = jmx.read_attribute(coordinator_reads_mbean, "Count")
pcent = sr / cr * 100
assert pcent < 10, "Speculative retry percentage %.2f%% too high on %s" % (pcent, node.address_and_port())
@since('3.0')
def test_14513_transient(self):
"""
@jira_ticket CASSANDRA-14513
A reproduction / regression test to illustrate CASSANDRA-14513:
transient data loss when doing reverse-order queries with range
tombstones in place.
This test shows how the bug can cause queries to return invalid
results by just a single node.
"""
cluster = self.cluster
# set column_index_size_in_kb to 1 for a slightly easier reproduction sequence
cluster.set_configuration_options(values={'column_index_size_in_kb': 1})
cluster.populate(1).start()
node1 = cluster.nodelist()[0]
session = self.patient_cql_connection(node1)
query = "CREATE KEYSPACE journals WITH replication = {'class': 'NetworkTopologyStrategy', 'datacenter1': 1};"
session.execute(query)
query = 'CREATE TABLE journals.logs (user text, year int, month int, day int, title text, body text, PRIMARY KEY ((user), year, month, day, title));';
session.execute(query)
# populate the table
stmt = session.prepare('INSERT INTO journals.logs (user, year, month, day, title, body) VALUES (?, ?, ?, ?, ?, ?);');
for year in range(2011, 2018):
for month in range(1, 13):
for day in range(1, 31):
session.execute(stmt, ['beobal', year, month, day, 'title', 'Lorem ipsum dolor sit amet'], ConsistencyLevel.ONE)
node1.flush()
# make sure the data is there
assert_all(session,
"SELECT COUNT(*) FROM journals.logs WHERE user = 'beobal' AND year < 2018 ORDER BY year DESC;",
[[7 * 12 * 30]],
cl=ConsistencyLevel.ONE)
# generate an sstable with an RT that opens in the penultimate block and closes in the last one
stmt = session.prepare('DELETE FROM journals.logs WHERE user = ? AND year = ? AND month = ? AND day = ?;')
batch = BatchStatement(batch_type=BatchType.UNLOGGED)
for day in range(1, 31):
batch.add(stmt, ['beobal', 2018, 1, day])
session.execute(batch)
node1.flush()
# the data should still be there for years 2011-2017, but prior to CASSANDRA-14513 it would've been gone
assert_all(session,
"SELECT COUNT(*) FROM journals.logs WHERE user = 'beobal' AND year < 2018 ORDER BY year DESC;",
[[7 * 12 * 30]],
cl=ConsistencyLevel.ONE)
@since('3.0')
def test_14513_permanent(self):
"""
@jira_ticket CASSANDRA-14513
A reproduction / regression test to illustrate CASSANDRA-14513:
permanent data loss when doing reverse-order queries with range
tombstones in place.
This test shows how the invalid RT can propagate to other replicas
and delete data permanently.
"""
cluster = self.cluster
# disable hinted handoff and set batch commit log so this doesn't interfere with the test
# set column_index_size_in_kb to 1 for a slightly easier reproduction sequence
cluster.set_configuration_options(values={'column_index_size_in_kb': 1, 'hinted_handoff_enabled': False})
cluster.set_batch_commitlog(enabled=True, use_batch_window = cluster.version() < '5.0')
cluster.populate(3).start()
node1, node2, node3 = cluster.nodelist()
session = self.patient_exclusive_cql_connection(node1)
query = "CREATE KEYSPACE journals WITH replication = {'class': 'NetworkTopologyStrategy', 'datacenter1': 3};"
session.execute(query)
query = 'CREATE TABLE journals.logs (user text, year int, month int, day int, title text, body text, PRIMARY KEY ((user), year, month, day, title));';
session.execute(query)
# populate the table
stmt = session.prepare('INSERT INTO journals.logs (user, year, month, day, title, body) VALUES (?, ?, ?, ?, ?, ?);');
for year in range(2011, 2018):
for month in range(1, 13):
for day in range(1, 31):
session.execute(stmt, ['beobal', year, month, day, 'title', 'Lorem ipsum dolor sit amet'], ConsistencyLevel.QUORUM)
cluster.flush()
# make sure the data is there
assert_all(session,
"SELECT COUNT(*) FROM journals.logs WHERE user = 'beobal' AND year < 2018 ORDER BY year DESC;",
[[7 * 12 * 30]],
cl=ConsistencyLevel.QUORUM)
# take one node down
node3.stop(wait_other_notice=True)
# generate an sstable with an RT that opens in the penultimate block and closes in the last one
stmt = session.prepare('DELETE FROM journals.logs WHERE user = ? AND year = ? AND month = ? AND day = ?;')
batch = BatchStatement(batch_type=BatchType.UNLOGGED)
for day in range(1, 31):
batch.add(stmt, ['beobal', 2018, 1, day])
session.execute(batch, [], ConsistencyLevel.QUORUM)
node1.flush()
node2.flush()
# take node2 down, get node3 up
node2.stop(wait_other_notice=True)
node3.start()
# insert an RT somewhere so that we would have a closing marker and RR makes its mutations
stmt = SimpleStatement("DELETE FROM journals.logs WHERE user = 'beobal' AND year = 2010 AND month = 12 AND day = 30",
consistency_level=ConsistencyLevel.QUORUM)
session.execute(stmt)
# this read will trigger read repair with the invalid RT and propagate the wide broken RT,
# permanently killing the partition
stmt = SimpleStatement("SELECT * FROM journals.logs WHERE user = 'beobal' AND year < 2018 ORDER BY year DESC;",
consistency_level=ConsistencyLevel.QUORUM)
session.execute(stmt)
# everything is gone
assert_all(session,
"SELECT COUNT(*) FROM journals.logs WHERE user = 'beobal';",
[[7 * 12 * 30]],
cl=ConsistencyLevel.QUORUM)
@since('3.0')
def test_14330(self):
"""
@jira_ticket CASSANDRA-14330
A regression test to prove that we no longer trigger
AssertionError during read repair in DataResolver
when encountering a repeat open RT bound from short
read protection responses.
"""
cluster = self.cluster
# disable hinted handoff and set batch commit log so this doesn't interfere with the test
cluster.set_configuration_options(values={'hinted_handoff_enabled': False})
cluster.set_batch_commitlog(enabled=True, use_batch_window = cluster.version() < '5.0')
cluster.populate(2).start()
node1, node2 = cluster.nodelist()
session = self.patient_cql_connection(node2)
query = "CREATE KEYSPACE test WITH replication = {'class': 'NetworkTopologyStrategy', 'datacenter1': 2};"
session.execute(query)
query = 'CREATE TABLE test.test (pk int, ck int, PRIMARY KEY (pk, ck));'
session.execute(query)
# with all nodes up, insert an RT and 2 rows on every node
#
# node1 | RT[0...] 0 1
# node2 | RT[0...] 0 1
session.execute('DELETE FROM test.test USING TIMESTAMP 0 WHERE pk = 0 AND ck >= 0;')
session.execute('INSERT INTO test.test (pk, ck) VALUES (0, 0) USING TIMESTAMP 1;')
session.execute('INSERT INTO test.test (pk, ck) VALUES (0, 1) USING TIMESTAMP 1;')
# with node1 down, delete row 0 on node2
#
# node1 | RT[0...] 0 1
# node2 | RT[0...] x 1
node1.stop(wait_other_notice=True)
session.execute('DELETE FROM test.test USING TIMESTAMP 1 WHERE pk = 0 AND ck = 0;')
node1.start(wait_for_binary_proto=True)
# with both nodes up, make a LIMIT 1 read that would trigger a short read protection
# request, which in turn will trigger the AssertionError in DataResolver (prior to
# CASSANDRA-14330 fix)
assert_all(session,
'SELECT ck FROM test.test WHERE pk = 0 LIMIT 1;',
[[1]],
cl=ConsistencyLevel.ALL)
@since('3.0')
@ported_to_in_jvm('4.0')
def test_13911(self):
"""
@jira_ticket CASSANDRA-13911
"""
cluster = self.cluster
# disable hinted handoff and set batch commit log so this doesn't interfere with the test
cluster.set_configuration_options(values={'hinted_handoff_enabled': False})
cluster.set_batch_commitlog(enabled=True, use_batch_window = cluster.version() < '5.0')
cluster.populate(2).start()
node1, node2 = cluster.nodelist()
session = self.patient_cql_connection(node1)
query = "CREATE KEYSPACE test WITH replication = {'class': 'NetworkTopologyStrategy', 'datacenter1': 2};"
session.execute(query)
query = 'CREATE TABLE test.test (pk int, ck int, PRIMARY KEY (pk, ck));'
session.execute(query)
# with node2 down, insert row 0 on node1