1 ##############################################################################
2 # Copyright (c) 2015 Ericsson AB and others.
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
10 """ Handler for yardstick command 'task' """
19 from yardstick.benchmark.context.model import Context
20 from yardstick.benchmark.runners import base as base_runner
21 from yardstick.common.task_template import TaskTemplate
22 from yardstick.common.utils import cliargs
24 output_file_default = "/tmp/yardstick.out"
27 class TaskCommands(object):
30 Set of commands to manage benchmark tasks.
33 @cliargs("taskfile", type=str, help="path to taskfile", nargs=1)
34 @cliargs("--task-args", dest="task_args",
35 help="Input task args (dict in json). These args are used"
36 "to render input task that is jinja2 template.")
37 @cliargs("--task-args-file", dest="task_args_file",
38 help="Path to the file with input task args (dict in "
39 "json/yaml). These args are used to render input"
40 "task that is jinja2 template.")
41 @cliargs("--keep-deploy", help="keep context deployed in cloud",
43 @cliargs("--parse-only", help="parse the benchmark config file and exit",
45 @cliargs("--output-file", help="file where output is stored, default %s" %
46 output_file_default, default=output_file_default)
47 def do_start(self, args):
48 '''Start a benchmark scenario.'''
50 atexit.register(atexit_handler)
52 parser = TaskParser(args.taskfile[0])
53 scenarios, run_in_parallel = parser.parse(args.task_args,
59 if os.path.isfile(args.output_file):
60 os.remove(args.output_file)
62 for context in Context.list:
67 for scenario in scenarios:
68 runner = run_one_scenario(scenario, args.output_file)
69 runners.append(runner)
71 # Wait for runners to finish
72 for runner in runners:
74 print "Runner ended, output in", args.output_file
77 for scenario in scenarios:
78 runner = run_one_scenario(scenario, args.output_file)
80 print "Runner ended, output in", args.output_file
83 # keep deployment, forget about stack (hide it for exit handler)
86 for context in Context.list:
91 # TODO: Move stuff below into TaskCommands class !?
94 class TaskParser(object):
95 '''Parser for task config files in yaml format'''
96 def __init__(self, path):
99 def parse(self, task_args=None, task_args_file=None):
100 '''parses the task file and return an context and scenario instances'''
101 print "Parsing task config:", self.path
106 with open(task_args_file) as f:
107 kw.update(parse_task_args("task_args_file", f.read()))
108 kw.update(parse_task_args("task_args", task_args))
113 with open(self.path) as f:
115 input_task = f.read()
116 rendered_task = TaskTemplate.render(input_task, **kw)
117 except Exception as e:
118 print(("Failed to render template:\n%(task)s\n%(err)s\n")
119 % {"task": input_task, "err": e})
121 print(("Input task is:\n%s\n") % rendered_task)
123 cfg = yaml.load(rendered_task)
124 except IOError as ioerror:
127 if cfg["schema"] != "yardstick:task:0.1":
128 sys.exit("error: file %s has unknown schema %s" % (self.path,
131 # TODO: support one or many contexts? Many would simpler and precise
133 context_cfgs = [cfg["context"]]
135 context_cfgs = cfg["contexts"]
137 for cfg_attrs in context_cfgs:
138 # config external_network based on env var
139 if "networks" in cfg_attrs:
140 for _, attrs in cfg_attrs["networks"].items():
141 attrs["external_network"] = os.environ.get(
142 'EXTERNAL_NETWORK', 'net04_ext')
144 context.init(cfg_attrs)
146 run_in_parallel = cfg.get("run_in_parallel", False)
148 # TODO we need something better here, a class that represent the file
149 return cfg["scenarios"], run_in_parallel
152 def atexit_handler():
153 '''handler for process termination'''
154 base_runner.Runner.terminate_all()
156 if len(Context.list) > 0:
157 print "Undeploying all contexts"
158 for context in Context.list:
162 def is_ip_addr(addr):
163 '''check if string addr is an IP address'''
165 ipaddress.ip_address(unicode(addr))
171 def run_one_scenario(scenario_cfg, output_file):
172 '''run one scenario using context'''
173 key_filename = pkg_resources.resource_filename(
174 'yardstick.resources', 'files/yardstick_key')
176 host = Context.get_server(scenario_cfg["host"])
178 runner_cfg = scenario_cfg["runner"]
179 runner_cfg['host'] = host.public_ip
180 runner_cfg['user'] = host.context.user
181 runner_cfg['key_filename'] = key_filename
182 runner_cfg['output_filename'] = output_file
184 if "target" in scenario_cfg:
185 if is_ip_addr(scenario_cfg["target"]):
186 scenario_cfg["ipaddr"] = scenario_cfg["target"]
188 target = Context.get_server(scenario_cfg["target"])
190 # get public IP for target server, some scenarios require it
192 runner_cfg['target'] = target.public_ip
194 # TODO scenario_cfg["ipaddr"] is bad naming
195 if host.context != target.context:
196 # target is in another context, get its public IP
197 scenario_cfg["ipaddr"] = target.public_ip
199 # target is in the same context, get its private IP
200 scenario_cfg["ipaddr"] = target.private_ip
202 runner = base_runner.Runner.get(runner_cfg)
204 print "Starting runner of type '%s'" % runner_cfg["type"]
205 runner.run(scenario_cfg["type"], scenario_cfg)
210 def runner_join(runner):
211 '''join (wait for) a runner, exit process at runner failure'''
212 status = runner.join()
213 base_runner.Runner.release(runner)
215 sys.exit("Runner failed")
218 def print_invalid_header(source_name, args):
219 print(("Invalid %(source)s passed:\n\n %(args)s\n")
220 % {"source": source_name, "args": args})
223 def parse_task_args(src_name, args):
225 kw = args and yaml.safe_load(args)
226 kw = {} if kw is None else kw
227 except yaml.parser.ParserError as e:
228 print_invalid_header(src_name, args)
229 print(("%(source)s has to be YAML. Details:\n\n%(err)s\n")
230 % {"source": src_name, "err": e})
233 if not isinstance(kw, dict):
234 print_invalid_header(src_name, args)
235 print(("%(src)s had to be dict, actually %(src_type)s\n")
236 % {"src": src_name, "src_type": type(kw)})