75942766d3e4fa28f7ec2c84adbf757063f6f948
[yardstick.git] / yardstick / benchmark / runners / duration.py
1 # Copyright 2014: Mirantis Inc.
2 # All Rights Reserved.
3 #
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
7 #
8 #         http://www.apache.org/licenses/LICENSE-2.0
9 #
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
14 #    under the License.
15
16 # yardstick comment: this is a modified copy of
17 # rally/rally/benchmark/runners/constant.py
18
19 """A runner that runs a specific time before it returns
20 """
21
22 from __future__ import absolute_import
23 import os
24 import multiprocessing
25 import logging
26 import traceback
27 import time
28
29 from yardstick.benchmark.runners import base
30
31 LOG = logging.getLogger(__name__)
32
33
34 def _worker_process(queue, cls, method_name, scenario_cfg,
35                     context_cfg, aborted, output_queue):
36
37     sequence = 1
38
39     runner_cfg = scenario_cfg['runner']
40
41     interval = runner_cfg.get("interval", 1)
42     duration = runner_cfg.get("duration", 60)
43     LOG.info("Worker START, duration is %ds", duration)
44     LOG.debug("class is %s", cls)
45
46     runner_cfg['runner_id'] = os.getpid()
47
48     benchmark = cls(scenario_cfg, context_cfg)
49     benchmark.setup()
50     method = getattr(benchmark, method_name)
51
52     sla_action = None
53     if "sla" in scenario_cfg:
54         sla_action = scenario_cfg["sla"].get("action", "assert")
55
56     start = time.time()
57     timeout = start + duration
58     while True:
59
60         LOG.debug("runner=%(runner)s seq=%(sequence)s START",
61                   {"runner": runner_cfg["runner_id"], "sequence": sequence})
62
63         data = {}
64         errors = ""
65
66         try:
67             result = method(data)
68         except AssertionError as assertion:
69             # SLA validation failed in scenario, determine what to do now
70             if sla_action == "assert":
71                 raise
72             elif sla_action == "monitor":
73                 LOG.warning("SLA validation failed: %s", assertion.args)
74                 errors = assertion.args
75         # catch all exceptions because with multiprocessing we can have un-picklable exception
76         # problems  https://bugs.python.org/issue9400
77         except Exception:
78             errors = traceback.format_exc()
79             LOG.exception("")
80         else:
81             if result:
82                 output_queue.put(result)
83
84         time.sleep(interval)
85
86         benchmark_output = {
87             'timestamp': time.time(),
88             'sequence': sequence,
89             'data': data,
90             'errors': errors
91         }
92
93         queue.put(benchmark_output)
94
95         LOG.debug("runner=%(runner)s seq=%(sequence)s END",
96                   {"runner": runner_cfg["runner_id"], "sequence": sequence})
97
98         sequence += 1
99
100         if (errors and sla_action is None) or time.time() > timeout or aborted.is_set():
101             LOG.info("Worker END")
102             break
103
104     try:
105         benchmark.teardown()
106     except Exception:
107         # catch any exception in teardown and convert to simple exception
108         # never pass exceptions back to multiprocessing, because some exceptions can
109         # be unpicklable
110         # https://bugs.python.org/issue9400
111         LOG.exception("")
112         raise SystemExit(1)
113
114     LOG.debug("queue.qsize() = %s", queue.qsize())
115     LOG.debug("output_queue.qsize() = %s", output_queue.qsize())
116
117
118 class DurationRunner(base.Runner):
119     """Run a scenario for a certain amount of time
120
121 If the scenario ends before the time has elapsed, it will be started again.
122
123   Parameters
124     duration - amount of time the scenario will be run for
125         type:    int
126         unit:    seconds
127         default: 1 sec
128     interval - time to wait between each scenario invocation
129         type:    int
130         unit:    seconds
131         default: 1 sec
132     """
133     __execution_type__ = 'Duration'
134
135     def _run_benchmark(self, cls, method, scenario_cfg, context_cfg):
136         self.process = multiprocessing.Process(
137             target=_worker_process,
138             args=(self.result_queue, cls, method, scenario_cfg,
139                   context_cfg, self.aborted, self.output_queue))
140         self.process.start()