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 for _, attrs in cfg_attrs["networks"].items():
140 attrs["external_network"] = os.environ.get('EXTERNAL_NETWORK',
143 context.init(cfg_attrs)
145 run_in_parallel = cfg.get("run_in_parallel", False)
147 # TODO we need something better here, a class that represent the file
148 return cfg["scenarios"], run_in_parallel
151 def atexit_handler():
152 '''handler for process termination'''
153 base_runner.Runner.terminate_all()
155 if len(Context.list) > 0:
156 print "Undeploying all contexts"
157 for context in Context.list:
161 def is_ip_addr(addr):
162 '''check if string addr is an IP address'''
164 ipaddress.ip_address(unicode(addr))
170 def run_one_scenario(scenario_cfg, output_file):
171 '''run one scenario using context'''
172 key_filename = pkg_resources.resource_filename(
173 'yardstick.resources', 'files/yardstick_key')
175 host = Context.get_server(scenario_cfg["host"])
177 runner_cfg = scenario_cfg["runner"]
178 runner_cfg['host'] = host.public_ip
179 runner_cfg['user'] = host.context.user
180 runner_cfg['key_filename'] = key_filename
181 runner_cfg['output_filename'] = output_file
183 if "target" in scenario_cfg:
184 if is_ip_addr(scenario_cfg["target"]):
185 scenario_cfg["ipaddr"] = scenario_cfg["target"]
187 target = Context.get_server(scenario_cfg["target"])
189 # get public IP for target server, some scenarios require it
191 runner_cfg['target'] = target.public_ip
193 # TODO scenario_cfg["ipaddr"] is bad naming
194 if host.context != target.context:
195 # target is in another context, get its public IP
196 scenario_cfg["ipaddr"] = target.public_ip
198 # target is in the same context, get its private IP
199 scenario_cfg["ipaddr"] = target.private_ip
201 runner = base_runner.Runner.get(runner_cfg)
203 print "Starting runner of type '%s'" % runner_cfg["type"]
204 runner.run(scenario_cfg["type"], scenario_cfg)
209 def runner_join(runner):
210 '''join (wait for) a runner, exit process at runner failure'''
211 status = runner.join()
212 base_runner.Runner.release(runner)
214 sys.exit("Runner failed")
217 def print_invalid_header(source_name, args):
218 print(("Invalid %(source)s passed:\n\n %(args)s\n")
219 % {"source": source_name, "args": args})
222 def parse_task_args(src_name, args):
224 kw = args and yaml.safe_load(args)
225 kw = {} if kw is None else kw
226 except yaml.parser.ParserError as e:
227 print_invalid_header(src_name, args)
228 print(("%(source)s has to be YAML. Details:\n\n%(err)s\n")
229 % {"source": src_name, "err": e})
232 if not isinstance(kw, dict):
233 print_invalid_header(src_name, args)
234 print(("%(src)s had to be dict, actually %(src_type)s\n")
235 % {"src": src_name, "src_type": type(kw)})