974fb21b371c7209396e0d9abab0d5eee2d223d3
[yardstick.git] / yardstick / benchmark / runners / arithmetic.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 every run arithmetically steps specified input value(s) to
20 the scenario. This just means step value(s) is added to the previous value(s).
21 It is possible to combine several named input values and run with those either
22 as nested for loops or combine each i:th index of each "input value list"
23 until the end of the shortest list is reached (optimally all lists should be
24 defined with the same number of values when using such iter_type).
25 """
26
27 from __future__ import absolute_import
28
29 import itertools
30 import logging
31 import multiprocessing
32 import os
33 import time
34 import traceback
35
36 import six
37 from six.moves import range
38
39 from yardstick.benchmark.runners import base
40
41 LOG = logging.getLogger(__name__)
42
43
44 def _worker_process(queue, cls, method_name, scenario_cfg,
45                     context_cfg, aborted, output_queue):
46
47     sequence = 1
48
49     # if we don't do this we can hang waiting for the queue to drain
50     # have to do this in the subprocess
51     queue.cancel_join_thread()
52     output_queue.cancel_join_thread()
53
54     runner_cfg = scenario_cfg['runner']
55
56     interval = runner_cfg.get("interval", 1)
57     if 'options' in scenario_cfg:
58         options = scenario_cfg['options']
59     else:  # options must be instatiated if not present in yaml
60         options = {}
61         scenario_cfg['options'] = options
62
63     runner_cfg['runner_id'] = os.getpid()
64
65     LOG.info("worker START, class %s", cls)
66
67     benchmark = cls(scenario_cfg, context_cfg)
68     benchmark.setup()
69     method = getattr(benchmark, method_name)
70
71     sla_action = None
72     if "sla" in scenario_cfg:
73         sla_action = scenario_cfg["sla"].get("action", "assert")
74
75     # To both be able to include the stop value and handle backwards stepping
76     def margin(start, stop):
77         return -1 if start > stop else 1
78
79     param_iters = \
80         [range(d['start'], d['stop'] + margin(d['start'], d['stop']),
81                d['step']) for d in runner_cfg['iterators']]
82     param_names = [d['name'] for d in runner_cfg['iterators']]
83
84     iter_type = runner_cfg.get("iter_type", "nested_for_loops")
85
86     if iter_type == 'nested_for_loops':
87         # Create a complete combination set of all parameter lists
88         loop_iter = itertools.product(*param_iters)
89     elif iter_type == 'tuple_loops':
90         # Combine each i;th index of respective parameter list
91         loop_iter = six.moves.zip(*param_iters)
92     else:
93         LOG.warning("iter_type unrecognized: %s", iter_type)
94         raise TypeError("iter_type unrecognized: %s", iter_type)
95
96     # Populate options and run the requested method for each value combination
97     for comb_values in loop_iter:
98
99         if aborted.is_set():
100             break
101
102         LOG.debug("runner=%(runner)s seq=%(sequence)s START",
103                   {"runner": runner_cfg["runner_id"], "sequence": sequence})
104
105         for i, value in enumerate(comb_values):
106             options[param_names[i]] = value
107
108         data = {}
109         errors = ""
110
111         try:
112             result = method(data)
113         except AssertionError as assertion:
114             # SLA validation failed in scenario, determine what to do now
115             if sla_action == "assert":
116                 raise
117             elif sla_action == "monitor":
118                 LOG.warning("SLA validation failed: %s", assertion.args)
119                 errors = assertion.args
120         except Exception as e:
121             errors = traceback.format_exc()
122             LOG.exception(e)
123         else:
124             if result:
125                 output_queue.put(result)
126
127         time.sleep(interval)
128
129         benchmark_output = {
130             'timestamp': time.time(),
131             'sequence': sequence,
132             'data': data,
133             'errors': errors
134         }
135
136         queue.put(benchmark_output)
137
138         LOG.debug("runner=%(runner)s seq=%(sequence)s END",
139                   {"runner": runner_cfg["runner_id"], "sequence": sequence})
140
141         sequence += 1
142
143         if errors and sla_action is None:
144             break
145
146     benchmark.teardown()
147     LOG.info("worker END")
148
149
150 class ArithmeticRunner(base.Runner):
151     """Run a scenario arithmetically stepping input value(s)
152
153   Parameters
154     interval - time to wait between each scenario invocation
155         type:    int
156         unit:    seconds
157         default: 1 sec
158     iter_type: - Iteration type of input parameter(s): nested_for_loops
159                  or tuple_loops
160         type:    string
161         unit:    na
162         default: nested_for_loops
163     -
164       name - name of scenario option that will be increased for each invocation
165           type:    string
166           unit:    na
167           default: na
168       start - value to use in first invocation of scenario
169           type:    int
170           unit:    na
171           default: none
172       stop - value indicating end of invocation. Can be set to same
173              value as start for one single value.
174           type:    int
175           unit:    na
176           default: none
177       step - value added to start value in next invocation of scenario.
178              Must not be set to zero. Can be set negative if start > stop
179           type:    int
180           unit:    na
181           default: none
182     -
183       name - and so on......
184     """
185
186     __execution_type__ = 'Arithmetic'
187
188     def _run_benchmark(self, cls, method, scenario_cfg, context_cfg):
189         self.process = multiprocessing.Process(
190             target=_worker_process,
191             args=(self.result_queue, cls, method, scenario_cfg,
192                   context_cfg, self.aborted, self.output_queue))
193         self.process.start()