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