-
Notifications
You must be signed in to change notification settings - Fork 0
/
bench.py
executable file
·383 lines (331 loc) · 18 KB
/
bench.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
#!venv/bin/python
from distutils.command.check import check
from pprint import pformat
import tempfile
import datetime
import sys
from bdd import ClientMongo
from execo import Timer
from execo_engine import Engine, sweep, ParamSweeper, slugify, logger
import os
import providerGD
import providerS3
import providerDB
import requests
def check_in_database(options,loca):
client = ClientMongo()
return client.checkExpExist(options,loca)
def check_Exp_database(options,loca):
client = ClientMongo()
return client.getAvgExp(options,loca)
def cb(option, a, b, parser):
"""
:param option: the option
:param value: the value
:param parser: the parser
:return: None
"""
args = []
for arg in parser.rargs:
if arg[0] != "-":
args.append(arg)
else:
del parser.rargs[:len(args)]
break
if getattr(parser.values, option.dest):
args.extend(getattr(parser.values, option.dest))
setattr(parser.values, option.dest, args)
def getFilSize(pathFile):
"""
:param pathFile: path of the file
:return: the size of the file
"""
statinfo = os.stat(pathFile)
return {long(statinfo.st_size)}
def getLocalisation():
"""
Return an object that contains localisation data
:return: dict with ip,lat,lon,city and country
"""
r = requests.get('http://ip-api.com/json/')
if r.status_code == 200:
content = r.json()
return {'ip': content['query'],
'lat': str(content['lat']),
'lon': str(content['lon']),
'city': str(content['city']),
'country': str(content['country'])}
else:
p = requests.get('http://www.telize.com/geoip?callback=getgeoip')
if r.status_code == 200:
content = p.json()
return {'ip': content['ip'],
'lat': str(content['latitude']),
'lon': str(content['longitude']),
'city': str(content['city']),
'country': str(content['country'])}
else:
return None
class Bench(Engine):
""" Bench is the engine that help running all the tests """
def check_parameters(self, options):
if self.options.driveAll:
self.drive = ['amazon', 'dropbox', 'googledrive']
self.transfert = [self.options.transfert]
self.OnlyDownload = False
if len(self.transfert) == 1:
if self.transfert[0] == 'download':
if not self.options.file:
self.OnlyDownload = True
print 'You must give a file with this option -t download '
if self.options.size is None and self.options.file is False:
print 'You have to give us a size or give us a file'
sys.exit()
if not self.options.drive:
if self.options.file:
print 'You choose to do all tests with this file ' + str(self.options.file)
else:
print 'You choose to do all tests with a random file of this size ' + str(self.options.size)
else:
print 'You choose to a specific tests on ' + str(self.options.drive) + ' with ' + str(self.transfert)
self.localisation = getLocalisation()
def __init__(self):
super(Bench, self).__init__()
self.options_parser.add_option('-s', '--size', dest='size',
help='Size of the random file test',
type=int)
self.options_parser.add_option('-o', '--only', dest='only',
help='Test only this size of the test',
action='store_true',
default=False)
self.options_parser.add_option('-p', '--protocol', dest='protocol',
choices=['sdk', 'rest', 'all'],
help='Specify a protocol from SDK or REST (default:all)',
default='all')
self.options_parser.add_option('-n', '--ntest', dest='ntest',
help='Number of tests',
default=5)
self.options_parser.add_option('-m', '--premium', dest='premium',
help='Account used is premium',
action='store_true',
default=False)
self.options_parser.add_option('-f', '--file', dest='file',
metavar="FILE",
help='File to test',
default=False)
self.options_parser.add_option('-t', '--transfert', dest='transfert',
choices=['inter', 'upload', 'download', 'upDown'],
help='Test a specific transfer type inter, upload, download, upDown(default:all)',
default='upDown')
self.options_parser.add_option('-d', '--drive',
callback=cb,
help='Test a specific drive from googledrive, amazon, dropbox',
action='callback',
dest='drive')
self.options_parser.add_option('-a', '--all',
action='store_true',
help='Test all the possible drives',
dest='driveAll')
self.options, self.args = self.options_parser.parse_args()
# Check if parameters are OK
self.check_parameters(self.options)
#Check if db doest not contain the experience
res = check_in_database(self.options,self.localisation)
if res.count() > 5:
logger.info('There is already at least 5 experiences like the one you want')
response = raw_input('Would you like to get results from our database? (Y/N)')
if response == "Y":
for t in check_Exp_database(self.options,self.localisation)['result']:
logger.info(t)
sys.exit()
def create_file(self, size):
""" Return the filename of file with the size of size """
fd, fname = tempfile.mkstemp()
with os.fdopen(fd, 'w') as fout:
fout.write(os.urandom(size))
# logger.info('Je cree '+ fname)
return fname
def run(self):
""" run method from engine in order to do our workflow """
mongo = ClientMongo()
size = dict
if not self.options.file:
if not self.options.only:
size = {1, long(self.options.size * 0.25),
long(self.options.size * 0.5),
long(self.options.size * 0.75),
long(self.options.size)}
else:
size = {long(self.options.size)}
else:
if self.OnlyDownload:
size = getFilSize(self.options.file)
else:
size = {0}
drive = None
if self.options.drive:
drive = self.options.drive
else:
drive = self.drive
interface = ['rest', 'sdk']
parameters = {'size': size,
'if': interface,
'drive': drive,
'transfert': self.transfert}
p = None
for n in range(0, int(self.options.ntest), 1):
logger.info('---------------------')
logger.info('Round %i', n+1)
combs = sweep(parameters)
date = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
pathResults = os.getcwd() + '/Results/Bench' + date
sweeper = ParamSweeper(pathResults + "/sweeps", combs)
f = open(pathResults + '/results.txt', 'w')
while len(sweeper.get_remaining()) > 0:
# sort the parameters
for i in interface:
for dr in drive:
for s in size:
comb = sweeper.get_next(
filtr=lambda r: filter(lambda x: x['drive'] == dr and x['size'] == s and x['if'] == i,
r))
if not comb: continue
# start of the workflow
if comb['drive'] == 'amazon':
p = providerS3.ProviderS3()
elif comb['drive'] == 'dropbox':
p = providerDB.ProviderDB()
else:
p = providerGD.ProviderGD()
logger.info('Treating combination %s', pformat(comb))
comb_dir = pathResults + '/' + slugify(comb)
if not os.path.isdir(comb_dir):
os.mkdir(comb_dir)
if not self.options.file:
fname = self.create_file(comb['size'])
else:
fname = self.options.file
timer = Timer()
up_time = 0
dl_time = 0
start_date = datetime.datetime.now()
if comb['if'] == 'sdk':
if p.provider_name == "amazon":
# AMAZON
clientAmz = p.getConnexion()
if self.OnlyDownload:
p.bucketKey += fname
else:
p.bucketKey += '/' + fname
if comb['transfert'] == "upload" or comb['transfert'] == 'upDown':
p.upload_file_sdk(clientAmz.get_bucket(p.bucketName),
p.bucketKey, fname)
up_time = timer.elapsed()
if comb['transfert'] == "download" or comb['transfert'] == 'upDown':
p.download_file_sdk(clientAmz.get_bucket(p.bucketName), p.bucketKey
, comb_dir + '/' + fname.split('/')[-1])
dl_time = timer.elapsed() - up_time
if not self.OnlyDownload:
p.delete_file_sdk(clientAmz.get_bucket(p.bucketName), p.bucketKey)
elif p.provider_name == "dropbox":
# DROPBOX
client = p.getToken()
if comb['transfert'] == "upload" or comb['transfert'] == 'upDown':
p.upload_file_sdk(client, fname, fname.split('/')[-1])
up_time = timer.elapsed()
if comb['transfert'] == "download" or comb['transfert'] == 'upDown':
p.download_file_sdk(client, fname.split('/')[-1],
comb_dir + '/' + fname.split('/')[-1])
dl_time = timer.elapsed() - up_time
if not self.OnlyDownload:
p.delete_file(client, fname.split('/')[-1])
elif p.provider_name == "googledrive":
# GOOGLEDRIVE
drive_service = p.getConnexion()
new_file = None
if comb['transfert'] == 'upload' or comb['transfert'] == 'upDown':
new_file = p.upload_file_sdk(drive_service, fname,
fname.split('/')[-1], 'text/plain')
up_time = timer.elapsed()
if comb['transfert'] == 'download' or comb['transfert'] == 'upDown':
p.download_file_sdk(drive_service, new_file,
comb_dir + '/' + fname.split('/')[-1])
dl_time = timer.elapsed() - up_time
if not self.OnlyDownload:
p.delete_file_sdk(drive_service, new_file['id'])
sweeper.done(comb)
elif comb['if'] == 'rest':
logger.warning('REST interface not implemented')
sweeper.skip(comb)
if not self.OnlyDownload:
# logger.info('delete de '+fname)
if os.path.isfile(fname):
os.remove(fname)
# delete only if rest is implmented
# os.remove(comb_dir + '/' + fname.split('/')[-1])
continue
if comb['transfert'] == "upload" or comb['transfert'] == "upDown":
f.write("%s %s %s %s %s %s %s %f %i %s %f\n" % (self.localisation['ip'],
self.localisation['lat'],
self.localisation['lon'],
self.localisation['city'],
self.localisation['country'],
comb['drive'],
comb['if'],
timer.start_date(),
comb['size'],
"upload",
up_time))
mongo.collection.insert({
'ip': self.localisation['ip'],
'latitude': self.localisation['lat'],
'longitude': self.localisation['lon'],
'city': self.localisation['city'],
'country': self.localisation['country'],
'drive': comb['drive'],
'interface': comb['if'],
'start_date': start_date,
'size': comb['size'],
'transfert': 'upload',
'time': up_time
})
if comb['transfert'] == "download" or comb['transfert'] == "upDown":
f.write("%s %s %s %s %s %s %s %f %i %s %f\n" % (self.localisation['ip'],
self.localisation['lat'],
self.localisation['lon'],
self.localisation['city'],
self.localisation['country'],
comb['drive'],
comb['if'],
timer.start_date(),
comb['size'],
"download",
dl_time))
mongo.collection.insert({
'ip': self.localisation['ip'],
'latitude': self.localisation['lat'],
'longitude': self.localisation['lon'],
'city': self.localisation['city'],
'country': self.localisation['country'],
'drive': comb['drive'],
'interface': comb['if'],
'start_date': start_date,
'size': comb['size'],
'transfert': 'download',
'time': dl_time
})
if not self.OnlyDownload:
# logger.info('delete de '+fname)
if os.path.isfile(fname):
os.remove(fname)
if os.path.isfile(comb_dir + '/' + fname):
os.remove(comb_dir + '/' + fname.split('/')[-1])
f.close()
# delete the Bench Folder
os.rmdir(self.result_dir)
logger.info("---------------------------------------")
for t in check_Exp_database(self.options,self.localisation)['result']:
logger.info(t)
if __name__ == "__main__":
e = Bench()
e.start()