Merge "Implement Virtual Switch resilience test case"
[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 QUEUE_PUT_TIMEOUT = 10
35
36
37 def _worker_process(queue, cls, method_name, scenario_cfg,
38                     context_cfg, aborted, output_queue):
39
40     sequence = 1
41
42     runner_cfg = scenario_cfg['runner']
43
44     interval = runner_cfg.get("interval", 1)
45     duration = runner_cfg.get("duration", 60)
46     LOG.info("Worker START, duration is %ds", duration)
47     LOG.debug("class is %s", cls)
48
49     runner_cfg['runner_id'] = os.getpid()
50
51     benchmark = cls(scenario_cfg, context_cfg)
52     benchmark.setup()
53     method = getattr(benchmark, method_name)
54
55     sla_action = None
56     if "sla" in scenario_cfg:
57         sla_action = scenario_cfg["sla"].get("action", "assert")
58
59     start = time.time()
60     timeout = start + duration
61     while True:
62
63         LOG.debug("runner=%(runner)s seq=%(sequence)s START",
64                   {"runner": runner_cfg["runner_id"], "sequence": sequence})
65
66         data = {}
67         errors = ""
68
69         benchmark.pre_run_wait_time(interval)
70
71         try:
72             result = method(data)
73         except AssertionError as assertion:
74             # SLA validation failed in scenario, determine what to do now
75             if sla_action == "assert":
76                 raise
77             elif sla_action == "monitor":
78                 LOG.warning("SLA validation failed: %s", assertion.args)
79                 errors = assertion.args
80         # catch all exceptions because with multiprocessing we can have un-picklable exception
81         # problems  https://bugs.python.org/issue9400
82         except Exception:  # pylint: disable=broad-except
83             errors = traceback.format_exc()
84             LOG.exception("")
85         else:
86             if result:
87                 # add timeout for put so we don't block test
88                 # if we do timeout we don't care about dropping individual KPIs
89                 output_queue.put(result, True, QUEUE_PUT_TIMEOUT)
90
91         benchmark.post_run_wait_time(interval)
92
93         benchmark_output = {
94             'timestamp': time.time(),
95             'sequence': sequence,
96             'data': data,
97             'errors': errors
98         }
99
100         queue.put(benchmark_output, True, QUEUE_PUT_TIMEOUT)
101
102         LOG.debug("runner=%(runner)s seq=%(sequence)s END",
103                   {"runner": runner_cfg["runner_id"], "sequence": sequence})
104
105         sequence += 1
106
107         if (errors and sla_action is None) or time.time() > timeout or aborted.is_set():
108             LOG.info("Worker END")
109             break
110
111     try:
112         benchmark.teardown()
113     except Exception:
114         # catch any exception in teardown and convert to simple exception
115         # never pass exceptions back to multiprocessing, because some exceptions can
116         # be unpicklable
117         # https://bugs.python.org/issue9400
118         LOG.exception("")
119         raise SystemExit(1)
120
121     LOG.debug("queue.qsize() = %s", queue.qsize())
122     LOG.debug("output_queue.qsize() = %s", output_queue.qsize())
123
124
125 class DurationRunner(base.Runner):
126     """Run a scenario for a certain amount of time
127
128 If the scenario ends before the time has elapsed, it will be started again.
129
130   Parameters
131     duration - amount of time the scenario will be run for
132         type:    int
133         unit:    seconds
134         default: 1 sec
135     interval - time to wait between each scenario invocation
136         type:    int
137         unit:    seconds
138         default: 1 sec
139     """
140     __execution_type__ = 'Duration'
141
142     def _run_benchmark(self, cls, method, scenario_cfg, context_cfg):
143         name = "{}-{}-{}".format(self.__execution_type__, scenario_cfg.get("type"), os.getpid())
144         self.process = multiprocessing.Process(
145             name=name,
146             target=_worker_process,
147             args=(self.result_queue, cls, method, scenario_cfg,
148                   context_cfg, self.aborted, self.output_queue))
149         self.process.start()