blob: 336b176beab2f19d21e5ce3e3dfe372c5852fe97 [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
151 yield sec
152
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])
220 counter[0] += 1
221 params['TEST_SUMM'] = get_test_summary(sec.vals)
222 sec.name = sec.name.format(**params)
223
224 yield sec
225
226
227def fio_config_to_str(sec_iter):
228 res = ""
229
230 for pos, sec in enumerate(sec_iter):
231 if pos != 0:
232 res += "\n"
233
234 res += "[{0}]\n".format(sec.name)
235
236 for name, val in sec.vals.items():
237 if name.startswith('_'):
238 continue
239
240 if val is None:
241 res += name + "\n"
242 else:
243 res += "{0}={1}\n".format(name, val)
244
245 return res
246
247
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300248def get_test_sync_mode(config):
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300249 try:
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300250 return config['sync_mode']
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300251 except KeyError:
252 pass
253
koder aka kdanilovea22c3d2015-04-21 03:42:22 +0300254 is_sync = str(config.get("sync", "0")) == "1"
255 is_direct = str(config.get("direct", "0")) == "1"
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300256
257 if is_sync and is_direct:
258 return 'x'
259 elif is_sync:
260 return 's'
261 elif is_direct:
262 return 'd'
263 else:
264 return 'a'
265
266
koder aka kdanilovda45e882015-04-06 02:24:42 +0300267def get_test_summary(params):
268 rw = {"randread": "rr",
269 "randwrite": "rw",
270 "read": "sr",
271 "write": "sw"}[params["rw"]]
272
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300273 sync_mode = get_test_sync_mode(params)
274 th_count = params.get('numjobs')
koder aka kdanilovea22c3d2015-04-21 03:42:22 +0300275
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300276 if th_count is None:
koder aka kdanilovea22c3d2015-04-21 03:42:22 +0300277 th_count = params.get('concurence', 1)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300278
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300279 return "{0}{1}{2}th{3}".format(rw,
280 sync_mode,
281 params['blocksize'],
282 th_count)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300283
284
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300285def calculate_execution_time(sec_iter):
koder aka kdanilovda45e882015-04-06 02:24:42 +0300286 time = 0
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300287 for sec in sec_iter:
288 time += sec.vals.get('ramp_time', 0)
289 time += sec.vals.get('runtime', 0)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300290 return time
291
292
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300293def slice_config(sec_iter, runcycle=None, max_jobs=1000):
294 jcount = 0
295 runtime = 0
296 curr_slice = []
koder aka kdanilovda45e882015-04-06 02:24:42 +0300297
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300298 for pos, sec in enumerate(sec_iter):
koder aka kdanilovda45e882015-04-06 02:24:42 +0300299
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300300 jc = sec.vals.get('numjobs', 1)
301 msg = "numjobs should be integer, not {0!r}".format(jc)
302 assert isinstance(jc, int), msg
koder aka kdanilovda45e882015-04-06 02:24:42 +0300303
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300304 curr_task_time = calculate_execution_time([sec])
koder aka kdanilovda45e882015-04-06 02:24:42 +0300305
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300306 if jc > max_jobs:
307 err_templ = "Can't process job {0!r} - too large numjobs"
308 raise ValueError(err_templ.format(sec.name))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300309
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300310 if runcycle is not None and len(curr_slice) != 0:
311 rc_ok = curr_task_time + runtime <= runcycle
koder aka kdanilovda45e882015-04-06 02:24:42 +0300312 else:
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300313 rc_ok = True
koder aka kdanilovda45e882015-04-06 02:24:42 +0300314
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300315 if jc + jcount <= max_jobs and rc_ok:
316 runtime += curr_task_time
317 jcount += jc
318 curr_slice.append(sec)
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300319 continue
320
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300321 assert len(curr_slice) != 0
322 yield curr_slice
koder aka kdanilovda45e882015-04-06 02:24:42 +0300323
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300324 if '_ramp_time' in sec.vals:
325 sec.vals['ramp_time'] = sec.vals.pop('_ramp_time')
326 curr_task_time = calculate_execution_time([sec])
327
328 runtime = curr_task_time
329 jcount = jc
330 curr_slice = [sec]
331
332 if curr_slice != []:
333 yield curr_slice
koder aka kdanilovda45e882015-04-06 02:24:42 +0300334
335
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300336def parse_all_in_1(source, test_params):
337 lexer_it = fio_config_lexer(source)
338 sec_it = fio_config_parse(lexer_it, test_params)
339 sec_it = process_cycles(sec_it)
340 sec_it = process_repeats(sec_it)
341 return format_params_into_section_finall(sec_it)
koder aka kdanilovb896f692015-04-07 14:57:55 +0300342
343
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300344def parse_and_slice_all_in_1(source, test_params, **slice_params):
345 sec_it = parse_all_in_1(source, test_params)
346 return slice_config(sec_it, **slice_params)
koder aka kdanilovb896f692015-04-07 14:57:55 +0300347
348
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300349def compile_all_in_1(source, test_params, **slice_params):
350 slices_it = parse_and_slice_all_in_1(source, test_params, **slice_params)
351 for slices in slices_it:
352 yield fio_config_to_str(slices)
koder aka kdanilovb896f692015-04-07 14:57:55 +0300353
354
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300355def do_run_fio(config_slice):
356 benchmark_config = fio_config_to_str(config_slice)
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300357 cmd = ["fio", "--output-format=json", "--alloc-size=262144", "-"]
koder aka kdanilove87ae652015-04-20 02:14:35 +0300358 p = subprocess.Popen(cmd,
359 stdin=subprocess.PIPE,
koder aka kdanilovda45e882015-04-06 02:24:42 +0300360 stdout=subprocess.PIPE,
koder aka kdanilove87ae652015-04-20 02:14:35 +0300361 stderr=subprocess.PIPE)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300362
363 # set timeout
koder aka kdanilove87ae652015-04-20 02:14:35 +0300364 raw_out, raw_err = p.communicate(benchmark_config)
365
koder aka kdanilov6b1341a2015-04-21 22:44:21 +0300366 # HACK
367 raw_out = "{" + raw_out.split('{', 1)[1]
368
koder aka kdanilove87ae652015-04-20 02:14:35 +0300369 if 0 != p.returncode:
370 msg = "Fio failed with code: {0}\nOutput={1}"
371 raise OSError(msg.format(p.returncode, raw_err))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300372
373 try:
374 parsed_out = json.loads(raw_out)["jobs"]
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300375 except KeyError:
376 msg = "Can't parse fio output {0!r}: no 'jobs' found"
377 raw_out = raw_out[:100]
378 raise ValueError(msg.format(raw_out))
379
380 except Exception as exc:
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300381 msg = "Can't parse fio output: {0!r}\nError: {1!s}"
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300382 raw_out = raw_out[:100]
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300383 raise ValueError(msg.format(raw_out, exc))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300384
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300385 return zip(parsed_out, config_slice)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300386
387
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300388def add_job_results(section, job_output, res):
koder aka kdanilovda45e882015-04-06 02:24:42 +0300389 if job_output['write']['iops'] != 0:
390 raw_result = job_output['write']
391 else:
392 raw_result = job_output['read']
393
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300394 vals = section.vals
395 if section.name not in res:
koder aka kdanilovda45e882015-04-06 02:24:42 +0300396 j_res = {}
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300397 j_res["rw"] = vals["rw"]
398 j_res["sync_mode"] = get_test_sync_mode(vals)
399 j_res["concurence"] = int(vals.get("numjobs", 1))
400 j_res["blocksize"] = vals["blocksize"]
koder aka kdanilovda45e882015-04-06 02:24:42 +0300401 j_res["jobname"] = job_output["jobname"]
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300402 j_res["timings"] = [int(vals.get("runtime", 0)),
403 int(vals.get("ramp_time", 0))]
koder aka kdanilovda45e882015-04-06 02:24:42 +0300404 else:
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300405 j_res = res[section.name]
406 assert j_res["rw"] == vals["rw"]
407 assert j_res["rw"] == vals["rw"]
408 assert j_res["sync_mode"] == get_test_sync_mode(vals)
409 assert j_res["concurence"] == int(vals.get("numjobs", 1))
410 assert j_res["blocksize"] == vals["blocksize"]
koder aka kdanilovda45e882015-04-06 02:24:42 +0300411 assert j_res["jobname"] == job_output["jobname"]
koder aka kdanilov652cd802015-04-13 12:21:07 +0300412
413 # ramp part is skipped for all tests, except first
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300414 # assert j_res["timings"] == (vals.get("runtime"),
415 # vals.get("ramp_time"))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300416
417 def j_app(name, x):
418 j_res.setdefault(name, []).append(x)
419
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300420 j_app("bw", raw_result["bw"])
koder aka kdanilovda45e882015-04-06 02:24:42 +0300421 j_app("iops", raw_result["iops"])
422 j_app("lat", raw_result["lat"]["mean"])
423 j_app("clat", raw_result["clat"]["mean"])
424 j_app("slat", raw_result["slat"]["mean"])
425
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300426 res[section.name] = j_res
koder aka kdanilovda45e882015-04-06 02:24:42 +0300427
428
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300429def run_fio(sliced_it, raw_results_func=None):
430 sliced_list = list(sliced_it)
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300431
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300432 curr_test_num = 0
433 executed_tests = 0
434 result = {}
koder aka kdanilovb896f692015-04-07 14:57:55 +0300435
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300436 for i, test_slice in enumerate(sliced_list):
437 res_cfg_it = do_run_fio(test_slice)
438 res_cfg_it = enumerate(res_cfg_it, curr_test_num)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300439
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300440 for curr_test_num, (job_output, section) in res_cfg_it:
441 executed_tests += 1
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300442
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300443 if raw_results_func is not None:
444 raw_results_func(executed_tests,
445 [job_output, section])
koder aka kdanilovda45e882015-04-06 02:24:42 +0300446
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300447 msg = "{0} != {1}".format(section.name, job_output["jobname"])
448 assert section.name == job_output["jobname"], msg
koder aka kdanilovda45e882015-04-06 02:24:42 +0300449
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300450 if section.name.startswith('_'):
451 continue
koder aka kdanilovda45e882015-04-06 02:24:42 +0300452
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300453 add_job_results(section, job_output, result)
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300454
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300455 curr_test_num += 1
456 msg_template = "Done {0} tests from {1}. ETA: {2}"
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300457
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300458 rest = sliced_list[i:]
459 time_eta = sum(map(calculate_execution_time, rest))
460 test_left = sum(map(len, rest))
461 print msg_template.format(curr_test_num,
462 test_left,
463 sec_to_str(time_eta))
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300464
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300465 return result, 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
koder aka kdanilov652cd802015-04-13 12:21:07 +0300474def read_config(fd, timeout=10):
475 job_cfg = ""
476 etime = time.time() + timeout
477 while True:
478 wtime = etime - time.time()
479 if wtime <= 0:
480 raise IOError("No config provided")
481
482 r, w, x = select.select([fd], [], [], wtime)
483 if len(r) == 0:
484 raise IOError("No config provided")
485
486 char = fd.read(1)
487 if '' == char:
488 return job_cfg
489
490 job_cfg += char
491
492
koder aka kdanilov652cd802015-04-13 12:21:07 +0300493def sec_to_str(seconds):
494 h = seconds // 3600
495 m = (seconds % 3600) // 60
496 s = seconds % 60
497 return "{0}:{1:02d}:{2:02d}".format(h, m, s)
498
499
koder aka kdanilovda45e882015-04-06 02:24:42 +0300500def parse_args(argv):
501 parser = argparse.ArgumentParser(
502 description="Run fio' and return result")
503 parser.add_argument("--type", metavar="BINARY_TYPE",
504 choices=['fio'], default='fio',
505 help=argparse.SUPPRESS)
506 parser.add_argument("--start-at", metavar="START_AT_UTC", type=int,
507 help="Start execution at START_AT_UTC")
508 parser.add_argument("--json", action="store_true", default=False,
509 help="Json output format")
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300510 parser.add_argument("-o", "--output", default='-', metavar="FILE_PATH",
koder aka kdanilovda45e882015-04-06 02:24:42 +0300511 help="Store results to FILE_PATH")
512 parser.add_argument("--estimate", action="store_true", default=False,
513 help="Only estimate task execution time")
514 parser.add_argument("--compile", action="store_true", default=False,
515 help="Compile config file to fio config")
516 parser.add_argument("--num-tests", action="store_true", default=False,
517 help="Show total number of tests")
518 parser.add_argument("--runcycle", type=int, default=None,
519 metavar="MAX_CYCLE_SECONDS",
520 help="Max cycle length in seconds")
521 parser.add_argument("--show-raw-results", action='store_true',
522 default=False, help="Output raw input and results")
koder aka kdanilovda45e882015-04-06 02:24:42 +0300523 parser.add_argument("--params", nargs="*", metavar="PARAM=VAL",
524 default=[],
525 help="Provide set of pairs PARAM=VAL to" +
526 "format into job description")
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300527 parser.add_argument("-p", "--pid-file", metavar="FILE_TO_STORE_PID",
528 default=None, help="Store pid to FILE_TO_STORE_PID " +
529 "and remove this file on exit")
koder aka kdanilovda45e882015-04-06 02:24:42 +0300530 parser.add_argument("jobfile")
531 return parser.parse_args(argv)
532
533
koder aka kdanilovda45e882015-04-06 02:24:42 +0300534def main(argv):
535 argv_obj = parse_args(argv)
536
537 if argv_obj.jobfile == '-':
538 job_cfg = read_config(sys.stdin)
539 else:
540 job_cfg = open(argv_obj.jobfile).read()
541
542 if argv_obj.output == '-':
543 out_fd = sys.stdout
544 else:
545 out_fd = open(argv_obj.output, "w")
546
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300547 if argv_obj.pid_file is not None:
548 with open(argv_obj.pid_file, "w") as fd:
549 fd.write(str(os.getpid()))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300550
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300551 try:
552 params = {}
553 for param_val in argv_obj.params:
554 assert '=' in param_val
555 name, val = param_val.split("=", 1)
556 params[name] = val
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300557
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300558 slice_params = {
559 'runcycle': argv_obj.runcycle,
560 }
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300561
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300562 sliced_it = parse_and_slice_all_in_1(job_cfg, params, **slice_params)
koder aka kdanilov652cd802015-04-13 12:21:07 +0300563
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300564 if argv_obj.estimate:
565 it = map(calculate_execution_time, sliced_it)
566 print sec_to_str(sum(it))
567 return 0
koder aka kdanilovda45e882015-04-06 02:24:42 +0300568
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300569 if argv_obj.num_tests or argv_obj.compile:
570 if argv_obj.compile:
571 for test_slice in sliced_it:
572 out_fd.write(fio_config_to_str(test_slice))
573 out_fd.write("\n#" + "-" * 70 + "\n\n")
koder aka kdanilovda45e882015-04-06 02:24:42 +0300574
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300575 if argv_obj.num_tests:
576 print len(list(sliced_it))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300577
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300578 return 0
koder aka kdanilovda45e882015-04-06 02:24:42 +0300579
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300580 if argv_obj.start_at is not None:
581 ctime = time.time()
582 if argv_obj.start_at >= ctime:
583 time.sleep(ctime - argv_obj.start_at)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300584
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300585 def raw_res_func(test_num, data):
586 pref = "========= RAW_RESULTS({0}) =========\n".format(test_num)
587 out_fd.write(pref)
588 out_fd.write(json.dumps(data))
589 out_fd.write("\n========= END OF RAW_RESULTS =========\n")
590 out_fd.flush()
koder aka kdanilovda45e882015-04-06 02:24:42 +0300591
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300592 rrfunc = raw_res_func if argv_obj.show_raw_results else None
koder aka kdanilovda45e882015-04-06 02:24:42 +0300593
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300594 stime = time.time()
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300595 job_res, num_tests = run_benchmark(argv_obj.type,
596 sliced_it, rrfunc)
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300597 etime = time.time()
koder aka kdanilovda45e882015-04-06 02:24:42 +0300598
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300599 res = {'__meta__': {'raw_cfg': job_cfg, 'params': params},
600 'res': job_res}
koder aka kdanilovda45e882015-04-06 02:24:42 +0300601
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300602 oformat = 'json' if argv_obj.json else 'eval'
603 msg = "\nRun {0} tests in {1} seconds\n"
604 out_fd.write(msg.format(num_tests, int(etime - stime)))
605
606 msg = "========= RESULTS(format={0}) =========\n"
607 out_fd.write(msg.format(oformat))
608 if argv_obj.json:
609 out_fd.write(json.dumps(res))
610 else:
611 out_fd.write(pprint.pformat(res) + "\n")
612 out_fd.write("\n========= END OF RESULTS =========\n")
613
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300614 return 0
615 except:
616 out_fd.write("============ ERROR =============\n")
617 out_fd.write(traceback.format_exc() + "\n")
618 out_fd.write("============ END OF ERROR =============\n")
619 return 1
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300620 finally:
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300621 try:
622 if out_fd is not sys.stdout:
623 out_fd.flush()
624 os.fsync(out_fd)
625 out_fd.close()
626 except Exception:
627 traceback.print_exc()
628
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300629 if argv_obj.pid_file is not None:
630 if os.path.exists(argv_obj.pid_file):
631 os.unlink(argv_obj.pid_file)
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300632
633
634def fake_main(x):
635 import yaml
636 time.sleep(60)
637 out_fd = sys.stdout
638 fname = "/tmp/perf_tests/metempirical_alisha/raw_results.yaml"
639 res = yaml.load(open(fname).read())[0][1]
640 out_fd.write("========= RESULTS(format=json) =========\n")
641 out_fd.write(json.dumps(res))
642 out_fd.write("\n========= END OF RESULTS =========\n")
koder aka kdanilovda45e882015-04-06 02:24:42 +0300643 return 0
644
645
646if __name__ == '__main__':
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300647 # exit(fake_main(sys.argv[1:]))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300648 exit(main(sys.argv[1:]))