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