Heat context code refactor part 2
[yardstick.git] / yardstick / benchmark / scenarios / compute / perf.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 import pkg_resources
10 import logging
11 import json
12
13 import yardstick.ssh as ssh
14 from yardstick.benchmark.scenarios import base
15
16 LOG = logging.getLogger(__name__)
17
18
19 class Perf(base.Scenario):
20     """Execute perf benchmark in a host
21
22   Parameters
23     events - perf tool software, hardware or tracepoint events
24         type:       [str]
25         unit:       na
26         default:    ['task-clock']
27     load - simulate load on the host by doing IO operations
28         type:       bool
29         unit:       na
30         default:    false
31
32     For more info about perf and perf events see https://perf.wiki.kernel.org
33     """
34
35     __scenario_type__ = "Perf"
36
37     TARGET_SCRIPT = 'perf_benchmark.bash'
38
39     def __init__(self, scenario_cfg, context_cfg):
40         self.scenario_cfg = scenario_cfg
41         self.context_cfg = context_cfg
42         self.setup_done = False
43
44     def setup(self):
45         """scenario setup"""
46         self.target_script = pkg_resources.resource_filename(
47             'yardstick.benchmark.scenarios.compute', Perf.TARGET_SCRIPT)
48         host = self.context_cfg['host']
49         user = host.get('user', 'ubuntu')
50         ip = host.get('ip', None)
51         key_filename = host.get('key_filename', '~/.ssh/id_rsa')
52
53         LOG.info("user:%s, host:%s", user, ip)
54         self.client = ssh.SSH(user, ip, key_filename=key_filename)
55         self.client.wait(timeout=600)
56
57         # copy script to host
58         self.client.run("cat > ~/perf_benchmark.sh",
59                         stdin=open(self.target_script, "rb"))
60
61         self.setup_done = True
62
63     def run(self, result):
64         """execute the benchmark"""
65
66         if not self.setup_done:
67             self.setup()
68
69         options = self.scenario_cfg['options']
70         events = options.get('events', ['task-clock'])
71
72         events_string = ""
73         for event in events:
74             events_string += event + " "
75
76         # if run by a duration runner
77         duration_time = self.scenario_cfg["runner"].get("duration", None) \
78             if "runner" in self.scenario_cfg else None
79         # if run by an arithmetic runner
80         arithmetic_time = options.get("duration", None)
81         if duration_time:
82             duration = duration_time
83         elif arithmetic_time:
84             duration = arithmetic_time
85         else:
86             duration = 30
87
88         if 'load' in options:
89             load = "dd if=/dev/urandom of=/dev/null"
90         else:
91             load = "sleep %d" % duration
92
93         cmd = "sudo bash perf_benchmark.sh '%s' %d %s" \
94             % (load, duration, events_string)
95
96         LOG.debug("Executing command: %s", cmd)
97         status, stdout, stderr = self.client.execute(cmd)
98
99         if status:
100             raise RuntimeError(stdout)
101
102         result.update(json.loads(stdout))
103
104         if "sla" in self.scenario_cfg:
105             metric = self.scenario_cfg['sla']['metric']
106             exp_val = self.scenario_cfg['sla']['expected_value']
107             smaller_than_exp = 'smaller_than_expected' \
108                                in self.scenario_cfg['sla']
109
110             if metric not in result:
111                 assert False, "Metric (%s) not found." % metric
112             else:
113                 if smaller_than_exp:
114                     assert result[metric] < exp_val, "%s %d >= %d (sla); " \
115                         % (metric, result[metric], exp_val)
116                 else:
117                     assert result[metric] >= exp_val, "%s %d < %d (sla); " \
118                         % (metric, result[metric], exp_val)
119
120
121 def _test():
122     """internal test function"""
123     key_filename = pkg_resources.resource_filename('yardstick.resources',
124                                                    'files/yardstick_key')
125     ctx = {
126         'host': {
127             'ip': '10.229.47.137',
128             'user': 'root',
129             'key_filename': key_filename
130         }
131     }
132
133     logger = logging.getLogger('yardstick')
134     logger.setLevel(logging.DEBUG)
135
136     options = {'load': True}
137     args = {'options': options}
138     result = {}
139
140     p = Perf(args, ctx)
141     p.run(result)
142     print result
143
144 if __name__ == '__main__':
145     _test()