aboutsummaryrefslogtreecommitdiffstats
path: root/tools/namespace.py
blob: 9131398fb5112284d44b97e9d15cc50e48a20c50 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

@media only all and (prefers-color-scheme: dark) {
.highlight .hll { background-color: #49483e }
.highlight .c { color: #75715e } /* Comment */
.highlight .err { color: #960050; background-color: #1e0010 } /* Error */
.highlight .k { color: #66d9ef } /* Keyword */
.highlight .l { color: #ae81ff } /* Literal */
.highlight .n { color: #f8f8f2 } /* Name */
.highlight .o { color: #f92672 } /* Operator */
.highlight .p { color: #f8f8f2 } /* Punctuation */
.highlight .ch { color: #75715e } /* Comment.Hashbang */
.highlight .cm { color: #75715e } /* Comment.Multiline */
.highlight .cp { color: #75715e } /* Comment.Preproc */
.highlight .cpf { color: #75715e } /* Comment.PreprocFile */
.highlight .c1 { color: #75715e } /* Comment.Single */
.highlight .cs { color: #75715e } /* Comment.Special */
.highlight .gd { color: #f92672 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gi { color: #a6e22e } /* Generic.Inserted */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #75715e } /* Generic.Subheading */
.highlight .kc { color: #66d9ef } /* Keyword.Constant */
.highlight .kd { color: #66d9ef } /* Keyword.Declaration */
.highlight .kn { color: #f92672 } /* Keyword.Namespace */
.highlight .kp { color: #66d9ef } /* Keyword.Pseudo */
.highlight .kr { color: #66d9ef } /* Keyword.Reserved */
.highlight .kt { color: #66d9ef } /* Keyword.Type */
.highlight .ld { color: #e6db74 } /* Literal.Date */
.highlight .m { color: #ae81ff } /* Literal.Number */
.highlight .s { color: #e6db74 } /* Literal.String */
.highlight .na { color: #a6e22e } /* Name.Attribute */
.highlight .nb { color: #f8f8f2 } /* Name.Builtin */
.highlight .nc { color: #a6e22e } /* Name.Class */
.highlight .no { color: #66d9ef } /* Name.Constant */
.highlight .nd { color: #a6e22e } /* Name.Decorator */
.highlight .ni { color: #f8f8f2 } /* Name.Entity */
.highlight .ne { color: #a6e22e } /* Name.Exception */
.highlight .nf { color: #a6e22e } /* Name.Function */
.highlight .nl { color: #f8f8f2 } /* Name.Label */
.highlight .nn { color: #f8f8f2 } /* Name.Namespace */
.highlight .nx { color: #a6e22e } /* Name.Other */
.highlight .py { color: #f8f8f2 } /* Name.Property */
.highlight .nt { color: #f92672 } /* Name.Tag */
.highlight .nv { color: #f8f8f2 } /* Name.Variable */
.highlight .ow { color: #f92672 } /* Operator.Word */
.highlight .w { color: #f8f8f2 } /* Text.Whitespace */
.highlight .mb { color: #ae81ff } /* Literal.Number.Bin */
.highlight .mf { color: #ae81ff } /* Literal.Number.Float */
.highlight .mh { color: #ae81ff } /* Literal.Number.Hex */
.highlight .mi { color: #ae81ff } /* Literal.Number.Integer */
.highlight .mo { color: #ae81ff } /* Literal.Number.Oct */
.highlight .sa { color: #e6db74 } /* Literal.String.Affix */
.highlight .sb { color: #e6db74 } /* Literal.String.Backtick */
.highlight .sc { color: #e6db74 } /* Literal.String.Char */
.highlight .dl { color: #e6db74 } /* Literal.String.Delimiter */
.highlight .sd { color: #e6db74 } /* Literal.String.Doc */
.highlight .s2 { color: #e6db74 } /* Literal.String.Double */
.highlight .se { color: #ae81ff } /* Literal.String.Escape */
.highlight .sh { color: #e6db74 } /* Literal.String.Heredoc */
.highlight .si { color: #e6db74 } /* Literal.String.Interpol */
.highlight .sx { color: #e6db74 } /* Literal.String.Other */
.highlight .sr { color: #e6db74 } /* Literal.String.Regex */
.highlight .s1 { color: #e6db74 } /* Literal.String.Single */
.highlight .ss { color: #e6db74 } /* Literal.String.Symbol */
.highlight .bp { color: #f8f8f2 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #a6e22e } /* Name.Function.Magic */
.highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */
.highlight .vg { color: #f8f8f2 } /
# Copyright 2016 Red Hat Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""
Network namespace emulation
"""

import logging
import os

from tools import tasks

_LOGGER = logging.getLogger(__name__)


def add_ip_to_namespace_eth(port, name, ip_addr, cidr):
    """
    Assign port ip address in namespace
    :param port: port to assign ip to
    :param name: namespace where port resides
    :param ip_addr: ip address in dot notation format
    :param cidr: cidr as string
    :return:
    """
    ip_string = '{}/{}'.format(ip_addr, cidr)
    tasks.run_task(['sudo', 'ip', 'netns', 'exec', name,
                    'ip', 'addr', 'add', ip_string, 'dev', port],
                   _LOGGER, 'Assigning ip to port {}...'.format(port), False)


def assign_port_to_namespace(port, name, port_up=False):
    """
    Assign NIC port to namespace
    :param port: port name as string
    :param name: namespace name as string
    :param port_up: Boolean if the port should be brought up on assignment
    :return: None
    """
    tasks.run_task(['sudo', 'ip', 'link', 'set',
                    'netns', name, 'dev', port],
                   _LOGGER, 'Assigning port {} to namespace {}...'.format(
                       port, name), False)
    if port_up:
        tasks.run_task(['sudo', 'ip', 'netns', 'exec', name,
                        'ip', 'link', 'set', port, 'up'],
                       _LOGGER, 'Bringing up port {}...'.format(port), False)


def create_namespace(name):
    """
    Create a linux namespace. Raises RuntimeError if namespace already exists
    in the system.
    :param name: name of the namespace to be created as string
    :return: None
    """
    if name in get_system_namespace_list():
        raise RuntimeError('Namespace already exists in system')

    # touch some files in a tmp area so we can track them separately from
    # the OS's internal namespace tracking. This allows us to track VSPerf
    # created namespaces so they can be cleaned up if needed.
    if not os.path.isdir('/tmp/namespaces'):
        try:
            os.mkdir('/tmp/namespaces')
        except os.error:
            # OK don't crash, but cleanup may be an issue...
            _LOGGER.error('Unable to create namespace temp folder.')
            _LOGGER.error(
                'Namespaces will not be removed on test case completion')
    if os.path.isdir('/tmp/namespaces'):
        with open('/tmp/namespaces/{}'.format(name), 'a'):
            os.utime('/tmp/namespaces/{}'.format(name), None)

    tasks.run_task(['sudo', 'ip', 'netns', 'add', name], _LOGGER,
                   'Creating namespace {}...'.format(name), False)
    tasks.run_task(['sudo', 'ip', 'netns', 'exec', name,
                    'ip', 'link', 'set', 'lo', 'up'], _LOGGER,
                   'Enabling loopback interface...', False)


def delete_namespace(name):
    """
    Delete linux network namespace
    :param name: namespace to delete
    :return: None
    """
    # delete the file if it exists in the temp area
    if os.path.exists('/tmp/namespaces/{}'.format(name)):
        os.remove('/tmp/namespaces/{}'.format(name))
    tasks.run_task(['sudo', 'ip', 'netns', 'delete', name], _LOGGER,
                   'Deleting namespace {}...'.format(name), False)


def get_system_namespace_list():
    """
    Return tuple of strings for namespaces on the system
    :return: tuple of namespaces as string
    """
    return tuple(os.listdir('/var/run/netns')) if os.path.exists(
        '/var/run/netns') else tuple()

def get_vsperf_namespace_list():
    """
    Return a tuple of strings for namespaces created by vsperf testcase
    :return: tuple of namespaces as string
    """
    if os.path.isdir('/tmp/namespaces'):
        return tuple(os.listdir('/tmp/namespaces'))
    else:
        return []


def reset_port_to_root(port, name):
    """
    Return the assigned port to the root namespace
    :param port: port to return as string
    :param name: namespace the port currently resides
    :return: None
    """
    tasks.run_task(['sudo', 'ip', 'netns', 'exec', name,
                    'ip', 'link', 'set', port, 'netns', '1'],
                   _LOGGER, 'Assigning port {} to namespace {}...'.format(
                       port, name), False)


# pylint: disable=unused-argument
# pylint: disable=invalid-name
def validate_add_ip_to_namespace_eth(result, port, name, ip_addr, cidr):
    """
    Validation function for integration testcases
    """
    ip_string = '{}/{}'.format(ip_addr, cidr)
    return ip_string in ''.join(tasks.run_task(
        ['sudo', 'ip', 'netns', 'exec', name, 'ip', 'addr', 'show', port],
        _LOGGER, 'Validating ip address in namespace...', False))


def validate_assign_port_to_namespace(result, port, name, port_up=False):
    """
    Validation function for integration testcases
    """
    # this could be improved...its not 100% accurate
    return port in ''.join(tasks.run_task(
        ['sudo', 'ip', 'netns', 'exec', name, 'ip', 'addr'],
        _LOGGER, 'Validating port in namespace...'))


def validate_create_namespace(result, name):
    """
    Validation function for integration testcases
    """
    return name in get_system_namespace_list()


def validate_delete_namespace(result, name):
    """
    Validation function for integration testcases
    """
    return name not in get_system_namespace_list()


def validate_reset_port_to_root(result, port, name):
    """
    Validation function for integration testcases
    """
    return not validate_assign_port_to_namespace(result, port, name)