-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_metrics.py
406 lines (323 loc) · 15.4 KB
/
test_metrics.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
# 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.
import time
from cassandra.connection import ConnectionShutdown
from cassandra.policies import HostFilterPolicy, RoundRobinPolicy, FallthroughRetryPolicy
try:
import unittest2 as unittest
except ImportError:
import unittest # noqa
from cassandra.query import SimpleStatement
from cassandra import ConsistencyLevel, WriteTimeout, Unavailable, ReadTimeout
from cassandra.protocol import SyntaxException
from cassandra.cluster import NoHostAvailable, ExecutionProfile, EXEC_PROFILE_DEFAULT
from tests.integration import get_cluster, get_node, use_singledc, execute_until_pass, TestCluster
from greplin import scales
from tests.integration import BasicSharedKeyspaceUnitTestCaseRF3WM, BasicExistingKeyspaceUnitTestCase, local
import pprint as pp
def setup_module():
use_singledc()
@local
class MetricsTests(unittest.TestCase):
def setUp(self):
contact_point = ['127.0.0.2']
self.cluster = TestCluster(contact_points=contact_point, metrics_enabled=True,
execution_profiles=
{EXEC_PROFILE_DEFAULT:
ExecutionProfile(
load_balancing_policy=HostFilterPolicy(
RoundRobinPolicy(), lambda host: host.address in contact_point),
retry_policy=FallthroughRetryPolicy()
)
}
)
self.session = self.cluster.connect("test3rf", wait_for_all_pools=True)
def tearDown(self):
self.cluster.shutdown()
def test_connection_error(self):
"""
Trigger and ensure connection_errors are counted
Stop all node with the driver knowing about the "DOWN" states.
"""
# Test writes
for i in range(0, 100):
self.session.execute_async("INSERT INTO test (k, v) VALUES ({0}, {1})".format(i, i))
# Stop the cluster
get_cluster().stop(wait=True, gently=False)
try:
# Ensure the nodes are actually down
query = SimpleStatement("SELECT * FROM test", consistency_level=ConsistencyLevel.ALL)
# both exceptions can happen depending on when the connection has been detected as defunct
with self.assertRaises((NoHostAvailable, ConnectionShutdown)):
self.session.execute(query)
finally:
get_cluster().start(wait_for_binary_proto=True, wait_other_notice=True)
# Give some time for the cluster to come back up, for the next test
time.sleep(5)
self.assertGreater(self.cluster.metrics.stats.connection_errors, 0)
def test_write_timeout(self):
"""
Trigger and ensure write_timeouts are counted
Write a key, value pair. Pause a node without the coordinator node knowing about the "DOWN" state.
Attempt a write at cl.ALL and receive a WriteTimeout.
"""
# Test write
self.session.execute("INSERT INTO test (k, v) VALUES (1, 1)")
# Assert read
query = SimpleStatement("SELECT * FROM test WHERE k=1", consistency_level=ConsistencyLevel.ALL)
results = execute_until_pass(self.session, query)
self.assertTrue(results)
# Pause node so it shows as unreachable to coordinator
get_node(1).pause()
try:
# Test write
query = SimpleStatement("INSERT INTO test (k, v) VALUES (2, 2)", consistency_level=ConsistencyLevel.ALL)
with self.assertRaises(WriteTimeout):
self.session.execute(query, timeout=None)
self.assertEqual(1, self.cluster.metrics.stats.write_timeouts)
finally:
get_node(1).resume()
def test_read_timeout(self):
"""
Trigger and ensure read_timeouts are counted
Write a key, value pair. Pause a node without the coordinator node knowing about the "DOWN" state.
Attempt a read at cl.ALL and receive a ReadTimeout.
"""
# Test write
self.session.execute("INSERT INTO test (k, v) VALUES (1, 1)")
# Assert read
query = SimpleStatement("SELECT * FROM test WHERE k=1", consistency_level=ConsistencyLevel.ALL)
results = execute_until_pass(self.session, query)
self.assertTrue(results)
# Pause node so it shows as unreachable to coordinator
get_node(1).pause()
try:
# Test read
query = SimpleStatement("SELECT * FROM test", consistency_level=ConsistencyLevel.ALL)
with self.assertRaises(ReadTimeout):
self.session.execute(query, timeout=None)
self.assertEqual(1, self.cluster.metrics.stats.read_timeouts)
finally:
get_node(1).resume()
def test_unavailable(self):
"""
Trigger and ensure unavailables are counted
Write a key, value pair. Stop a node with the coordinator node knowing about the "DOWN" state.
Attempt an insert/read at cl.ALL and receive a Unavailable Exception.
"""
# Test write
self.session.execute("INSERT INTO test (k, v) VALUES (1, 1)")
# Assert read
query = SimpleStatement("SELECT * FROM test WHERE k=1", consistency_level=ConsistencyLevel.ALL)
results = execute_until_pass(self.session, query)
self.assertTrue(results)
# Stop node gracefully
# Sometimes this commands continues with the other nodes having not noticed
# 1 is down, and a Timeout error is returned instead of an Unavailable
get_node(1).stop(wait=True, wait_other_notice=True)
time.sleep(5)
try:
# Test write
query = SimpleStatement("INSERT INTO test (k, v) VALUES (2, 2)", consistency_level=ConsistencyLevel.ALL)
with self.assertRaises(Unavailable):
self.session.execute(query)
self.assertEqual(self.cluster.metrics.stats.unavailables, 1)
# Test write
query = SimpleStatement("SELECT * FROM test", consistency_level=ConsistencyLevel.ALL)
with self.assertRaises(Unavailable):
self.session.execute(query, timeout=None)
self.assertEqual(self.cluster.metrics.stats.unavailables, 2)
finally:
get_node(1).start(wait_other_notice=True, wait_for_binary_proto=True)
# Give some time for the cluster to come back up, for the next test
time.sleep(5)
self.cluster.shutdown()
# def test_other_error(self):
# # TODO: Bootstrapping or Overloaded cases
# pass
#
# def test_ignore(self):
# # TODO: Look for ways to generate ignores
# pass
#
# def test_retry(self):
# # TODO: Look for ways to generate retries
# pass
class MetricsNamespaceTest(BasicSharedKeyspaceUnitTestCaseRF3WM):
@local
def test_metrics_per_cluster(self):
"""
Test to validate that metrics can be scopped to invdividual clusters
@since 3.6.0
@jira_ticket PYTHON-561
@expected_result metrics should be scopped to a cluster level
@test_category metrics
"""
cluster2 = TestCluster(
metrics_enabled=True,
execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(retry_policy=FallthroughRetryPolicy())}
)
cluster2.connect(self.ks_name, wait_for_all_pools=True)
self.assertEqual(len(cluster2.metadata.all_hosts()), 3)
query = SimpleStatement("SELECT * FROM {0}.{0}".format(self.ks_name), consistency_level=ConsistencyLevel.ALL)
self.session.execute(query)
# Pause node so it shows as unreachable to coordinator
get_node(1).pause()
try:
# Test write
query = SimpleStatement("INSERT INTO {0}.{0} (k, v) VALUES (2, 2)".format(self.ks_name), consistency_level=ConsistencyLevel.ALL)
with self.assertRaises(WriteTimeout):
self.session.execute(query, timeout=None)
finally:
get_node(1).resume()
# Change the scales stats_name of the cluster2
cluster2.metrics.set_stats_name('cluster2-metrics')
stats_cluster1 = self.cluster.metrics.get_stats()
stats_cluster2 = cluster2.metrics.get_stats()
# Test direct access to stats
self.assertEqual(1, self.cluster.metrics.stats.write_timeouts)
self.assertEqual(0, cluster2.metrics.stats.write_timeouts)
# Test direct access to a child stats
self.assertNotEqual(0.0, self.cluster.metrics.request_timer['mean'])
self.assertEqual(0.0, cluster2.metrics.request_timer['mean'])
# Test access via metrics.get_stats()
self.assertNotEqual(0.0, stats_cluster1['request_timer']['mean'])
self.assertEqual(0.0, stats_cluster2['request_timer']['mean'])
# Test access by stats_name
self.assertEqual(0.0, scales.getStats()['cluster2-metrics']['request_timer']['mean'])
cluster2.shutdown()
def test_duplicate_metrics_per_cluster(self):
"""
Test to validate that cluster metrics names can't overlap.
@since 3.6.0
@jira_ticket PYTHON-561
@expected_result metric names should not be allowed to be same.
@test_category metrics
"""
cluster2 = TestCluster(
metrics_enabled=True,
monitor_reporting_enabled=False,
execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(retry_policy=FallthroughRetryPolicy())}
)
cluster3 = TestCluster(
metrics_enabled=True,
monitor_reporting_enabled=False,
execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(retry_policy=FallthroughRetryPolicy())}
)
# Ensure duplicate metric names are not allowed
cluster2.metrics.set_stats_name("appcluster")
cluster2.metrics.set_stats_name("appcluster")
with self.assertRaises(ValueError):
cluster3.metrics.set_stats_name("appcluster")
cluster3.metrics.set_stats_name("devops")
session2 = cluster2.connect(self.ks_name, wait_for_all_pools=True)
session3 = cluster3.connect(self.ks_name, wait_for_all_pools=True)
# Basic validation that naming metrics doesn't impact their segration or accuracy
for i in range(10):
query = SimpleStatement("SELECT * FROM {0}.{0}".format(self.ks_name), consistency_level=ConsistencyLevel.ALL)
session2.execute(query)
for i in range(5):
query = SimpleStatement("SELECT * FROM {0}.{0}".format(self.ks_name), consistency_level=ConsistencyLevel.ALL)
session3.execute(query)
self.assertEqual(cluster2.metrics.get_stats()['request_timer']['count'], 10)
self.assertEqual(cluster3.metrics.get_stats()['request_timer']['count'], 5)
# Check scales to ensure they are appropriately named
self.assertTrue("appcluster" in scales._Stats.stats.keys())
self.assertTrue("devops" in scales._Stats.stats.keys())
cluster2.shutdown()
cluster3.shutdown()
class RequestAnalyzer(object):
"""
Class used to track request and error counts for a Session.
Also computes statistics on encoded request size.
"""
requests = scales.PmfStat('request size')
errors = scales.IntStat('errors')
successful = scales.IntStat("success")
# Throw exceptions when invoked.
throw_on_success = False
throw_on_fail = False
def __init__(self, session, throw_on_success=False, throw_on_fail=False):
scales.init(self, '/request')
# each instance will be registered with a session, and receive a callback for each request generated
session.add_request_init_listener(self.on_request)
self.throw_on_fail = throw_on_fail
self.throw_on_success = throw_on_success
def on_request(self, rf):
# This callback is invoked each time a request is created, on the thread creating the request.
# We can use this to count events, or add callbacks
rf.add_callbacks(self.on_success, self.on_error, callback_args=(rf,), errback_args=(rf,))
def on_success(self, _, response_future):
# future callback on a successful request; just record the size
self.requests.addValue(response_future.request_encoded_size)
self.successful += 1
if self.throw_on_success:
raise AttributeError
def on_error(self, _, response_future):
# future callback for failed; record size and increment errors
self.requests.addValue(response_future.request_encoded_size)
self.errors += 1
if self.throw_on_fail:
raise AttributeError
def remove_ra(self, session):
session.remove_request_init_listener(self.on_request)
def __str__(self):
# just extracting request count from the size stats (which are recorded on all requests)
request_sizes = dict(self.requests)
count = request_sizes.pop('count')
return "%d requests (%d errors)\nRequest size statistics:\n%s" % (count, self.errors, pp.pformat(request_sizes))
class MetricsRequestSize(BasicExistingKeyspaceUnitTestCase):
@classmethod
def setUpClass(cls):
cls.common_setup(1, keyspace_creation=False, monitor_reporting_enabled=False)
def wait_for_count(self, ra, expected_count, error=False):
for _ in range(10):
if not error:
if ra.successful is expected_count:
return True
else:
if ra.errors is expected_count:
return True
time.sleep(.01)
return False
def test_metrics_per_cluster(self):
"""
Test to validate that requests listeners.
This test creates a simple metrics based request listener to track request size, it then
check to ensure that on_success and on_error methods are invoked appropriately.
@since 3.7.0
@jira_ticket PYTHON-284
@expected_result in_error, and on_success should be invoked apropriately
@test_category metrics
"""
ra = RequestAnalyzer(self.session)
for _ in range(10):
self.session.execute("SELECT release_version FROM system.local")
for _ in range(3):
try:
self.session.execute("nonesense")
except SyntaxException:
continue
self.assertTrue(self.wait_for_count(ra, 10))
self.assertTrue(self.wait_for_count(ra, 3, error=True))
ra.remove_ra(self.session)
# Make sure a poorly coded RA doesn't cause issues
ra = RequestAnalyzer(self.session, throw_on_success=False, throw_on_fail=True)
self.session.execute("SELECT release_version FROM system.local")
ra.remove_ra(self.session)
RequestAnalyzer(self.session, throw_on_success=True)
try:
self.session.execute("nonesense")
except SyntaxException:
pass