forked from apache/cassandra-python-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
332 lines (254 loc) · 9.83 KB
/
utils.py
File metadata and controls
332 lines (254 loc) · 9.83 KB
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
# 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
from six.moves.urllib.request import build_opener, Request, HTTPHandler
import json
from tests.integration import CASSANDRA_VERSION, SIMULACRON_JAR
import subprocess
import time
import nose
DEFAULT_CLUSTER = "python_simulacron_cluster"
class SimulacronCluster(object):
"""
Represents a Cluster object as returned by simulacron
"""
def __init__(self, json_text):
self.json = json_text
self.o = json.loads(json_text)
@property
def cluster_id(self):
return self.o["id"]
@property
def cluster_name(self):
return self.o["name"]
@property
def data_center_ids(self):
return [dc["id"] for dc in self.o["data_centers"]]
@property
def data_centers_names(self):
return [dc["name"] for dc in self.o["data_centers"]]
def get_node_ids(self, datacenter_id):
datacenter = list(filter(lambda x: x["id"] == datacenter_id, self.o["data_centers"])).pop()
return [node["id"] for node in datacenter["nodes"]]
class SimulacronServer(object):
"""
Class for starting and stopping the server from within the tests
"""
def __init__(self, jar_path):
self.jar_path = jar_path
self.running = False
self.proc = None
def start(self):
self.proc = subprocess.Popen(['java', '-jar', self.jar_path, "--loglevel", "ERROR"], shell=False)
self.running = True
def stop(self):
if self.proc:
self.proc.terminate()
self.running = False
def is_running(self):
# We could check self.proc.poll here instead
return self.running
SERVER_SIMULACRON = SimulacronServer(SIMULACRON_JAR)
def start_simulacron():
"""
Starts and waits for simulacron to run
"""
if SERVER_SIMULACRON.is_running():
SERVER_SIMULACRON.stop()
SERVER_SIMULACRON.start()
#TODO improve this sleep, maybe check the logs like ccm
time.sleep(5)
def stop_simulacron():
SERVER_SIMULACRON.stop()
class SimulacronClient(object):
def __init__(self, admin_addr="127.0.0.1:8187"):
self.admin_addr = admin_addr
def submit_request(self, query):
opener = build_opener(HTTPHandler)
data = json.dumps(query.fetch_json()).encode('utf8')
request = Request("http://{}/{}{}".format(
self.admin_addr, query.path, query.fetch_url_params()), data=data)
request.get_method = lambda: 'POST'
request.add_header("Content-Type", 'application/json')
request.add_header("Content-Length", len(data))
connection = opener.open(request)
return connection.read().decode('utf-8')
def prime_server_versions(self):
"""
This information has to be primed for the test harness to run
"""
system_local_row = {}
system_local_row["cql_version"] = CASSANDRA_VERSION
system_local_row["release_version"] = CASSANDRA_VERSION + "-SNAPSHOT"
column_types = {"cql_version": "ascii", "release_version": "ascii"}
system_local = PrimeQuery("SELECT cql_version, release_version FROM system.local",
rows=[system_local_row],
column_types=column_types)
self.submit_request(system_local)
def clear_all_queries(self, cluster_name=DEFAULT_CLUSTER):
"""
Clear all the primed queries from a particular cluster
:param cluster_name: cluster to clear queries from
"""
opener = build_opener(HTTPHandler)
request = Request("http://{0}/{1}/{2}".format(
self.admin_addr, "prime", cluster_name))
request.get_method = lambda: 'DELETE'
connection = opener.open(request)
return connection.read()
NO_THEN = object()
class SimulacronRequest(object):
def fetch_json(self):
raise NotImplementedError()
def fetch_url_params(self):
raise NotImplementedError()
class PrimeOptions(SimulacronRequest):
"""
Class used for specifying how should simulacron respond to an OptionsMessage
"""
def __init__(self, then=None, cluster_name=DEFAULT_CLUSTER):
self.path = "prime/{}".format(cluster_name)
self.then = then
def fetch_json(self):
json_dict = {}
then = {}
when = {}
when['request'] = "options"
if self.then is not None and self.then is not NO_THEN:
then.update(self.then)
json_dict['when'] = when
if self.then is not NO_THEN:
json_dict['then'] = then
return json_dict
def fetch_url_params(self):
return ""
class PrimeQuery(SimulacronRequest):
"""
Class used for specifying how should simulacron respond to particular query
"""
def __init__(self, expected_query, result="success", rows=None,
column_types=None, when=None, then=None, cluster_name=DEFAULT_CLUSTER):
self.expected_query = expected_query
self.rows = rows
self.result = result
self.column_types = column_types
self.path = "prime/{}".format(cluster_name)
self.then = then
self.when = when
def fetch_json(self):
json_dict = {}
then = {}
when = {}
when['query'] = self.expected_query
then['result'] = self.result
if self.rows is not None:
then['rows'] = self.rows
if self.column_types is not None:
then['column_types'] = self.column_types
if self.then is not None and self.then is not NO_THEN:
then.update(self.then)
if self.then is not NO_THEN:
json_dict['then'] = then
if self.when is not None:
when.update(self.when)
json_dict['when'] = when
return json_dict
def set_node(self, cluster_id, datacenter_id, node_id):
self.cluster_id = cluster_id
self.datacenter_id = datacenter_id
self.node_id = node_id
self.path += '/'.join([component for component in
(self.cluster_id, self.datacenter_id, self.node_id)
if component is not None])
def fetch_url_params(self):
return ""
class ClusterQuery(SimulacronRequest):
"""
Class used for creating a cluster
"""
def __init__(self, cluster_name, cassandra_version, data_centers="3", json_dict=None):
self.cluster_name = cluster_name
self.cassandra_version = cassandra_version
self.data_centers = data_centers
if json_dict is None:
self.json_dict = {}
else:
self.json_dict = json_dict
self.path = "cluster"
def fetch_json(self):
return self.json_dict
def fetch_url_params(self):
return "?cassandra_version={0}&data_centers={1}&name={2}".\
format(self.cassandra_version, self.data_centers, self.cluster_name)
def prime_driver_defaults():
"""
Function to prime the necessary queries so the test harness can run
"""
client_simulacron = SimulacronClient()
client_simulacron.prime_server_versions()
def prime_cluster(data_centers="3", version=None, cluster_name=DEFAULT_CLUSTER):
"""
Creates a new cluster in the simulacron server
:param cluster_name: name of the cluster
:param data_centers: string describing the datacenter, e.g. 2/3 would be two
datacenters of 2 nodes and three nodes
:param version: C* version
"""
version = version or CASSANDRA_VERSION
cluster_query = ClusterQuery(cluster_name, version, data_centers)
client_simulacron = SimulacronClient()
response = client_simulacron.submit_request(cluster_query)
return SimulacronCluster(response)
def start_and_prime_singledc(cluster_name=DEFAULT_CLUSTER):
"""
Starts simulacron and creates a cluster with a single datacenter
:param cluster_name: name of the cluster to start and prime
:return:
"""
return start_and_prime_cluster_defaults(number_of_dc=1, nodes_per_dc=3, cluster_name=cluster_name)
def start_and_prime_cluster_defaults(number_of_dc=1, nodes_per_dc=3, version=None, cluster_name=DEFAULT_CLUSTER):
"""
:param number_of_dc: number of datacentes
:param nodes_per_dc: number of nodes per datacenter
:param version: C* version
"""
start_simulacron()
data_centers = ",".join([str(nodes_per_dc)] * number_of_dc)
simulacron_cluster = prime_cluster(data_centers=data_centers, version=version, cluster_name=cluster_name)
prime_driver_defaults()
return simulacron_cluster
default_column_types = {
"key": "bigint",
"value": "ascii"
}
default_row = {"key": 2, "value": "value"}
default_rows = [default_row]
def prime_request(request):
"""
:param request: It could be PrimeQuery class or an PrimeOptions class
"""
return SimulacronClient().submit_request(request)
def prime_query(query, rows=default_rows, column_types=default_column_types, when=None, then=None, cluster_name=DEFAULT_CLUSTER):
"""
Shortcut function for priming a query
:return:
"""
# If then is set, then rows and column_types should not
query = PrimeQuery(query, rows=rows, column_types=column_types, when=when, then=then, cluster_name=cluster_name)
response = prime_request(query)
return response
def clear_queries():
"""
Clears all the queries that have been primed to simulacron
"""
SimulacronClient().clear_all_queries()