b2d8367f130ad77bdccb99b99d8ca8e648fce98d
[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         """
39         Runs TRex server for specified traffic profile.
40
41         :param traffic_profile: traffic profile object based on config file
42         :param filename: path where to save TRex config file
43         """
44         cfg = self.__save_config(generator_config, filename)
45         cores = generator_config.cores
46         vtep_vlan = generator_config.gen_config.get('vtep_vlan')
47         sw_mode = "--software" if generator_config.software_mode else ""
48         vlan_opt = "--vlan" if (generator_config.vlan_tagging or vtep_vlan) else ""
49         subprocess.Popen(['nohup', '/bin/bash', '-c',
50                           './t-rex-64 -i -c {} --iom 0 --no-scapy-server --close-at-end {} '
51                           '{} --cfg {} &> /tmp/trex.log & disown'.format(cores, sw_mode,
52                                                                          vlan_opt, cfg)],
53                          cwd=self.trex_dir)
54         LOG.info('TRex server is running...')
55
56     def __save_config(self, generator_config, filename):
57         ifs = ",".join([repr(pci) for pci in generator_config.pcis])
58
59         result = """# Config generated by NFVbench
60         - port_limit : 2
61           version    : 2
62           interfaces : [{ifs}]""".format(ifs=ifs)
63
64         yaml.safe_load(result)
65         if os.path.exists(filename):
66             os.remove(filename)
67         with open(filename, 'w') as f:
68             f.write(result)
69
70         return filename