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