85e35af2dc2229861816c8b86839c676cc982bdf
[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
26
27 class TaskCommands(object):
28     '''Task commands.
29
30        Set of commands to manage benchmark tasks.
31     '''
32
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",
42              action="store_true")
43     @cliargs("--parse-only", help="parse the benchmark config file and exit",
44              action="store_true")
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.'''
49
50         atexit.register(atexit_handler)
51
52         parser = TaskParser(args.taskfile[0])
53         scenarios, run_in_parallel = parser.parse(args.task_args,
54                                                   args.task_args_file)
55
56         if args.parse_only:
57             sys.exit(0)
58
59         if os.path.isfile(args.output_file):
60             os.remove(args.output_file)
61
62         for context in Context.list:
63             context.deploy()
64
65         runners = []
66         if run_in_parallel:
67             for scenario in scenarios:
68                 runner = run_one_scenario(scenario, args.output_file)
69                 runners.append(runner)
70
71             # Wait for runners to finish
72             for runner in runners:
73                 runner_join(runner)
74                 print "Runner ended, output in", args.output_file
75         else:
76             # run serially
77             for scenario in scenarios:
78                 runner = run_one_scenario(scenario, args.output_file)
79                 runner_join(runner)
80                 print "Runner ended, output in", args.output_file
81
82         if args.keep_deploy:
83             # keep deployment, forget about stack (hide it for exit handler)
84             Context.list = []
85         else:
86             for context in Context.list:
87                 context.undeploy()
88
89         print "Done, exiting"
90
91 # TODO: Move stuff below into TaskCommands class !?
92
93
94 class TaskParser(object):
95     '''Parser for task config files in yaml format'''
96     def __init__(self, path):
97         self.path = path
98
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
102
103         try:
104             kw = {}
105             if task_args_file:
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))
109         except TypeError:
110             raise TypeError()
111
112         try:
113             with open(self.path) as f:
114                 try:
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})
120                     raise e
121                 print(("Input task is:\n%s\n") % rendered_task)
122
123                 cfg = yaml.load(rendered_task)
124         except IOError as ioerror:
125             sys.exit(ioerror)
126
127         if cfg["schema"] != "yardstick:task:0.1":
128             sys.exit("error: file %s has unknown schema %s" % (self.path,
129                                                                cfg["schema"]))
130
131         # TODO: support one or many contexts? Many would simpler and precise
132         if "context" in cfg:
133             context_cfgs = [cfg["context"]]
134         else:
135             context_cfgs = cfg["contexts"]
136
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')
143             context = Context()
144             context.init(cfg_attrs)
145
146         run_in_parallel = cfg.get("run_in_parallel", False)
147
148         # TODO we need something better here, a class that represent the file
149         return cfg["scenarios"], run_in_parallel
150
151
152 def atexit_handler():
153     '''handler for process termination'''
154     base_runner.Runner.terminate_all()
155
156     if len(Context.list) > 0:
157         print "Undeploying all contexts"
158         for context in Context.list:
159             context.undeploy()
160
161
162 def is_ip_addr(addr):
163     '''check if string addr is an IP address'''
164     try:
165         ipaddress.ip_address(unicode(addr))
166         return True
167     except ValueError:
168         return False
169
170
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')
175
176     host = Context.get_server(scenario_cfg["host"])
177
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
183
184     if "target" in scenario_cfg:
185         if is_ip_addr(scenario_cfg["target"]):
186             scenario_cfg["ipaddr"] = scenario_cfg["target"]
187         else:
188             target = Context.get_server(scenario_cfg["target"])
189
190             # get public IP for target server, some scenarios require it
191             if target.public_ip:
192                 runner_cfg['target'] = target.public_ip
193
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
198             else:
199                 # target is in the same context, get its private IP
200                 scenario_cfg["ipaddr"] = target.private_ip
201
202     runner = base_runner.Runner.get(runner_cfg)
203
204     print "Starting runner of type '%s'" % runner_cfg["type"]
205     runner.run(scenario_cfg["type"], scenario_cfg)
206
207     return runner
208
209
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)
214     if status != 0:
215         sys.exit("Runner failed")
216
217
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})
221
222
223 def parse_task_args(src_name, args):
224     try:
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})
231         raise TypeError()
232
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)})
237         raise TypeError()
238     return kw