blob: ffad0fff824fb19d99ffb2011fddab275439e19a [file] [log] [blame]
koder aka kdanilov4af80852015-02-01 23:36:38 +02001import os
2import re
3import sys
4import time
5import yaml
6import json
koder aka kdanilov78ba8952015-02-03 01:11:23 +02007import pprint
koder aka kdanilov4af80852015-02-01 23:36:38 +02008import os.path
koder aka kdanilov80cb6192015-02-02 03:06:08 +02009import argparse
koder aka kdanilov4af80852015-02-01 23:36:38 +020010import datetime
11import warnings
12import functools
13import contextlib
14import multiprocessing
15
16from rally import exceptions
17from rally.cmd import cliutils
18from rally.cmd.main import categories
19from rally.benchmark.scenarios.vm.utils import VMScenario
koder aka kdanilov479b8d82015-02-09 12:56:22 +020020from rally.benchmark.scenarios.vm.vmtasks import VMTasks
koder aka kdanilov4af80852015-02-01 23:36:38 +020021
koder aka kdanilov80cb6192015-02-02 03:06:08 +020022from ssh_copy_directory import put_dir_recursively, ssh_copy_file
23
koder aka kdanilov4af80852015-02-01 23:36:38 +020024
25def log(x):
26 dt_str = datetime.datetime.now().strftime("%H:%M:%S")
27 pref = dt_str + " " + str(os.getpid()) + " >>>> "
28 sys.stderr.write(pref + x.replace("\n", "\n" + pref) + "\n")
29
30
koder aka kdanilov479b8d82015-02-09 12:56:22 +020031@contextlib.contextmanager
32def patch_VMTasks_boot_runcommand_delete():
33
34 try:
35 orig = VMTasks.boot_runcommand_delete
36 except AttributeError:
37 # rally code was changed
38 log("VMTasks class was changed and have no boot_runcommand_delete"
39 " method anymore. Update patch code.")
40 raise exceptions.ScriptError("monkeypatch code fails on "
41 "VMTasks.boot_runcommand_delete")
42
43 @functools.wraps(orig)
44 def new_boot_runcommand_delete(self, *args, **kwargs):
45 if 'rally_affinity_group' in os.environ:
46 group_id = os.environ['rally_affinity_group']
47 kwargs['scheduler_hints'] = {'group': group_id}
48 return orig(self, *args, **kwargs)
49
50 VMTasks.boot_runcommand_delete = new_boot_runcommand_delete
51
52 try:
53 yield
54 finally:
55 VMTasks.boot_runcommand_delete = orig
56
57
koder aka kdanilov4af80852015-02-01 23:36:38 +020058def get_barrier(count):
59 val = multiprocessing.Value('i', count)
60 cond = multiprocessing.Condition()
61
62 def closure(timeout):
koder aka kdanilov80cb6192015-02-02 03:06:08 +020063 me_released = False
koder aka kdanilov4af80852015-02-01 23:36:38 +020064 with cond:
65 val.value -= 1
koder aka kdanilov4af80852015-02-01 23:36:38 +020066 if val.value == 0:
koder aka kdanilov80cb6192015-02-02 03:06:08 +020067 me_released = True
koder aka kdanilov4af80852015-02-01 23:36:38 +020068 cond.notify_all()
69 else:
70 cond.wait(timeout)
71 return val.value == 0
72
koder aka kdanilov80cb6192015-02-02 03:06:08 +020073 if me_released:
74 log("Test begins!")
75
koder aka kdanilov4af80852015-02-01 23:36:38 +020076 return closure
77
78
koder aka kdanilov56ee3ed2015-02-02 19:00:31 +020079# should actually use mock module for this,
80# but don't wanna to add new dependency
koder aka kdanilov4af80852015-02-01 23:36:38 +020081@contextlib.contextmanager
82def patch_VMScenario_run_command_over_ssh(paths,
koder aka kdanilov80cb6192015-02-02 03:06:08 +020083 on_result_cb,
koder aka kdanilov4af80852015-02-01 23:36:38 +020084 barrier=None,
85 latest_start_time=None):
86
koder aka kdanilov1b0d3502015-02-03 21:32:31 +020087 try:
88 orig = VMScenario.run_action
89 except AttributeError:
90 # rally code was changed
91 log("VMScenario class was changed and have no run_action"
92 " method anymore. Update patch code.")
93 raise exceptions.ScriptError("monkeypatch code fails on "
94 "VMScenario.run_action")
koder aka kdanilov4af80852015-02-01 23:36:38 +020095
96 @functools.wraps(orig)
97 def closure(self, ssh, *args, **kwargs):
98 try:
99 sftp = ssh._client.open_sftp()
100 except AttributeError:
101 # rally code was changed
102 log("Prototype of VMScenario.run_command_over_ssh "
103 "was changed. Update patch code.")
koder aka kdanilov80cb6192015-02-02 03:06:08 +0200104 raise exceptions.ScriptError("monkeypatch code fails on "
koder aka kdanilov4af80852015-02-01 23:36:38 +0200105 "ssh._client.open_sftp()")
koder aka kdanilov80cb6192015-02-02 03:06:08 +0200106 try:
107 for src, dst in paths.items():
108 try:
109 if os.path.isfile(src):
110 ssh_copy_file(sftp, src, dst)
111 elif os.path.isdir(src):
112 put_dir_recursively(sftp, src, dst)
113 else:
114 templ = "Can't copy {0!r} - " + \
koder aka kdanilov56ee3ed2015-02-02 19:00:31 +0200115 "it neither a file not a directory"
koder aka kdanilov80cb6192015-02-02 03:06:08 +0200116 msg = templ.format(src)
117 log(msg)
118 raise exceptions.ScriptError(msg)
119 except exceptions.ScriptError:
120 raise
121 except Exception as exc:
122 tmpl = "Scp {0!r} => {1!r} failed - {2!r}"
123 msg = tmpl.format(src, dst, exc)
124 log(msg)
125 raise exceptions.ScriptError(msg)
126 finally:
127 sftp.close()
koder aka kdanilov4af80852015-02-01 23:36:38 +0200128
129 log("Start io test")
130
131 if barrier is not None:
132 if latest_start_time is not None:
133 timeout = latest_start_time - time.time()
134 else:
135 timeout = None
136
137 if timeout is not None and timeout > 0:
138 msg = "Ready and waiting on barrier. " + \
139 "Will wait at most {0} seconds"
140 log(msg.format(int(timeout)))
141
142 if not barrier(timeout):
143 log("Barrier timeouted")
144
145 try:
146 code, out, err = orig(self, ssh, *args, **kwargs)
147 except Exception as exc:
148 log("Rally raises exception {0}".format(exc.message))
149 raise
150
151 if 0 != code:
152 templ = "Script returns error! code={0}\n {1}"
153 log(templ.format(code, err.rstrip()))
154 else:
155 log("Test finished")
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200156
koder aka kdanilov4af80852015-02-01 23:36:38 +0200157 try:
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200158 for line in out.split("\n"):
159 if line.strip() != "":
160 result = json.loads(line)
161 on_result_cb(result)
koder aka kdanilov4af80852015-02-01 23:36:38 +0200162 except Exception as err:
163 log("Error during postprocessing results: {0!r}".format(err))
164
koder aka kdanilov1b0d3502015-02-03 21:32:31 +0200165 # result = {"rally": 0, "srally": 1}
166 result = {"rally": 0}
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200167 out = json.dumps(result)
168
koder aka kdanilov4af80852015-02-01 23:36:38 +0200169 return code, out, err
170
koder aka kdanilov1b0d3502015-02-03 21:32:31 +0200171 VMScenario.run_action = closure
koder aka kdanilov4af80852015-02-01 23:36:38 +0200172
173 try:
174 yield
175 finally:
koder aka kdanilov1b0d3502015-02-03 21:32:31 +0200176 VMScenario.run_action = orig
koder aka kdanilov4af80852015-02-01 23:36:38 +0200177
178
179def run_rally(rally_args):
180 return cliutils.run(['rally'] + rally_args, categories)
181
182
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200183def prepare_files(testtool_py_args_v, dst_testtool_path, files_dir):
koder aka kdanilov4af80852015-02-01 23:36:38 +0200184
185 # we do need temporary named files
186 with warnings.catch_warnings():
187 warnings.simplefilter("ignore")
188 py_file = os.tmpnam()
189 yaml_file = os.tmpnam()
190
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200191 testtool_py_inp_path = os.path.join(files_dir, "io.py")
192 py_src_cont = open(testtool_py_inp_path).read()
193 args_repl_rr = r'INSERT_TOOL_ARGS\(sys\.argv.*?\)'
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200194 py_dst_cont = re.sub(args_repl_rr, repr(testtool_py_args_v), py_src_cont)
koder aka kdanilov4af80852015-02-01 23:36:38 +0200195
196 if py_dst_cont == args_repl_rr:
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200197 templ = "Can't find replace marker in file {0}"
koder aka kdanilov56ee3ed2015-02-02 19:00:31 +0200198 msg = templ.format(testtool_py_inp_path)
199 log(msg)
200 raise ValueError(msg)
koder aka kdanilov4af80852015-02-01 23:36:38 +0200201
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200202 yaml_src_cont = open(os.path.join(files_dir, "io.yaml")).read()
koder aka kdanilov4af80852015-02-01 23:36:38 +0200203 task_params = yaml.load(yaml_src_cont)
204 rcd_params = task_params['VMTasks.boot_runcommand_delete']
205 rcd_params[0]['args']['script'] = py_file
206 yaml_dst_cont = yaml.dump(task_params)
207
208 open(py_file, "w").write(py_dst_cont)
209 open(yaml_file, "w").write(yaml_dst_cont)
210
211 return yaml_file, py_file
212
213
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200214def run_test(tool, testtool_py_args_v, dst_testtool_path, files_dir,
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200215 rally_extra_opts, max_preparation_time=300,
216 keet_temp_files=False):
koder aka kdanilov56ee3ed2015-02-02 19:00:31 +0200217
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200218 path = 'iozone' if 'iozone' == tool else 'fio'
219 testtool_local = os.path.join(files_dir, path)
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200220 yaml_file, py_file = prepare_files(testtool_py_args_v,
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200221 dst_testtool_path,
koder aka kdanilov4af80852015-02-01 23:36:38 +0200222 files_dir)
koder aka kdanilov4af80852015-02-01 23:36:38 +0200223 try:
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200224 config = yaml.load(open(yaml_file).read())
225
226 vm_sec = 'VMTasks.boot_runcommand_delete'
227 concurrency = config[vm_sec][0]['runner']['concurrency']
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200228 copy_files = {testtool_local: dst_testtool_path}
koder aka kdanilov4af80852015-02-01 23:36:38 +0200229
230 result_queue = multiprocessing.Queue()
koder aka kdanilov80cb6192015-02-02 03:06:08 +0200231 results_cb = result_queue.put
koder aka kdanilov4af80852015-02-01 23:36:38 +0200232
koder aka kdanilov479b8d82015-02-09 12:56:22 +0200233 do_patch1 = patch_VMScenario_run_command_over_ssh
koder aka kdanilov4af80852015-02-01 23:36:38 +0200234
235 barrier = get_barrier(concurrency)
236 max_release_time = time.time() + max_preparation_time
237
koder aka kdanilov479b8d82015-02-09 12:56:22 +0200238 with patch_VMTasks_boot_runcommand_delete():
239 with do_patch1(copy_files, results_cb, barrier, max_release_time):
240 opts = ['task', 'start', yaml_file] + list(rally_extra_opts)
241 log("Start rally with opts '{0}'".format(" ".join(opts)))
242 run_rally(opts)
koder aka kdanilov4af80852015-02-01 23:36:38 +0200243
koder aka kdanilov56ee3ed2015-02-02 19:00:31 +0200244 rally_result = []
245 while not result_queue.empty():
246 rally_result.append(result_queue.get())
koder aka kdanilov4af80852015-02-01 23:36:38 +0200247
248 return rally_result
249
250 finally:
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200251 if not keet_temp_files:
252 os.unlink(yaml_file)
253 os.unlink(py_file)
koder aka kdanilov80cb6192015-02-02 03:06:08 +0200254
255
256def parse_args(argv):
257 parser = argparse.ArgumentParser(
258 description="Run rally disk io performance test")
259 parser.add_argument("tool_type", help="test tool type",
260 choices=['iozone', 'fio'])
koder aka kdanilov80cb6192015-02-02 03:06:08 +0200261 parser.add_argument("-l", dest='extra_logs',
262 action='store_true', default=False,
263 help="print some extra log info")
264 parser.add_argument("-o", "--io-opts", dest='io_opts',
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200265 nargs="*", default=[],
266 help="cmd line options for io.py")
267 parser.add_argument("-t", "--test-directory", help="directory with test",
koder aka kdanilov56ee3ed2015-02-02 19:00:31 +0200268 dest="test_directory", required=True)
koder aka kdanilov56ee3ed2015-02-02 19:00:31 +0200269 parser.add_argument("--max-preparation-time", default=300,
270 type=int, dest="max_preparation_time")
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200271 parser.add_argument("-k", "--keep", default=False,
272 help="keep temporary files",
273 dest="keet_temp_files", action='store_true')
274 parser.add_argument("--rally-extra-opts", dest="rally_extra_opts",
275 default="", help="rally extra options")
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200276
koder aka kdanilov80cb6192015-02-02 03:06:08 +0200277 return parser.parse_args(argv)
koder aka kdanilov4af80852015-02-01 23:36:38 +0200278
279
280def main(argv):
koder aka kdanilov80cb6192015-02-02 03:06:08 +0200281 opts = parse_args(argv)
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200282 dst_testtool_path = '/tmp/io_tool'
283
koder aka kdanilov80cb6192015-02-02 03:06:08 +0200284 if not opts.extra_logs:
285 global log
286
287 def nolog(x):
288 pass
289
290 log = nolog
291
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200292 if opts.io_opts == []:
293 testtool_py_args_v = []
294
295 block_sizes = ["4k", "64k"]
296 ops = ['randwrite']
297 iodepths = ['8']
298 syncs = [True]
299
300 for block_size in block_sizes:
301 for op in ops:
302 for iodepth in iodepths:
303 for sync in syncs:
304 tt_argv = ['--type', opts.tool_type,
305 '-a', op,
306 '--iodepth', iodepth,
307 '--blocksize', block_size,
koder aka kdanilov1b0d3502015-02-03 21:32:31 +0200308 '--iosize', '20M']
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200309 if sync:
310 tt_argv.append('-s')
311 testtool_py_args_v.append(tt_argv)
koder aka kdanilov80cb6192015-02-02 03:06:08 +0200312 else:
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200313 testtool_py_args_v = []
314 for o in opts.io_opts:
315 ttopts = [opt.strip() for opt in o.split(" ") if opt.strip() != ""]
316 testtool_py_args_v.append(ttopts)
koder aka kdanilov80cb6192015-02-02 03:06:08 +0200317
koder aka kdanilov1b0d3502015-02-03 21:32:31 +0200318 for io_argv_list in testtool_py_args_v:
319 io_argv_list.extend(['--binary-path', dst_testtool_path])
320
koder aka kdanilov56ee3ed2015-02-02 19:00:31 +0200321 res = run_test(opts.tool_type,
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200322 testtool_py_args_v,
koder aka kdanilov56ee3ed2015-02-02 19:00:31 +0200323 dst_testtool_path,
324 files_dir=opts.test_directory,
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200325 rally_extra_opts=opts.rally_extra_opts.split(" "),
326 max_preparation_time=opts.max_preparation_time,
327 keet_temp_files=opts.keet_temp_files)
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200328
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200329 print "=" * 80
330 print pprint.pformat(res)
331 print "=" * 80
332
333 if len(res) != 0:
334 bw_mean = 0.0
335 for measurement in res:
336 bw_mean += measurement["bw_mean"]
337
338 bw_mean /= len(res)
339
340 it = ((bw_mean - measurement["bw_mean"]) ** 2 for measurement in res)
341 bw_dev = sum(it) ** 0.5
342
343 meta = res[0]['__meta__']
344 key = "{0} {1} {2}k".format(meta['action'],
345 's' if meta['sync'] else 'a',
346 meta['blocksize'])
347
348 print
349 print "====> " + json.dumps({key: (int(bw_mean), int(bw_dev))})
350 print
351 print "=" * 80
koder aka kdanilov78ba8952015-02-03 01:11:23 +0200352
koder aka kdanilov80cb6192015-02-02 03:06:08 +0200353 return 0
koder aka kdanilov4af80852015-02-01 23:36:38 +0200354
355# ubuntu cloud image
356# https://cloud-images.ubuntu.com/trusty/current/trusty-server-cloudimg-amd64-disk1.img
357
358# glance image-create --name 'ubuntu' --disk-format qcow2
359# --container-format bare --is-public true --copy-from
360# https://cloud-images.ubuntu.com/trusty/current/trusty-server-cloudimg-amd64-disk1.img
koder aka kdanilov4a72f122015-02-09 12:25:54 +0200361# nova flavor-create ceph.512 ceph.512 512 50 1
362# nova server-group-create --policy anti-affinity ceph
koder aka kdanilov4af80852015-02-01 23:36:38 +0200363
364if __name__ == '__main__':
koder aka kdanilov98615bf2015-02-02 00:59:07 +0200365 exit(main(sys.argv[1:]))