blob: 5de3038a1409f817d9efa98979619e9a92003ee5 [file] [log] [blame]
koder aka kdanilov2e928022015-04-08 13:47:15 +03001import re
koder aka kdanilovda45e882015-04-06 02:24:42 +03002import sys
3import time
4import json
koder aka kdanilovb896f692015-04-07 14:57:55 +03005import random
koder aka kdanilovda45e882015-04-06 02:24:42 +03006import select
7import pprint
8import argparse
9import traceback
10import subprocess
11import itertools
12from collections import OrderedDict
13
14
15SECTION = 0
16SETTING = 1
17
18
19def get_test_summary(params):
20 rw = {"randread": "rr",
21 "randwrite": "rw",
22 "read": "sr",
23 "write": "sw"}[params["rw"]]
24
25 if params.get("direct") == '1':
26 sync_mode = 'd'
27 elif params.get("sync") == '1':
28 sync_mode = 's'
29 else:
30 sync_mode = 'a'
31
32 th_count = int(params.get('numjobs', '1'))
33
34 return "{0}{1}{2}th{3}".format(rw, sync_mode,
35 params['blocksize'], th_count)
36
37
38counter = [0]
39
40
41def process_section(name, vals, defaults, format_params):
42 vals = vals.copy()
43 params = format_params.copy()
44
45 if '*' in name:
46 name, repeat = name.split('*')
47 name = name.strip()
48 repeat = int(repeat.format(**params))
49 else:
50 repeat = 1
51
52 # this code can be optimized
koder aka kdanilovb896f692015-04-07 14:57:55 +030053 iterable_names = []
54 iterable_values = []
55 processed_vals = {}
koder aka kdanilovda45e882015-04-06 02:24:42 +030056
koder aka kdanilovb896f692015-04-07 14:57:55 +030057 for val_name, val in vals.items():
58 if val is None:
59 processed_vals[val_name] = val
60 # remove hardcode
61 elif val.startswith('{%'):
62 assert val.endswith("%}")
63 content = val[2:-2].format(**params)
64 iterable_names.append(val_name)
65 iterable_values.append(list(i.strip() for i in content.split(',')))
66 else:
67 processed_vals[val_name] = val.format(**params)
koder aka kdanilovda45e882015-04-06 02:24:42 +030068
koder aka kdanilov2e928022015-04-08 13:47:15 +030069 group_report_err_msg = "Group reporting should be set if numjobs != 1"
70
koder aka kdanilovb896f692015-04-07 14:57:55 +030071 if iterable_values == []:
72 params['UNIQ'] = 'UN{0}'.format(counter[0])
73 counter[0] += 1
74 params['TEST_SUMM'] = get_test_summary(processed_vals)
koder aka kdanilov2e928022015-04-08 13:47:15 +030075
76 if processed_vals.get('numjobs', '1') != '1':
77 assert 'group_reporting' in processed_vals, group_report_err_msg
78
koder aka kdanilovb896f692015-04-07 14:57:55 +030079 for i in range(repeat):
koder aka kdanilov2e928022015-04-08 13:47:15 +030080 yield name.format(**params), processed_vals.copy()
koder aka kdanilovb896f692015-04-07 14:57:55 +030081 else:
82 for it_vals in itertools.product(*iterable_values):
83 processed_vals.update(dict(zip(iterable_names, it_vals)))
koder aka kdanilovda45e882015-04-06 02:24:42 +030084 params['UNIQ'] = 'UN{0}'.format(counter[0])
85 counter[0] += 1
86 params['TEST_SUMM'] = get_test_summary(processed_vals)
koder aka kdanilov2e928022015-04-08 13:47:15 +030087
88 if processed_vals.get('numjobs', '1') != '1':
89 assert 'group_reporting' in processed_vals,\
90 group_report_err_msg
91
koder aka kdanilov66839a92015-04-11 13:22:31 +030092 ramp_time = processed_vals.get('ramp_time')
93
koder aka kdanilovb896f692015-04-07 14:57:55 +030094 for i in range(repeat):
95 yield name.format(**params), processed_vals.copy()
koder aka kdanilov66839a92015-04-11 13:22:31 +030096 if 'ramp_time' in processed_vals:
97 del processed_vals['ramp_time']
98
99 if ramp_time is not None:
100 processed_vals['ramp_time'] = ramp_time
koder aka kdanilovda45e882015-04-06 02:24:42 +0300101
102
103def calculate_execution_time(combinations):
104 time = 0
105 for _, params in combinations:
106 time += int(params.get('ramp_time', 0))
107 time += int(params.get('runtime', 0))
108 return time
109
110
111def parse_fio_config_full(fio_cfg, params=None):
112 defaults = {}
113 format_params = {}
114
115 if params is None:
116 ext_params = {}
117 else:
118 ext_params = params.copy()
119
120 curr_section = None
121 curr_section_name = None
122
123 for tp, name, val in parse_fio_config_iter(fio_cfg):
124 if tp == SECTION:
125 non_def = curr_section_name != 'defaults'
126 if curr_section_name is not None and non_def:
127 format_params.update(ext_params)
128 for sec in process_section(curr_section_name,
129 curr_section,
130 defaults,
131 format_params):
132 yield sec
133
134 if name == 'defaults':
135 curr_section = defaults
136 else:
137 curr_section = OrderedDict()
138 curr_section.update(defaults)
139 curr_section_name = name
140
141 else:
142 assert tp == SETTING
143 assert curr_section_name is not None, "no section name"
144 if name == name.upper():
145 assert curr_section_name == 'defaults'
146 format_params[name] = val
147 else:
148 curr_section[name] = val
149
150 if curr_section_name is not None and curr_section_name != 'defaults':
151 format_params.update(ext_params)
152 for sec in process_section(curr_section_name,
153 curr_section,
154 defaults,
155 format_params):
156 yield sec
157
158
159def parse_fio_config_iter(fio_cfg):
160 for lineno, line in enumerate(fio_cfg.split("\n")):
161 try:
162 line = line.strip()
163
164 if line.startswith("#") or line.startswith(";"):
165 continue
166
167 if line == "":
168 continue
169
170 if line.startswith('['):
171 assert line.endswith(']'), "name should ends with ]"
172 yield SECTION, line[1:-1], None
173 elif '=' in line:
174 opt_name, opt_val = line.split('=', 1)
175 yield SETTING, opt_name.strip(), opt_val.strip()
176 else:
177 yield SETTING, line, None
178 except Exception as exc:
179 pref = "During parsing line number {0}\n".format(lineno)
180 raise ValueError(pref + exc.message)
181
182
183def format_fio_config(fio_cfg):
184 res = ""
185 for pos, (name, section) in enumerate(fio_cfg):
186 if pos != 0:
187 res += "\n"
188
189 res += "[{0}]\n".format(name)
190 for opt_name, opt_val in section.items():
191 if opt_val is None:
192 res += opt_name + "\n"
193 else:
194 res += "{0}={1}\n".format(opt_name, opt_val)
195 return res
196
197
koder aka kdanilovb896f692015-04-07 14:57:55 +0300198count = 0
199
200
201def to_bytes(sz):
202 sz = sz.lower()
203 try:
204 return int(sz)
205 except ValueError:
206 if sz[-1] == 'm':
207 return (1024 ** 2) * int(sz[:-1])
208 if sz[-1] == 'k':
209 return 1024 * int(sz[:-1])
210 raise
211
212
koder aka kdanilovb896f692015-04-07 14:57:55 +0300213def do_run_fio_fake(bconf):
koder aka kdanilov66839a92015-04-11 13:22:31 +0300214 def estimate_iops(sz, bw, lat):
215 return 1 / (lat + float(sz) / bw)
koder aka kdanilovb896f692015-04-07 14:57:55 +0300216 global count
217 count += 1
218 parsed_out = []
219
220 BW = 120.0 * (1024 ** 2)
221 LAT = 0.003
222
223 for name, cfg in bconf:
224 sz = to_bytes(cfg['blocksize'])
225 curr_lat = LAT * ((random.random() - 0.5) * 0.1 + 1)
226 curr_ulat = curr_lat * 1000000
227 curr_bw = BW * ((random.random() - 0.5) * 0.1 + 1)
228 iops = estimate_iops(sz, curr_bw, curr_lat)
229 bw = iops * sz
230
231 res = {'ctx': 10683,
232 'error': 0,
233 'groupid': 0,
234 'jobname': name,
235 'majf': 0,
236 'minf': 30,
237 'read': {'bw': 0,
238 'bw_agg': 0.0,
239 'bw_dev': 0.0,
240 'bw_max': 0,
241 'bw_mean': 0.0,
242 'bw_min': 0,
243 'clat': {'max': 0,
244 'mean': 0.0,
245 'min': 0,
246 'stddev': 0.0},
247 'io_bytes': 0,
248 'iops': 0,
249 'lat': {'max': 0, 'mean': 0.0,
250 'min': 0, 'stddev': 0.0},
251 'runtime': 0,
252 'slat': {'max': 0, 'mean': 0.0,
253 'min': 0, 'stddev': 0.0}
254 },
255 'sys_cpu': 0.64,
256 'trim': {'bw': 0,
257 'bw_agg': 0.0,
258 'bw_dev': 0.0,
259 'bw_max': 0,
260 'bw_mean': 0.0,
261 'bw_min': 0,
262 'clat': {'max': 0,
263 'mean': 0.0,
264 'min': 0,
265 'stddev': 0.0},
266 'io_bytes': 0,
267 'iops': 0,
268 'lat': {'max': 0, 'mean': 0.0,
269 'min': 0, 'stddev': 0.0},
270 'runtime': 0,
271 'slat': {'max': 0, 'mean': 0.0,
272 'min': 0, 'stddev': 0.0}
273 },
274 'usr_cpu': 0.23,
275 'write': {'bw': 0,
276 'bw_agg': 0,
277 'bw_dev': 0,
278 'bw_max': 0,
279 'bw_mean': 0,
280 'bw_min': 0,
281 'clat': {'max': 0, 'mean': 0,
282 'min': 0, 'stddev': 0},
283 'io_bytes': 0,
284 'iops': 0,
285 'lat': {'max': 0, 'mean': 0,
286 'min': 0, 'stddev': 0},
287 'runtime': 0,
288 'slat': {'max': 0, 'mean': 0.0,
289 'min': 0, 'stddev': 0.0}
290 }
291 }
292
293 if cfg['rw'] in ('read', 'randread'):
294 key = 'read'
295 elif cfg['rw'] in ('write', 'randwrite'):
296 key = 'write'
297 else:
298 raise ValueError("Uknown op type {0}".format(key))
299
300 res[key]['bw'] = bw
301 res[key]['iops'] = iops
302 res[key]['runtime'] = 30
303 res[key]['io_bytes'] = res[key]['runtime'] * bw
304 res[key]['bw_agg'] = bw
305 res[key]['bw_dev'] = bw / 30
306 res[key]['bw_max'] = bw * 1.5
307 res[key]['bw_min'] = bw / 1.5
308 res[key]['bw_mean'] = bw
309 res[key]['clat'] = {'max': curr_ulat * 10, 'mean': curr_ulat,
310 'min': curr_ulat / 2, 'stddev': curr_ulat}
311 res[key]['lat'] = res[key]['clat'].copy()
312 res[key]['slat'] = res[key]['clat'].copy()
313
314 parsed_out.append(res)
315
316 return zip(parsed_out, bconf)
317
318
koder aka kdanilovda45e882015-04-06 02:24:42 +0300319def do_run_fio(bconf):
320 benchmark_config = format_fio_config(bconf)
321 cmd = ["fio", "--output-format=json", "-"]
322 p = subprocess.Popen(cmd, stdin=subprocess.PIPE,
323 stdout=subprocess.PIPE,
324 stderr=subprocess.STDOUT)
325
326 # set timeout
327 raw_out, _ = p.communicate(benchmark_config)
328
329 try:
330 parsed_out = json.loads(raw_out)["jobs"]
331 except Exception:
332 msg = "Can't parse fio output: {0!r}\nError: {1}"
333 raise ValueError(msg.format(raw_out, traceback.format_exc()))
334
335 return zip(parsed_out, bconf)
336
koder aka kdanilovda45e882015-04-06 02:24:42 +0300337# limited by fio
338MAX_JOBS = 1000
339
340
341def next_test_portion(whole_conf, runcycle):
342 jcount = 0
343 runtime = 0
344 bconf = []
345
346 for pos, (name, sec) in enumerate(whole_conf):
347 jc = int(sec.get('numjobs', '1'))
348
349 if runcycle is not None:
350 curr_task_time = calculate_execution_time([(name, sec)])
351 else:
352 curr_task_time = 0
353
354 if jc > MAX_JOBS:
355 err_templ = "Can't process job {0!r} - too large numjobs"
356 raise ValueError(err_templ.format(name))
357
358 if runcycle is not None and len(bconf) != 0:
359 rc_ok = curr_task_time + runtime <= runcycle
360 else:
361 rc_ok = True
362
363 if jc + jcount <= MAX_JOBS and rc_ok:
364 runtime += curr_task_time
365 jcount += jc
366 bconf.append((name, sec))
367 continue
368
369 assert len(bconf) != 0
370 yield bconf
371
372 runtime = curr_task_time
373 jcount = jc
374 bconf = [(name, sec)]
375
376 if bconf != []:
377 yield bconf
378
379
380def add_job_results(jname, job_output, jconfig, res):
381 if job_output['write']['iops'] != 0:
382 raw_result = job_output['write']
383 else:
384 raw_result = job_output['read']
385
386 if jname not in res:
387 j_res = {}
388 j_res["action"] = jconfig["rw"]
389 j_res["direct_io"] = jconfig.get("direct", "0") == "1"
390 j_res["sync"] = jconfig.get("sync", "0") == "1"
391 j_res["concurence"] = int(jconfig.get("numjobs", 1))
koder aka kdanilov2e928022015-04-08 13:47:15 +0300392 j_res["blocksize"] = jconfig["blocksize"]
koder aka kdanilovda45e882015-04-06 02:24:42 +0300393 j_res["jobname"] = job_output["jobname"]
koder aka kdanilov66839a92015-04-11 13:22:31 +0300394 j_res["timings"] = [int(jconfig.get("runtime", 0)),
395 int(jconfig.get("ramp_time", 0))]
koder aka kdanilovda45e882015-04-06 02:24:42 +0300396 else:
397 j_res = res[jname]
398 assert j_res["action"] == jconfig["rw"]
399
400 assert j_res["direct_io"] == \
401 (jconfig.get("direct", "0") == "1")
402
403 assert j_res["sync"] == (jconfig.get("sync", "0") == "1")
404 assert j_res["concurence"] == int(jconfig.get("numjobs", 1))
koder aka kdanilov2e928022015-04-08 13:47:15 +0300405 assert j_res["blocksize"] == jconfig["blocksize"]
koder aka kdanilovda45e882015-04-06 02:24:42 +0300406 assert j_res["jobname"] == job_output["jobname"]
407 assert j_res["timings"] == (jconfig.get("runtime"),
408 jconfig.get("ramp_time"))
409
410 def j_app(name, x):
411 j_res.setdefault(name, []).append(x)
412
413 # 'bw_dev bw_mean bw_max bw_min'.split()
414 j_app("bw_mean", raw_result["bw_mean"])
415 j_app("iops", raw_result["iops"])
416 j_app("lat", raw_result["lat"]["mean"])
417 j_app("clat", raw_result["clat"]["mean"])
418 j_app("slat", raw_result["slat"]["mean"])
419
420 res[jname] = j_res
421
422
423def run_fio(benchmark_config,
424 params,
425 runcycle=None,
426 raw_results_func=None,
koder aka kdanilovb896f692015-04-07 14:57:55 +0300427 skip_tests=0,
428 fake_fio=False):
koder aka kdanilovda45e882015-04-06 02:24:42 +0300429
430 whole_conf = list(parse_fio_config_full(benchmark_config, params))
431 whole_conf = whole_conf[skip_tests:]
432 res = {}
433 curr_test_num = skip_tests
koder aka kdanilov2e928022015-04-08 13:47:15 +0300434 executed_tests = 0
koder aka kdanilovda45e882015-04-06 02:24:42 +0300435 try:
436 for bconf in next_test_portion(whole_conf, runcycle):
koder aka kdanilovb896f692015-04-07 14:57:55 +0300437
438 if fake_fio:
439 res_cfg_it = do_run_fio_fake(bconf)
440 else:
441 res_cfg_it = do_run_fio(bconf)
442
koder aka kdanilovda45e882015-04-06 02:24:42 +0300443 res_cfg_it = enumerate(res_cfg_it, curr_test_num)
444
445 for curr_test_num, (job_output, (jname, jconfig)) in res_cfg_it:
koder aka kdanilov2e928022015-04-08 13:47:15 +0300446 executed_tests += 1
koder aka kdanilovda45e882015-04-06 02:24:42 +0300447 if raw_results_func is not None:
koder aka kdanilov2e928022015-04-08 13:47:15 +0300448 raw_results_func(executed_tests,
koder aka kdanilovda45e882015-04-06 02:24:42 +0300449 [job_output, jname, jconfig])
450
koder aka kdanilovb896f692015-04-07 14:57:55 +0300451 assert jname == job_output["jobname"], \
452 "{0} != {1}".format(jname, job_output["jobname"])
koder aka kdanilovda45e882015-04-06 02:24:42 +0300453
454 if jname.startswith('_'):
455 continue
456
457 add_job_results(jname, job_output, jconfig, res)
458
459 except (SystemExit, KeyboardInterrupt):
460 pass
461
462 except Exception:
463 traceback.print_exc()
464
koder aka kdanilov2e928022015-04-08 13:47:15 +0300465 return res, executed_tests
koder aka kdanilovda45e882015-04-06 02:24:42 +0300466
467
468def run_benchmark(binary_tp, *argv, **kwargs):
469 if 'fio' == binary_tp:
470 return run_fio(*argv, **kwargs)
471 raise ValueError("Unknown behcnmark {0}".format(binary_tp))
472
473
474def parse_args(argv):
475 parser = argparse.ArgumentParser(
476 description="Run fio' and return result")
477 parser.add_argument("--type", metavar="BINARY_TYPE",
478 choices=['fio'], default='fio',
479 help=argparse.SUPPRESS)
480 parser.add_argument("--start-at", metavar="START_AT_UTC", type=int,
481 help="Start execution at START_AT_UTC")
482 parser.add_argument("--json", action="store_true", default=False,
483 help="Json output format")
484 parser.add_argument("--output", default='-', metavar="FILE_PATH",
485 help="Store results to FILE_PATH")
486 parser.add_argument("--estimate", action="store_true", default=False,
487 help="Only estimate task execution time")
488 parser.add_argument("--compile", action="store_true", default=False,
489 help="Compile config file to fio config")
490 parser.add_argument("--num-tests", action="store_true", default=False,
491 help="Show total number of tests")
492 parser.add_argument("--runcycle", type=int, default=None,
493 metavar="MAX_CYCLE_SECONDS",
494 help="Max cycle length in seconds")
495 parser.add_argument("--show-raw-results", action='store_true',
496 default=False, help="Output raw input and results")
497 parser.add_argument("--skip-tests", type=int, default=0, metavar="NUM",
498 help="Skip NUM tests")
koder aka kdanilovb896f692015-04-07 14:57:55 +0300499 parser.add_argument("--faked-fio", action='store_true',
500 default=False, help="Emulate fio with 0 test time")
koder aka kdanilovda45e882015-04-06 02:24:42 +0300501 parser.add_argument("--params", nargs="*", metavar="PARAM=VAL",
502 default=[],
503 help="Provide set of pairs PARAM=VAL to" +
504 "format into job description")
505 parser.add_argument("jobfile")
506 return parser.parse_args(argv)
507
508
509def read_config(fd, timeout=10):
510 job_cfg = ""
511 etime = time.time() + timeout
512 while True:
513 wtime = etime - time.time()
514 if wtime <= 0:
515 raise IOError("No config provided")
516
517 r, w, x = select.select([fd], [], [], wtime)
518 if len(r) == 0:
519 raise IOError("No config provided")
520
521 char = fd.read(1)
522 if '' == char:
523 return job_cfg
524
525 job_cfg += char
526
527
528def main(argv):
529 argv_obj = parse_args(argv)
530
531 if argv_obj.jobfile == '-':
532 job_cfg = read_config(sys.stdin)
533 else:
534 job_cfg = open(argv_obj.jobfile).read()
535
536 if argv_obj.output == '-':
537 out_fd = sys.stdout
538 else:
539 out_fd = open(argv_obj.output, "w")
540
541 params = {}
542 for param_val in argv_obj.params:
543 assert '=' in param_val
544 name, val = param_val.split("=", 1)
545 params[name] = val
546
547 if argv_obj.num_tests or argv_obj.compile or argv_obj.estimate:
548 bconf = list(parse_fio_config_full(job_cfg, params))
549 bconf = bconf[argv_obj.skip_tests:]
550
551 if argv_obj.compile:
552 out_fd.write(format_fio_config(bconf))
553 out_fd.write("\n")
554
555 if argv_obj.num_tests:
556 print len(bconf)
557
558 if argv_obj.estimate:
559 seconds = calculate_execution_time(bconf)
560
561 h = seconds // 3600
562 m = (seconds % 3600) // 60
563 s = seconds % 60
564
565 print "{0}:{1}:{2}".format(h, m, s)
566 return 0
567
568 if argv_obj.start_at is not None:
569 ctime = time.time()
570 if argv_obj.start_at >= ctime:
571 time.sleep(ctime - argv_obj.start_at)
572
573 def raw_res_func(test_num, data):
574 pref = "========= RAW_RESULTS({0}) =========\n".format(test_num)
575 out_fd.write(pref)
576 out_fd.write(json.dumps(data))
577 out_fd.write("\n========= END OF RAW_RESULTS =========\n")
578 out_fd.flush()
579
580 rrfunc = raw_res_func if argv_obj.show_raw_results else None
581
582 stime = time.time()
583 job_res, num_tests = run_benchmark(argv_obj.type,
584 job_cfg,
585 params,
586 argv_obj.runcycle,
587 rrfunc,
koder aka kdanilovb896f692015-04-07 14:57:55 +0300588 argv_obj.skip_tests,
589 argv_obj.faked_fio)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300590 etime = time.time()
591
592 res = {'__meta__': {'raw_cfg': job_cfg}, 'res': job_res}
593
594 oformat = 'json' if argv_obj.json else 'eval'
595 out_fd.write("\nRun {} tests in {} seconds\n".format(num_tests,
596 int(etime - stime)))
597 out_fd.write("========= RESULTS(format={0}) =========\n".format(oformat))
598 if argv_obj.json:
599 out_fd.write(json.dumps(res))
600 else:
601 out_fd.write(pprint.pformat(res) + "\n")
602 out_fd.write("\n========= END OF RESULTS =========\n".format(oformat))
603
604 return 0
605
606
607if __name__ == '__main__':
608 exit(main(sys.argv[1:]))