-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjcount.py
More file actions
212 lines (173 loc) · 7.41 KB
/
Copy pathobjcount.py
File metadata and controls
212 lines (173 loc) · 7.41 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
import argparse
import configparser
import datetime
import random
import string
from os.path import exists
import sys
from ssl import SSLContext, CERT_REQUIRED, PROTOCOL_TLS_CLIENT
from cassandra.cluster import Cluster, ExecutionProfile, EXEC_PROFILE_DEFAULT
from cassandra.query import SimpleStatement
from cassandra.auth import PlainTextAuthProvider
from cassandra.policies import (
ConsistencyLevel,
DCAwareRoundRobinPolicy)
def arguments():
parser = argparse.ArgumentParser(description='Statistics script')
parser.add_argument('-c', '--conf', type=str, required=False, help="Configuration file to connect", default='conf_dummy.ini')
parser.add_argument('-i', '--host', type=str, required=True, help="IP address for Cassandra")
parser.add_argument('-k', '--keyspace', type=str, required=True, help="Keyspace to query")
parser.add_argument('-t', '--table', type=str, required=False, help="Table to query - defaults to count_perf", default='count_perf')
parser.add_argument('-f', '--fetch', type=int, required=False, help="fetch size", default='5000')
parser.add_argument('-d', '--debug', type=str, required=False, help="debug file", default='query_debug.log')
args = parser.parse_args()
casshost = args.host
ks = args.keyspace
tbl = args.table
fetch = args.fetch
debug_file = args.debug
conf_file = args.conf
return casshost, ks, tbl, fetch, debug_file, conf_file
# Read config
def read_config(conf_file):
if exists(conf_file):
print("Using conf file: " + conf_file)
config = configparser.ConfigParser()
config.read(conf_file)
return config
else:
sys.exit("ERROR: File not found %s, \n Exiting now... ", conf_file)
def randomword(length):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(length))
def insert_blob(session, ks, tbl):
blob_insert = "INSERT INTO " + ks + "." + tbl + "(key, blob) VALUES (?, ?) ;"
blobins_prep = session.prepare(blob_insert)
blobins_prep.consistency_level = ConsistencyLevel.LOCAL_QUORUM
return blobins_prep
def gateway_insert(session, ks, tbl):
#session.execute("CREATE KEYSPACE IF NOT EXISTS " + ks + " WITH replication = {'class': 'SimpleStrategy' , 'replication_factor': 3};")
#session.execute("CREATE TABLE IF NOT EXISTS " + ks + "." + tbl + " (key int primary key, blob text);")
blobins_prep = insert_blob(session, ks, tbl)
for i in range (0, 100000):
genblob = randomword(10000)
blobins_bind = blobins_prep.bind((i, genblob))
session.execute(blobins_bind)
if i%1000 == 0:
print( "Written " + str(i) + " records so far, time now " + str(datetime.datetime.now()) )
def gateway_query(session, ks, tbl, fetch):
row_count = 0
row_sizes = []
row_keys = []
# portalquery = SimpleStatement("select key from " + ks + "." + tbl + ";",
# consistency_level=ConsistencyLevel.LOCAL_QUORUM, fetch_size=fetch)
portalquerywithblob = SimpleStatement("select key, blob from " + ks + "." + tbl + ";",
consistency_level=ConsistencyLevel.LOCAL_QUORUM, fetch_size=fetch)
query_start = datetime.datetime.now()
try:
rows = session.execute(portalquerywithblob)
for row in rows:
row_count += 1
row_keys.append(row.key)
#print(row)
# TODO: define how to calculate the full row size. Query based on SELECT key at this time.
if row.blob is not None:
row_size = len(row.blob)
row_sizes.append(row_size)
except Exception as e:
print(e)
query_end = datetime.datetime.now()
query_diff = query_end - query_start
print("# SELECT #\nRow count:", row_count)
print("Query timing with fetch " + str(fetch) + ": " + str(query_diff))
statistics = calculate_row_statistics(row_sizes)
print("Average row size:", statistics["average_size"])
print("Max row size:", statistics["max_size"])
print("Min row size:", statistics["min_size"])
def gateway_query_count(session, ks, tbl, fetch, debug_file):
portalcount = SimpleStatement("select count(*) as count from " + ks + "." + tbl + ";",
consistency_level=ConsistencyLevel.LOCAL_QUORUM, fetch_size=fetch)
count_start = datetime.datetime.now()
print("# COUNT #")
try:
### Sync query
result = session.execute(portalcount, execution_profile='long', trace=True)
trace = result.get_query_trace()
print(trace.trace_id)
f = open(debug_file, "w")
for e in trace.events:
f.write(str(e.source_elapsed) + "\t" + str( e.description) + "\n")
f.close()
### Async query
# future = session.execute_async(portalcount, trace=True)
# result = future.result()
# trace = future.get_query_trace()
# for e in trace.events:
# print(e.source_elapsed, e.description)
for row in result:
print("Row count:" + str(row.count))
except Exception as e:
print(e)
count_end = datetime.datetime.now()
count_diff = count_end - count_start
print("Count timing with fetch " + str(fetch) + ": " + str(count_diff))
def calculate_row_statistics(row_sizes):
if not row_sizes:
return {
"average_size": 0,
"max_size": 0,
"min_size": 0,
"row_count": 0
}
row_count = len(row_sizes)
average_size = sum(row_sizes) / row_count
max_size = max(row_sizes)
min_size = min(row_sizes)
return {
"average_size": average_size,
"max_size": max_size,
"min_size": min_size,
"row_count": row_count
}
def main():
host, ks, tbl, fetch, debug_file, conf_file = arguments()
### Doesn't work as the default value is defined as conf_dummy.ini
# if conf_file == 'conf_dummy.ini':
# print("INFO: Default configuration file used. Using conf_dummy and assuming there's no authentication or SSL")
config = read_config(conf_file)
dcname = config['general']['dcname']
if config['general']['username'] and config['general']['password']:
my_user = config['general']['username']
my_pwd = config['general']['password']
auth_provider = PlainTextAuthProvider(username=my_user, password=my_pwd)
else:
auth_provider = None
if config['general']['ca_cert']:
ca_cert = config['general']['ca_cert']
ssl_context = SSLContext(PROTOCOL_TLS_CLIENT)
ssl_context.load_verify_locations(cafile=ca_cert)
ssl_context.check_hostname = False # Bypass hostname verification
ssl_context.verify_mode = CERT_REQUIRED
else:
ssl_context = None
profile = ExecutionProfile(
# load_balancing_policy=RoundRobinPolicy(),
request_timeout=10
)
profile_long = ExecutionProfile(
request_timeout=30,
load_balancing_policy=DCAwareRoundRobinPolicy(local_dc=dcname)
)
cluster = Cluster(
[host],
port=9042,
execution_profiles={EXEC_PROFILE_DEFAULT: profile, 'long': profile_long},
auth_provider=auth_provider,
ssl_context=ssl_context)
session = cluster.connect()
### DO NOT ENABLE gateway_insert IN PRODUCTION AS IT MAY OVERWRITE DATA
#gateway_insert(session, ks, tbl)
gateway_query(session, ks, tbl, fetch)
gateway_query_count(session, ks, tbl, fetch, debug_file)
if __name__ == "__main__":
main()