1 | #!/usr/bin/env python3 |
---|
2 | #-*- mode: Python;-*- |
---|
3 | |
---|
4 | import sys |
---|
5 | import os |
---|
6 | import time |
---|
7 | import random |
---|
8 | import tempfile |
---|
9 | import argparse |
---|
10 | import socket |
---|
11 | import json |
---|
12 | try: |
---|
13 | import requests |
---|
14 | except: |
---|
15 | sys.stderr.write('ERROR: Could not import requests module. Ensure it is installed.\n') |
---|
16 | sys.stderr.write(' Under Debian, the package name is "python3-requests"\n.') |
---|
17 | sys.exit(1) |
---|
18 | |
---|
19 | VERSION = "{DEVELOPMENT}" |
---|
20 | if VERSION == "{DEVELOPMENT}": |
---|
21 | script_dir = '.' |
---|
22 | try: |
---|
23 | script_dir = os.path.dirname(os.path.realpath(__file__)) |
---|
24 | except: |
---|
25 | try: |
---|
26 | script_dir = os.path.dirname(os.path.abspath(sys.argv[0])) |
---|
27 | except: |
---|
28 | pass |
---|
29 | sys.path.append("%s/../../trunk/lib" % script_dir) |
---|
30 | |
---|
31 | from nanownlib import * |
---|
32 | import nanownlib.storage |
---|
33 | |
---|
34 | parser = argparse.ArgumentParser( |
---|
35 | description="") |
---|
36 | parser.add_argument('-c', dest='cases', type=str, default='{"valid":"0012-5969","invalid":"0012-9999"}', |
---|
37 | help='JSON representation of echo timing cases.') |
---|
38 | parser.add_argument('--no-tcpts', action='store_true', help='Disbale TCP timestamp profiling') |
---|
39 | parser.add_argument('--no-control', action='store_true', help='Do not collect separate control data. Instead, synthesize it from test and train data.') |
---|
40 | parser.add_argument('session_name', default=None, |
---|
41 | help='Name for the sampler session (used in output filenames)') |
---|
42 | parser.add_argument('sample_count', type=int, default=None, |
---|
43 | help='Number of samples to collect') |
---|
44 | parser.add_argument('host', default=None, |
---|
45 | help='IP address or host name of server') |
---|
46 | parser.add_argument('port', nargs='?', type=int, default=80, |
---|
47 | help='TCP port number of HTTP service (default: 80)') |
---|
48 | options = parser.parse_args() |
---|
49 | |
---|
50 | |
---|
51 | session_name = options.session_name |
---|
52 | num_samples=options.sample_count |
---|
53 | hostname = options.host |
---|
54 | port = options.port |
---|
55 | protocol = 'http' |
---|
56 | |
---|
57 | cases = json.loads(options.cases) |
---|
58 | |
---|
59 | |
---|
60 | def extractReportedRuntime(headers, body): |
---|
61 | try: |
---|
62 | if 'X-Response-Time' in headers: |
---|
63 | t = headers['X-Response-Time'].split('ms')[0] |
---|
64 | return int(float(t)*1000000) |
---|
65 | except: |
---|
66 | pass |
---|
67 | |
---|
68 | return None |
---|
69 | |
---|
70 | |
---|
71 | def sendRequest(data=None): |
---|
72 | method = 'POST' |
---|
73 | path = '/jregistrate/register' |
---|
74 | url = "%s://%s:%d%s" % (protocol,hostname,port,path) |
---|
75 | headers = {"Content-Type":"application/x-www-form-urlencoded"} |
---|
76 | body = (b'member_id='+data.encode('utf-8')+b'&last_four=1111&zip_code=97219&username=bob&password=&conf_pwd=') |
---|
77 | req = requests.Request(method, url, headers=headers, data=body).prepare() |
---|
78 | |
---|
79 | retry = True |
---|
80 | while retry: |
---|
81 | try: |
---|
82 | session = requests.Session() |
---|
83 | response = session.send(req, verify=False) |
---|
84 | #print(repr(response.raw._original_response.local_address)) |
---|
85 | reported = extractReportedRuntime(response.headers, response.text) |
---|
86 | retry = False |
---|
87 | except Exception as e: |
---|
88 | sys.stderr.write("ERROR: HTTP request problem: %s\n" % repr(e)) |
---|
89 | time.sleep(1.0) |
---|
90 | sys.stderr.write("ERROR: retrying...\n") |
---|
91 | #print(data.encode('utf-8'), reported) |
---|
92 | |
---|
93 | return {'userspace_rtt':response.elapsed.microseconds*1000, |
---|
94 | 'reported':reported, |
---|
95 | 'local_port':response.raw._original_response.local_address[1]} |
---|
96 | |
---|
97 | |
---|
98 | def fetch(probedata, data): |
---|
99 | # http://docs.python-requests.org/en/latest/api/#requests.Response |
---|
100 | result = sendRequest(data) |
---|
101 | result.update(probedata) |
---|
102 | |
---|
103 | return result |
---|
104 | |
---|
105 | |
---|
106 | setCPUAffinity() |
---|
107 | setTCPTimestamps() |
---|
108 | host_ip = socket.gethostbyname(hostname) #XXX: what about multiple A records? |
---|
109 | |
---|
110 | meta = {'tcpts_mean':None,'tcpts_stddev':None,'tcpts_slopes':None} |
---|
111 | if not options.no_tcpts: |
---|
112 | sys.stderr.write("INFO: Probing target for TCP timestamp precision...\n") |
---|
113 | sniffer_fp = tempfile.NamedTemporaryFile('w+t') |
---|
114 | sniffer = startSniffer(host_ip, port, sniffer_fp.name) |
---|
115 | time.sleep(1.0) |
---|
116 | ports = runTimestampProbes(host_ip, port, hostname, 12) |
---|
117 | time.sleep(1.0) |
---|
118 | stopSniffer(sniffer) |
---|
119 | sniffer_fp.seek(0) |
---|
120 | mean,stddev,slopes = computeTimestampPrecision(sniffer_fp, ports) |
---|
121 | meta = {'tcpts_mean':mean,'tcpts_stddev':stddev,'tcpts_slopes':json.dumps(slopes)} |
---|
122 | |
---|
123 | if meta['tcpts_mean'] == None: |
---|
124 | sys.stderr.write("INFO: TCP timestamps not supported.\n") |
---|
125 | elif meta['tcpts_stddev'] == None: |
---|
126 | sys.stderr.write("INFO: Not enough TCP timestamp samples.\n") |
---|
127 | elif meta['tcpts_stddev']/meta['tcpts_mean'] > 0.05: |
---|
128 | sys.stderr.write("INFO: TCP timestamp precision is inconsistent.\n") |
---|
129 | sys.stderr.write("INFO: mean=%(tcpts_mean)f,stddev=%(tcpts_stddev)f,samples=%(tcpts_slopes)s\n" |
---|
130 | % meta) |
---|
131 | else: |
---|
132 | sys.stderr.write("INFO: Estimated TCP timestamp precision: %f (stddev: %f, %f%%)\n" |
---|
133 | % (meta['tcpts_mean'], meta['tcpts_stddev'], 100*meta['tcpts_stddev']/meta['tcpts_mean'])) |
---|
134 | |
---|
135 | |
---|
136 | sniffer_fp = tempfile.NamedTemporaryFile('w+t') |
---|
137 | db_file = "%s.db" % session_name |
---|
138 | |
---|
139 | sniffer = startSniffer(host_ip, port, sniffer_fp.name) |
---|
140 | db = nanownlib.storage.db(db_file) |
---|
141 | db.addMeta(meta) |
---|
142 | time.sleep(0.5) # ensure sniffer is fully ready and our process is migrated |
---|
143 | |
---|
144 | if options.no_control: |
---|
145 | num_control = 0 |
---|
146 | else: |
---|
147 | num_control = int(num_samples*1/3) |
---|
148 | |
---|
149 | num_train = int((num_samples-num_control)/2) |
---|
150 | num_test = num_samples-num_train-num_control |
---|
151 | |
---|
152 | sample_types = [('train',num_train), |
---|
153 | ('train_null',num_control), |
---|
154 | ('test',num_test)] |
---|
155 | |
---|
156 | sid = 0 |
---|
157 | report_interval = 20 |
---|
158 | start = time.time() |
---|
159 | next_report = start+report_interval |
---|
160 | for st,count in sample_types: |
---|
161 | if sniffer.poll() != None: |
---|
162 | sys.stderr.write('ERROR: Sniffer quit, sender exiting...\n') |
---|
163 | break |
---|
164 | |
---|
165 | for k in range(0,count): |
---|
166 | sample_order = list(cases.items()) |
---|
167 | random.shuffle(sample_order) |
---|
168 | if st.endswith('null'): |
---|
169 | for i in range(1,len(sample_order)): |
---|
170 | sample_order[i] = (sample_order[i][0],sample_order[0][1]) |
---|
171 | random.shuffle(sample_order) |
---|
172 | #print('after', sample_order) |
---|
173 | |
---|
174 | results = [] |
---|
175 | now = int(time.time()*1000000000) |
---|
176 | for i in range(len(sample_order)): |
---|
177 | results.append(fetch({'sample':sid, 'test_case':sample_order[i][0], |
---|
178 | 'type':st, 'tc_order':i, 'time_of_day':now}, |
---|
179 | sample_order[i][1])) |
---|
180 | |
---|
181 | #print(results) |
---|
182 | db.addProbes(results) |
---|
183 | db.conn.commit() |
---|
184 | sid += 1 |
---|
185 | |
---|
186 | if (time.time() > next_report): |
---|
187 | #s = time.time() |
---|
188 | reportProgress(db, sample_types, start) |
---|
189 | #print("reportProgress time:", time.time()-s) |
---|
190 | next_report += report_interval |
---|
191 | |
---|
192 | print("probes complete in %f" % (time.time()-start)) |
---|
193 | time.sleep(2.0) # Give sniffer a chance to collect remaining packets |
---|
194 | stopSniffer(sniffer) |
---|
195 | |
---|
196 | start = time.time() |
---|
197 | associatePackets(sniffer_fp, db) |
---|
198 | sniffer_fp.close() |
---|
199 | end = time.time() |
---|
200 | print("associate time:", end-start) |
---|
201 | |
---|
202 | if options.no_control: |
---|
203 | print("TODO: implement control synthesizing!") |
---|
204 | |
---|
205 | start = time.time() |
---|
206 | num_probes = analyzeProbes(db) |
---|
207 | end = time.time() |
---|
208 | print("analyzed %d probes' packets in: %f" % (num_probes, end-start)) |
---|