Merge "Adding python package requirement for VNF testing."
[yardstick.git] / yardstick / benchmark / scenarios / networking / netperf_node.py
1 ##############################################################################
2 # Copyright (c) 2016 Huawei Technologies Co.,Ltd 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 # bulk data test and req/rsp test are supported
10 from __future__ import absolute_import
11 from __future__ import print_function
12
13 import logging
14
15 import pkg_resources
16 from oslo_serialization import jsonutils
17
18 import yardstick.ssh as ssh
19 from yardstick.benchmark.scenarios import base
20
21 LOG = logging.getLogger(__name__)
22
23
24 class NetperfNode(base.Scenario):
25     """Execute netperf between two nodes
26
27   Parameters
28     testname - to specify the test you wish to perform.
29     the valid testnames are TCP_STREAM, TCP_RR, UDP_STREAM, UDP_RR
30         type:    string
31         unit:    na
32         default: TCP_STREAM
33     send_msg_size - value set the local send size to value bytes.
34         type:    int
35         unit:    bytes
36         default: na
37     recv_msg_size - setting the receive size for the remote system.
38         type:    int
39         unit:    bytes
40         default: na
41     req_rsp_size - set the request and/or response sizes based on sizespec.
42         type:    string
43         unit:    na
44         default: na
45     duration - duration of the test
46         type:    int
47         unit:    seconds
48         default: 20
49
50     read link below for more netperf args description:
51     http://www.netperf.org/netperf/training/Netperf.html
52     """
53     __scenario_type__ = "NetperfNode"
54     TARGET_SCRIPT = 'netperf_benchmark.bash'
55     INSTALL_SCRIPT = 'netperf_install.bash'
56     REMOVE_SCRIPT = 'netperf_remove.bash'
57
58     def __init__(self, scenario_cfg, context_cfg):
59         self.scenario_cfg = scenario_cfg
60         self.context_cfg = context_cfg
61         self.setup_done = False
62
63     def setup(self):
64         '''scenario setup'''
65         self.target_script = pkg_resources.resource_filename(
66             'yardstick.benchmark.scenarios.networking',
67             NetperfNode.TARGET_SCRIPT)
68         host = self.context_cfg['host']
69         host_user = host.get('user', 'ubuntu')
70         host_ssh_port = host.get('ssh_port', ssh.DEFAULT_PORT)
71         host_ip = host.get('ip', None)
72         target = self.context_cfg['target']
73         target_user = target.get('user', 'ubuntu')
74         target_ssh_port = target.get('ssh_port', ssh.DEFAULT_PORT)
75         target_ip = target.get('ip', None)
76         self.target_ip = target.get('ip', None)
77         host_password = host.get('password', None)
78         target_password = target.get('password', None)
79
80         LOG.info("host_pw:%s, target_pw:%s", host_password, target_password)
81         # netserver start automatically during the vm boot
82         LOG.info("user:%s, target:%s", target_user, target_ip)
83         self.server = ssh.SSH(target_user, target_ip,
84                               password=target_password, port=target_ssh_port)
85         self.server.wait(timeout=600)
86
87         LOG.info("user:%s, host:%s", host_user, host_ip)
88         self.client = ssh.SSH(host_user, host_ip,
89                               password=host_password, port=host_ssh_port)
90         self.client.wait(timeout=600)
91
92         # copy script to host
93         with open(self.target_script, "rb") as file_run:
94             self.client.run("cat > ~/netperf.sh", stdin=file_run)
95         # copy script to host and client
96         self.install_script = pkg_resources.resource_filename(
97             'yardstick.benchmark.scenarios.networking',
98             NetperfNode.INSTALL_SCRIPT)
99         self.remove_script = pkg_resources.resource_filename(
100             'yardstick.benchmark.scenarios.networking',
101             NetperfNode.REMOVE_SCRIPT)
102
103         with open(self.install_script, "rb") as file_install:
104             self.server.run("cat > ~/netperf_install.sh", stdin=file_install)
105         with open(self.install_script, "rb") as file_install:
106             self.client.run("cat > ~/netperf_install.sh", stdin=file_install)
107         with open(self.remove_script, "rb") as file_remove:
108             self.server.run("cat > ~/netperf_remove.sh", stdin=file_remove)
109         with open(self.remove_script, "rb") as file_remove:
110             self.client.run("cat > ~/netperf_remove.sh", stdin=file_remove)
111         self.server.execute("sudo bash netperf_install.sh")
112         self.client.execute("sudo bash netperf_install.sh")
113
114         self.setup_done = True
115
116     def run(self, result):
117         """execute the benchmark"""
118
119         if not self.setup_done:
120             self.setup()
121
122         # get global options
123         ipaddr = self.context_cfg['target'].get("ipaddr", '127.0.0.1')
124         ipaddr = self.target_ip
125         options = self.scenario_cfg['options']
126         testname = options.get("testname", 'TCP_STREAM')
127         duration_time = self.scenario_cfg["runner"].get("duration", None) \
128             if "runner" in self.scenario_cfg else None
129         arithmetic_time = options.get("duration", None)
130         if duration_time:
131             testlen = duration_time
132         elif arithmetic_time:
133             testlen = arithmetic_time
134         else:
135             testlen = 20
136
137         cmd_args = "-H %s -l %s -t %s -c -C" % (ipaddr, testlen, testname)
138
139         # get test specific options
140         output_opt = options.get(
141             "output_opt", "THROUGHPUT,THROUGHPUT_UNITS,MEAN_LATENCY")
142         default_args = "-O %s" % output_opt
143         cmd_args += " -- %s" % default_args
144         option_pair_list = [("send_msg_size", "-m"),
145                             ("recv_msg_size", "-M"),
146                             ("req_rsp_size", "-r")]
147         for option_pair in option_pair_list:
148             if option_pair[0] in options:
149                 cmd_args += " %s %s" % (option_pair[1],
150                                         options[option_pair[0]])
151
152         cmd = "sudo bash netperf.sh %s" % (cmd_args)
153         LOG.debug("Executing command: %s", cmd)
154         status, stdout, stderr = self.client.execute(cmd)
155
156         if status:
157             raise RuntimeError(stderr)
158
159         result.update(jsonutils.loads(stdout))
160
161         if result['mean_latency'] == '':
162             raise RuntimeError(stdout)
163
164         # sla check
165         mean_latency = float(result['mean_latency'])
166         if "sla" in self.scenario_cfg:
167             sla_max_mean_latency = int(
168                 self.scenario_cfg["sla"]["mean_latency"])
169
170             assert mean_latency <= sla_max_mean_latency, \
171                 "mean_latency %f > sla_max_mean_latency(%f); " % \
172                 (mean_latency, sla_max_mean_latency)
173
174     def teardown(self):
175         '''remove netperf from nodes after test'''
176         self.server.execute("sudo bash netperf_remove.sh")
177         self.client.execute("sudo bash netperf_remove.sh")
178
179
180 def _test():    # pragma: no cover
181     '''internal test function'''
182     ctx = {
183         "host": {
184             "ip": "192.168.10.10",
185             "user": "root",
186             "password": "root"
187         },
188         "target": {
189             "ip": "192.168.10.11",
190             "user": "root",
191             "password": "root"
192         }
193     }
194
195     logger = logging.getLogger("yardstick")
196     logger.setLevel(logging.DEBUG)
197
198     options = {
199         "testname": 'TCP_STREAM'
200     }
201
202     args = {"options": options}
203     result = {}
204
205     netperf = NetperfNode(args, ctx)
206     netperf.run(result)
207     print(result)
208
209
210 if __name__ == '__main__':
211     _test()