use context manager for stdin files and use _put_file_shell
[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._put_file_shell(self.target_script, '~/netperf.sh')
89
90         self.setup_done = True
91
92     def run(self, result):
93         """execute the benchmark"""
94
95         if not self.setup_done:
96             self.setup()
97
98         # get global options
99         ipaddr = self.context_cfg['target'].get("ipaddr", '127.0.0.1')
100         options = self.scenario_cfg['options']
101         testname = options.get("testname", 'TCP_STREAM')
102         duration_time = self.scenario_cfg["runner"].get("duration", None) \
103             if "runner" in self.scenario_cfg else None
104         arithmetic_time = options.get("duration", None)
105         if duration_time:
106             testlen = duration_time
107         elif arithmetic_time:
108             testlen = arithmetic_time
109         else:
110             testlen = 20
111
112         cmd_args = "-H %s -l %s -t %s" % (ipaddr, testlen, testname)
113
114         # get test specific options
115         default_args = "-O 'THROUGHPUT,THROUGHPUT_UNITS,MEAN_LATENCY'"
116         cmd_args += " -- %s" % default_args
117         option_pair_list = [("send_msg_size", "-m"),
118                             ("recv_msg_size", "-M"),
119                             ("req_rsp_size", "-r")]
120         for option_pair in option_pair_list:
121             if option_pair[0] in options:
122                 cmd_args += " %s %s" % (option_pair[1],
123                                         options[option_pair[0]])
124
125         cmd = "sudo bash netperf.sh %s" % (cmd_args)
126         LOG.debug("Executing command: %s", cmd)
127         status, stdout, stderr = self.client.execute(cmd)
128
129         if status:
130             raise RuntimeError(stderr)
131
132         result.update(json.loads(stdout))
133
134         if result['mean_latency'] == '':
135             raise RuntimeError(stdout)
136
137         # sla check
138         mean_latency = float(result['mean_latency'])
139         if "sla" in self.scenario_cfg:
140             sla_max_mean_latency = int(
141                 self.scenario_cfg["sla"]["mean_latency"])
142
143             assert mean_latency <= sla_max_mean_latency, \
144                 "mean_latency %f > sla_max_mean_latency(%f); " % \
145                 (mean_latency, sla_max_mean_latency)
146
147
148 def _test():
149     '''internal test function'''
150     key_filename = pkg_resources.resource_filename("yardstick.resources",
151                                                    "files/yardstick_key")
152     ctx = {
153         "host": {
154             "ip": "10.229.47.137",
155             "user": "root",
156             "key_filename": key_filename
157         },
158         "target": {
159             "ip": "10.229.47.137",
160             "user": "root",
161             "key_filename": key_filename,
162             "ipaddr": "10.229.47.137"
163         }
164     }
165
166     logger = logging.getLogger("yardstick")
167     logger.setLevel(logging.DEBUG)
168
169     options = {
170         "testname": 'TCP_STREAM'
171     }
172
173     args = {"options": options}
174     result = {}
175
176     netperf = Netperf(args, ctx)
177     netperf.run(result)
178     print result
179
180
181 if __name__ == '__main__':
182     _test()