blob: f6c330883f80b75dfe52e4fc3042cb3c16b4c5cd [file] [log] [blame]
koder aka kdanilov4d4771c2015-04-23 01:32:02 +03001import os
koder aka kdanilovda45e882015-04-06 02:24:42 +03002import sys
3import time
4import json
koder aka kdanilov0c598a12015-04-21 03:01:40 +03005import copy
koder aka kdanilovda45e882015-04-06 02:24:42 +03006import select
7import pprint
koder aka kdanilov4d4771c2015-04-23 01:32:02 +03008import os.path
koder aka kdanilovda45e882015-04-06 02:24:42 +03009import argparse
10import traceback
11import subprocess
12import itertools
13from collections import OrderedDict
14
15
16SECTION = 0
17SETTING = 1
18
19
koder aka kdanilov0c598a12015-04-21 03:01:40 +030020class FioJobSection(object):
21 def __init__(self, name):
22 self.name = name
23 self.vals = OrderedDict()
24 self.format_params = {}
25
26 def copy(self):
27 return copy.deepcopy(self)
28
29
30def to_bytes(sz):
31 sz = sz.lower()
32 try:
33 return int(sz)
34 except ValueError:
35 if sz[-1] == 'm':
36 return (1024 ** 2) * int(sz[:-1])
37 if sz[-1] == 'k':
38 return 1024 * int(sz[:-1])
39 if sz[-1] == 'g':
40 return (1024 ** 3) * int(sz[:-1])
41 raise
42
43
44def fio_config_lexer(fio_cfg):
45 for lineno, line in enumerate(fio_cfg.split("\n")):
46 try:
47 line = line.strip()
48
49 if line.startswith("#") or line.startswith(";"):
50 continue
51
52 if line == "":
53 continue
54
55 if line.startswith('['):
56 assert line.endswith(']'), "name should ends with ]"
57 yield lineno, SECTION, line[1:-1], None
58 elif '=' in line:
59 opt_name, opt_val = line.split('=', 1)
60 yield lineno, SETTING, opt_name.strip(), opt_val.strip()
61 else:
62 yield lineno, SETTING, line, None
63 except Exception as exc:
koder aka kdanilovec1b9732015-04-23 20:43:29 +030064 pref = "During parsing line number {0}\n{1!s}".format(lineno, exc)
65 raise ValueError(pref)
koder aka kdanilov0c598a12015-04-21 03:01:40 +030066
67
68def fio_config_parse(lexer_iter, format_params):
69 orig_format_params_keys = set(format_params)
70 format_params = format_params.copy()
71 in_defaults = False
72 curr_section = None
73 defaults = OrderedDict()
74
75 for lineno, tp, name, val in lexer_iter:
76 if tp == SECTION:
77 if curr_section is not None:
78 yield curr_section
79
80 if name == 'defaults':
81 in_defaults = True
82 curr_section = None
83 else:
84 in_defaults = False
85 curr_section = FioJobSection(name)
86 curr_section.format_params = format_params.copy()
87 curr_section.vals = defaults.copy()
88 else:
89 assert tp == SETTING
90 if name == name.upper():
91 msg = "Param not in default section in line " + str(lineno)
92 assert in_defaults, msg
93 if name not in orig_format_params_keys:
94 # don't make parse_value for PARAMS
95 # they would be parsed later
96 # or this would breakes arrays
97 format_params[name] = val
98 elif in_defaults:
99 defaults[name] = parse_value(val)
100 else:
101 msg = "data outside section, line " + str(lineno)
102 assert curr_section is not None, msg
103 curr_section.vals[name] = parse_value(val)
104
105 if curr_section is not None:
106 yield curr_section
107
108
109def parse_value(val):
110 if val is None:
111 return None
112
113 try:
114 return int(val)
115 except ValueError:
116 pass
117
118 try:
119 return float(val)
120 except ValueError:
121 pass
122
123 if val.startswith('{%'):
124 assert val.endswith("%}")
125 content = val[2:-2]
126 vals = list(i.strip() for i in content.split(','))
127 return map(parse_value, vals)
128 return val
129
130
131def process_repeats(sec_iter):
132
133 for sec in sec_iter:
134 if '*' in sec.name:
135 msg = "Only one '*' allowed in section name"
136 assert sec.name.count('*') == 1, msg
137
138 name, count = sec.name.split("*")
139 sec.name = name.strip()
140 count = count.strip()
141
142 try:
143 count = int(count.strip().format(**sec.format_params))
144 except KeyError:
145 raise ValueError("No parameter {0} given".format(count[1:-1]))
146 except ValueError:
147 msg = "Parameter {0} nas non-int value {1!r}"
148 raise ValueError(msg.format(count[1:-1],
149 count.format(**sec.format_params)))
150
koder aka kdanilov7e0f7cf2015-05-01 17:24:35 +0300151 yield sec.copy()
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300152
153 if 'ramp_time' in sec.vals:
154 sec = sec.copy()
155 sec.vals['_ramp_time'] = sec.vals.pop('ramp_time')
156
157 for _ in range(count - 1):
158 yield sec.copy()
159 else:
160 yield sec
161
162
163def process_cycles(sec_iter):
164 # insert parametrized cycles
165 sec_iter = try_format_params_into_section(sec_iter)
166
167 for sec in sec_iter:
168
169 cycles_var_names = []
170 cycles_var_values = []
171
172 for name, val in sec.vals.items():
173 if isinstance(val, list):
174 cycles_var_names.append(name)
175 cycles_var_values.append(val)
176
177 if len(cycles_var_names) == 0:
178 yield sec
179 else:
180 for combination in itertools.product(*cycles_var_values):
181 new_sec = sec.copy()
182 new_sec.vals.update(zip(cycles_var_names, combination))
183 yield new_sec
184
185
186def try_format_params_into_section(sec_iter):
187 for sec in sec_iter:
188 params = sec.format_params
189 for name, val in sec.vals.items():
190 if isinstance(val, basestring):
191 try:
192 sec.vals[name] = parse_value(val.format(**params))
193 except:
194 pass
195
196 yield sec
197
198
199def format_params_into_section_finall(sec_iter, counter=[0]):
200 group_report_err_msg = "Group reporting should be set if numjobs != 1"
201
202 for sec in sec_iter:
203
204 num_jobs = int(sec.vals.get('numjobs', '1'))
205 if num_jobs != 1:
206 assert 'group_reporting' in sec.vals, group_report_err_msg
207
208 params = sec.format_params
209
210 fsize = to_bytes(sec.vals['size'])
211 params['PER_TH_OFFSET'] = fsize // num_jobs
212
213 for name, val in sec.vals.items():
214 if isinstance(val, basestring):
215 sec.vals[name] = parse_value(val.format(**params))
216 else:
217 assert isinstance(val, (int, float)) or val is None
218
219 params['UNIQ'] = 'UN{0}'.format(counter[0])
koder aka kdanilov7e0f7cf2015-05-01 17:24:35 +0300220 params['COUNTER'] = str(counter[0])
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300221 counter[0] += 1
222 params['TEST_SUMM'] = get_test_summary(sec.vals)
koder aka kdanilov7e0f7cf2015-05-01 17:24:35 +0300223
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300224 sec.name = sec.name.format(**params)
225
226 yield sec
227
228
229def fio_config_to_str(sec_iter):
230 res = ""
231
232 for pos, sec in enumerate(sec_iter):
233 if pos != 0:
234 res += "\n"
235
236 res += "[{0}]\n".format(sec.name)
237
238 for name, val in sec.vals.items():
239 if name.startswith('_'):
240 continue
241
242 if val is None:
243 res += name + "\n"
244 else:
245 res += "{0}={1}\n".format(name, val)
246
247 return res
248
249
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300250def get_test_sync_mode(config):
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300251 try:
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300252 return config['sync_mode']
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300253 except KeyError:
254 pass
255
koder aka kdanilovea22c3d2015-04-21 03:42:22 +0300256 is_sync = str(config.get("sync", "0")) == "1"
257 is_direct = str(config.get("direct", "0")) == "1"
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300258
259 if is_sync and is_direct:
260 return 'x'
261 elif is_sync:
262 return 's'
263 elif is_direct:
264 return 'd'
265 else:
266 return 'a'
267
268
koder aka kdanilovda45e882015-04-06 02:24:42 +0300269def get_test_summary(params):
270 rw = {"randread": "rr",
271 "randwrite": "rw",
272 "read": "sr",
273 "write": "sw"}[params["rw"]]
274
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300275 sync_mode = get_test_sync_mode(params)
276 th_count = params.get('numjobs')
koder aka kdanilovea22c3d2015-04-21 03:42:22 +0300277
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300278 if th_count is None:
koder aka kdanilovea22c3d2015-04-21 03:42:22 +0300279 th_count = params.get('concurence', 1)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300280
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300281 return "{0}{1}{2}th{3}".format(rw,
282 sync_mode,
283 params['blocksize'],
284 th_count)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300285
286
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300287def calculate_execution_time(sec_iter):
koder aka kdanilovda45e882015-04-06 02:24:42 +0300288 time = 0
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300289 for sec in sec_iter:
290 time += sec.vals.get('ramp_time', 0)
291 time += sec.vals.get('runtime', 0)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300292 return time
293
294
koder aka kdanilov57ce4db2015-04-25 21:25:51 +0300295def slice_config(sec_iter, runcycle=None, max_jobs=1000,
296 soft_runcycle=None):
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300297 jcount = 0
298 runtime = 0
299 curr_slice = []
koder aka kdanilov57ce4db2015-04-25 21:25:51 +0300300 prev_name = None
koder aka kdanilovda45e882015-04-06 02:24:42 +0300301
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300302 for pos, sec in enumerate(sec_iter):
koder aka kdanilov57ce4db2015-04-25 21:25:51 +0300303 if soft_runcycle is not None and prev_name != sec.name:
304 if runtime > soft_runcycle:
305 yield curr_slice
306 curr_slice = []
307 runtime = 0
308 jcount = 0
309
310 prev_name = sec.name
koder aka kdanilovda45e882015-04-06 02:24:42 +0300311
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300312 jc = sec.vals.get('numjobs', 1)
313 msg = "numjobs should be integer, not {0!r}".format(jc)
314 assert isinstance(jc, int), msg
koder aka kdanilovda45e882015-04-06 02:24:42 +0300315
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300316 curr_task_time = calculate_execution_time([sec])
koder aka kdanilovda45e882015-04-06 02:24:42 +0300317
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300318 if jc > max_jobs:
319 err_templ = "Can't process job {0!r} - too large numjobs"
320 raise ValueError(err_templ.format(sec.name))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300321
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300322 if runcycle is not None and len(curr_slice) != 0:
323 rc_ok = curr_task_time + runtime <= runcycle
koder aka kdanilovda45e882015-04-06 02:24:42 +0300324 else:
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300325 rc_ok = True
koder aka kdanilovda45e882015-04-06 02:24:42 +0300326
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300327 if jc + jcount <= max_jobs and rc_ok:
328 runtime += curr_task_time
329 jcount += jc
330 curr_slice.append(sec)
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300331 continue
332
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300333 assert len(curr_slice) != 0
334 yield curr_slice
koder aka kdanilovda45e882015-04-06 02:24:42 +0300335
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300336 if '_ramp_time' in sec.vals:
337 sec.vals['ramp_time'] = sec.vals.pop('_ramp_time')
338 curr_task_time = calculate_execution_time([sec])
339
340 runtime = curr_task_time
341 jcount = jc
342 curr_slice = [sec]
koder aka kdanilov57ce4db2015-04-25 21:25:51 +0300343 prev_name = None
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300344
345 if curr_slice != []:
346 yield curr_slice
koder aka kdanilovda45e882015-04-06 02:24:42 +0300347
348
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300349def parse_all_in_1(source, test_params):
350 lexer_it = fio_config_lexer(source)
351 sec_it = fio_config_parse(lexer_it, test_params)
352 sec_it = process_cycles(sec_it)
353 sec_it = process_repeats(sec_it)
354 return format_params_into_section_finall(sec_it)
koder aka kdanilovb896f692015-04-07 14:57:55 +0300355
356
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300357def parse_and_slice_all_in_1(source, test_params, **slice_params):
358 sec_it = parse_all_in_1(source, test_params)
359 return slice_config(sec_it, **slice_params)
koder aka kdanilovb896f692015-04-07 14:57:55 +0300360
361
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300362def compile_all_in_1(source, test_params, **slice_params):
363 slices_it = parse_and_slice_all_in_1(source, test_params, **slice_params)
364 for slices in slices_it:
365 yield fio_config_to_str(slices)
koder aka kdanilovb896f692015-04-07 14:57:55 +0300366
367
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300368def do_run_fio(config_slice):
369 benchmark_config = fio_config_to_str(config_slice)
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300370 cmd = ["fio", "--output-format=json", "--alloc-size=262144", "-"]
koder aka kdanilove87ae652015-04-20 02:14:35 +0300371 p = subprocess.Popen(cmd,
372 stdin=subprocess.PIPE,
koder aka kdanilovda45e882015-04-06 02:24:42 +0300373 stdout=subprocess.PIPE,
koder aka kdanilove87ae652015-04-20 02:14:35 +0300374 stderr=subprocess.PIPE)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300375
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300376 start_time = time.time()
koder aka kdanilovda45e882015-04-06 02:24:42 +0300377 # set timeout
koder aka kdanilove87ae652015-04-20 02:14:35 +0300378 raw_out, raw_err = p.communicate(benchmark_config)
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300379 end_time = time.time()
koder aka kdanilove87ae652015-04-20 02:14:35 +0300380
koder aka kdanilov6b1341a2015-04-21 22:44:21 +0300381 # HACK
382 raw_out = "{" + raw_out.split('{', 1)[1]
383
koder aka kdanilove87ae652015-04-20 02:14:35 +0300384 if 0 != p.returncode:
385 msg = "Fio failed with code: {0}\nOutput={1}"
386 raise OSError(msg.format(p.returncode, raw_err))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300387
388 try:
389 parsed_out = json.loads(raw_out)["jobs"]
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300390 except KeyError:
391 msg = "Can't parse fio output {0!r}: no 'jobs' found"
392 raw_out = raw_out[:100]
393 raise ValueError(msg.format(raw_out))
394
395 except Exception as exc:
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300396 msg = "Can't parse fio output: {0!r}\nError: {1!s}"
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300397 raw_out = raw_out[:100]
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300398 raise ValueError(msg.format(raw_out, exc))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300399
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300400 return zip(parsed_out, config_slice), (start_time, end_time)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300401
402
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300403def add_job_results(section, job_output, res):
koder aka kdanilovda45e882015-04-06 02:24:42 +0300404 if job_output['write']['iops'] != 0:
405 raw_result = job_output['write']
406 else:
407 raw_result = job_output['read']
408
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300409 vals = section.vals
410 if section.name not in res:
koder aka kdanilovda45e882015-04-06 02:24:42 +0300411 j_res = {}
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300412 j_res["rw"] = vals["rw"]
413 j_res["sync_mode"] = get_test_sync_mode(vals)
414 j_res["concurence"] = int(vals.get("numjobs", 1))
415 j_res["blocksize"] = vals["blocksize"]
koder aka kdanilovda45e882015-04-06 02:24:42 +0300416 j_res["jobname"] = job_output["jobname"]
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300417 j_res["timings"] = [int(vals.get("runtime", 0)),
418 int(vals.get("ramp_time", 0))]
koder aka kdanilovda45e882015-04-06 02:24:42 +0300419 else:
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300420 j_res = res[section.name]
421 assert j_res["rw"] == vals["rw"]
422 assert j_res["rw"] == vals["rw"]
423 assert j_res["sync_mode"] == get_test_sync_mode(vals)
424 assert j_res["concurence"] == int(vals.get("numjobs", 1))
425 assert j_res["blocksize"] == vals["blocksize"]
koder aka kdanilovda45e882015-04-06 02:24:42 +0300426 assert j_res["jobname"] == job_output["jobname"]
koder aka kdanilov652cd802015-04-13 12:21:07 +0300427
428 # ramp part is skipped for all tests, except first
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300429 # assert j_res["timings"] == (vals.get("runtime"),
430 # vals.get("ramp_time"))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300431
432 def j_app(name, x):
433 j_res.setdefault(name, []).append(x)
434
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300435 j_app("bw", raw_result["bw"])
koder aka kdanilovda45e882015-04-06 02:24:42 +0300436 j_app("iops", raw_result["iops"])
437 j_app("lat", raw_result["lat"]["mean"])
438 j_app("clat", raw_result["clat"]["mean"])
439 j_app("slat", raw_result["slat"]["mean"])
440
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300441 res[section.name] = j_res
koder aka kdanilovda45e882015-04-06 02:24:42 +0300442
443
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300444def run_fio(sliced_it, raw_results_func=None):
445 sliced_list = list(sliced_it)
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300446
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300447 curr_test_num = 0
448 executed_tests = 0
449 result = {}
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300450 timings = []
koder aka kdanilovb896f692015-04-07 14:57:55 +0300451
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300452 for i, test_slice in enumerate(sliced_list):
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300453 res_cfg_it, slice_timings = do_run_fio(test_slice)
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300454 res_cfg_it = enumerate(res_cfg_it, curr_test_num)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300455
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300456 section_names = []
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300457 for curr_test_num, (job_output, section) in res_cfg_it:
458 executed_tests += 1
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300459 section_names.append(section.name)
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300460
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300461 if raw_results_func is not None:
462 raw_results_func(executed_tests,
463 [job_output, section])
koder aka kdanilovda45e882015-04-06 02:24:42 +0300464
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300465 msg = "{0} != {1}".format(section.name, job_output["jobname"])
466 assert section.name == job_output["jobname"], msg
koder aka kdanilovda45e882015-04-06 02:24:42 +0300467
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300468 if section.name.startswith('_'):
469 continue
koder aka kdanilovda45e882015-04-06 02:24:42 +0300470
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300471 add_job_results(section, job_output, result)
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300472
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300473 timings.append((section_names, slice_timings))
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300474 curr_test_num += 1
475 msg_template = "Done {0} tests from {1}. ETA: {2}"
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300476
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300477 rest = sliced_list[i:]
478 time_eta = sum(map(calculate_execution_time, rest))
479 test_left = sum(map(len, rest))
480 print msg_template.format(curr_test_num,
481 test_left,
482 sec_to_str(time_eta))
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300483
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300484 return result, executed_tests, timings
koder aka kdanilovda45e882015-04-06 02:24:42 +0300485
486
487def run_benchmark(binary_tp, *argv, **kwargs):
488 if 'fio' == binary_tp:
489 return run_fio(*argv, **kwargs)
490 raise ValueError("Unknown behcnmark {0}".format(binary_tp))
491
492
koder aka kdanilov652cd802015-04-13 12:21:07 +0300493def read_config(fd, timeout=10):
494 job_cfg = ""
495 etime = time.time() + timeout
496 while True:
497 wtime = etime - time.time()
498 if wtime <= 0:
499 raise IOError("No config provided")
500
501 r, w, x = select.select([fd], [], [], wtime)
502 if len(r) == 0:
503 raise IOError("No config provided")
504
505 char = fd.read(1)
506 if '' == char:
507 return job_cfg
508
509 job_cfg += char
510
511
koder aka kdanilov652cd802015-04-13 12:21:07 +0300512def sec_to_str(seconds):
513 h = seconds // 3600
514 m = (seconds % 3600) // 60
515 s = seconds % 60
516 return "{0}:{1:02d}:{2:02d}".format(h, m, s)
517
518
koder aka kdanilovda45e882015-04-06 02:24:42 +0300519def parse_args(argv):
520 parser = argparse.ArgumentParser(
521 description="Run fio' and return result")
522 parser.add_argument("--type", metavar="BINARY_TYPE",
523 choices=['fio'], default='fio',
524 help=argparse.SUPPRESS)
525 parser.add_argument("--start-at", metavar="START_AT_UTC", type=int,
526 help="Start execution at START_AT_UTC")
527 parser.add_argument("--json", action="store_true", default=False,
528 help="Json output format")
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300529 parser.add_argument("-o", "--output", default='-', metavar="FILE_PATH",
koder aka kdanilovda45e882015-04-06 02:24:42 +0300530 help="Store results to FILE_PATH")
531 parser.add_argument("--estimate", action="store_true", default=False,
532 help="Only estimate task execution time")
533 parser.add_argument("--compile", action="store_true", default=False,
534 help="Compile config file to fio config")
535 parser.add_argument("--num-tests", action="store_true", default=False,
536 help="Show total number of tests")
537 parser.add_argument("--runcycle", type=int, default=None,
538 metavar="MAX_CYCLE_SECONDS",
539 help="Max cycle length in seconds")
540 parser.add_argument("--show-raw-results", action='store_true',
541 default=False, help="Output raw input and results")
koder aka kdanilovda45e882015-04-06 02:24:42 +0300542 parser.add_argument("--params", nargs="*", metavar="PARAM=VAL",
543 default=[],
544 help="Provide set of pairs PARAM=VAL to" +
545 "format into job description")
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300546 parser.add_argument("-p", "--pid-file", metavar="FILE_TO_STORE_PID",
547 default=None, help="Store pid to FILE_TO_STORE_PID " +
548 "and remove this file on exit")
koder aka kdanilovda45e882015-04-06 02:24:42 +0300549 parser.add_argument("jobfile")
550 return parser.parse_args(argv)
551
552
koder aka kdanilovda45e882015-04-06 02:24:42 +0300553def main(argv):
554 argv_obj = parse_args(argv)
555
556 if argv_obj.jobfile == '-':
557 job_cfg = read_config(sys.stdin)
558 else:
559 job_cfg = open(argv_obj.jobfile).read()
560
561 if argv_obj.output == '-':
562 out_fd = sys.stdout
563 else:
564 out_fd = open(argv_obj.output, "w")
565
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300566 if argv_obj.pid_file is not None:
567 with open(argv_obj.pid_file, "w") as fd:
568 fd.write(str(os.getpid()))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300569
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300570 try:
571 params = {}
572 for param_val in argv_obj.params:
573 assert '=' in param_val
574 name, val = param_val.split("=", 1)
575 params[name] = val
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300576
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300577 slice_params = {
578 'runcycle': argv_obj.runcycle,
579 }
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300580
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300581 sliced_it = parse_and_slice_all_in_1(job_cfg, params, **slice_params)
koder aka kdanilov652cd802015-04-13 12:21:07 +0300582
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300583 if argv_obj.estimate:
584 it = map(calculate_execution_time, sliced_it)
585 print sec_to_str(sum(it))
586 return 0
koder aka kdanilovda45e882015-04-06 02:24:42 +0300587
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300588 if argv_obj.num_tests or argv_obj.compile:
589 if argv_obj.compile:
590 for test_slice in sliced_it:
591 out_fd.write(fio_config_to_str(test_slice))
592 out_fd.write("\n#" + "-" * 70 + "\n\n")
koder aka kdanilovda45e882015-04-06 02:24:42 +0300593
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300594 if argv_obj.num_tests:
595 print len(list(sliced_it))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300596
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300597 return 0
koder aka kdanilovda45e882015-04-06 02:24:42 +0300598
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300599 if argv_obj.start_at is not None:
600 ctime = time.time()
601 if argv_obj.start_at >= ctime:
602 time.sleep(ctime - argv_obj.start_at)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300603
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300604 def raw_res_func(test_num, data):
605 pref = "========= RAW_RESULTS({0}) =========\n".format(test_num)
606 out_fd.write(pref)
607 out_fd.write(json.dumps(data))
608 out_fd.write("\n========= END OF RAW_RESULTS =========\n")
609 out_fd.flush()
koder aka kdanilovda45e882015-04-06 02:24:42 +0300610
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300611 rrfunc = raw_res_func if argv_obj.show_raw_results else None
koder aka kdanilovda45e882015-04-06 02:24:42 +0300612
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300613 stime = time.time()
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300614 job_res, num_tests, timings = run_benchmark(argv_obj.type,
615 sliced_it, rrfunc)
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300616 etime = time.time()
koder aka kdanilovda45e882015-04-06 02:24:42 +0300617
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300618 res = {'__meta__': {'raw_cfg': job_cfg,
619 'params': params,
620 'timings': timings},
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300621 'res': job_res}
koder aka kdanilovda45e882015-04-06 02:24:42 +0300622
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300623 oformat = 'json' if argv_obj.json else 'eval'
624 msg = "\nRun {0} tests in {1} seconds\n"
625 out_fd.write(msg.format(num_tests, int(etime - stime)))
626
627 msg = "========= RESULTS(format={0}) =========\n"
628 out_fd.write(msg.format(oformat))
629 if argv_obj.json:
630 out_fd.write(json.dumps(res))
631 else:
632 out_fd.write(pprint.pformat(res) + "\n")
633 out_fd.write("\n========= END OF RESULTS =========\n")
634
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300635 return 0
636 except:
637 out_fd.write("============ ERROR =============\n")
638 out_fd.write(traceback.format_exc() + "\n")
639 out_fd.write("============ END OF ERROR =============\n")
640 return 1
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300641 finally:
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300642 try:
643 if out_fd is not sys.stdout:
644 out_fd.flush()
645 os.fsync(out_fd)
646 out_fd.close()
647 except Exception:
648 traceback.print_exc()
649
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300650 if argv_obj.pid_file is not None:
651 if os.path.exists(argv_obj.pid_file):
652 os.unlink(argv_obj.pid_file)
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300653
654
655def fake_main(x):
656 import yaml
657 time.sleep(60)
658 out_fd = sys.stdout
659 fname = "/tmp/perf_tests/metempirical_alisha/raw_results.yaml"
660 res = yaml.load(open(fname).read())[0][1]
661 out_fd.write("========= RESULTS(format=json) =========\n")
662 out_fd.write(json.dumps(res))
663 out_fd.write("\n========= END OF RESULTS =========\n")
koder aka kdanilovda45e882015-04-06 02:24:42 +0300664 return 0
665
666
667if __name__ == '__main__':
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300668 # exit(fake_main(sys.argv[1:]))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300669 exit(main(sys.argv[1:]))