5c25c576a2e0e98bd07bdf110fede1c89e387055
[yardstick.git] / yardstick / cmd / commands / task.py
1 ##############################################################################
2 # Copyright (c) 2015 Ericsson AB and others.
3 #
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 ##############################################################################
9
10 """ Handler for yardstick command 'task' """
11
12 import sys
13 import os
14 import yaml
15 import atexit
16 import pkg_resources
17 import ipaddress
18
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
23
24 output_file_default = "/tmp/yardstick.out"
25 test_cases_dir_default = "tests/opnfv/test_cases/"
26
27
28 class TaskCommands(object):
29     '''Task commands.
30
31        Set of commands to manage benchmark tasks.
32     '''
33
34     @cliargs("inputfile", type=str, help="path to task or suite file", nargs=1)
35     @cliargs("--task-args", dest="task_args",
36              help="Input task args (dict in json). These args are used"
37              "to render input task that is jinja2 template.")
38     @cliargs("--task-args-file", dest="task_args_file",
39              help="Path to the file with input task args (dict in "
40              "json/yaml). These args are used to render input"
41              "task that is jinja2 template.")
42     @cliargs("--keep-deploy", help="keep context deployed in cloud",
43              action="store_true")
44     @cliargs("--parse-only", help="parse the config file and exit",
45              action="store_true")
46     @cliargs("--output-file", help="file where output is stored, default %s" %
47              output_file_default, default=output_file_default)
48     @cliargs("--suite", help="process test suite file instead of a task file",
49              action="store_true")
50     def do_start(self, args):
51         '''Start a benchmark scenario.'''
52
53         atexit.register(atexit_handler)
54
55         parser = TaskParser(args.inputfile[0])
56
57         suite_params = {}
58         if args.suite:
59             suite_params = parser.parse_suite()
60             test_cases_dir = suite_params["test_cases_dir"]
61             if test_cases_dir[-1] != os.sep:
62                 test_cases_dir += os.sep
63             task_files = [test_cases_dir + task
64                           for task in suite_params["task_fnames"]]
65         else:
66             task_files = [parser.path]
67
68         task_args = suite_params.get("task_args", [args.task_args])
69         task_args_fnames = suite_params.get("task_args_fnames",
70                                             [args.task_args_file])
71
72         if args.parse_only:
73             sys.exit(0)
74
75         if os.path.isfile(args.output_file):
76             os.remove(args.output_file)
77
78         for i in range(0, len(task_files)):
79             parser.path = task_files[i]
80             scenarios, run_in_parallel = parser.parse_task(task_args[i],
81                                                            task_args_fnames[i])
82
83             self._run(scenarios, run_in_parallel, args.output_file)
84
85             if args.keep_deploy:
86                 # keep deployment, forget about stack
87                 # (hide it for exit handler)
88                 Context.list = []
89             else:
90                 for context in Context.list:
91                     context.undeploy()
92                 Context.list = []
93
94         print "Done, exiting"
95
96     def _run(self, scenarios, run_in_parallel, output_file):
97         '''Deploys context and calls runners'''
98         for context in Context.list:
99             context.deploy()
100
101         runners = []
102         if run_in_parallel:
103             for scenario in scenarios:
104                 runner = run_one_scenario(scenario, output_file)
105                 runners.append(runner)
106
107             # Wait for runners to finish
108             for runner in runners:
109                 runner_join(runner)
110                 print "Runner ended, output in", output_file
111         else:
112             # run serially
113             for scenario in scenarios:
114                 runner = run_one_scenario(scenario, output_file)
115                 runner_join(runner)
116                 print "Runner ended, output in", output_file
117
118 # TODO: Move stuff below into TaskCommands class !?
119
120
121 class TaskParser(object):
122     '''Parser for task config files in yaml format'''
123     def __init__(self, path):
124         self.path = path
125
126     def parse_suite(self):
127         '''parse the suite file and return a list of task config file paths
128            and lists of optional parameters if present'''
129         print "Parsing suite file:", self.path
130
131         try:
132             with open(self.path) as stream:
133                 cfg = yaml.load(stream)
134         except IOError as ioerror:
135             sys.exit(ioerror)
136
137         self._check_schema(cfg["schema"], "suite")
138         print "Starting suite:", cfg["name"]
139
140         test_cases_dir = cfg.get("test_cases_dir", test_cases_dir_default)
141         task_fnames = []
142         task_args = []
143         task_args_fnames = []
144
145         for task in cfg["test_cases"]:
146             task_fnames.append(task["file_name"])
147             if "task_args" in task:
148                 task_args.append(task["task_args"])
149             else:
150                 task_args.append(None)
151
152             if "task_args_file" in task:
153                 task_args_fnames.append(task["task_args_file"])
154             else:
155                 task_args_fnames.append(None)
156
157         suite_params = {
158             "test_cases_dir": test_cases_dir,
159             "task_fnames": task_fnames,
160             "task_args": task_args,
161             "task_args_fnames": task_args_fnames
162         }
163
164         return suite_params
165
166     def parse_task(self, task_args=None, task_args_file=None):
167         '''parses the task file and return an context and scenario instances'''
168         print "Parsing task config:", self.path
169
170         try:
171             kw = {}
172             if task_args_file:
173                 with open(task_args_file) as f:
174                     kw.update(parse_task_args("task_args_file", f.read()))
175             kw.update(parse_task_args("task_args", task_args))
176         except TypeError:
177             raise TypeError()
178
179         try:
180             with open(self.path) as f:
181                 try:
182                     input_task = f.read()
183                     rendered_task = TaskTemplate.render(input_task, **kw)
184                 except Exception as e:
185                     print(("Failed to render template:\n%(task)s\n%(err)s\n")
186                           % {"task": input_task, "err": e})
187                     raise e
188                 print(("Input task is:\n%s\n") % rendered_task)
189
190                 cfg = yaml.load(rendered_task)
191         except IOError as ioerror:
192             sys.exit(ioerror)
193
194         self._check_schema(cfg["schema"], "task")
195
196         # TODO: support one or many contexts? Many would simpler and precise
197         if "context" in cfg:
198             context_cfgs = [cfg["context"]]
199         else:
200             context_cfgs = cfg["contexts"]
201
202         for cfg_attrs in context_cfgs:
203             # config external_network based on env var
204             if "networks" in cfg_attrs:
205                 for _, attrs in cfg_attrs["networks"].items():
206                     attrs["external_network"] = os.environ.get(
207                         'EXTERNAL_NETWORK', 'net04_ext')
208             context = Context()
209             context.init(cfg_attrs)
210
211         run_in_parallel = cfg.get("run_in_parallel", False)
212
213         # TODO we need something better here, a class that represent the file
214         return cfg["scenarios"], run_in_parallel
215
216     def _check_schema(self, cfg_schema, schema_type):
217         '''Check if config file is using the correct schema type'''
218
219         if cfg_schema != "yardstick:" + schema_type + ":0.1":
220             sys.exit("error: file %s has unknown schema %s" % (self.path,
221                                                                cfg_schema))
222
223
224 def atexit_handler():
225     '''handler for process termination'''
226     base_runner.Runner.terminate_all()
227
228     if len(Context.list) > 0:
229         print "Undeploying all contexts"
230         for context in Context.list:
231             context.undeploy()
232
233
234 def is_ip_addr(addr):
235     '''check if string addr is an IP address'''
236     try:
237         ipaddress.ip_address(unicode(addr))
238         return True
239     except ValueError:
240         return False
241
242
243 def run_one_scenario(scenario_cfg, output_file):
244     '''run one scenario using context'''
245     key_filename = pkg_resources.resource_filename(
246         'yardstick.resources', 'files/yardstick_key')
247
248     host = Context.get_server(scenario_cfg["host"])
249
250     runner_cfg = scenario_cfg["runner"]
251     runner_cfg['host'] = host.public_ip
252     runner_cfg['user'] = host.context.user
253     runner_cfg['key_filename'] = key_filename
254     runner_cfg['output_filename'] = output_file
255
256     if "target" in scenario_cfg:
257         if is_ip_addr(scenario_cfg["target"]):
258             scenario_cfg["ipaddr"] = scenario_cfg["target"]
259         else:
260             target = Context.get_server(scenario_cfg["target"])
261
262             # get public IP for target server, some scenarios require it
263             if target.public_ip:
264                 runner_cfg['target'] = target.public_ip
265
266             # TODO scenario_cfg["ipaddr"] is bad naming
267             if host.context != target.context:
268                 # target is in another context, get its public IP
269                 scenario_cfg["ipaddr"] = target.public_ip
270             else:
271                 # target is in the same context, get its private IP
272                 scenario_cfg["ipaddr"] = target.private_ip
273
274     runner = base_runner.Runner.get(runner_cfg)
275
276     print "Starting runner of type '%s'" % runner_cfg["type"]
277     runner.run(scenario_cfg["type"], scenario_cfg)
278
279     return runner
280
281
282 def runner_join(runner):
283     '''join (wait for) a runner, exit process at runner failure'''
284     status = runner.join()
285     base_runner.Runner.release(runner)
286     if status != 0:
287         sys.exit("Runner failed")
288
289
290 def print_invalid_header(source_name, args):
291     print(("Invalid %(source)s passed:\n\n %(args)s\n")
292           % {"source": source_name, "args": args})
293
294
295 def parse_task_args(src_name, args):
296     try:
297         kw = args and yaml.safe_load(args)
298         kw = {} if kw is None else kw
299     except yaml.parser.ParserError as e:
300         print_invalid_header(src_name, args)
301         print(("%(source)s has to be YAML. Details:\n\n%(err)s\n")
302               % {"source": src_name, "err": e})
303         raise TypeError()
304
305     if not isinstance(kw, dict):
306         print_invalid_header(src_name, args)
307         print(("%(src)s had to be dict, actually %(src_type)s\n")
308               % {"src": src_name, "src_type": type(kw)})
309         raise TypeError()
310     return kw