Heat context code refactor part 2
[yardstick.git] / yardstick / benchmark / scenarios / networking / pktgen.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 import pkg_resources
10 import logging
11 import json
12
13 import yardstick.ssh as ssh
14 from yardstick.benchmark.scenarios import base
15
16 LOG = logging.getLogger(__name__)
17
18
19 class Pktgen(base.Scenario):
20     """Execute pktgen between two hosts
21
22   Parameters
23     packetsize - packet size in bytes without the CRC
24         type:    int
25         unit:    bytes
26         default: 60
27     number_of_ports - number of UDP ports to test
28         type:    int
29         unit:    na
30         default: 10
31     duration - duration of the test
32         type:    int
33         unit:    seconds
34         default: 20
35     """
36     __scenario_type__ = "Pktgen"
37
38     TARGET_SCRIPT = 'pktgen_benchmark.bash'
39
40     def __init__(self, scenario_cfg, context_cfg):
41         self.scenario_cfg = scenario_cfg
42         self.context_cfg = context_cfg
43         self.setup_done = False
44
45     def setup(self):
46         '''scenario setup'''
47         self.target_script = pkg_resources.resource_filename(
48             'yardstick.benchmark.scenarios.networking',
49             Pktgen.TARGET_SCRIPT)
50         host = self.context_cfg['host']
51         host_user = host.get('user', 'ubuntu')
52         host_ip = host.get('ip', None)
53         host_key_filename = host.get('key_filename', '~/.ssh/id_rsa')
54         target = self.context_cfg['target']
55         target_user = target.get('user', 'ubuntu')
56         target_ip = target.get('ip', None)
57         target_key_filename = target.get('key_filename', '~/.ssh/id_rsa')
58
59         LOG.info("user:%s, target:%s", target_user, target_ip)
60         self.server = ssh.SSH(target_user, target_ip,
61                               key_filename=target_key_filename)
62         self.server.wait(timeout=600)
63
64         LOG.info("user:%s, host:%s", host_user, host_ip)
65         self.client = ssh.SSH(host_user, host_ip,
66                               key_filename=host_key_filename)
67         self.client.wait(timeout=600)
68
69         # copy script to host
70         self.client.run("cat > ~/pktgen.sh",
71                         stdin=open(self.target_script, "rb"))
72
73         self.setup_done = True
74
75     def _iptables_setup(self):
76         """Setup iptables on server to monitor for received packets"""
77         cmd = "sudo iptables -F; " \
78               "sudo iptables -A INPUT -p udp --dport 1000:%s -j DROP" \
79               % (1000 + self.number_of_ports)
80         LOG.debug("Executing command: %s", cmd)
81         status, _, stderr = self.server.execute(cmd)
82         if status:
83             raise RuntimeError(stderr)
84
85     def _iptables_get_result(self):
86         """Get packet statistics from server"""
87         cmd = "sudo iptables -L INPUT -vnx |" \
88               "awk '/dpts:1000:%s/ {{printf \"%%s\", $1}}'" \
89               % (1000 + self.number_of_ports)
90         LOG.debug("Executing command: %s", cmd)
91         status, stdout, stderr = self.server.execute(cmd)
92         if status:
93             raise RuntimeError(stderr)
94         return int(stdout)
95
96     def run(self, result):
97         """execute the benchmark"""
98
99         if not self.setup_done:
100             self.setup()
101
102         ipaddr = self.context_cfg["target"].get("ipaddr", '127.0.0.1')
103
104         options = self.scenario_cfg['options']
105         packetsize = options.get("packetsize", 60)
106         self.number_of_ports = options.get("number_of_ports", 10)
107         # if run by a duration runner
108         duration_time = self.scenario_cfg["runner"].get("duration", None) \
109             if "runner" in self.scenario_cfg else None
110         # if run by an arithmetic runner
111         arithmetic_time = options.get("duration", None)
112
113         if duration_time:
114             duration = duration_time
115         elif arithmetic_time:
116             duration = arithmetic_time
117         else:
118             duration = 20
119
120         self._iptables_setup()
121
122         cmd = "sudo bash pktgen.sh %s %s %s %s" \
123             % (ipaddr, self.number_of_ports, packetsize, duration)
124         LOG.debug("Executing command: %s", cmd)
125         status, stdout, stderr = self.client.execute(cmd)
126
127         if status:
128             raise RuntimeError(stderr)
129
130         result.update(json.loads(stdout))
131
132         result['packets_received'] = self._iptables_get_result()
133
134         if "sla" in self.scenario_cfg:
135             sent = result['packets_sent']
136             received = result['packets_received']
137             ppm = 1000000 * (sent - received) / sent
138             sla_max_ppm = int(self.scenario_cfg["sla"]["max_ppm"])
139             assert ppm <= sla_max_ppm, "ppm %d > sla_max_ppm %d; " \
140                 % (ppm, sla_max_ppm)
141
142
143 def _test():
144     '''internal test function'''
145     key_filename = pkg_resources.resource_filename('yardstick.resources',
146                                                    'files/yardstick_key')
147     ctx = {
148         'host': {
149             'ip': '10.229.47.137',
150             'user': 'root',
151             'key_filename': key_filename
152         },
153         'target': {
154             'ip': '10.229.47.137',
155             'user': 'root',
156             'key_filename': key_filename,
157             'ipaddr': '10.229.47.137',
158         }
159     }
160
161     logger = logging.getLogger('yardstick')
162     logger.setLevel(logging.DEBUG)
163
164     options = {'packetsize': 120}
165     args = {'options': options}
166     result = {}
167
168     p = Pktgen(args, ctx)
169     p.run(result)
170     print result
171
172 if __name__ == '__main__':
173     _test()