summaryrefslogtreecommitdiff
path: root/python/ovstest/args.py
blob: 8e23a894603f7e5cf5527d5cc14b5e423f55009b (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# Copyright (c) 2011, 2012 Nicira, Inc.
#
# 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.

"""
ovsargs provide argument parsing for ovs-test utility
"""

import argparse
import re
import socket
import sys

CONTROL_PORT = 15531
DATA_PORT = 15532

def ip_address(string):
    """Verifies if string is a valid IP address"""
    try:
        socket.inet_aton(string)
    except socket.error:
        raise argparse.ArgumentTypeError("Not a valid IPv4 address")
    return string


def ip_optional_mask(string):
    """
    Verifies if string contains a valid IP address and an optional mask in
    CIDR notation.
    """
    token = string.split("/")
    if len(token) > 2:
        raise argparse.ArgumentTypeError("IP address and netmask must be "
                                         "separated by a single slash")
    elif len(token) == 2:
        try:
            mask = int(token[1])
        except ValueError:
            raise argparse.ArgumentTypeError("Netmask is not a valid integer")
        if mask < 0 or mask > 31:
            raise argparse.ArgumentTypeError("Netmask must be in range 0..31")
    ip_address(token[0])
    return string


def port(string):
    """Convert a string into a TCP/UDP Port (integer)"""
    try:
        port_number = int(string)
        if port_number < 1 or port_number > 65535:
            raise argparse.ArgumentTypeError("Port is out of range")
    except ValueError:
        raise argparse.ArgumentTypeError("Port is not an integer")
    return port_number


def ip_optional_port(string, default_port, ip_callback):
    """Convert a string into IP and Port pair. If port was absent then use
    default_port as the port. The third argument is a callback that verifies
    whether IP address is given in correct format."""
    value = string.split(':')
    if len(value) == 1:
        return (ip_callback(value[0]), default_port)
    elif len(value) == 2:
        return (ip_callback(value[0]), port(value[1]))
    else:
        raise argparse.ArgumentTypeError("IP address from the optional Port "
                                         "must be colon-separated")


def vlan_tag(string):
    """
    This function verifies whether given string is a correct VLAN tag.
    """
    try:
        value = int(string)
    except ValueError:
        raise argparse.ArgumentTypeError("VLAN tag is not a valid integer")
    if value < 1 or value > 4094:
        raise argparse.ArgumentTypeError("Not a valid VLAN tag. "
                                         "VLAN tag should be in the "
                                         "range 1..4094.")
    return string


def server_endpoint(string):
    """Converts a string OuterIP[:OuterPort],InnerIP[/Mask][:InnerPort]
    into a 4-tuple, where:
    1. First element is OuterIP
    2. Second element is OuterPort (if omitted will use default value 15531)
    3  Third element is InnerIP with optional mask
    4. Fourth element is InnerPort (if omitted will use default value 15532)
    """
    value = string.split(',')
    if len(value) == 2:
        ret1 = ip_optional_port(value[0], CONTROL_PORT, ip_address)
        ret2 = ip_optional_port(value[1], DATA_PORT, ip_optional_mask)
        return (ret1[0], ret1[1], ret2[0], ret2[1])
    else:
        raise argparse.ArgumentTypeError("OuterIP:OuterPort and InnerIP/Mask:"
                                         "InnerPort must be comma separated")


class UniqueServerAction(argparse.Action):
    """
    This custom action class will prevent user from entering multiple ovs-test
    servers with the same OuterIP. If there is an server with 127.0.0.1 outer
    IP address then it will be inserted in the front of the list.
    """
    def __call__(self, parser, namespace, values, option_string=None):
        outer_ips = set()
        endpoints = []
        for server in values:
            try:
                endpoint = server_endpoint(server)
            except argparse.ArgumentTypeError:
                raise argparse.ArgumentError(self, str(sys.exc_info()[1]))
            if endpoint[0] in outer_ips:
                raise argparse.ArgumentError(self, "Duplicate OuterIPs found")
            else:
                outer_ips.add(endpoint[0])
                if endpoint[0] == "127.0.0.1":
                    endpoints.insert(0, endpoint)
                else:
                    endpoints.append(endpoint)
        setattr(namespace, self.dest, endpoints)


def bandwidth(string):
    """Convert a string (given in bits/second with optional magnitude for
    units) into a long (bytes/second)"""
    if re.match("^[1-9][0-9]*[MK]?$", string) is None:
        raise argparse.ArgumentTypeError("Not a valid target bandwidth")
    bwidth = string.replace("M", "000000")
    bwidth = bwidth.replace("K", "000")
    return long(bwidth) / 8  # Convert from bits to bytes


def tunnel_types(string):
    """
    This function converts a string into a list that contains all tunnel types
    that user intended to test.
    """
    return string.split(',')


def ovs_initialize_args():
    """
    Initialize argument parsing for ovs-test utility.
    """
    parser = argparse.ArgumentParser(description='Test connectivity '
                                                'between two Open vSwitches.')

    parser.add_argument('-v', '--version', action='version',
                version='ovs-test (Open vSwitch) @VERSION@')

    parser.add_argument("-b", "--bandwidth", action='store',
                dest="targetBandwidth", default="1M", type=bandwidth,
                help='Target bandwidth for UDP tests in bits/second. Use '
                'postfix M or K to alter unit magnitude.')
    parser.add_argument("-i", "--interval", action='store',
                dest="testInterval", default=5, type=int,
                help='Interval for how long to run each test in seconds.')

    parser.add_argument("-t", "--tunnel-modes", action='store',
                dest="tunnelModes", default=(), type=tunnel_types,
                help='Do L3 tests with the given tunnel modes.')
    parser.add_argument("-l", "--vlan-tag", action='store',
                dest="vlanTag", default=None, type=vlan_tag,
                help='Do VLAN tests and use the given VLAN tag.')
    parser.add_argument("-d", "--direct", action='store_true',
                dest="direct", default=None,
                help='Do direct tests between both ovs-test servers.')

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("-s", "--server", action="store", dest="port",
                type=port,
                help='Run in server mode and wait for the client to '
                'connect to this port.')
    group.add_argument('-c', "--client", nargs=2,
                dest="servers", action=UniqueServerAction,
                metavar=("SERVER1", "SERVER2"),
                help='Run in client mode and do tests between these '
                'two ovs-test servers. Each server must be specified in '
                'following format - OuterIP:OuterPort,InnerIP[/mask] '
                ':InnerPort. It is possible to start local instance of '
                'ovs-test server in the client mode by using 127.0.0.1 as '
                'OuterIP.')
    return parser.parse_args()