1 # Copyright 2014: Mirantis Inc.
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
16 # yardstick comment: this is a modified copy of
17 # rally/rally/benchmark/runners/base.py
19 from __future__ import absolute_import
22 import multiprocessing
27 from oslo_config import cfg
29 import yardstick.common.utils as utils
30 from yardstick.benchmark.scenarios import base as base_scenario
31 from yardstick.dispatcher.base import Base as DispatcherBase
33 log = logging.getLogger(__name__)
38 def _output_serializer_main(filename, queue, config):
39 """entrypoint for the singleton subprocess writing to outfile
40 Use of this process enables multiple instances of a scenario without
41 messing up the output file.
43 out_type = config['yardstick'].get('DEFAULT', {}).get('dispatcher', 'file')
45 'type': out_type.capitalize(),
49 dispatcher = DispatcherBase.get(conf, config)
52 # blocks until data becomes available
54 if record == '_TERMINATE_':
55 dispatcher.flush_result_data()
58 dispatcher.record_result_data(record)
61 def _execute_shell_command(command):
62 """execute shell script with error handling"""
66 output = subprocess.check_output(command, shell=True)
69 output = traceback.format_exc()
70 log.error("exec command '%s' error:\n ", command)
71 log.error(traceback.format_exc())
73 return exitcode, output
76 def _single_action(seconds, command, queue):
77 """entrypoint for the single action process"""
78 log.debug("single action, fires after %d seconds (from now)", seconds)
80 log.debug("single action: executing command: '%s'", command)
81 ret_code, data = _execute_shell_command(command)
83 log.error("single action error! command:%s", command)
84 queue.put({'single-action-data': data})
86 log.debug("single action data: \n%s", data)
87 queue.put({'single-action-data': data})
90 def _periodic_action(interval, command, queue):
91 """entrypoint for the periodic action process"""
92 log.debug("periodic action, fires every: %d seconds", interval)
96 time_spent += interval
97 log.debug("periodic action, executing command: '%s'", command)
98 ret_code, data = _execute_shell_command(command)
100 log.error("periodic action error! command:%s", command)
101 queue.put({'periodic-action-data': data})
103 log.debug("periodic action data: \n%s", data)
104 queue.put({'periodic-action-data': data})
107 class Runner(object):
113 def get_cls(runner_type):
114 """return class of specified type"""
115 for runner in utils.itersubclasses(Runner):
116 if runner_type == runner.__execution_type__:
118 raise RuntimeError("No such runner_type %s" % runner_type)
122 """return a list of known runner type (class) names"""
124 for runner in utils.itersubclasses(Runner):
129 def get(runner_cfg, config):
130 """Returns instance of a scenario runner for execution type.
132 # if there is no runner, start the output serializer subprocess
133 if not Runner.runners:
134 log.debug("Starting dump process file '%s'",
135 runner_cfg["output_filename"])
136 Runner.queue = multiprocessing.Queue()
137 Runner.dump_process = multiprocessing.Process(
138 target=_output_serializer_main,
140 args=(runner_cfg["output_filename"], Runner.queue, config))
141 Runner.dump_process.start()
143 return Runner.get_cls(runner_cfg["type"])(runner_cfg, Runner.queue)
146 def release_dump_process():
147 """Release the dumper process"""
148 log.debug("Stopping dump process")
149 if Runner.dump_process:
150 Runner.queue.put('_TERMINATE_')
151 Runner.dump_process.join()
152 Runner.dump_process = None
156 """Release the runner"""
157 if runner in Runner.runners:
158 Runner.runners.remove(runner)
160 # if this was the last runner, stop the output serializer subprocess
161 if not Runner.runners:
162 Runner.release_dump_process()
165 def terminate(runner):
166 """Terminate the runner"""
167 if runner.process and runner.process.is_alive():
168 runner.process.terminate()
172 """Terminate all runners (subprocesses)"""
173 log.debug("Terminating all runners")
175 # release dumper process as some errors before any runner is created
176 if not Runner.runners:
177 Runner.release_dump_process()
180 for runner in Runner.runners:
181 log.debug("Terminating runner: %s", runner)
183 runner.process.terminate()
184 runner.process.join()
185 if runner.periodic_action_process:
186 log.debug("Terminating periodic action process")
187 runner.periodic_action_process.terminate()
188 runner.periodic_action_process = None
189 Runner.release(runner)
191 def __init__(self, config, queue):
193 self.periodic_action_process = None
194 self.result_queue = queue
196 self.aborted = multiprocessing.Event()
197 Runner.runners.append(self)
199 def run_post_stop_action(self):
200 """run a potentially configured post-stop action"""
201 if "post-stop-action" in self.config:
202 command = self.config["post-stop-action"]["command"]
203 log.debug("post stop action: command: '%s'", command)
204 ret_code, data = _execute_shell_command(command)
206 log.error("post action error! command:%s", command)
207 self.result_queue.put({'post-stop-action-data': data})
209 log.debug("post-stop data: \n%s", data)
210 self.result_queue.put({'post-stop-action-data': data})
212 def run(self, scenario_cfg, context_cfg):
213 scenario_type = scenario_cfg["type"]
214 class_name = base_scenario.Scenario.get(scenario_type)
215 path_split = class_name.split(".")
216 module_path = ".".join(path_split[:-1])
217 module = importlib.import_module(module_path)
218 cls = getattr(module, path_split[-1])
220 self.config['object'] = class_name
223 # run a potentially configured pre-start action
224 if "pre-start-action" in self.config:
225 command = self.config["pre-start-action"]["command"]
226 log.debug("pre start action: command: '%s'", command)
227 ret_code, data = _execute_shell_command(command)
229 log.error("pre-start action error! command:%s", command)
230 self.result_queue.put({'pre-start-action-data': data})
232 log.debug("pre-start data: \n%s", data)
233 self.result_queue.put({'pre-start-action-data': data})
235 if "single-shot-action" in self.config:
236 single_action_process = multiprocessing.Process(
237 target=_single_action,
238 name="single-shot-action",
239 args=(self.config["single-shot-action"]["after"],
240 self.config["single-shot-action"]["command"],
242 single_action_process.start()
244 if "periodic-action" in self.config:
245 self.periodic_action_process = multiprocessing.Process(
246 target=_periodic_action,
247 name="periodic-action",
248 args=(self.config["periodic-action"]["interval"],
249 self.config["periodic-action"]["command"],
251 self.periodic_action_process.start()
253 self._run_benchmark(cls, "run", scenario_cfg, context_cfg)
256 """Abort the execution of a scenario"""
259 def join(self, timeout=None):
260 self.process.join(timeout)
261 if self.periodic_action_process:
262 self.periodic_action_process.terminate()
263 self.periodic_action_process = None
265 self.run_post_stop_action()
266 return self.process.exitcode