blob: e1756f6def6e5dbc69c43b6885f0f4ca13aec214 [file] [log] [blame]
koder aka kdanilov4af80852015-02-01 23:36:38 +02001import re
2import os
3import sys
4import stat
5import time
6import json
7import os.path
8import argparse
9import warnings
10import subprocess
11
12
13class BenchmarkOption(object):
14 def __init__(self, concurence, iodepth, action, blocksize, size):
15 self.iodepth = iodepth
16 self.action = action
17 self.blocksize = blocksize
18 self.concurence = concurence
19 self.size = size
20 self.direct_io = False
21 self.use_hight_io_priority = True
22 self.sync = False
23
24
koder aka kdanilov98615bf2015-02-02 00:59:07 +020025def which(program):
26 def is_exe(fpath):
27 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
28
29 fpath, fname = os.path.split(program)
30 if fpath:
31 if is_exe(program):
32 return program
33 else:
34 for path in os.environ["PATH"].split(os.pathsep):
35 path = path.strip('"')
36 exe_file = os.path.join(path, program)
37 if is_exe(exe_file):
38 return exe_file
39
40 return None
41
42
43# ------------------------------ IOZONE SUPPORT ------------------------------
44
45
koder aka kdanilov4af80852015-02-01 23:36:38 +020046class IOZoneParser(object):
47 "class to parse iozone results"
48
49 start_tests = re.compile(r"^\s+KB\s+reclen\s+")
50 resuts = re.compile(r"[\s0-9]+")
51 mt_iozone_re = re.compile(r"\s+Children see throughput " +
52 r"for\s+\d+\s+(?P<cmd>.*?)\s+=\s+" +
53 r"(?P<perf>[\d.]+)\s+KB/sec")
54
55 cmap = {'initial writers': 'write',
56 'rewriters': 'rewrite',
57 'initial readers': 'read',
58 're-readers': 'reread',
59 'random readers': 'random read',
60 'random writers': 'random write'}
61
62 string1 = " " + \
63 " random random " + \
64 "bkwd record stride "
65
66 string2 = "KB reclen write rewrite " + \
67 "read reread read write " + \
68 "read rewrite read fwrite frewrite fread freread"
69
70 @classmethod
71 def apply_parts(cls, parts, string, sep=' \t\n'):
72 add_offset = 0
73 for part in parts:
74 _, start, stop = part
75 start += add_offset
76 add_offset = 0
77
78 # condition splited to make pylint happy
79 while stop + add_offset < len(string):
80
81 # condition splited to make pylint happy
82 if not (string[stop + add_offset] not in sep):
83 break
84
85 add_offset += 1
86
87 yield part, string[start:stop + add_offset]
88
89 @classmethod
90 def make_positions(cls):
91 items = [i for i in cls.string2.split() if i]
92
93 pos = 0
94 cls.positions = []
95
96 for item in items:
97 npos = cls.string2.index(item, 0 if pos == 0 else pos + 1)
98 cls.positions.append([item, pos, npos + len(item)])
99 pos = npos + len(item)
100
101 for itm, val in cls.apply_parts(cls.positions, cls.string1):
102 if val.strip():
103 itm[0] = val.strip() + " " + itm[0]
104
105 @classmethod
106 def parse_iozone_res(cls, res, mthreads=False):
107 parsed_res = None
108
109 sres = res.split('\n')
110
111 if not mthreads:
112 for pos, line in enumerate(sres[1:]):
113 if line.strip() == cls.string2 and \
114 sres[pos].strip() == cls.string1.strip():
115 add_pos = line.index(cls.string2)
116 parsed_res = {}
117
118 npos = [(name, start + add_pos, stop + add_pos)
119 for name, start, stop in cls.positions]
120
121 for itm, res in cls.apply_parts(npos, sres[pos + 2]):
122 if res.strip() != '':
123 parsed_res[itm[0]] = int(res.strip())
124
125 del parsed_res['KB']
126 del parsed_res['reclen']
127 else:
128 parsed_res = {}
129 for line in sres:
130 rr = cls.mt_iozone_re.match(line)
131 if rr is not None:
132 cmd = rr.group('cmd')
133 key = cls.cmap.get(cmd, cmd)
134 perf = int(float(rr.group('perf')))
135 parsed_res[key] = perf
136 return parsed_res
137
138
koder aka kdanilov4af80852015-02-01 23:36:38 +0200139IOZoneParser.make_positions()
140
141
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800142def iozone_do_prepare(params, filename, pattern):
koder aka kdanilov4af80852015-02-01 23:36:38 +0200143 all_files = []
144 threads = int(params.concurence)
145 if 1 != threads:
koder aka kdanilov4af80852015-02-01 23:36:38 +0200146 filename = filename + "_{}"
koder aka kdanilov4af80852015-02-01 23:36:38 +0200147 all_files.extend(filename % i for i in range(threads))
148 else:
koder aka kdanilov4af80852015-02-01 23:36:38 +0200149 all_files.append(filename)
150
151 bsz = 1024 if params.size > 1024 else params.size
152 if params.size % bsz != 0:
153 fsz = (params.size // bsz + 1) * bsz
154 else:
155 fsz = params.size
156
157 for fname in all_files:
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200158 with open(fname, "wb") as fd:
159 if fsz > 1024:
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800160 pattern = pattern * 1024 * 1024
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200161 for _ in range(int(fsz / 1024) + 1):
162 fd.write(pattern)
163 else:
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800164 fd.write(pattern * 1024 * fsz)
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200165 fd.flush()
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800166 return all_files
167
168
169VERIFY_PATTERN = "\x6d"
170
171
172def do_run_iozone(params, filename, timeout, iozone_path='iozone',
173 microsecond_mode=False,
174 prepare_only=False):
175
176 cmd = [iozone_path, "-V", str(ord(VERIFY_PATTERN))]
177
178 if params.sync:
179 cmd.append('-o')
180
181 if params.direct_io:
182 cmd.append('-I')
183
184 if microsecond_mode:
185 cmd.append('-N')
186
187 all_files = iozone_do_prepare(params, filename, VERIFY_PATTERN)
188
189 threads = int(params.concurence)
190 if 1 != threads:
191 cmd.extend(('-t', str(threads), '-F'))
192 cmd.extend(all_files)
193 else:
194 cmd.extend(('-f', all_files[0]))
koder aka kdanilov4af80852015-02-01 23:36:38 +0200195
196 cmd.append('-i')
197
198 if params.action == 'write':
199 cmd.append("0")
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200200 elif params.action == 'read':
201 cmd.append("1")
202 elif params.action == 'randwrite' or params.action == 'randread':
koder aka kdanilov4af80852015-02-01 23:36:38 +0200203 cmd.append("2")
204 else:
205 raise ValueError("Unknown action {0!r}".format(params.action))
206
207 cmd.extend(('-s', str(params.size)))
208 cmd.extend(('-r', str(params.blocksize)))
209
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200210 # no retest
211 cmd.append('-+n')
212
koder aka kdanilov4af80852015-02-01 23:36:38 +0200213 raw_res = subprocess.check_output(cmd)
214
215 try:
216 parsed_res = IOZoneParser.parse_iozone_res(raw_res, threads > 1)
217
218 res = {}
219
220 if params.action == 'write':
221 res['bw_mean'] = parsed_res['write']
222 elif params.action == 'randwrite':
223 res['bw_mean'] = parsed_res['random write']
224 elif params.action == 'read':
225 res['bw_mean'] = parsed_res['read']
226 elif params.action == 'randread':
227 res['bw_mean'] = parsed_res['random read']
228 except:
koder aka kdanilov4af80852015-02-01 23:36:38 +0200229 raise
230
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200231 return res, " ".join(cmd)
koder aka kdanilov4af80852015-02-01 23:36:38 +0200232
233
234def run_iozone(benchmark, iozone_path, tmpname, timeout=None):
235 if timeout is not None:
236 benchmark.size = benchmark.blocksize * 50
237 res_time = do_run_iozone(benchmark, tmpname, timeout,
238 iozone_path=iozone_path,
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200239 microsecond_mode=True)[0]
koder aka kdanilov4af80852015-02-01 23:36:38 +0200240
241 size = (benchmark.blocksize * timeout * 1000000)
242 size /= res_time["bw_mean"]
243 size = (size // benchmark.blocksize + 1) * benchmark.blocksize
244 benchmark.size = size
245
246 return do_run_iozone(benchmark, tmpname, timeout,
247 iozone_path=iozone_path)
248
249
koder aka kdanilov4af80852015-02-01 23:36:38 +0200250def install_iozone_package():
251 if which('iozone'):
252 return
253
254 is_redhat = os.path.exists('/etc/centos-release')
255 is_redhat = is_redhat or os.path.exists('/etc/fedora-release')
256 is_redhat = is_redhat or os.path.exists('/etc/redhat-release')
257
258 if is_redhat:
259 subprocess.check_output(["yum", "install", 'iozone3'])
260 return
261
262 try:
263 os_release_cont = open('/etc/os-release').read()
264
265 is_ubuntu = "Ubuntu" in os_release_cont
266
267 if is_ubuntu or "Debian GNU/Linux" in os_release_cont:
268 subprocess.check_output(["apt-get", "install", "iozone3"])
269 return
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200270 except (IOError, OSError):
koder aka kdanilov4af80852015-02-01 23:36:38 +0200271 pass
272
273 raise RuntimeError("Unknown host OS.")
274
275
276def install_iozone_static(iozone_url, dst):
277 if not os.path.isfile(dst):
278 import urllib
279 urllib.urlretrieve(iozone_url, dst)
280
281 st = os.stat(dst)
282 os.chmod(dst, st.st_mode | stat.S_IEXEC)
283
284
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200285def locate_iozone():
286 binary_path = which('iozone')
287
288 if binary_path is None:
289 binary_path = which('iozone3')
290
291 if binary_path is None:
292 sys.stderr.write("Can't found neither iozone not iozone3 binary"
Kostiantyn Danylov aka koder02adc1d2015-02-02 01:10:04 +0200293 "Provide --bonary-path or --binary-url option")
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200294 return False, None
295
296 return False, binary_path
297
298# ------------------------------ FIO SUPPORT ---------------------------------
299
300
301def run_fio_once(benchmark, fio_path, tmpname, timeout=None):
302
303 cmd_line = [fio_path,
304 "--name=%s" % benchmark.action,
305 "--rw=%s" % benchmark.action,
306 "--blocksize=%sk" % benchmark.blocksize,
307 "--iodepth=%d" % benchmark.iodepth,
308 "--filename=%s" % tmpname,
309 "--size={0}k".format(benchmark.size),
310 "--numjobs={0}".format(benchmark.concurence),
311 "--output-format=json",
312 "--sync=" + ('1' if benchmark.sync else '0')]
313
314 if timeout is not None:
315 cmd_line.append("--timeout=%d" % timeout)
316 cmd_line.append("--runtime=%d" % timeout)
317
318 if benchmark.direct_io:
319 cmd_line.append("--direct=1")
320
321 if benchmark.use_hight_io_priority:
322 cmd_line.append("--prio=0")
323
324 raw_out = subprocess.check_output(cmd_line)
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200325 return json.loads(raw_out)["jobs"][0], " ".join(cmd_line)
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200326
327
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800328def run_fio(benchmark, fio_path, tmpname, timeout=None, prepare_only=False):
329 if prepare_only:
330 return {}, ""
331
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200332 job_output, cmd_line = run_fio_once(benchmark, fio_path, tmpname, timeout)
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200333
334 if benchmark.action in ('write', 'randwrite'):
335 raw_result = job_output['write']
336 else:
337 raw_result = job_output['read']
338
339 res = {}
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200340
341 # 'bw_dev bw_mean bw_max bw_min'.split()
342 for field in ["bw_mean"]:
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200343 res[field] = raw_result[field]
344
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200345 return res, cmd_line
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200346
347
348def locate_fio():
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200349 return False, which('fio')
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200350
351
352# ----------------------------------------------------------------------------
353
354
355def locate_binary(binary_tp, binary_url, binary_path):
356 remove_binary = False
357
358 if binary_url is not None:
359 if binary_path is not None:
360 sys.stderr.write("At most one option from --binary-path and "
361 "--binary-url should be provided")
362 return False, None
363
364 binary_path = os.tmpnam()
365 install_iozone_static(binary_url, binary_path)
366 remove_binary = True
367
368 elif binary_path is not None:
369 if os.path.isfile(binary_path):
370 if not os.access(binary_path, os.X_OK):
371 st = os.stat(binary_path)
372 os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
373 else:
374 binary_path = None
375
376 if binary_path is not None:
377 return remove_binary, binary_path
378
379 if 'iozone' == binary_tp:
380 return locate_iozone()
381 else:
382 return locate_fio()
383
384
385def run_benchmark(binary_tp, *argv, **kwargs):
386 if 'iozone' == binary_tp:
387 return run_iozone(*argv, **kwargs)
388 else:
389 return run_fio(*argv, **kwargs)
390
391
koder aka kdanilov4af80852015-02-01 23:36:38 +0200392def type_size(string):
393 try:
394 return re.match("\d+[KGBM]?", string, re.I).group(0)
395 except:
396 msg = "{0!r} don't looks like size-description string".format(string)
397 raise ValueError(msg)
398
399
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200400def type_size_ext(string):
401 if string.startswith("x"):
402 int(string[1:])
403 return string
404
405 if string.startswith("r"):
406 int(string[1:])
407 return string
408
409 try:
410 return re.match("\d+[KGBM]?", string, re.I).group(0)
411 except:
412 msg = "{0!r} don't looks like size-description string".format(string)
413 raise ValueError(msg)
414
415
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200416def ssize_to_kb(ssize):
417 try:
418 smap = dict(k=1, K=1, M=1024, m=1024, G=1024**2, g=1024**2)
419 for ext, coef in smap.items():
420 if ssize.endswith(ext):
421 return int(ssize[:-1]) * coef
422
423 if int(ssize) % 1024 != 0:
424 raise ValueError()
425
426 return int(ssize) / 1024
427
428 except (ValueError, TypeError, AttributeError):
429 tmpl = "Unknow size format {0!r} (or size not multiples 1024)"
430 raise ValueError(tmpl.format(ssize))
431
432
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200433def get_ram_size():
434 try:
435 with open("/proc/meminfo") as fd:
436 for ln in fd:
437 if "MemTotal:" in ln:
438 sz, kb = ln.split(':')[1].strip().split(" ")
439 assert kb == 'kB'
440 return int(sz)
441 except (ValueError, TypeError, AssertionError):
442 raise
443 # return None
444
445
koder aka kdanilov4af80852015-02-01 23:36:38 +0200446def parse_args(argv):
447 parser = argparse.ArgumentParser(
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200448 description="Run 'iozone' or 'fio' and return result")
449 parser.add_argument(
450 "--type", metavar="BINARY_TYPE",
451 choices=['iozone', 'fio'], required=True)
koder aka kdanilov4af80852015-02-01 23:36:38 +0200452 parser.add_argument(
453 "--iodepth", metavar="IODEPTH", type=int,
454 help="I/O depths to test in kb", required=True)
455 parser.add_argument(
456 '-a', "--action", metavar="ACTION", type=str,
457 help="actions to run", required=True,
458 choices=["read", "write", "randread", "randwrite"])
459 parser.add_argument(
460 "--blocksize", metavar="BLOCKSIZE", type=type_size,
461 help="single operation block size", required=True)
462 parser.add_argument(
463 "--timeout", metavar="TIMEOUT", type=int,
464 help="runtime of a single run", default=None)
465 parser.add_argument(
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200466 "--iosize", metavar="SIZE", type=type_size_ext,
koder aka kdanilov4af80852015-02-01 23:36:38 +0200467 help="file size", default=None)
468 parser.add_argument(
469 "-s", "--sync", default=False, action="store_true",
470 help="exec sync after each write")
471 parser.add_argument(
472 "-d", "--direct-io", default=False, action="store_true",
473 help="use O_DIRECT", dest='directio')
474 parser.add_argument(
475 "-t", "--sync-time", default=None, type=int,
476 help="sleep till sime utc time", dest='sync_time')
477 parser.add_argument(
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200478 "--binary-url", help="static binary url",
479 dest="binary_url", default=None)
koder aka kdanilov4af80852015-02-01 23:36:38 +0200480 parser.add_argument(
481 "--test-file", help="file path to run test on",
482 default=None, dest='test_file')
483 parser.add_argument(
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200484 "--binary-path", help="binary path",
485 default=None, dest='binary_path')
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800486 parser.add_argument(
487 "--prepare-only", default=False, dest='prepare_only',
488 action="store_true")
koder aka kdanilov4af80852015-02-01 23:36:38 +0200489 return parser.parse_args(argv)
490
491
492def main(argv):
493 argv_obj = parse_args(argv)
494 argv_obj.blocksize = ssize_to_kb(argv_obj.blocksize)
495
496 if argv_obj.iosize is not None:
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200497 if argv_obj.iosize.startswith('x'):
498 argv_obj.iosize = argv_obj.blocksize * int(argv_obj.iosize[1:])
499 elif argv_obj.iosize.startswith('r'):
500 rs = get_ram_size()
501 if rs is None:
502 sys.stderr.write("Can't determine ram size\n")
503 exit(1)
504 argv_obj.iosize = rs * int(argv_obj.iosize[1:])
505 else:
506 argv_obj.iosize = ssize_to_kb(argv_obj.iosize)
koder aka kdanilov4af80852015-02-01 23:36:38 +0200507
508 benchmark = BenchmarkOption(1,
509 argv_obj.iodepth,
510 argv_obj.action,
511 argv_obj.blocksize,
512 argv_obj.iosize)
513
514 benchmark.direct_io = argv_obj.directio
515
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200516 if argv_obj.sync:
517 benchmark.sync = True
518
koder aka kdanilov4af80852015-02-01 23:36:38 +0200519 test_file_name = argv_obj.test_file
520 if test_file_name is None:
521 with warnings.catch_warnings():
522 warnings.simplefilter("ignore")
523 test_file_name = os.tmpnam()
524
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200525 remove_binary, binary_path = locate_binary(argv_obj.type,
526 argv_obj.binary_url,
527 argv_obj.binary_path)
koder aka kdanilov4af80852015-02-01 23:36:38 +0200528
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200529 if binary_path is None:
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200530 sys.stderr.write("Can't locate binary {0}\n".format(argv_obj.type))
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200531 return 1
koder aka kdanilov4af80852015-02-01 23:36:38 +0200532
533 try:
534 if argv_obj.sync_time is not None:
535 dt = argv_obj.sync_time - time.time()
536 if dt > 0:
537 time.sleep(dt)
538
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200539 res, cmd = run_benchmark(argv_obj.type,
540 benchmark,
541 binary_path,
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800542 test_file_name,
543 argv_obj.prepare_only)
544 if not argv_obj.prepare_only:
545 res['__meta__'] = benchmark.__dict__.copy()
546 res['__meta__']['cmdline'] = cmd
547
548 sys.stdout.write(json.dumps(res))
549
550 if not argv_obj.prepare_only:
551 sys.stdout.write("\n")
552
koder aka kdanilov4af80852015-02-01 23:36:38 +0200553 finally:
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200554 if remove_binary:
555 os.unlink(binary_path)
koder aka kdanilov4af80852015-02-01 23:36:38 +0200556
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800557 if os.path.isfile(test_file_name) and not argv_obj.prepare_only:
koder aka kdanilov4af80852015-02-01 23:36:38 +0200558 os.unlink(test_file_name)
559
560
koder aka kdanilov4af80852015-02-01 23:36:38 +0200561if __name__ == '__main__':
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800562 exit(main(sys.argv[1:]))