forked from apache/cassandra-dtest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
consistency_test.py
1393 lines (1132 loc) · 58.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
from collections import OrderedDict, namedtuple
from copy import deepcopy
from cassandra import ConsistencyLevel, consistency_value_to_name
from cassandra.query import SimpleStatement
from nose.plugins.attrib import attr
from nose.tools import assert_greater_equal
from tools.assertions import (assert_all, assert_length_equal, assert_none,
assert_unavailable)
from dtest import DISABLE_VNODES, MultiError, Tester, debug, create_ks, create_cf
from tools.data import (create_c1c2_table, insert_c1c2, insert_columns,
query_c1c2, rows_to_list)
from tools.decorators import since
from tools.jmxutils import JolokiaAgent, make_mbean, remove_perf_disable_shared_mem
ExpectedConsistency = namedtuple('ExpectedConsistency', ('num_write_nodes', 'num_read_nodes', 'is_strong'))
class TestHelper(Tester):
def __init__(self, *args, **kwargs):
Tester.__init__(self, *args, **kwargs)
self.lock = threading.Lock()
def log(self, message):
with self.lock:
debug(message)
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 xrange(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 xrange(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.
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(wait_for_binary_proto=True, wait_other_notice=True)
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()
session.execute(create_cmd)
@staticmethod
def get_local_reads_properties():
"""
If we must read from the local replica first, then we should disable read repair and
speculative retry, see CASSANDRA-12092
"""
return " dclocal_read_repair_chance = 0 AND read_repair_chance = 0 AND 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:
self.assertTrue(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()
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:
self.assertEqual(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 xrange(nodes):
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 = rf.values()
for i in xrange(0, len(nodes)): # for each dc
self.log('Testing dc {} with rf {} and {} nodes alive'.format(i, rf_factors[i], nodes_alive))
for n in xrange(nodes[i]): # for each node in this dc
self.log('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.
"""
self.log("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 xrange(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 xrange(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)
@attr("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)
@attr("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
outer.log('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_greater_equal(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 xrange(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_greater_equal(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 xrange(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)
self.log("Waiting for workers to complete")
while exceptions_queue.empty():
time.sleep(0.1)
if len(filter(lambda t: t.isAlive(), threads)) == 0:
break
if not exceptions_queue.empty():
_, exceptions, tracebacks = zip(*exceptions_queue.queue)
raise MultiError(exceptions=exceptions, tracebacks=tracebacks)
@attr("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),
]
self.log("Testing single dc, users")
self._run_test_function_in_parallel(TestAccuracy.Validation.validate_users, [self.nodes], [self.rf], combinations)
@attr("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),
]
self.log("Testing single dc, users, each quorum reads")
self._run_test_function_in_parallel(TestAccuracy.Validation.validate_users, [self.nodes], [self.rf], combinations)
@attr("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),
]
self.log("Testing multiple dcs, users")
self._run_test_function_in_parallel(TestAccuracy.Validation.validate_users, self.nodes, self.rf.values(), combinations),
@attr("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),
]
self.log("Testing multiple dcs, users, each quorum reads")
self._run_test_function_in_parallel(TestAccuracy.Validation.validate_users, self.nodes, 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),
]
self.log("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),
]
self.log("Testing single dc, counters, each quorum reads")
self._run_test_function_in_parallel(TestAccuracy.Validation.validate_counters, [self.nodes], [self.rf], combinations)
@attr("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),
]
self.log("Testing multiple dcs, counters")
self._run_test_function_in_parallel(TestAccuracy.Validation.validate_counters, self.nodes, self.rf.values(), combinations),
@attr("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),
]
self.log("Testing multiple dcs, counters, each quorum reads")
self._run_test_function_in_parallel(TestAccuracy.Validation.validate_counters, self.nodes, self.rf.values(), combinations),
class TestConsistency(Tester):
@since('3.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)
cluster.populate(2).start(wait_other_notice=True)
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
#
# node1, partition 0 | 0
# node2, partition 0 |
node2.stop(wait_other_notice=True)
session.execute('INSERT INTO test.test (pk, ck) VALUES (0, 0);')
node2.start(wait_other_notice=True, wait_for_binary_proto=True)
# with node1 down, delete row 1 and 2 on node2
#
# node1, partition 0 | 0
# node2, partition 0 | x x
session = self.patient_cql_connection(node2)
node1.stop(wait_other_notice=True)
session.execute('DELETE FROM test.test WHERE pk = 0 AND ck IN (1, 2);')
node1.start(wait_other_notice=True, wait_for_binary_proto=True)
# with both nodes up, do a CL.ALL query with per partition limit of 1;
# prior to CASSANDRA-13911 this would trigger an IllegalStateException
assert_all(session,
'SELECT DISTINCT pk FROM test.test;',
[[0]],
cl=ConsistencyLevel.ALL)
@since('3.11')
def test_13911_rows_srp(self):
"""
@jira_ticket CASSANDRA-13911
A regression test to prove that we can no longer rely on
!singleResultCounter.isDoneForPartition() to abort single
partition SRP early if a per partition limit is set.
"""
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)
cluster.populate(2).start(wait_other_notice=True)
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
#
# node1, partition 0 | 0 1 - -
# node1, partition 2 | 0 x - -
node2.stop(wait_other_notice=True)
session.execute('INSERT INTO test.test (pk, ck) VALUES (0, 0) USING TIMESTAMP 42;')
session.execute('INSERT INTO test.test (pk, ck) VALUES (0, 1) USING TIMESTAMP 42;')
session.execute('INSERT INTO test.test (pk, ck) VALUES (2, 0) USING TIMESTAMP 42;')
session.execute('DELETE FROM test.test USING TIMESTAMP 42 WHERE pk = 2 AND ck = 1;')
node2.start(wait_other_notice=True, wait_for_binary_proto=True)
# with node1 down
#
# node2, partition 0 | - - 2 3
# node2, partition 2 | x 1 2 -
session = self.patient_cql_connection(node2)
node1.stop(wait_other_notice=True)
session.execute('INSERT INTO test.test (pk, ck) VALUES (0, 2) USING TIMESTAMP 42;')
session.execute('INSERT INTO test.test (pk, ck) VALUES (0, 3) USING TIMESTAMP 42;')
session.execute('DELETE FROM test.test USING TIMESTAMP 42 WHERE pk = 2 AND ck = 0;')
session.execute('INSERT INTO test.test (pk, ck) VALUES (2, 1) USING TIMESTAMP 42;')
session.execute('INSERT INTO test.test (pk, ck) VALUES (2, 2) USING TIMESTAMP 42;')
node1.start(wait_other_notice=True, wait_for_binary_proto=True)
# with both nodes up, do a CL.ALL query with per partition limit of 2 and limit of 3;
# without the change to if (!singleResultCounter.isDoneForPartition()) branch,
# the query would skip SRP on node2, partition 2, and incorrectly return just
# [[0, 0], [0, 1]]
assert_all(session,
'SELECT pk, ck FROM test.test PER PARTITION LIMIT 2 LIMIT 3;',
[[0, 0], [0, 1],
[2, 2]],
cl=ConsistencyLevel.ALL)
@since('3.11')
def test_13911_partitions_srp(self):
"""
@jira_ticket CASSANDRA-13911
A regression test to prove that we can't rely on
!singleResultCounter.isDone() to abort ranged
partition SRP early if a per partition limit is set.
"""
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)
cluster.populate(2).start(wait_other_notice=True)
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
#
# node1, partition 0 | 0 1 - -
# node1, partition 2 | x x - -
node2.stop(wait_other_notice=True)
session.execute('INSERT INTO test.test (pk, ck) VALUES (0, 0) USING TIMESTAMP 42;')
session.execute('INSERT INTO test.test (pk, ck) VALUES (0, 1) USING TIMESTAMP 42;')
session.execute('DELETE FROM test.test USING TIMESTAMP 42 WHERE pk = 2 AND ck IN (0, 1);')
node2.start(wait_other_notice=True, wait_for_binary_proto=True)
# with node1 down
#
# node2, partition 0 | - - 2 3
# node2, partition 2 | 0 1 - -
# node2, partition 4 | 0 1 - -
session = self.patient_cql_connection(node2)
node1.stop(wait_other_notice=True)
session.execute('INSERT INTO test.test (pk, ck) VALUES (0, 2) USING TIMESTAMP 42;')
session.execute('INSERT INTO test.test (pk, ck) VALUES (0, 3) USING TIMESTAMP 42;')
session.execute('INSERT INTO test.test (pk, ck) VALUES (2, 0) USING TIMESTAMP 42;')
session.execute('INSERT INTO test.test (pk, ck) VALUES (2, 1) USING TIMESTAMP 42;')
session.execute('INSERT INTO test.test (pk, ck) VALUES (4, 0) USING TIMESTAMP 42;')
session.execute('INSERT INTO test.test (pk, ck) VALUES (4, 1) USING TIMESTAMP 42;')
node1.start(wait_other_notice=True, wait_for_binary_proto=True)
# with both nodes up, do a CL.ALL query with per partition limit of 2 and limit of 4;
# without the extra condition in if (!singleResultCounter.isDone()) branch,
# the query would skip partitions SRP on node2 at the end of partition 2,
# and incorrectly return just [[0, 0], [0, 1]]
assert_all(session,
'SELECT pk, ck FROM test.test PER PARTITION LIMIT 2 LIMIT 4;',
[[0, 0], [0, 1],
[4, 0], [4, 1]],
cl=ConsistencyLevel.ALL)
@since('3.0')
def test_13880(self):
"""
@jira_ticket CASSANDRA-13880
"""
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)
cluster.populate(2).start(wait_other_notice=True)
node1, node2 = cluster.nodelist()
session = self.patient_cql_connection(node1)
query = "CREATE KEYSPACE IF NOT EXISTS test WITH replication = {'class': 'NetworkTopologyStrategy', 'datacenter1': 2};"
session.execute(query)
query = "CREATE TABLE IF NOT EXISTS test.test (id int PRIMARY KEY);"
session.execute(query)
stmt = SimpleStatement("INSERT INTO test.test (id) VALUES (0);",
consistency_level=ConsistencyLevel.ALL)
session.execute(stmt)
# with node2 down and hints disabled, delete the partition on node1
node2.stop(wait_other_notice=True)
session.execute("DELETE FROM test.test WHERE id = 0;")
node2.start(wait_other_notice=True)
# with both nodes up, do a CL.ALL query with per partition limit of 1;
# prior to CASSANDRA-13880 this would cause short read protection to loop forever
assert_none(session, "SELECT DISTINCT id FROM test.test WHERE id = 0;", cl=ConsistencyLevel.ALL)
@since('3.0')
def test_13747(self):
"""
@jira_ticket CASSANDRA-13747
"""
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)
cluster.populate(2).start(wait_other_notice=True)
node1, node2 = cluster.nodelist()