ac232655dd2c0970cf6bca2c2dd883c3384b3ccc
[nfvbench.git] / nfvbench / traffic_server.py
1 # Copyright 2016 Cisco Systems, Inc.  All rights reserved.
2 #
3 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
4 #    not use this file except in compliance with the License. You may obtain
5 #    a copy of the License at
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
9 #    Unless required by applicable law or agreed to in writing, software
10 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 #    License for the specific language governing permissions and limitations
13 #    under the License.
14
15 import os
16 import subprocess
17 import yaml
18
19 from log import LOG
20
21
22 class TrafficServerException(Exception):
23     pass
24
25 class TrafficServer(object):
26     """Base class for traffic servers."""
27
28 class TRexTrafficServer(TrafficServer):
29     """Creates configuration file for TRex and runs server."""
30
31     def __init__(self, trex_base_dir='/opt/trex'):
32         contents = os.listdir(trex_base_dir)
33         # only one version of TRex should be supported in container
34         assert len(contents) == 1
35         self.trex_dir = os.path.join(trex_base_dir, contents[0])
36
37     def run_server(self, generator_config, filename='/etc/trex_cfg.yaml'):
38         """Run TRex server for specified traffic profile.
39
40         :param traffic_profile: traffic profile object based on config file
41         :param filename: path where to save TRex config file
42         """
43         cfg = self.__save_config(generator_config, filename)
44         cores = generator_config.cores
45         vtep_vlan = generator_config.gen_config.get('vtep_vlan')
46         sw_mode = "--software" if generator_config.software_mode else ""
47         vlan_opt = "--vlan" if (generator_config.vlan_tagging or vtep_vlan) else ""
48         if generator_config.mbuf_factor:
49             mbuf_opt = "--mbuf-factor " + str(generator_config.mbuf_factor)
50         else:
51             mbuf_opt = ""
52         # --unbind-unused-ports: for NIC that have more than 2 ports such as Intel X710
53         # this will instruct trex to unbind all ports that are unused instead of
54         # erroring out with an exception (i40e only)
55         cmd = ['nohup', '/bin/bash', '-c',
56                './t-rex-64 -i -c {} --iom 0 --no-scapy-server '
57                '--unbind-unused-ports --close-at-end {} '
58                '{} {} --cfg {} &> /tmp/trex.log & disown'.format(cores, sw_mode,
59                                                                  vlan_opt,
60                                                                  mbuf_opt, cfg)]
61         LOG.info(' '.join(cmd))
62         subprocess.Popen(cmd, cwd=self.trex_dir)
63         LOG.info('TRex server is running...')
64
65     def __load_config(self, filename):
66         result = {}
67         if os.path.exists(filename):
68             with open(filename, 'r') as stream:
69                 try:
70                     result = yaml.safe_load(stream)
71                 except yaml.YAMLError as exc:
72                     print exc
73         return result
74
75     def __save_config(self, generator_config, filename):
76         result = self.__prepare_config(generator_config)
77         yaml.safe_load(result)
78         if os.path.exists(filename):
79             os.remove(filename)
80         with open(filename, 'w') as f:
81             f.write(result)
82         return filename
83
84     def __prepare_config(self, generator_config):
85         ifs = ",".join([repr(pci) for pci in generator_config.pcis])
86         result = """# Config generated by NFVbench
87         - port_limit : 2
88           version    : 2
89           zmq_pub_port : {zmq_pub_port}
90           zmq_rpc_port : {zmq_rpc_port}
91           prefix       : {prefix}
92           limit_memory : {limit_memory}
93           interfaces : [{ifs}]""".format(zmq_pub_port=generator_config.zmq_pub_port,
94                                          zmq_rpc_port=generator_config.zmq_rpc_port,
95                                          prefix=generator_config.name,
96                                          limit_memory=generator_config.limit_memory,
97                                          ifs=ifs)
98         if generator_config.platform.master_thread_id and \
99            generator_config.platform.latency_thread_id:
100             try:
101                 platform = """
102               platform     :
103             master_thread_id  : {master_thread_id}
104             latency_thread_id : {latency_thread_id}
105             dual_if:""".format(master_thread_id=generator_config.platform.master_thread_id,
106                                latency_thread_id=generator_config.platform.latency_thread_id)
107                 result += platform
108
109                 for core in generator_config.platform.dual_if:
110                     threads = ""
111                     try:
112                         threads = ",".join([repr(thread) for thread in core.threads])
113                     except TypeError:
114                         LOG.warn("No threads defined for socket %s", core.socket)
115                     core_result = """
116                   - socket : {socket}
117                     threads : [{threads}]""".format(socket=core.socket, threads=threads)
118                     result += core_result
119             except (KeyError, AttributeError):
120                 pass
121         return result
122
123     def check_config_updated(self, generator_config):
124         existing_config = self.__load_config(filename='/etc/trex_cfg.yaml')
125         new_config = yaml.safe_load(self.__prepare_config(generator_config))
126         LOG.debug("Existing config: %s", existing_config)
127         LOG.debug("New config: %s", new_config)
128         if existing_config == new_config:
129             return False
130         return True