-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_cluster.py
1569 lines (1288 loc) · 61.5 KB
/
test_cluster.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
# Copyright DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
import unittest2 as unittest
except ImportError:
import unittest # noqa
from collections import deque
from copy import copy
from mock import Mock, call, patch
import time
from uuid import uuid4
import logging
import warnings
from packaging.version import Version
import cassandra
from cassandra.cluster import NoHostAvailable, ExecutionProfile, EXEC_PROFILE_DEFAULT, ControlConnection, Cluster
from cassandra.concurrent import execute_concurrent
from cassandra.policies import (RoundRobinPolicy, ExponentialReconnectionPolicy,
RetryPolicy, SimpleConvictionPolicy, HostDistance,
AddressTranslator, TokenAwarePolicy, HostFilterPolicy)
from cassandra import ConsistencyLevel
from cassandra.query import SimpleStatement, TraceUnavailable, tuple_factory
from cassandra.auth import PlainTextAuthProvider, SaslAuthProvider
from cassandra import connection
from cassandra.connection import DefaultEndPoint
from tests import notwindows
from tests.integration import use_singledc, get_server_versions, CASSANDRA_VERSION, \
execute_until_pass, execute_with_long_wait_retry, get_node, MockLoggingHandler, get_unsupported_lower_protocol, \
get_unsupported_upper_protocol, protocolv5, local, CASSANDRA_IP, greaterthanorequalcass30, lessthanorequalcass40, \
DSE_VERSION, TestCluster, PROTOCOL_VERSION
from tests.integration.util import assert_quiescent_pool_state
import sys
log = logging.getLogger(__name__)
def setup_module():
use_singledc()
warnings.simplefilter("always")
class IgnoredHostPolicy(RoundRobinPolicy):
def __init__(self, ignored_hosts):
self.ignored_hosts = ignored_hosts
RoundRobinPolicy.__init__(self)
def distance(self, host):
if(host.address in self.ignored_hosts):
return HostDistance.IGNORED
else:
return HostDistance.LOCAL
class ClusterTests(unittest.TestCase):
@local
def test_ignored_host_up(self):
"""
Test to ensure that is_up is not set by default on ignored hosts
@since 3.6
@jira_ticket PYTHON-551
@expected_result ignored hosts should have None set for is_up
@test_category connection
"""
ignored_host_policy = IgnoredHostPolicy(["127.0.0.2", "127.0.0.3"])
cluster = TestCluster(
execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(load_balancing_policy=ignored_host_policy)}
)
cluster.connect()
for host in cluster.metadata.all_hosts():
if str(host) == "127.0.0.1:9042":
self.assertTrue(host.is_up)
else:
self.assertIsNone(host.is_up)
cluster.shutdown()
@local
def test_host_resolution(self):
"""
Test to insure A records are resolved appropriately.
@since 3.3
@jira_ticket PYTHON-415
@expected_result hostname will be transformed into IP
@test_category connection
"""
cluster = TestCluster(contact_points=["localhost"], connect_timeout=1)
self.assertTrue(DefaultEndPoint('127.0.0.1') in cluster.endpoints_resolved)
@local
def test_host_duplication(self):
"""
Ensure that duplicate hosts in the contact points are surfaced in the cluster metadata
@since 3.3
@jira_ticket PYTHON-103
@expected_result duplicate hosts aren't surfaced in cluster.metadata
@test_category connection
"""
cluster = TestCluster(
contact_points=["localhost", "127.0.0.1", "localhost", "localhost", "localhost"],
connect_timeout=1
)
cluster.connect(wait_for_all_pools=True)
self.assertEqual(len(cluster.metadata.all_hosts()), 3)
cluster.shutdown()
cluster = TestCluster(contact_points=["127.0.0.1", "localhost"], connect_timeout=1)
cluster.connect(wait_for_all_pools=True)
self.assertEqual(len(cluster.metadata.all_hosts()), 3)
cluster.shutdown()
@local
def test_raise_error_on_control_connection_timeout(self):
"""
Test for initial control connection timeout
test_raise_error_on_control_connection_timeout tests that the driver times out after the set initial connection
timeout. It first pauses node1, essentially making it unreachable. It then attempts to create a Cluster object
via connecting to node1 with a timeout of 1 second, and ensures that a NoHostAvailable is raised, along with
an OperationTimedOut for 1 second.
@expected_errors NoHostAvailable When node1 is paused, and a connection attempt is made.
@since 2.6.0
@jira_ticket PYTHON-206
@expected_result NoHostAvailable exception should be raised after 1 second.
@test_category connection
"""
get_node(1).pause()
cluster = TestCluster(contact_points=['127.0.0.1'], connect_timeout=1)
with self.assertRaisesRegexp(NoHostAvailable, "OperationTimedOut\('errors=Timed out creating connection \(1 seconds\)"):
cluster.connect()
cluster.shutdown()
get_node(1).resume()
def test_basic(self):
"""
Test basic connection and usage
"""
cluster = TestCluster()
session = cluster.connect()
result = execute_until_pass(session,
"""
CREATE KEYSPACE clustertests
WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}
""")
self.assertFalse(result)
result = execute_with_long_wait_retry(session,
"""
CREATE TABLE clustertests.cf0 (
a text,
b text,
c text,
PRIMARY KEY (a, b)
)
""")
self.assertFalse(result)
result = session.execute(
"""
INSERT INTO clustertests.cf0 (a, b, c) VALUES ('a', 'b', 'c')
""")
self.assertFalse(result)
result = session.execute("SELECT * FROM clustertests.cf0")
self.assertEqual([('a', 'b', 'c')], result)
execute_with_long_wait_retry(session, "DROP KEYSPACE clustertests")
cluster.shutdown()
def test_session_host_parameter(self):
"""
Test for protocol negotiation
Very that NoHostAvailable is risen in Session.__init__ when there are no valid connections and that
no error is arisen otherwise, despite maybe being some invalid hosts
@since 3.9
@jira_ticket PYTHON-665
@expected_result NoHostAvailable when the driver is unable to connect to a valid host,
no exception otherwise
@test_category connection
"""
def cleanup():
"""
When this test fails, the inline .shutdown() calls don't get
called, so we register this as a cleanup.
"""
self.cluster_to_shutdown.shutdown()
self.addCleanup(cleanup)
# Test with empty list
self.cluster_to_shutdown = TestCluster(contact_points=[])
with self.assertRaises(NoHostAvailable):
self.cluster_to_shutdown.connect()
self.cluster_to_shutdown.shutdown()
# Test with only invalid
self.cluster_to_shutdown = TestCluster(contact_points=('1.2.3.4',))
with self.assertRaises(NoHostAvailable):
self.cluster_to_shutdown.connect()
self.cluster_to_shutdown.shutdown()
# Test with valid and invalid hosts
self.cluster_to_shutdown = TestCluster(contact_points=("127.0.0.1", "127.0.0.2", "1.2.3.4"))
self.cluster_to_shutdown.connect()
self.cluster_to_shutdown.shutdown()
def test_protocol_negotiation(self):
"""
Test for protocol negotiation
test_protocol_negotiation tests that the driver will select the correct protocol version to match
the correct cassandra version. Please note that 2.1.5 has a
bug https://issues.apache.org/jira/browse/CASSANDRA-9451 that will cause this test to fail
that will cause this to not pass. It was rectified in 2.1.6
@since 2.6.0
@jira_ticket PYTHON-240
@expected_result the correct protocol version should be selected
@test_category connection
"""
cluster = Cluster()
self.assertLessEqual(cluster.protocol_version, cassandra.ProtocolVersion.MAX_SUPPORTED)
session = cluster.connect()
updated_protocol_version = session._protocol_version
updated_cluster_version = cluster.protocol_version
# Make sure the correct protocol was selected by default
if DSE_VERSION and DSE_VERSION >= Version("6.0"):
self.assertEqual(updated_protocol_version, cassandra.ProtocolVersion.DSE_V2)
self.assertEqual(updated_cluster_version, cassandra.ProtocolVersion.DSE_V2)
elif DSE_VERSION and DSE_VERSION >= Version("5.1"):
self.assertEqual(updated_protocol_version, cassandra.ProtocolVersion.DSE_V1)
self.assertEqual(updated_cluster_version, cassandra.ProtocolVersion.DSE_V1)
elif CASSANDRA_VERSION >= Version('2.2'):
self.assertEqual(updated_protocol_version, 4)
self.assertEqual(updated_cluster_version, 4)
elif CASSANDRA_VERSION >= Version('2.1'):
self.assertEqual(updated_protocol_version, 3)
self.assertEqual(updated_cluster_version, 3)
elif CASSANDRA_VERSION >= Version('2.0'):
self.assertEqual(updated_protocol_version, 2)
self.assertEqual(updated_cluster_version, 2)
else:
self.assertEqual(updated_protocol_version, 1)
self.assertEqual(updated_cluster_version, 1)
cluster.shutdown()
def test_invalid_protocol_negotation(self):
"""
Test for protocol negotiation when explicit versions are set
If an explicit protocol version that is not compatible with the server version is set
an exception should be thrown. It should not attempt to negotiate
for reference supported protocol version to server versions is as follows/
1.2 -> 1
2.0 -> 2, 1
2.1 -> 3, 2, 1
2.2 -> 4, 3, 2, 1
3.X -> 4, 3
@since 3.6.0
@jira_ticket PYTHON-537
@expected_result downgrading should not be allowed when explicit protocol versions are set.
@test_category connection
"""
upper_bound = get_unsupported_upper_protocol()
log.debug('got upper_bound of {}'.format(upper_bound))
if upper_bound is not None:
cluster = TestCluster(protocol_version=upper_bound)
with self.assertRaises(NoHostAvailable):
cluster.connect()
cluster.shutdown()
lower_bound = get_unsupported_lower_protocol()
log.debug('got lower_bound of {}'.format(lower_bound))
if lower_bound is not None:
cluster = TestCluster(protocol_version=lower_bound)
with self.assertRaises(NoHostAvailable):
cluster.connect()
cluster.shutdown()
def test_connect_on_keyspace(self):
"""
Ensure clusters that connect on a keyspace, do
"""
cluster = TestCluster()
session = cluster.connect()
result = session.execute(
"""
INSERT INTO test1rf.test (k, v) VALUES (8889, 8889)
""")
self.assertFalse(result)
result = session.execute("SELECT * FROM test1rf.test")
self.assertEqual([(8889, 8889)], result, "Rows in ResultSet are {0}".format(result.current_rows))
# test_connect_on_keyspace
session2 = cluster.connect('test1rf')
result2 = session2.execute("SELECT * FROM test")
self.assertEqual(result, result2)
cluster.shutdown()
def test_set_keyspace_twice(self):
cluster = TestCluster()
session = cluster.connect()
session.execute("USE system")
session.execute("USE system")
cluster.shutdown()
def test_default_connections(self):
"""
Ensure errors are not thrown when using non-default policies
"""
TestCluster(
reconnection_policy=ExponentialReconnectionPolicy(1.0, 600.0),
conviction_policy_factory=SimpleConvictionPolicy,
protocol_version=PROTOCOL_VERSION
)
def test_connect_to_already_shutdown_cluster(self):
"""
Ensure you cannot connect to a cluster that's been shutdown
"""
cluster = TestCluster()
cluster.shutdown()
self.assertRaises(Exception, cluster.connect)
def test_auth_provider_is_callable(self):
"""
Ensure that auth_providers are always callable
"""
self.assertRaises(TypeError, Cluster, auth_provider=1, protocol_version=1)
c = TestCluster(protocol_version=1)
self.assertRaises(TypeError, setattr, c, 'auth_provider', 1)
def test_v2_auth_provider(self):
"""
Check for v2 auth_provider compliance
"""
bad_auth_provider = lambda x: {'username': 'foo', 'password': 'bar'}
self.assertRaises(TypeError, Cluster, auth_provider=bad_auth_provider, protocol_version=2)
c = TestCluster(protocol_version=2)
self.assertRaises(TypeError, setattr, c, 'auth_provider', bad_auth_provider)
def test_conviction_policy_factory_is_callable(self):
"""
Ensure that conviction_policy_factory are always callable
"""
self.assertRaises(ValueError, Cluster, conviction_policy_factory=1)
def test_connect_to_bad_hosts(self):
"""
Ensure that a NoHostAvailable Exception is thrown
when a cluster cannot connect to given hosts
"""
cluster = TestCluster(contact_points=['127.1.2.9', '127.1.2.10'],
protocol_version=PROTOCOL_VERSION)
self.assertRaises(NoHostAvailable, cluster.connect)
def test_cluster_settings(self):
"""
Test connection setting getters and setters
"""
if PROTOCOL_VERSION >= 3:
raise unittest.SkipTest("min/max requests and core/max conns aren't used with v3 protocol")
cluster = TestCluster()
min_requests_per_connection = cluster.get_min_requests_per_connection(HostDistance.LOCAL)
self.assertEqual(cassandra.cluster.DEFAULT_MIN_REQUESTS, min_requests_per_connection)
cluster.set_min_requests_per_connection(HostDistance.LOCAL, min_requests_per_connection + 1)
self.assertEqual(cluster.get_min_requests_per_connection(HostDistance.LOCAL), min_requests_per_connection + 1)
max_requests_per_connection = cluster.get_max_requests_per_connection(HostDistance.LOCAL)
self.assertEqual(cassandra.cluster.DEFAULT_MAX_REQUESTS, max_requests_per_connection)
cluster.set_max_requests_per_connection(HostDistance.LOCAL, max_requests_per_connection + 1)
self.assertEqual(cluster.get_max_requests_per_connection(HostDistance.LOCAL), max_requests_per_connection + 1)
core_connections_per_host = cluster.get_core_connections_per_host(HostDistance.LOCAL)
self.assertEqual(cassandra.cluster.DEFAULT_MIN_CONNECTIONS_PER_LOCAL_HOST, core_connections_per_host)
cluster.set_core_connections_per_host(HostDistance.LOCAL, core_connections_per_host + 1)
self.assertEqual(cluster.get_core_connections_per_host(HostDistance.LOCAL), core_connections_per_host + 1)
max_connections_per_host = cluster.get_max_connections_per_host(HostDistance.LOCAL)
self.assertEqual(cassandra.cluster.DEFAULT_MAX_CONNECTIONS_PER_LOCAL_HOST, max_connections_per_host)
cluster.set_max_connections_per_host(HostDistance.LOCAL, max_connections_per_host + 1)
self.assertEqual(cluster.get_max_connections_per_host(HostDistance.LOCAL), max_connections_per_host + 1)
def test_refresh_schema(self):
cluster = TestCluster()
session = cluster.connect()
original_meta = cluster.metadata.keyspaces
# full schema refresh, with wait
cluster.refresh_schema_metadata()
self.assertIsNot(original_meta, cluster.metadata.keyspaces)
self.assertEqual(original_meta, cluster.metadata.keyspaces)
cluster.shutdown()
def test_refresh_schema_keyspace(self):
cluster = TestCluster()
session = cluster.connect()
original_meta = cluster.metadata.keyspaces
original_system_meta = original_meta['system']
# only refresh one keyspace
cluster.refresh_keyspace_metadata('system')
current_meta = cluster.metadata.keyspaces
self.assertIs(original_meta, current_meta)
current_system_meta = current_meta['system']
self.assertIsNot(original_system_meta, current_system_meta)
self.assertEqual(original_system_meta.as_cql_query(), current_system_meta.as_cql_query())
cluster.shutdown()
def test_refresh_schema_table(self):
cluster = TestCluster()
session = cluster.connect()
original_meta = cluster.metadata.keyspaces
original_system_meta = original_meta['system']
original_system_schema_meta = original_system_meta.tables['local']
# only refresh one table
cluster.refresh_table_metadata('system', 'local')
current_meta = cluster.metadata.keyspaces
current_system_meta = current_meta['system']
current_system_schema_meta = current_system_meta.tables['local']
self.assertIs(original_meta, current_meta)
self.assertIs(original_system_meta, current_system_meta)
self.assertIsNot(original_system_schema_meta, current_system_schema_meta)
self.assertEqual(original_system_schema_meta.as_cql_query(), current_system_schema_meta.as_cql_query())
cluster.shutdown()
def test_refresh_schema_type(self):
if get_server_versions()[0] < (2, 1, 0):
raise unittest.SkipTest('UDTs were introduced in Cassandra 2.1')
if PROTOCOL_VERSION < 3:
raise unittest.SkipTest('UDTs are not specified in change events for protocol v2')
# We may want to refresh types on keyspace change events in that case(?)
cluster = TestCluster()
session = cluster.connect()
keyspace_name = 'test1rf'
type_name = self._testMethodName
execute_until_pass(session, 'CREATE TYPE IF NOT EXISTS %s.%s (one int, two text)' % (keyspace_name, type_name))
original_meta = cluster.metadata.keyspaces
original_test1rf_meta = original_meta[keyspace_name]
original_type_meta = original_test1rf_meta.user_types[type_name]
# only refresh one type
cluster.refresh_user_type_metadata('test1rf', type_name)
current_meta = cluster.metadata.keyspaces
current_test1rf_meta = current_meta[keyspace_name]
current_type_meta = current_test1rf_meta.user_types[type_name]
self.assertIs(original_meta, current_meta)
self.assertEqual(original_test1rf_meta.export_as_string(), current_test1rf_meta.export_as_string())
self.assertIsNot(original_type_meta, current_type_meta)
self.assertEqual(original_type_meta.as_cql_query(), current_type_meta.as_cql_query())
cluster.shutdown()
@local
@notwindows
def test_refresh_schema_no_wait(self):
original_wait_for_responses = connection.Connection.wait_for_responses
def patched_wait_for_responses(*args, **kwargs):
# When selecting schema version, replace the real schema UUID with an unexpected UUID
response = original_wait_for_responses(*args, **kwargs)
if len(args) > 2 and hasattr(args[2], "query") and args[2].query == "SELECT schema_version FROM system.local WHERE key='local'":
new_uuid = uuid4()
response[1].parsed_rows[0] = (new_uuid,)
return response
with patch.object(connection.Connection, "wait_for_responses", patched_wait_for_responses):
agreement_timeout = 1
# cluster agreement wait exceeded
c = TestCluster(max_schema_agreement_wait=agreement_timeout)
c.connect()
self.assertTrue(c.metadata.keyspaces)
# cluster agreement wait used for refresh
original_meta = c.metadata.keyspaces
start_time = time.time()
self.assertRaisesRegexp(Exception, r"Schema metadata was not refreshed.*", c.refresh_schema_metadata)
end_time = time.time()
self.assertGreaterEqual(end_time - start_time, agreement_timeout)
self.assertIs(original_meta, c.metadata.keyspaces)
# refresh wait overrides cluster value
original_meta = c.metadata.keyspaces
start_time = time.time()
c.refresh_schema_metadata(max_schema_agreement_wait=0)
end_time = time.time()
self.assertLess(end_time - start_time, agreement_timeout)
self.assertIsNot(original_meta, c.metadata.keyspaces)
self.assertEqual(original_meta, c.metadata.keyspaces)
c.shutdown()
refresh_threshold = 0.5
# cluster agreement bypass
c = TestCluster(max_schema_agreement_wait=0)
start_time = time.time()
s = c.connect()
end_time = time.time()
self.assertLess(end_time - start_time, refresh_threshold)
self.assertTrue(c.metadata.keyspaces)
# cluster agreement wait used for refresh
original_meta = c.metadata.keyspaces
start_time = time.time()
c.refresh_schema_metadata()
end_time = time.time()
self.assertLess(end_time - start_time, refresh_threshold)
self.assertIsNot(original_meta, c.metadata.keyspaces)
self.assertEqual(original_meta, c.metadata.keyspaces)
# refresh wait overrides cluster value
original_meta = c.metadata.keyspaces
start_time = time.time()
self.assertRaisesRegexp(Exception, r"Schema metadata was not refreshed.*", c.refresh_schema_metadata,
max_schema_agreement_wait=agreement_timeout)
end_time = time.time()
self.assertGreaterEqual(end_time - start_time, agreement_timeout)
self.assertIs(original_meta, c.metadata.keyspaces)
c.shutdown()
def test_trace(self):
"""
Ensure trace can be requested for async and non-async queries
"""
cluster = TestCluster()
session = cluster.connect()
result = session.execute( "SELECT * FROM system.local", trace=True)
self._check_trace(result.get_query_trace())
query = "SELECT * FROM system.local"
statement = SimpleStatement(query)
result = session.execute(statement, trace=True)
self._check_trace(result.get_query_trace())
query = "SELECT * FROM system.local"
statement = SimpleStatement(query)
result = session.execute(statement)
self.assertIsNone(result.get_query_trace())
statement2 = SimpleStatement(query)
future = session.execute_async(statement2, trace=True)
future.result()
self._check_trace(future.get_query_trace())
statement2 = SimpleStatement(query)
future = session.execute_async(statement2)
future.result()
self.assertIsNone(future.get_query_trace())
prepared = session.prepare("SELECT * FROM system.local")
future = session.execute_async(prepared, parameters=(), trace=True)
future.result()
self._check_trace(future.get_query_trace())
cluster.shutdown()
def test_trace_unavailable(self):
"""
First checks that TraceUnavailable is arisen if the
max_wait parameter is negative
Then checks that TraceUnavailable is arisen if the
result hasn't been set yet
@since 3.10
@jira_ticket PYTHON-196
@expected_result TraceUnavailable is arisen in both cases
@test_category query
"""
cluster = TestCluster()
self.addCleanup(cluster.shutdown)
session = cluster.connect()
query = "SELECT * FROM system.local"
statement = SimpleStatement(query)
max_retry_count = 10
for i in range(max_retry_count):
future = session.execute_async(statement, trace=True)
future.result()
try:
result = future.get_query_trace(-1.0)
# In case the result has time to come back before this timeout due to a race condition
self._check_trace(result)
except TraceUnavailable:
break
else:
raise Exception("get_query_trace didn't raise TraceUnavailable after {} tries".format(max_retry_count))
for i in range(max_retry_count):
future = session.execute_async(statement, trace=True)
try:
result = future.get_query_trace(max_wait=120)
# In case the result has been set check the trace
self._check_trace(result)
except TraceUnavailable:
break
else:
raise Exception("get_query_trace didn't raise TraceUnavailable after {} tries".format(max_retry_count))
def test_one_returns_none(self):
"""
Test ResulSet.one returns None if no rows where found
@since 3.14
@jira_ticket PYTHON-947
@expected_result ResulSet.one is None
@test_category query
"""
with TestCluster() as cluster:
session = cluster.connect()
self.assertIsNone(session.execute("SELECT * from system.local WHERE key='madeup_key'").one())
def test_string_coverage(self):
"""
Ensure str(future) returns without error
"""
cluster = TestCluster()
session = cluster.connect()
query = "SELECT * FROM system.local"
statement = SimpleStatement(query)
future = session.execute_async(statement)
self.assertIn(query, str(future))
future.result()
self.assertIn(query, str(future))
self.assertIn('result', str(future))
cluster.shutdown()
def test_can_connect_with_plainauth(self):
"""
Verify that we can connect setting PlainTextAuthProvider against a
C* server without authentication set. We also verify a warning is
issued per connection. This test is here instead of in test_authentication.py
because the C* server running in that module has auth set.
@since 3.14
@jira_ticket PYTHON-940
@expected_result we can connect, query C* and warning are issued
@test_category auth
"""
auth_provider = PlainTextAuthProvider(
username="made_up_username",
password="made_up_password"
)
self._warning_are_issued_when_auth(auth_provider)
def test_can_connect_with_sslauth(self):
"""
Verify that we can connect setting SaslAuthProvider against a
C* server without authentication set. We also verify a warning is
issued per connection. This test is here instead of in test_authentication.py
because the C* server running in that module has auth set.
@since 3.14
@jira_ticket PYTHON-940
@expected_result we can connect, query C* and warning are issued
@test_category auth
"""
sasl_kwargs = {'service': 'cassandra',
'mechanism': 'PLAIN',
'qops': ['auth'],
'username': "made_up_username",
'password': "made_up_password"}
auth_provider = SaslAuthProvider(**sasl_kwargs)
self._warning_are_issued_when_auth(auth_provider)
def _warning_are_issued_when_auth(self, auth_provider):
with MockLoggingHandler().set_module_name(connection.__name__) as mock_handler:
with TestCluster(auth_provider=auth_provider) as cluster:
session = cluster.connect()
self.assertIsNotNone(session.execute("SELECT * from system.local"))
# Three conenctions to nodes plus the control connection
auth_warning = mock_handler.get_message_count('warning', "An authentication challenge was not sent")
self.assertGreaterEqual(auth_warning, 4)
self.assertEqual(
auth_warning,
mock_handler.get_message_count("debug", "Got ReadyMessage on new connection")
)
def test_idle_heartbeat(self):
interval = 2
cluster = TestCluster(idle_heartbeat_interval=interval,
monitor_reporting_enabled=False)
if PROTOCOL_VERSION < 3:
cluster.set_core_connections_per_host(HostDistance.LOCAL, 1)
session = cluster.connect(wait_for_all_pools=True)
# This test relies on impl details of connection req id management to see if heartbeats
# are being sent. May need update if impl is changed
connection_request_ids = {}
for h in cluster.get_connection_holders():
for c in h.get_connections():
# make sure none are idle (should have startup messages
self.assertFalse(c.is_idle)
with c.lock:
connection_request_ids[id(c)] = deque(c.request_ids) # copy of request ids
# let two heatbeat intervals pass (first one had startup messages in it)
time.sleep(2 * interval + interval/2)
connections = [c for holders in cluster.get_connection_holders() for c in holders.get_connections()]
# make sure requests were sent on all connections
for c in connections:
expected_ids = connection_request_ids[id(c)]
expected_ids.rotate(-1)
with c.lock:
self.assertListEqual(list(c.request_ids), list(expected_ids))
# assert idle status
self.assertTrue(all(c.is_idle for c in connections))
# send messages on all connections
statements_and_params = [("SELECT release_version FROM system.local", ())] * len(cluster.metadata.all_hosts())
results = execute_concurrent(session, statements_and_params)
for success, result in results:
self.assertTrue(success)
# assert not idle status
self.assertFalse(any(c.is_idle if not c.is_control_connection else False for c in connections))
# holders include session pools and cc
holders = cluster.get_connection_holders()
self.assertIn(cluster.control_connection, holders)
self.assertEqual(len(holders), len(cluster.metadata.all_hosts()) + 1) # hosts pools, 1 for cc
# include additional sessions
session2 = cluster.connect(wait_for_all_pools=True)
holders = cluster.get_connection_holders()
self.assertIn(cluster.control_connection, holders)
self.assertEqual(len(holders), 2 * len(cluster.metadata.all_hosts()) + 1) # 2 sessions' hosts pools, 1 for cc
cluster._idle_heartbeat.stop()
cluster._idle_heartbeat.join()
assert_quiescent_pool_state(self, cluster)
cluster.shutdown()
@patch('cassandra.cluster.Cluster.idle_heartbeat_interval', new=0.1)
def test_idle_heartbeat_disabled(self):
self.assertTrue(Cluster.idle_heartbeat_interval)
# heartbeat disabled with '0'
cluster = TestCluster(idle_heartbeat_interval=0)
self.assertEqual(cluster.idle_heartbeat_interval, 0)
session = cluster.connect()
# let two heatbeat intervals pass (first one had startup messages in it)
time.sleep(2 * Cluster.idle_heartbeat_interval)
connections = [c for holders in cluster.get_connection_holders() for c in holders.get_connections()]
# assert not idle status (should never get reset because there is not heartbeat)
self.assertFalse(any(c.is_idle for c in connections))
cluster.shutdown()
def test_pool_management(self):
# Ensure that in_flight and request_ids quiesce after cluster operations
cluster = TestCluster(idle_heartbeat_interval=0) # no idle heartbeat here, pool management is tested in test_idle_heartbeat
session = cluster.connect()
session2 = cluster.connect()
# prepare
p = session.prepare("SELECT * FROM system.local WHERE key=?")
self.assertTrue(session.execute(p, ('local',)))
# simple
self.assertTrue(session.execute("SELECT * FROM system.local WHERE key='local'"))
# set keyspace
session.set_keyspace('system')
session.set_keyspace('system_traces')
# use keyspace
session.execute('USE system')
session.execute('USE system_traces')
# refresh schema
cluster.refresh_schema_metadata()
cluster.refresh_schema_metadata(max_schema_agreement_wait=0)
assert_quiescent_pool_state(self, cluster)
cluster.shutdown()
@local
def test_profile_load_balancing(self):
"""
Tests that profile load balancing policies are honored.
@since 3.5
@jira_ticket PYTHON-569
@expected_result Execution Policy should be used when applicable.
@test_category config_profiles
"""
query = "select release_version from system.local"
node1 = ExecutionProfile(
load_balancing_policy=HostFilterPolicy(
RoundRobinPolicy(), lambda host: host.address == CASSANDRA_IP
)
)
with TestCluster(execution_profiles={'node1': node1}, monitor_reporting_enabled=False) as cluster:
session = cluster.connect(wait_for_all_pools=True)
# default is DCA RR for all hosts
expected_hosts = set(cluster.metadata.all_hosts())
queried_hosts = set()
for _ in expected_hosts:
rs = session.execute(query)
queried_hosts.add(rs.response_future._current_host)
self.assertEqual(queried_hosts, expected_hosts)
# by name we should only hit the one
expected_hosts = set(h for h in cluster.metadata.all_hosts() if h.address == CASSANDRA_IP)
queried_hosts = set()
for _ in cluster.metadata.all_hosts():
rs = session.execute(query, execution_profile='node1')
queried_hosts.add(rs.response_future._current_host)
self.assertEqual(queried_hosts, expected_hosts)
# use a copied instance and override the row factory
# assert last returned value can be accessed as a namedtuple so we can prove something different
named_tuple_row = rs[0]
self.assertIsInstance(named_tuple_row, tuple)
self.assertTrue(named_tuple_row.release_version)
tmp_profile = copy(node1)
tmp_profile.row_factory = tuple_factory
queried_hosts = set()
for _ in cluster.metadata.all_hosts():
rs = session.execute(query, execution_profile=tmp_profile)
queried_hosts.add(rs.response_future._current_host)
self.assertEqual(queried_hosts, expected_hosts)
tuple_row = rs[0]
self.assertIsInstance(tuple_row, tuple)
with self.assertRaises(AttributeError):
tuple_row.release_version
# make sure original profile is not impacted
self.assertTrue(session.execute(query, execution_profile='node1')[0].release_version)
def test_setting_lbp_legacy(self):
cluster = TestCluster()
self.addCleanup(cluster.shutdown)
cluster.load_balancing_policy = RoundRobinPolicy()
self.assertEqual(
list(cluster.load_balancing_policy.make_query_plan()), []
)
cluster.connect()
self.assertNotEqual(
list(cluster.load_balancing_policy.make_query_plan()), []
)
def test_profile_lb_swap(self):
"""
Tests that profile load balancing policies are not shared
Creates two LBP, runs a few queries, and validates that each LBP is execised
seperately between EP's
@since 3.5
@jira_ticket PYTHON-569
@expected_result LBP should not be shared.
@test_category config_profiles
"""
query = "select release_version from system.local"
rr1 = ExecutionProfile(load_balancing_policy=RoundRobinPolicy())
rr2 = ExecutionProfile(load_balancing_policy=RoundRobinPolicy())
exec_profiles = {'rr1': rr1, 'rr2': rr2}
with TestCluster(execution_profiles=exec_profiles) as cluster:
session = cluster.connect(wait_for_all_pools=True)
# default is DCA RR for all hosts
expected_hosts = set(cluster.metadata.all_hosts())
rr1_queried_hosts = set()
rr2_queried_hosts = set()
rs = session.execute(query, execution_profile='rr1')
rr1_queried_hosts.add(rs.response_future._current_host)
rs = session.execute(query, execution_profile='rr2')
rr2_queried_hosts.add(rs.response_future._current_host)
self.assertEqual(rr2_queried_hosts, rr1_queried_hosts)
def test_ta_lbp(self):
"""
Test that execution profiles containing token aware LBP can be added
@since 3.5
@jira_ticket PYTHON-569
@expected_result Queries can run
@test_category config_profiles
"""
query = "select release_version from system.local"
ta1 = ExecutionProfile()
with TestCluster() as cluster:
session = cluster.connect()
cluster.add_execution_profile("ta1", ta1)
rs = session.execute(query, execution_profile='ta1')
def test_clone_shared_lbp(self):
"""
Tests that profile load balancing policies are shared on clone
Creates one LBP clones it, and ensures that the LBP is shared between
the two EP's
@since 3.5
@jira_ticket PYTHON-569
@expected_result LBP is shared
@test_category config_profiles
"""
query = "select release_version from system.local"
rr1 = ExecutionProfile(load_balancing_policy=RoundRobinPolicy())
exec_profiles = {'rr1': rr1}
with TestCluster(execution_profiles=exec_profiles) as cluster:
session = cluster.connect(wait_for_all_pools=True)
self.assertGreater(len(cluster.metadata.all_hosts()), 1, "We only have one host connected at this point")
rr1_clone = session.execution_profile_clone_update('rr1', row_factory=tuple_factory)
cluster.add_execution_profile("rr1_clone", rr1_clone)
rr1_queried_hosts = set()
rr1_clone_queried_hosts = set()
rs = session.execute(query, execution_profile='rr1')
rr1_queried_hosts.add(rs.response_future._current_host)
rs = session.execute(query, execution_profile='rr1_clone')
rr1_clone_queried_hosts.add(rs.response_future._current_host)
self.assertNotEqual(rr1_clone_queried_hosts, rr1_queried_hosts)
def test_missing_exec_prof(self):