Add new scenario NSPerf-RFC2544
[yardstick.git] / yardstick / benchmark / runners / iteration.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 configurable number of times before it returns
20 """
21
22 from __future__ import absolute_import
23
24 import logging
25 import multiprocessing
26 import traceback
27
28 import os
29
30 from yardstick.benchmark.runners import base
31 from yardstick.common import exceptions as y_exc
32
33 LOG = logging.getLogger(__name__)
34
35
36 QUEUE_PUT_TIMEOUT = 10
37
38
39 def _worker_process(queue, cls, method_name, scenario_cfg,
40                     context_cfg, aborted, output_queue):
41
42     runner_cfg = scenario_cfg['runner']
43
44     interval = runner_cfg.get("interval", 1)
45     iterations = runner_cfg.get("iterations", 1)
46     run_step = runner_cfg.get("run_step", "setup,run,teardown")
47
48     delta = runner_cfg.get("delta", 2)
49     LOG.info("worker START, iterations %d times, class %s", iterations, cls)
50
51     runner_cfg['runner_id'] = os.getpid()
52
53     scenario_output = base.ScenarioOutput(queue, sequence=1, errors="")
54     benchmark = cls(scenario_cfg, context_cfg)
55     if "setup" in run_step:
56         benchmark.setup()
57
58     method = getattr(benchmark, method_name)
59
60     sla_action = None
61     if "sla" in scenario_cfg:
62         sla_action = scenario_cfg["sla"].get("action", "assert")
63     if "run" in run_step:
64         while True:
65
66             LOG.debug("runner=%(runner)s seq=%(sequence)s START",
67                       {"runner": runner_cfg["runner_id"],
68                        "sequence": scenario_output.sequence})
69
70             scenario_output.clear()
71             scenario_output.errors = ""
72             benchmark.pre_run_wait_time(interval)
73
74             try:
75                 result = method(scenario_output)
76             except y_exc.SLAValidationError as error:
77                 # SLA validation failed in scenario, determine what to do now
78                 if sla_action == "assert":
79                     raise
80                 elif sla_action == "monitor":
81                     LOG.warning("SLA validation failed: %s", error.args)
82                     scenario_output.errors = error.args
83                 elif sla_action == "rate-control":
84                     try:
85                         scenario_cfg['options']['rate']
86                     except KeyError:
87                         scenario_cfg.setdefault('options', {})
88                         scenario_cfg['options']['rate'] = 100
89
90                     scenario_cfg['options']['rate'] -= delta
91                     scenario_output.sequence = 1
92                     continue
93             except Exception:  # pylint: disable=broad-except
94                 scenario_output.errors = traceback.format_exc()
95                 LOG.exception("")
96                 raise
97             else:
98                 if result:
99                     # add timeout for put so we don't block test
100                     # if we do timeout we don't care about dropping individual KPIs
101                     output_queue.put(result, True, QUEUE_PUT_TIMEOUT)
102
103             benchmark.post_run_wait_time(interval)
104
105             if scenario_output:
106                 scenario_output.push()
107
108             LOG.debug("runner=%(runner)s seq=%(sequence)s END",
109                       {"runner": runner_cfg["runner_id"],
110                        "sequence": scenario_output.sequence})
111
112             scenario_output.sequence += 1
113
114             if (scenario_output.errors and sla_action is None) or \
115                     (scenario_output.sequence > iterations or aborted.is_set()):
116                 LOG.info("worker END")
117                 break
118     if "teardown" in run_step:
119         try:
120             benchmark.teardown()
121         except Exception:
122             # catch any exception in teardown and convert to simple exception
123             # never pass exceptions back to multiprocessing, because some exceptions can
124             # be unpicklable
125             # https://bugs.python.org/issue9400
126             LOG.exception("")
127             raise SystemExit(1)
128
129     LOG.debug("queue.qsize() = %s", queue.qsize())
130     LOG.debug("output_queue.qsize() = %s", output_queue.qsize())
131
132
133 class IterationRunner(base.Runner):
134     """Run a scenario for a configurable number of times
135
136 If the scenario ends before the time has elapsed, it will be started again.
137
138   Parameters
139     iterations - amount of times the scenario will be run for
140         type:    int
141         unit:    na
142         default: 1
143     interval - time to wait between each scenario invocation
144         type:    int
145         unit:    seconds
146         default: 1 sec
147     """
148     __execution_type__ = 'Iteration'
149
150     def _run_benchmark(self, cls, method, scenario_cfg, context_cfg):
151         name = "{}-{}-{}".format(self.__execution_type__, scenario_cfg.get("type"), os.getpid())
152         self.process = multiprocessing.Process(
153             name=name,
154             target=_worker_process,
155             args=(self.result_queue, cls, method, scenario_cfg,
156                   context_cfg, self.aborted, self.output_queue))
157         self.process.start()