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
29 from six.moves.queue import Empty
31 import yardstick.common.utils as utils
32 from yardstick.benchmark.scenarios import base as base_scenario
34 log = logging.getLogger(__name__)
37 def _execute_shell_command(command):
38 """execute shell script with error handling"""
41 output = subprocess.check_output(command, shell=True)
44 output = traceback.format_exc()
45 log.error("exec command '%s' error:\n ", command)
46 log.error(traceback.format_exc())
48 return exitcode, output
51 def _single_action(seconds, command, queue):
52 """entrypoint for the single action process"""
53 log.debug("single action, fires after %d seconds (from now)", seconds)
55 log.debug("single action: executing command: '%s'", command)
56 ret_code, data = _execute_shell_command(command)
58 log.error("single action error! command:%s", command)
59 queue.put({'single-action-data': data})
61 log.debug("single action data: \n%s", data)
62 queue.put({'single-action-data': data})
65 def _periodic_action(interval, command, queue):
66 """entrypoint for the periodic action process"""
67 log.debug("periodic action, fires every: %d seconds", interval)
71 time_spent += interval
72 log.debug("periodic action, executing command: '%s'", command)
73 ret_code, data = _execute_shell_command(command)
75 log.error("periodic action error! command:%s", command)
76 queue.put({'periodic-action-data': data})
78 log.debug("periodic action data: \n%s", data)
79 queue.put({'periodic-action-data': data})
86 def get_cls(runner_type):
87 """return class of specified type"""
88 for runner in utils.itersubclasses(Runner):
89 if runner_type == runner.__execution_type__:
91 raise RuntimeError("No such runner_type %s" % runner_type)
95 """return a list of known runner type (class) names"""
97 for runner in utils.itersubclasses(Runner):
103 """Returns instance of a scenario runner for execution type.
105 return Runner.get_cls(runner_cfg["type"])(runner_cfg)
109 """Release the runner"""
110 if runner in Runner.runners:
111 Runner.runners.remove(runner)
114 def terminate(runner):
115 """Terminate the runner"""
116 if runner.process and runner.process.is_alive():
117 runner.process.terminate()
121 """Terminate all runners (subprocesses)"""
122 log.debug("Terminating all runners", exc_info=True)
124 # release dumper process as some errors before any runner is created
125 if not Runner.runners:
128 for runner in Runner.runners:
129 log.debug("Terminating runner: %s", runner)
131 runner.process.terminate()
132 runner.process.join()
133 if runner.periodic_action_process:
134 log.debug("Terminating periodic action process")
135 runner.periodic_action_process.terminate()
136 runner.periodic_action_process = None
137 Runner.release(runner)
139 def __init__(self, config):
141 self.periodic_action_process = None
142 self.output_queue = multiprocessing.Queue()
143 self.result_queue = multiprocessing.Queue()
145 self.aborted = multiprocessing.Event()
146 Runner.runners.append(self)
148 def run_post_stop_action(self):
149 """run a potentially configured post-stop action"""
150 if "post-stop-action" in self.config:
151 command = self.config["post-stop-action"]["command"]
152 log.debug("post stop action: command: '%s'", command)
153 ret_code, data = _execute_shell_command(command)
155 log.error("post action error! command:%s", command)
156 self.result_queue.put({'post-stop-action-data': data})
158 log.debug("post-stop data: \n%s", data)
159 self.result_queue.put({'post-stop-action-data': data})
161 def _run_benchmark(self, cls, method_name, scenario_cfg, context_cfg):
162 raise NotImplementedError
164 def run(self, scenario_cfg, context_cfg):
165 scenario_type = scenario_cfg["type"]
166 class_name = base_scenario.Scenario.get(scenario_type)
167 path_split = class_name.split(".")
168 module_path = ".".join(path_split[:-1])
169 module = importlib.import_module(module_path)
170 cls = getattr(module, path_split[-1])
172 self.config['object'] = class_name
175 # run a potentially configured pre-start action
176 if "pre-start-action" in self.config:
177 command = self.config["pre-start-action"]["command"]
178 log.debug("pre start action: command: '%s'", command)
179 ret_code, data = _execute_shell_command(command)
181 log.error("pre-start action error! command:%s", command)
182 self.result_queue.put({'pre-start-action-data': data})
184 log.debug("pre-start data: \n%s", data)
185 self.result_queue.put({'pre-start-action-data': data})
187 if "single-shot-action" in self.config:
188 single_action_process = multiprocessing.Process(
189 target=_single_action,
190 name="single-shot-action",
191 args=(self.config["single-shot-action"]["after"],
192 self.config["single-shot-action"]["command"],
194 single_action_process.start()
196 if "periodic-action" in self.config:
197 self.periodic_action_process = multiprocessing.Process(
198 target=_periodic_action,
199 name="periodic-action",
200 args=(self.config["periodic-action"]["interval"],
201 self.config["periodic-action"]["command"],
203 self.periodic_action_process.start()
205 self._run_benchmark(cls, "run", scenario_cfg, context_cfg)
208 """Abort the execution of a scenario"""
211 QUEUE_JOIN_INTERVAL = 5
213 def join(self, outputs, result, interval=QUEUE_JOIN_INTERVAL):
214 while self.process.exitcode is None:
215 # drain the queue while we are running otherwise we won't terminate
216 outputs.update(self.get_output())
217 result.extend(self.get_result())
218 self.process.join(interval)
219 # drain after the process has exited
220 outputs.update(self.get_output())
221 result.extend(self.get_result())
223 self.process.terminate()
224 if self.periodic_action_process:
225 self.periodic_action_process.join(1)
226 self.periodic_action_process.terminate()
227 self.periodic_action_process = None
229 self.run_post_stop_action()
230 return self.process.exitcode
232 def get_output(self):
234 while not self.output_queue.empty():
235 log.debug("output_queue size %s", self.output_queue.qsize())
237 result.update(self.output_queue.get(True, 1))
242 def get_result(self):
244 while not self.result_queue.empty():
245 log.debug("result_queue size %s", self.result_queue.qsize())
247 result.append(self.result_queue.get(True, 1))