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' """
20 from itertools import ifilter
22 from yardstick.benchmark.contexts.base import Context
23 from yardstick.benchmark.runners import base as base_runner
24 from yardstick.common.task_template import TaskTemplate
25 from yardstick.common.utils import cliargs
27 output_file_default = "/tmp/yardstick.out"
28 test_cases_dir_default = "tests/opnfv/test_cases/"
29 LOG = logging.getLogger(__name__)
32 class TaskCommands(object):
35 Set of commands to manage benchmark tasks.
38 @cliargs("inputfile", type=str, help="path to task or suite file", nargs=1)
39 @cliargs("--task-args", dest="task_args",
40 help="Input task args (dict in json). These args are used"
41 "to render input task that is jinja2 template.")
42 @cliargs("--task-args-file", dest="task_args_file",
43 help="Path to the file with input task args (dict in "
44 "json/yaml). These args are used to render input"
45 "task that is jinja2 template.")
46 @cliargs("--keep-deploy", help="keep context deployed in cloud",
48 @cliargs("--parse-only", help="parse the config file and exit",
50 @cliargs("--output-file", help="file where output is stored, default %s" %
51 output_file_default, default=output_file_default)
52 @cliargs("--suite", help="process test suite file instead of a task file",
54 def do_start(self, args):
55 '''Start a benchmark scenario.'''
57 atexit.register(atexit_handler)
59 total_start_time = time.time()
60 parser = TaskParser(args.inputfile[0])
64 suite_params = parser.parse_suite()
65 test_cases_dir = suite_params["test_cases_dir"]
66 if test_cases_dir[-1] != os.sep:
67 test_cases_dir += os.sep
68 task_files = [test_cases_dir + task
69 for task in suite_params["task_fnames"]]
71 task_files = [parser.path]
73 task_args = suite_params.get("task_args", [args.task_args])
74 task_args_fnames = suite_params.get("task_args_fnames",
75 [args.task_args_file])
80 if os.path.isfile(args.output_file):
81 os.remove(args.output_file)
83 for i in range(0, len(task_files)):
84 one_task_start_time = time.time()
85 parser.path = task_files[i]
86 task_name = os.path.splitext(os.path.basename(task_files[i]))[0]
87 scenarios, run_in_parallel, meet_precondition = parser.parse_task(
88 task_name, task_args[i], task_args_fnames[i])
90 if not meet_precondition:
91 LOG.info("meet_precondition is %s, please check envrionment",
95 self._run(scenarios, run_in_parallel, args.output_file)
98 # keep deployment, forget about stack
99 # (hide it for exit handler)
102 for context in Context.list:
105 one_task_end_time = time.time()
106 LOG.info("task %s finished in %d secs", task_files[i],
107 one_task_end_time - one_task_start_time)
109 total_end_time = time.time()
110 LOG.info("total finished in %d secs",
111 total_end_time - total_start_time)
113 print "Done, exiting"
115 def _run(self, scenarios, run_in_parallel, output_file):
116 '''Deploys context and calls runners'''
117 for context in Context.list:
120 background_runners = []
122 # Start all background scenarios
123 for scenario in ifilter(_is_background_scenario, scenarios):
124 scenario["runner"] = dict(type="Duration", duration=1000000000)
125 runner = run_one_scenario(scenario, output_file)
126 background_runners.append(runner)
130 for scenario in scenarios:
131 if not _is_background_scenario(scenario):
132 runner = run_one_scenario(scenario, output_file)
133 runners.append(runner)
135 # Wait for runners to finish
136 for runner in runners:
138 print "Runner ended, output in", output_file
141 for scenario in scenarios:
142 if not _is_background_scenario(scenario):
143 runner = run_one_scenario(scenario, output_file)
145 print "Runner ended, output in", output_file
147 # Abort background runners
148 for runner in background_runners:
151 # Wait for background runners to finish
152 for runner in background_runners:
153 if runner.join(timeout=60) is None:
154 # Nuke if it did not stop nicely
155 base_runner.Runner.terminate(runner)
158 base_runner.Runner.release(runner)
159 print "Background task ended"
162 # TODO: Move stuff below into TaskCommands class !?
165 class TaskParser(object):
166 '''Parser for task config files in yaml format'''
167 def __init__(self, path):
170 def parse_suite(self):
171 '''parse the suite file and return a list of task config file paths
172 and lists of optional parameters if present'''
173 print "Parsing suite file:", self.path
176 with open(self.path) as stream:
177 cfg = yaml.load(stream)
178 except IOError as ioerror:
181 self._check_schema(cfg["schema"], "suite")
182 print "Starting suite:", cfg["name"]
184 test_cases_dir = cfg.get("test_cases_dir", test_cases_dir_default)
187 task_args_fnames = []
189 for task in cfg["test_cases"]:
190 task_fnames.append(task["file_name"])
191 if "task_args" in task:
192 task_args.append(task["task_args"])
194 task_args.append(None)
196 if "task_args_file" in task:
197 task_args_fnames.append(task["task_args_file"])
199 task_args_fnames.append(None)
202 "test_cases_dir": test_cases_dir,
203 "task_fnames": task_fnames,
204 "task_args": task_args,
205 "task_args_fnames": task_args_fnames
210 def parse_task(self, task_name, task_args=None, task_args_file=None):
211 '''parses the task file and return an context and scenario instances'''
212 print "Parsing task config:", self.path
217 with open(task_args_file) as f:
218 kw.update(parse_task_args("task_args_file", f.read()))
219 kw.update(parse_task_args("task_args", task_args))
224 with open(self.path) as f:
226 input_task = f.read()
227 rendered_task = TaskTemplate.render(input_task, **kw)
228 except Exception as e:
229 print(("Failed to render template:\n%(task)s\n%(err)s\n")
230 % {"task": input_task, "err": e})
232 print(("Input task is:\n%s\n") % rendered_task)
234 cfg = yaml.load(rendered_task)
235 except IOError as ioerror:
238 self._check_schema(cfg["schema"], "task")
239 meet_precondition = self._check_precondition(cfg)
241 # TODO: support one or many contexts? Many would simpler and precise
242 # TODO: support hybrid context type
244 context_cfgs = [cfg["context"]]
245 elif "contexts" in cfg:
246 context_cfgs = cfg["contexts"]
248 context_cfgs = [{"type": "Dummy"}]
250 for cfg_attrs in context_cfgs:
251 context_type = cfg_attrs.get("type", "Heat")
252 if "Heat" == context_type and "networks" in cfg_attrs:
253 # config external_network based on env var
254 for _, attrs in cfg_attrs["networks"].items():
255 attrs["external_network"] = os.environ.get(
256 'EXTERNAL_NETWORK', 'net04_ext')
257 context = Context.get(context_type)
258 context.init(cfg_attrs)
260 run_in_parallel = cfg.get("run_in_parallel", False)
262 # add tc and task id for influxdb extended tags
263 task_id = str(uuid.uuid4())
264 for scenario in cfg["scenarios"]:
265 scenario["tc"] = task_name
266 scenario["task_id"] = task_id
268 # TODO we need something better here, a class that represent the file
269 return cfg["scenarios"], run_in_parallel, meet_precondition
271 def _check_schema(self, cfg_schema, schema_type):
272 '''Check if config file is using the correct schema type'''
274 if cfg_schema != "yardstick:" + schema_type + ":0.1":
275 sys.exit("error: file %s has unknown schema %s" % (self.path,
278 def _check_precondition(self, cfg):
279 '''Check if the envrionment meet the preconditon'''
281 if "precondition" in cfg:
282 precondition = cfg["precondition"]
283 installer_type = precondition.get("installer_type", None)
284 deploy_scenarios = precondition.get("deploy_scenarios", None)
285 installer_type_env = os.environ.get('INSTALL_TYPE', None)
286 deploy_scenario_env = os.environ.get('DEPLOY_SCENARIO', None)
287 if installer_type and installer_type_env:
288 if installer_type_env not in installer_type:
290 if deploy_scenarios and deploy_scenario_env:
291 deploy_scenarios_list = deploy_scenarios.split(',')
292 for deploy_scenario in deploy_scenarios_list:
293 if deploy_scenario_env.startswith(deploy_scenario):
299 def atexit_handler():
300 '''handler for process termination'''
301 base_runner.Runner.terminate_all()
303 if len(Context.list) > 0:
304 print "Undeploying all contexts"
305 for context in Context.list:
309 def is_ip_addr(addr):
310 '''check if string addr is an IP address'''
312 ipaddress.ip_address(unicode(addr))
318 def _is_same_heat_context(host_attr, target_attr):
319 '''check if two servers are in the same heat context
320 host_attr: either a name for a server created by yardstick or a dict
321 with attribute name mapping when using external heat templates
322 target_attr: either a name for a server created by yardstick or a dict
323 with attribute name mapping when using external heat templates
327 for context in Context.list:
328 if context.__context_type__ != "Heat":
331 host = context._get_server(host_attr)
335 target = context._get_server(target_attr)
339 # Both host and target is not None, then they are in the
346 def _is_background_scenario(scenario):
347 if "run_in_background" in scenario:
348 return scenario["run_in_background"]
353 def run_one_scenario(scenario_cfg, output_file):
354 '''run one scenario using context'''
355 runner_cfg = scenario_cfg["runner"]
356 runner_cfg['output_filename'] = output_file
358 # TODO support get multi hosts/vms info
360 if "host" in scenario_cfg:
361 context_cfg['host'] = Context.get_server(scenario_cfg["host"])
363 if "target" in scenario_cfg:
364 if is_ip_addr(scenario_cfg["target"]):
365 context_cfg['target'] = {}
366 context_cfg['target']["ipaddr"] = scenario_cfg["target"]
368 context_cfg['target'] = Context.get_server(scenario_cfg["target"])
369 if _is_same_heat_context(scenario_cfg["host"],
370 scenario_cfg["target"]):
371 context_cfg["target"]["ipaddr"] = \
372 context_cfg["target"]["private_ip"]
374 context_cfg["target"]["ipaddr"] = \
375 context_cfg["target"]["ip"]
377 if "nodes" in scenario_cfg:
378 context_cfg["nodes"] = parse_nodes_with_context(scenario_cfg)
379 runner = base_runner.Runner.get(runner_cfg)
381 print "Starting runner of type '%s'" % runner_cfg["type"]
382 runner.run(scenario_cfg, context_cfg)
387 def parse_nodes_with_context(scenario_cfg):
388 '''paras the 'nodes' fields in scenario '''
389 nodes = scenario_cfg["nodes"]
392 for nodename in nodes:
393 nodes_cfg[nodename] = Context.get_server(nodes[nodename])
398 def runner_join(runner):
399 '''join (wait for) a runner, exit process at runner failure'''
400 status = runner.join()
401 base_runner.Runner.release(runner)
403 sys.exit("Runner failed")
406 def print_invalid_header(source_name, args):
407 print(("Invalid %(source)s passed:\n\n %(args)s\n")
408 % {"source": source_name, "args": args})
411 def parse_task_args(src_name, args):
413 kw = args and yaml.safe_load(args)
414 kw = {} if kw is None else kw
415 except yaml.parser.ParserError as e:
416 print_invalid_header(src_name, args)
417 print(("%(source)s has to be YAML. Details:\n\n%(err)s\n")
418 % {"source": src_name, "err": e})
421 if not isinstance(kw, dict):
422 print_invalid_header(src_name, args)
423 print(("%(src)s had to be dict, actually %(src_type)s\n")
424 % {"src": src_name, "src_type": type(kw)})