Merge "standardize ssh auth"
[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 from __future__ import absolute_import
14 from __future__ import print_function
15
16 import logging
17
18 import pkg_resources
19 from oslo_serialization import jsonutils
20
21 import yardstick.ssh as ssh
22 from yardstick.benchmark.scenarios import base
23
24 LOG = logging.getLogger(__name__)
25
26
27 class Iperf(base.Scenario):
28     """Execute iperf3 between two hosts
29
30 By default TCP is used but UDP can also be configured.
31 For more info see http://software.es.net/iperf
32
33   Parameters
34     bytes - number of bytes to transmit
35       only valid with a non duration runner, mutually exclusive with blockcount
36         type:    int
37         unit:    bytes
38         default: 56
39     udp - use UDP rather than TCP
40         type:    bool
41         unit:    na
42         default: false
43     nodelay - set TCP no delay, disabling Nagle's Algorithm
44         type:    bool
45         unit:    na
46         default: false
47     blockcount - number of blocks (packets) to transmit,
48       only valid with a non duration runner, mutually exclusive with bytes
49         type:    int
50         unit:    bytes
51         default: -
52     """
53     __scenario_type__ = "Iperf3"
54
55     def __init__(self, scenario_cfg, context_cfg):
56         self.scenario_cfg = scenario_cfg
57         self.context_cfg = context_cfg
58         self.setup_done = False
59
60     def setup(self):
61         host = self.context_cfg['host']
62         target = self.context_cfg['target']
63
64         LOG.info("user:%s, target:%s", target['user'], target['ip'])
65         self.target = ssh.SSH.from_node(target, defaults={"user": "ubuntu"})
66         self.target.wait(timeout=600)
67
68         LOG.info("user:%s, host:%s", host['user'], host['ip'])
69         self.host = ssh.SSH.from_node(host, defaults={"user": "ubuntu"})
70         self.host.wait(timeout=600)
71
72         cmd = "iperf3 -s -D"
73         LOG.debug("Starting iperf3 server with command: %s", cmd)
74         status, _, stderr = self.target.execute(cmd)
75         if status:
76             raise RuntimeError(stderr)
77
78         self.setup_done = True
79
80     def teardown(self):
81         LOG.debug("teardown")
82         self.host.close()
83         status, stdout, stderr = self.target.execute("pkill iperf3")
84         if status:
85             LOG.warning(stderr)
86         self.target.close()
87
88     def run(self, result):
89         """execute the benchmark"""
90         if not self.setup_done:
91             self.setup()
92
93         # if run by a duration runner, get the duration time and setup as arg
94         time = self.scenario_cfg["runner"].get("duration", None) \
95             if "runner" in self.scenario_cfg else None
96         options = self.scenario_cfg['options']
97
98         cmd = "iperf3 -c %s --json" % (self.context_cfg['target']['ipaddr'])
99
100         # If there are no options specified
101         if not options:
102             options = ""
103
104         use_UDP = False
105         if "udp" in options:
106             cmd += " --udp"
107             use_UDP = True
108             if "bandwidth" in options:
109                 cmd += " --bandwidth %s" % options["bandwidth"]
110         else:
111             # tcp obviously
112             if "nodelay" in options:
113                 cmd += " --nodelay"
114
115         # these options are mutually exclusive in iperf3
116         if time:
117             cmd += " %d" % time
118         elif "bytes" in options:
119             # number of bytes to transmit (instead of --time)
120             cmd += " --bytes %d" % options["bytes"]
121         elif "blockcount" in options:
122             cmd += " --blockcount %d" % options["blockcount"]
123
124         LOG.debug("Executing command: %s", cmd)
125
126         status, stdout, stderr = self.host.execute(cmd)
127         if status:
128             # error cause in json dict on stdout
129             raise RuntimeError(stdout)
130
131         # Note: convert all ints to floats in order to avoid
132         # schema conflicts in influxdb. We probably should add
133         # a format func in the future.
134         result.update(
135             jsonutils.loads(stdout, parse_int=float))
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
188 if __name__ == '__main__':
189     _test()