Heat context code refactor part 2
[yardstick.git] / yardstick / benchmark / scenarios / networking / iperf3.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
10 # iperf3 scenario
11 # iperf3 homepage at: http://software.es.net/iperf/
12
13 import logging
14 import json
15 import pkg_resources
16
17 import yardstick.ssh as ssh
18 from yardstick.benchmark.scenarios import base
19
20 LOG = logging.getLogger(__name__)
21
22
23 class Iperf(base.Scenario):
24     """Execute iperf3 between two hosts
25
26 By default TCP is used but UDP can also be configured.
27 For more info see http://software.es.net/iperf
28
29   Parameters
30     bytes - number of bytes to transmit
31       only valid with a non duration runner, mutually exclusive with blockcount
32         type:    int
33         unit:    bytes
34         default: 56
35     udp - use UDP rather than TCP
36         type:    bool
37         unit:    na
38         default: false
39     nodelay - set TCP no delay, disabling Nagle's Algorithm
40         type:    bool
41         unit:    na
42         default: false
43     blockcount - number of blocks (packets) to transmit,
44       only valid with a non duration runner, mutually exclusive with bytes
45         type:    int
46         unit:    bytes
47         default: -
48     """
49     __scenario_type__ = "Iperf3"
50
51     def __init__(self, scenario_cfg, context_cfg):
52         self.scenario_cfg = scenario_cfg
53         self.context_cfg = context_cfg
54         self.setup_done = False
55
56     def setup(self):
57         host = self.context_cfg['host']
58         host_user = host.get('user', 'ubuntu')
59         host_ip = host.get('ip', None)
60         host_key_filename = host.get('key_filename', '~/.ssh/id_rsa')
61         target = self.context_cfg['target']
62         target_user = target.get('user', 'ubuntu')
63         target_ip = target.get('ip', None)
64         target_key_filename = target.get('key_filename', '~/.ssh/id_rsa')
65
66         LOG.info("user:%s, target:%s", target_user, target_ip)
67         self.target = ssh.SSH(target_user, target_ip,
68                               key_filename=target_key_filename)
69         self.target.wait(timeout=600)
70
71         LOG.info("user:%s, host:%s", host_user, host_ip)
72         self.host = ssh.SSH(host_user, host_ip,
73                             key_filename=host_key_filename)
74         self.host.wait(timeout=600)
75
76         cmd = "iperf3 -s -D"
77         LOG.debug("Starting iperf3 server with command: %s", cmd)
78         status, _, stderr = self.target.execute(cmd)
79         if status:
80             raise RuntimeError(stderr)
81
82         self.setup_done = True
83
84     def teardown(self):
85         LOG.debug("teardown")
86         self.host.close()
87         status, stdout, stderr = self.target.execute("pkill iperf3")
88         if status:
89             LOG.warn(stderr)
90         self.target.close()
91
92     def run(self, result):
93         """execute the benchmark"""
94         if not self.setup_done:
95             self.setup()
96
97         # if run by a duration runner, get the duration time and setup as arg
98         time = self.scenario_cfg["runner"].get("duration", None) \
99             if "runner" in self.scenario_cfg else None
100         options = self.scenario_cfg['options']
101
102         cmd = "iperf3 -c %s --json" % (self.context_cfg['target']['ipaddr'])
103
104         # If there are no options specified
105         if not options:
106             options = ""
107
108         use_UDP = False
109         if "udp" in options:
110             cmd += " --udp"
111             use_UDP = True
112             if "bandwidth" in options:
113                 cmd += " --bandwidth %s" % options["bandwidth"]
114         else:
115             # tcp obviously
116             if "nodelay" in options:
117                 cmd += " --nodelay"
118
119         # these options are mutually exclusive in iperf3
120         if time:
121             cmd += " %d" % time
122         elif "bytes" in options:
123             # number of bytes to transmit (instead of --time)
124             cmd += " --bytes %d" % options["bytes"]
125         elif "blockcount" in options:
126             cmd += " --blockcount %d" % options["blockcount"]
127
128         LOG.debug("Executing command: %s", cmd)
129
130         status, stdout, stderr = self.host.execute(cmd)
131         if status:
132             # error cause in json dict on stdout
133             raise RuntimeError(stdout)
134
135         result.update(json.loads(stdout))
136
137         if "sla" in self.scenario_cfg:
138             sla_iperf = self.scenario_cfg["sla"]
139             if not use_UDP:
140                 sla_bytes_per_second = int(sla_iperf["bytes_per_second"])
141
142                 # convert bits per second to bytes per second
143                 bit_per_second = \
144                     int(result["end"]["sum_received"]["bits_per_second"])
145                 bytes_per_second = bit_per_second / 8
146                 assert bytes_per_second >= sla_bytes_per_second, \
147                     "bytes_per_second %d < sla:bytes_per_second (%d); " % \
148                     (bytes_per_second, sla_bytes_per_second)
149             else:
150                 sla_jitter = float(sla_iperf["jitter"])
151
152                 jitter_ms = float(result["end"]["sum"]["jitter_ms"])
153                 assert jitter_ms <= sla_jitter, \
154                     "jitter_ms  %f > sla:jitter %f; " % \
155                     (jitter_ms, sla_jitter)
156
157
158 def _test():
159     '''internal test function'''
160     key_filename = pkg_resources.resource_filename('yardstick.resources',
161                                                    'files/yardstick_key')
162     ctx = {
163         'host': {
164             'ip': '10.229.47.137',
165             'user': 'root',
166             'key_filename': key_filename
167         },
168         'target': {
169             'ip': '10.229.47.137',
170             'user': 'root',
171             'key_filename': key_filename,
172             'ipaddr': '10.229.47.137',
173         }
174     }
175
176     logger = logging.getLogger('yardstick')
177     logger.setLevel(logging.DEBUG)
178
179     options = {'packetsize': 120}
180     args = {'options': options}
181     result = {}
182
183     p = Iperf(args, ctx)
184     p.run(result)
185     print result
186
187 if __name__ == '__main__':
188     _test()