05f20e56225413e3abb44f055d6cb29daa6a7abe
[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 from log import LOG
16 import os
17 import subprocess
18 import yaml
19
20 class TrafficServerException(Exception):
21     pass
22
23 class TrafficServer(object):
24     """Base class for traffic servers."""
25
26 class TRexTrafficServer(TrafficServer):
27     """Creates configuration file for TRex and runs server."""
28
29     def __init__(self, trex_base_dir='/opt/trex'):
30         contents = os.listdir(trex_base_dir)
31         # only one version of TRex should be supported in container
32         assert(len(contents) == 1)
33         self.trex_dir = os.path.join(trex_base_dir, contents[0])
34
35     def run_server(self, traffic_profile, filename='/etc/trex_cfg.yaml'):
36         """
37         Runs TRex server for specified traffic profile.
38
39         :param traffic_profile: traffic profile object based on config file
40         :param filename: path where to save TRex config file
41         """
42         cfg = self.__save_config(traffic_profile, filename)
43         cores = traffic_profile.cores
44         subprocess.Popen(['nohup', '/bin/bash', '-c',
45                           './t-rex-64 -i -c {} --iom 0 --no-scapy-server --close-at-end --vlan'
46                           ' --cfg {} &> /tmp/trex.log & disown'.format(cores, cfg)],
47                          cwd=self.trex_dir)
48         LOG.info('TRex server is running...')
49
50     def __save_config(self, traffic_profile, filename):
51         ifs = ",".join([repr(pci) for pci in traffic_profile.pcis])
52
53         result = """# Config generated by NFVBench tool
54         - port_limit : 2
55           version    : 2
56           interfaces : [{ifs}]""".format(ifs=ifs)
57
58         yaml.safe_load(result)
59         if os.path.exists(filename):
60             os.remove(filename)
61         with open(filename, 'w') as f:
62             f.write(result)
63
64         return filename