cc8c93cb6d3d6053cb043400a345f4000f3ed1b5
[yardstick.git] / yardstick / benchmark / runners / base.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 import importlib
11 import logging
12 import multiprocessing
13 import subprocess
14 import time
15 import traceback
16
17 log = logging.getLogger(__name__)
18
19 from oslo_config import cfg
20
21 import yardstick.common.utils as utils
22 from yardstick.benchmark.scenarios import base as base_scenario
23 from yardstick.dispatcher.base import Base as DispatcherBase
24
25 CONF = cfg.CONF
26
27
28 def _output_serializer_main(filename, queue):
29     '''entrypoint for the singleton subprocess writing to outfile
30     Use of this process enables multiple instances of a scenario without
31     messing up the output file.
32     '''
33     config = {}
34     config["type"] = CONF.dispatcher.capitalize()
35     config["file_path"] = filename
36     dispatcher = DispatcherBase.get(config)
37
38     while True:
39         # blocks until data becomes available
40         record = queue.get()
41         if record == '_TERMINATE_':
42             dispatcher.flush_result_data()
43             break
44         else:
45             dispatcher.record_result_data(record)
46
47
48 def _execute_shell_command(command):
49     '''execute shell script with error handling'''
50     exitcode = 0
51     output = []
52     try:
53         output = subprocess.check_output(command, shell=True)
54     except Exception:
55         exitcode = -1
56         output = traceback.format_exc()
57         log.error("exec command '%s' error:\n " % command)
58         log.error(traceback.format_exc())
59
60     return exitcode, output
61
62
63 def _single_action(seconds, command, queue):
64     '''entrypoint for the single action process'''
65     log.debug("single action, fires after %d seconds (from now)", seconds)
66     time.sleep(seconds)
67     log.debug("single action: executing command: '%s'", command)
68     ret_code, data = _execute_shell_command(command)
69     if ret_code < 0:
70         log.error("single action error! command:%s" % command)
71         queue.put({'single-action-data': data})
72         return
73     log.debug("single action data: \n%s" % data)
74     queue.put({'single-action-data': data})
75
76
77 def _periodic_action(interval, command, queue):
78     '''entrypoint for the periodic action process'''
79     log.debug("periodic action, fires every: %d seconds", interval)
80     time_spent = 0
81     while True:
82         time.sleep(interval)
83         time_spent += interval
84         log.debug("periodic action, executing command: '%s'", command)
85         ret_code, data = _execute_shell_command(command)
86         if ret_code < 0:
87             log.error("periodic action error! command:%s", command)
88             queue.put({'periodic-action-data': data})
89             break
90         log.debug("periodic action data: \n%s" % data)
91         queue.put({'periodic-action-data': data})
92
93
94 class Runner(object):
95     queue = None
96     dump_process = None
97     runners = []
98
99     @staticmethod
100     def get_cls(runner_type):
101         '''return class of specified type'''
102         for runner in utils.itersubclasses(Runner):
103             if runner_type == runner.__execution_type__:
104                 return runner
105         raise RuntimeError("No such runner_type %s" % runner_type)
106
107     @staticmethod
108     def get_types():
109         '''return a list of known runner type (class) names'''
110         types = []
111         for runner in utils.itersubclasses(Runner):
112             types.append(runner)
113         return types
114
115     @staticmethod
116     def get(config):
117         """Returns instance of a scenario runner for execution type.
118         """
119         # if there is no runner, start the output serializer subprocess
120         if len(Runner.runners) == 0:
121             log.debug("Starting dump process file '%s'" %
122                       config["output_filename"])
123             Runner.queue = multiprocessing.Queue()
124             Runner.dump_process = multiprocessing.Process(
125                 target=_output_serializer_main,
126                 name="Dumper",
127                 args=(config["output_filename"], Runner.queue))
128             Runner.dump_process.start()
129
130         return Runner.get_cls(config["type"])(config, Runner.queue)
131
132     @staticmethod
133     def release_dump_process():
134         '''Release the dumper process'''
135         log.debug("Stopping dump process")
136         if Runner.dump_process:
137             Runner.queue.put('_TERMINATE_')
138             Runner.dump_process.join()
139             Runner.dump_process = None
140
141     @staticmethod
142     def release(runner):
143         '''Release the runner'''
144         Runner.runners.remove(runner)
145
146         # if this was the last runner, stop the output serializer subprocess
147         if len(Runner.runners) == 0:
148             Runner.release_dump_process()
149
150     @staticmethod
151     def terminate_all():
152         '''Terminate all runners (subprocesses)'''
153         log.debug("Terminating all runners")
154
155         # release dumper process as some errors before any runner is created
156         if len(Runner.runners) == 0:
157             Runner.release_dump_process()
158             return
159
160         for runner in Runner.runners:
161             log.debug("Terminating runner: %s", runner)
162             if runner.process:
163                 runner.process.terminate()
164                 runner.process.join()
165             if runner.periodic_action_process:
166                 log.debug("Terminating periodic action process")
167                 runner.periodic_action_process.terminate()
168                 runner.periodic_action_process = None
169             Runner.release(runner)
170
171     def __init__(self, config, queue):
172         self.context = {}
173         self.config = config
174         self.periodic_action_process = None
175         self.result_queue = queue
176         self.process = None
177         Runner.runners.append(self)
178
179     def run_post_stop_action(self):
180         '''run a potentially configured post-stop action'''
181         if "post-stop-action" in self.config:
182             command = self.config["post-stop-action"]["command"]
183             log.debug("post stop action: command: '%s'" % command)
184             ret_code, data = _execute_shell_command(command)
185             if ret_code < 0:
186                 log.error("post action error! command:%s", command)
187                 self.result_queue.put({'post-stop-action-data': data})
188                 return
189             log.debug("post-stop data: \n%s" % data)
190             self.result_queue.put({'post-stop-action-data': data})
191
192     def run(self, scenario_type, scenario_cfg):
193         class_name = base_scenario.Scenario.get(scenario_type)
194         path_split = class_name.split(".")
195         module_path = ".".join(path_split[:-1])
196         module = importlib.import_module(module_path)
197         cls = getattr(module, path_split[-1])
198
199         self.config['object'] = class_name
200
201         # run a potentially configured pre-start action
202         if "pre-start-action" in self.config:
203             command = self.config["pre-start-action"]["command"]
204             log.debug("pre start action: command: '%s'" % command)
205             ret_code, data = _execute_shell_command(command)
206             if ret_code < 0:
207                 log.error("pre-start action error! command:%s", command)
208                 self.result_queue.put({'pre-start-action-data': data})
209                 return
210             log.debug("pre-start data: \n%s" % data)
211             self.result_queue.put({'pre-start-action-data': data})
212
213         if "single-shot-action" in self.config:
214             single_action_process = multiprocessing.Process(
215                 target=_single_action,
216                 name="single-shot-action",
217                 args=(self.config["single-shot-action"]["after"],
218                       self.config["single-shot-action"]["command"],
219                       self.result_queue))
220             single_action_process.start()
221
222         if "periodic-action" in self.config:
223             self.periodic_action_process = multiprocessing.Process(
224                 target=_periodic_action,
225                 name="periodic-action",
226                 args=(self.config["periodic-action"]["interval"],
227                       self.config["periodic-action"]["command"],
228                       self.result_queue))
229             self.periodic_action_process.start()
230
231         self._run_benchmark(cls, "run", scenario_cfg)
232
233     def join(self):
234         self.process.join()
235         if self.periodic_action_process:
236             self.periodic_action_process.terminate()
237             self.periodic_action_process = None
238
239         self.run_post_stop_action()
240         return self.process.exitcode