guest_binding: Add dpdk driver binding options for guests
[vswitchperf.git] / tools / namespace.py
1 # Copyright 2016 Red Hat Corporation.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain 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,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15
16 """
17 Network namespace emulation
18 """
19
20 import logging
21 import os
22
23 from tools import tasks
24
25 _LOGGER = logging.getLogger(__name__)
26
27
28 def add_ip_to_namespace_eth(port, name, ip_addr, cidr):
29     """
30     Assign port ip address in namespace
31     :param port: port to assign ip to
32     :param name: namespace where port resides
33     :param ip_addr: ip address in dot notation format
34     :param cidr: cidr as string
35     :return:
36     """
37     ip_string = '{}/{}'.format(ip_addr, cidr)
38     tasks.run_task(['sudo', 'ip', 'netns', 'exec', name,
39                     'ip', 'addr', 'add', ip_string, 'dev', port],
40                    _LOGGER, 'Assigning ip to port {}...'.format(port), False)
41
42
43 def assign_port_to_namespace(port, name, port_up=False):
44     """
45     Assign NIC port to namespace
46     :param port: port name as string
47     :param name: namespace name as string
48     :param port_up: Boolean if the port should be brought up on assignment
49     :return: None
50     """
51     tasks.run_task(['sudo', 'ip', 'link', 'set',
52                     'netns', name, 'dev', port],
53                    _LOGGER, 'Assigning port {} to namespace {}...'.format(
54                        port, name), False)
55     if port_up:
56         tasks.run_task(['sudo', 'ip', 'netns', 'exec', name,
57                         'ip', 'link', 'set', port, 'up'],
58                        _LOGGER, 'Bringing up port {}...'.format(port), False)
59
60
61 def create_namespace(name):
62     """
63     Create a linux namespace. Raises RuntimeError if namespace already exists
64     in the system.
65     :param name: name of the namespace to be created as string
66     :return: None
67     """
68     if name in get_system_namespace_list():
69         raise RuntimeError('Namespace already exists in system')
70
71     # touch some files in a tmp area so we can track them separately from
72     # the OS's internal namespace tracking. This allows us to track VSPerf
73     # created namespaces so they can be cleaned up if needed.
74     if not os.path.isdir('/tmp/namespaces'):
75         try:
76             os.mkdir('/tmp/namespaces')
77         except os.error:
78             # OK don't crash, but cleanup may be an issue...
79             _LOGGER.error('Unable to create namespace temp folder.')
80             _LOGGER.error(
81                 'Namespaces will not be removed on test case completion')
82     if os.path.isdir('/tmp/namespaces'):
83         with open('/tmp/namespaces/{}'.format(name), 'a'):
84             os.utime('/tmp/namespaces/{}'.format(name), None)
85
86     tasks.run_task(['sudo', 'ip', 'netns', 'add', name], _LOGGER,
87                    'Creating namespace {}...'.format(name), False)
88     tasks.run_task(['sudo', 'ip', 'netns', 'exec', name,
89                     'ip', 'link', 'set', 'lo', 'up'], _LOGGER,
90                    'Enabling loopback interface...', False)
91
92
93 def delete_namespace(name):
94     """
95     Delete linux network namespace
96     :param name: namespace to delete
97     :return: None
98     """
99     # delete the file if it exists in the temp area
100     if os.path.exists('/tmp/namespaces/{}'.format(name)):
101         os.remove('/tmp/namespaces/{}'.format(name))
102     tasks.run_task(['sudo', 'ip', 'netns', 'delete', name], _LOGGER,
103                    'Deleting namespace {}...'.format(name), False)
104
105
106 def get_system_namespace_list():
107     """
108     Return tuple of strings for namespaces on the system
109     :return: tuple of namespaces as string
110     """
111     return tuple(os.listdir('/var/run/netns')) if os.path.exists(
112         '/var/run/netns') else tuple()
113
114 def get_vsperf_namespace_list():
115     """
116     Return a tuple of strings for namespaces created by vsperf testcase
117     :return: tuple of namespaces as string
118     """
119     if os.path.isdir('/tmp/namespaces'):
120         return tuple(os.listdir('/tmp/namespaces'))
121     else:
122         return []
123
124
125 def reset_port_to_root(port, name):
126     """
127     Return the assigned port to the root namespace
128     :param port: port to return as string
129     :param name: namespace the port currently resides
130     :return: None
131     """
132     tasks.run_task(['sudo', 'ip', 'netns', 'exec', name,
133                     'ip', 'link', 'set', port, 'netns', '1'],
134                    _LOGGER, 'Assigning port {} to namespace {}...'.format(
135                        port, name), False)
136
137
138 # pylint: disable=unused-argument
139 # pylint: disable=invalid-name
140 def validate_add_ip_to_namespace_eth(result, port, name, ip_addr, cidr):
141     """
142     Validation function for integration testcases
143     """
144     ip_string = '{}/{}'.format(ip_addr, cidr)
145     return ip_string in ''.join(tasks.run_task(
146         ['sudo', 'ip', 'netns', 'exec', name, 'ip', 'addr', 'show', port],
147         _LOGGER, 'Validating ip address in namespace...', False))
148
149
150 def validate_assign_port_to_namespace(result, port, name, port_up=False):
151     """
152     Validation function for integration testcases
153     """
154     # this could be improved...its not 100% accurate
155     return port in ''.join(tasks.run_task(
156         ['sudo', 'ip', 'netns', 'exec', name, 'ip', 'addr'],
157         _LOGGER, 'Validating port in namespace...'))
158
159
160 def validate_create_namespace(result, name):
161     """
162     Validation function for integration testcases
163     """
164     return name in get_system_namespace_list()
165
166
167 def validate_delete_namespace(result, name):
168     """
169     Validation function for integration testcases
170     """
171     return name not in get_system_namespace_list()
172
173
174 def validate_reset_port_to_root(result, port, name):
175     """
176     Validation function for integration testcases
177     """
178     return not validate_assign_port_to_namespace(result, port, name)