Add support to list and show runners & scenarios
[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 yaml
14 import atexit
15 import pkg_resources
16 import ipaddress
17
18 from yardstick.benchmark.context.model import Context
19 from yardstick.benchmark.runners import base as base_runner
20
21 from yardstick.common.utils import cliargs
22
23 output_file_default = "/tmp/yardstick.out"
24
25
26 class TaskCommands(object):
27     '''Task commands.
28
29        Set of commands to manage benchmark tasks.
30     '''
31
32     @cliargs("taskfile", type=str, help="path to taskfile", nargs=1)
33     @cliargs("--keep-deploy", help="keep context deployed in cloud",
34              action="store_true")
35     @cliargs("--parse-only", help="parse the benchmark config file and exit",
36              action="store_true")
37     @cliargs("--output-file", help="file where output is stored, default %s" %
38              output_file_default, default=output_file_default)
39     def do_start(self, args):
40         '''Start a benchmark scenario.'''
41
42         atexit.register(atexit_handler)
43
44         parser = TaskParser(args.taskfile[0])
45         scenarios, run_in_parallel = parser.parse()
46
47         if args.parse_only:
48             sys.exit(0)
49
50         for context in Context.list:
51             context.deploy()
52
53         runners = []
54         if run_in_parallel:
55             for scenario in scenarios:
56                 runner = run_one_scenario(scenario, args.output_file)
57                 runners.append(runner)
58
59             # Wait for runners to finish
60             for runner in runners:
61                 runner_join(runner)
62                 print "Runner ended, output in", args.output_file
63         else:
64             # run serially
65             for scenario in scenarios:
66                 runner = run_one_scenario(scenario, args.output_file)
67                 runner_join(runner)
68                 print "Runner ended, output in", args.output_file
69
70         if args.keep_deploy:
71             # keep deployment, forget about stack (hide it for exit handler)
72             Context.list = []
73         else:
74             for context in Context.list:
75                 context.undeploy()
76
77         print "Done, exiting"
78
79
80 # TODO: Move stuff below into TaskCommands class !?
81
82 class TaskParser(object):
83     '''Parser for task config files in yaml format'''
84     def __init__(self, path):
85         self.path = path
86
87     def parse(self):
88         '''parses the task file and return an context and scenario instances'''
89         print "Parsing task config:", self.path
90         try:
91             with open(self.path) as stream:
92                 cfg = yaml.load(stream)
93         except IOError as ioerror:
94             sys.exit(ioerror)
95
96         if cfg["schema"] != "yardstick:task:0.1":
97             sys.exit("error: file %s has unknown schema %s" % (self.path,
98                                                                cfg["schema"]))
99
100         # TODO: support one or many contexts? Many would simpler and precise
101         if "context" in cfg:
102             context_cfgs = [cfg["context"]]
103         else:
104             context_cfgs = cfg["contexts"]
105
106         for cfg_attrs in context_cfgs:
107             context = Context()
108             context.init(cfg_attrs)
109
110         run_in_parallel = cfg.get("run_in_parallel", False)
111
112         # TODO we need something better here, a class that represent the file
113         return cfg["scenarios"], run_in_parallel
114
115
116 def atexit_handler():
117     '''handler for process termination'''
118     base_runner.Runner.terminate_all()
119
120     if len(Context.list) > 0:
121         print "Undeploying all contexts"
122         for context in Context.list:
123             context.undeploy()
124
125
126 def is_ip_addr(addr):
127     '''check if string addr is an IP address'''
128     try:
129         ipaddress.ip_address(unicode(addr))
130         return True
131     except ValueError:
132         return False
133
134
135 def run_one_scenario(scenario_cfg, output_file):
136     '''run one scenario using context'''
137     key_filename = pkg_resources.resource_filename(
138         'yardstick.resources', 'files/yardstick_key')
139
140     host = Context.get_server(scenario_cfg["host"])
141
142     runner_cfg = scenario_cfg["runner"]
143     runner_cfg['host'] = host.public_ip
144     runner_cfg['user'] = host.context.user
145     runner_cfg['key_filename'] = key_filename
146     runner_cfg['output_filename'] = output_file
147
148     if "target" in scenario_cfg:
149         if is_ip_addr(scenario_cfg["target"]):
150             scenario_cfg["ipaddr"] = scenario_cfg["target"]
151         else:
152             target = Context.get_server(scenario_cfg["target"])
153
154             # get public IP for target server, some scenarios require it
155             if target.public_ip:
156                 runner_cfg['target'] = target.public_ip
157
158             # TODO scenario_cfg["ipaddr"] is bad naming
159             if host.context != target.context:
160                 # target is in another context, get its public IP
161                 scenario_cfg["ipaddr"] = target.public_ip
162             else:
163                 # target is in the same context, get its private IP
164                 scenario_cfg["ipaddr"] = target.private_ip
165
166     runner = base_runner.Runner.get(runner_cfg)
167
168     print "Starting runner of type '%s'" % runner_cfg["type"]
169     runner.run(scenario_cfg["type"], scenario_cfg)
170
171     return runner
172
173
174 def runner_join(runner):
175     '''join (wait for) a runner, exit process at runner failure'''
176     status = runner.join()
177     base_runner.Runner.release(runner)
178     if status != 0:
179         sys.exit("Runner failed")