-
Notifications
You must be signed in to change notification settings - Fork 0
/
master.py
441 lines (382 loc) · 13.4 KB
/
master.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
import sys
import socket
import os
from argparse import ArgumentParser
import requests
import time
import datetime
import random
import threading
import multiprocessing
import json
import yaml
from dxf import *
from multiprocessing import Process, Queue
import importlib
import hash_ring
## get requests
def send_request_get(client, payload):
## Read from the queue
s = requests.session()
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
s.post("http://" + str(client) + "/up", data=json.dumps(payload), headers=headers, timeout=100)
def send_warmup_thread(requests, q, registry, generate_random):
trace = {}
dxf = DXF(registry, 'test_repo', insecure=True)
f = open(str(os.getpid()), 'wb')
f.write('\0')
f.close()
for request in requests:
if request['size'] < 0:
trace[request['uri']] = 'bad'
elif not (request['uri'] in trace):
with open(str(os.getpid()), 'wb') as f:
if generate_random is True:
f.seek(request['size'] - 9)
f.write(str(random.getrandbits(64)))
f.write('\0')
else:
f.seek(request['size'] - 1)
f.write('\0')
try:
dgst = dxf.push_blob(str(os.getpid()))
except:
dgst = 'bad'
print request['uri'], dgst
trace[request['uri']] = dgst
os.remove(str(os.getpid()))
q.put(trace)
def warmup(data, out_trace, registry, threads, generate_random):
trace = {}
processes = []
q = Queue()
process_data = []
for i in range(threads):
process_data.append([])
i = 0
for request in data:
if request['method'] == 'GET':
process_data[i % threads].append(request)
i += 1
for i in range(threads):
p = Process(target=send_warmup_thread, args=(process_data[i], q, registry, generate_random))
processes.append(p)
for p in processes:
p.start()
for i in range(threads):
d = q.get()
for thing in d:
if thing in trace:
if trace[thing] == 'bad' and d[thing] != 'bad':
trace[thing] = d[thing]
else:
trace[thing] = d[thing]
for p in processes:
p.join()
with open(out_trace, 'w') as f:
json.dump(trace, f)
def stats(responses):
responses.sort(key = lambda x: x['time'])
endtime = 0
data = 0
latency = 0
total = len(responses)
onTimes = 0
failed = 0
startTime = responses[0]['time']
for r in responses:
if r['onTime'] == 'failed':
total -= 1
failed += 1
continue
if r['time'] + r['duration'] > endtime:
endtime = r['time'] + r['duration']
latency += r['duration']
data += r['size']
if r['onTime'] == 'yes':
onTimes += 1
duration = endtime - startTime
print 'Statistics'
print 'Successful Requests: ' + str(total)
print 'Failed Requests: ' + str(failed)
print 'Duration: ' + str(duration)
print 'Data Transfered: ' + str(data) + ' bytes'
print 'Average Latency: ' + str(latency / total)
print '% requests on time: ' + str(1.*onTimes / total)
print 'Throughput: ' + str(1.*total / duration) + ' requests/second'
def serve(port, ids, q, out_file):
server_address = ("0.0.0.0", port)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.bind(server_address)
sock.listen(len(ids))
except:
print "Port already in use: " + str(port)
q.put('fail')
quit()
q.put('success')
i = 0
response = []
print "server waiting"
while i < len(ids):
connection, client_address = sock.accept()
resp = ''
while True:
r = connection.recv(1024)
if not r:
break
resp += r
connection.close()
try:
info = json.loads(resp)
if info[0]['id'] in ids:
info = info[1:]
response.extend(info)
i += 1
except:
print 'exception occured in server'
pass
with open(out_file, 'w') as f:
json.dump(response, f)
print 'results written to ' + out_file
stats(response)
## Get blobs
def get_blobs(data, clients_list, port, out_file):
processess = []
ids = []
for d in data:
ids.append(d[0]['id'])
serveq = Queue()
server = Process(target=serve, args=(port, ids, serveq, out_file))
server.start()
status = serveq.get()
if status == 'fail':
quit()
## Lets start processes
i = 0
for client in clients_list:
p1 = Process(target = send_request_get, args=(client, data[i], ))
processess.append(p1)
i += 1
print "starting client ..."
for p in processess:
p.start()
for p in processess:
p.join()
server.join()
def get_requests(files, t, limit):
ret = []
for filename in files:
with open(filename, 'r') as f:
requests = json.load(f)
for request in requests:
method = request['http.request.method']
uri = request['http.request.uri']
if (('GET' == method) or ('PUT' == method)) and (('manifest' in uri) or ('blobs' in uri)):
size = request['http.response.written']
if size > 0:
timestamp = datetime.datetime.strptime(request['timestamp'], '%Y-%m-%dT%H:%M:%S.%fZ')
duration = request['http.request.duration']
client = request['http.request.remoteaddr']
r = {
'delay': timestamp,
'uri': uri,
'size': size,
'method': method,
'duration': duration,
'client': client
}
ret.append(r)
ret.sort(key= lambda x: x['delay'])
begin = ret[0]['delay']
for r in ret:
r['delay'] = (r['delay'] - begin).total_seconds()
if t == 'seconds':
begin = ret[0]['delay']
i = 0
for r in ret:
if r['delay'] > limit:
break
i += 1
print i
return ret[:i]
elif t == 'requests':
return ret[:limit]
else:
return ret
def organize(requests, out_trace, numclients, client_threads, port, wait, registries, round_robin, push_rand):
organized = []
if round_robin is False:
ring = hash_ring.HashRing(range(numclients))
with open(out_trace, 'r') as f:
blob = json.load(f)
for i in range(numclients):
organized.append([{'port': port, 'id': random.getrandbits(32), 'threads': client_threads, 'wait': wait, 'registry': registries, 'random': push_rand}])
print organized[-1][0]['id']
i = 0
for r in requests:
request = {
'delay': r['delay'],
'duration': r['duration'],
}
if r['uri'] in blob:
b = blob[r['uri']]
if b != 'bad':
request['blob'] = b
request['method'] = 'GET'
if round_robin is True:
organized[i % numclients].append(request)
i += 1
else:
organized[ring.get_node(r['client'])].append(request)
else:
request['size'] = r['size']
request['method'] = 'PUT'
if round_robin is True:
organized[i % numclients].append(request)
i += 1
else:
organized[ring.get_node(r['client'])].append[(request)]
return organized
def main():
parser = ArgumentParser(description='Trace Player, allows for anonymized traces to be replayed to a registry, or for caching and prefecting simulations.')
parser.add_argument('-i', '--input', dest='input', type=str, required=True, help = 'Input YAML configuration file, should contain all the inputs requried for processing')
parser.add_argument('-c', '--command', dest='command', type=str, required=True, help= 'Trace player command. Possible commands: warmup, run, simulate, warmup is used to populate the registry with the layers of the trace, run replays the trace, and simulate is used to test different caching and prefecting policies.')
args = parser.parse_args()
config = file(args.input, 'r')
try:
inputs = yaml.load(config)
except Exception as inst:
print 'error reading config file'
print inst
exit(-1)
verbose = False
if 'verbose' in inputs:
if inputs['verbose'] is True:
verbose = True
print 'Verbose Mode'
if 'trace' not in inputs:
print 'trace field required in config file'
exit(1)
trace_files = []
if 'location' in inputs['trace']:
location = inputs['trace']['location']
if '/' != location[-1]:
location += '/'
for fname in inputs['trace']['traces']:
trace_files.append(location + fname)
else:
trace_files.extend(inputs['trace']['traces'])
if verbose:
print 'Input traces'
for f in trace_files:
print f
limit_type = None
limit = 0
if 'limit' in inputs['trace']:
limit_type = inputs['trace']['limit']['type']
if limit_type in ['seconds', 'requests']:
limit = inputs['trace']['limit']['amount']
else:
print 'Invalid trace limit_type: limit_type must be either seconds or requests'
print exit(1)
elif verbose:
print 'limit_type not specified, entirety of trace files will be used will be used.'
if 'output' in inputs['trace']:
out_file = inputs['trace']['output']
else:
out_file = 'output.json'
if verbose:
print 'Output trace not specified, ./output.json will be used'
generate_random = False
if args.command != 'simulate':
if "warmup" not in inputs or 'output' not in inputs['warmup']:
print 'warmup not specified in config, warmup output required. Exiting'
exit(1)
else:
interm = inputs['warmup']['output']
if 'random' in inputs['warmup']:
if inputs['warmup']['random'] is True:
generate_random = True
registries = []
if 'registry' in inputs:
registries.extend(inputs['registry'])
json_data = get_requests(trace_files, limit_type, limit)
if args.command == 'warmup':
if verbose:
print 'warmup mode'
if 'threads' in inputs['warmup']:
threads = inputs['warmup']['threads']
else:
threads = 1
if verbose:
print 'warmup threads: ' + str(threads)
warmup(json_data, interm, registries[0], threads, generate_random)
elif args.command == 'run':
if verbose:
print 'run mode'
if 'client_info' not in inputs or inputs['client_info'] is None:
print 'client_info required for run mode in config file'
print 'exiting'
exit(1)
if 'port' not in inputs['client_info']:
if verbose:
print 'master server port not specified, assuming 8080'
port = 8080
else:
port = inputs['client_info']['port']
if verbose:
print 'master port: ' + str(port)
if 'threads' not in inputs['client_info']:
if verbose:
print 'client threads not specified, 1 thread will be used'
client_threads = 1
else:
client_threads = inputs['client_info']['threads']
if verbose:
print str(client_threads) + ' client threads'
if 'client_list' not in inputs['client_info']:
print 'client_list entries are required in config file'
exit(1)
else:
client_list = inputs['client_info']['client_list']
if 'wait' not in inputs['client_info']:
if verbose:
print 'Wait not specified, clients will not wait'
wait = False
elif inputs['client_info']['wait'] is True:
wait = True
else:
wait = False
round_robin = True
if 'route' in inputs['client_info']:
if inputs['client_info']['route'] is True:
round_robin = False
data = organize(json_data, interm, len(client_list), client_threads, port, wait, registries, round_robin, generate_random)
## Perform GET
get_blobs(data, client_list, port, out_file)
elif args.command == 'simulate':
if verbose:
print 'simulate mode'
if 'simulate' not in inputs:
print 'simulate file required in config'
exit(1)
pi = inputs['simulate']['name']
if '.py' in pi:
pi = pi[:-3]
try:
plugin = importlib.import_module(pi)
except Exception as inst:
print 'Plugin did not work!'
print inst
exit(1)
try:
if 'args' in inputs['simulate']:
plugin.init(json_data, inputs['simulate']['args'])
else:
plugin.init(json_data)
except Exception as inst:
print 'Error running plugin init!'
print inst
if __name__ == "__main__":
main()