File: team_basic_test.py

package info (click to toggle)
libteam 1.12-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,320 kB
  • ctags: 2,189
  • sloc: ansic: 16,808; sh: 1,190; python: 613; makefile: 110
file content (206 lines) | stat: -rwxr-xr-x 7,018 bytes parent folder | download | duplicates (2)
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
200
201
202
203
204
205
206
#! /usr/bin/env python
"""
Basic test.

   Copyright (C) 2012-2013 Jiri Pirko <jiri@resnulli.us>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
"""

__author__ = """
jiri@resnulli.us (Jiri Pirko)
"""

import sys
import os
import getopt
import subprocess

def usage():
    """
    Print usage of this app
    """
    print "Usage: team_basic_test.py [OPTION...]"
    print ""
    print "  -h, --help                         print this message"
    print "  -c, --loop-count=NUMBER            number of loops (default 1)"
    print "  -p, --port=NETDEV                  port device (can be defined multiple times)"
    sys.exit()

class CmdExecFailedException(Exception):
    def __init__(self, retval):
        self.__retval = retval

    def __str__(self):
        return "Command execution failed: %s" % self.__retval

class CmdExecUnexpectedOutputException(Exception):
    def __init__(self, output, expected_output):
        self.__output = output
        self.__expected_output = expected_output

    def __str__(self):
        return "Command execution output unexpected: \"%s\" != \"%s\"" % (self.__output, self.__expected_output)

def print_output(out_type, string):
    print("%s:\n"
          "----------------------------\n"
          "%s"
          "----------------------------" % (out_type, string))

def cmd_exec(cmd, expected_output=None, cleaner=False):
    cmd = cmd.rstrip(" ")
    if not cleaner:
        print("# \"%s\"" % cmd)
    subp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    (data_stdout, data_stderr) = subp.communicate()

    if subp.returncode and not cleaner:
        if data_stdout:
            print_output("Stdout", data_stdout)
        if data_stderr:
            print_output("Stderr", data_stderr)
        raise CmdExecFailedException(subp.returncode)
    output = data_stdout.rstrip()
    if expected_output:
        if output != expected_output:
            raise CmdExecUnexpectedOutputException(output, expected_output)
    return output

class TeamBasicTest:
    def __init__(self):
        self._team_dev_name = "testteamx"
        self._team_modes = ["broadcast", "roundrobin", "activebackup", "loadbalance"]
        self._loop_count = 1
        self._port_names = []

    def set_loop_count(self, new_loop_count):
        self._loop_count = new_loop_count

    def port_add(self, port_name):
        self._port_names.append(port_name)

    def _run_one_mode(self, mode_name):
        team_name = self._team_dev_name
        cmd_exec("ip link add %s type team" % team_name)
        try:
            self._created_teams.append(team_name)
            cmd_exec("teamnl %s getoption mode" % team_name, "*NOMODE*")
            cmd_exec("teamnl %s setoption mode %s" % (team_name, mode_name))
            cmd_exec("teamnl %s getoption mode" % team_name, mode_name)

            for port_name in self._port_names:
                cmd_exec("ip link set %s down" % port_name)
                cmd_exec("ip link set %s master %s" % (port_name, team_name))

            cmd_exec("ip link set %s up" % team_name)
            cmd_exec("ip addr add 192.168.241.231/24 dev %s" % team_name)
            cmd_exec("ip link set %s down" % team_name)
            cmd_exec("ip addr flush dev %s" % team_name)

            cmd_exec("teamnl %s options" % team_name)
            cmd_exec("teamnl %s ports" % team_name)

            for port_name in self._port_names:
                cmd_exec("ip link set %s nomaster" % port_name)
        finally:
                cmd_exec("ip link del %s" % team_name)

    def _create_team_initscript(self):
        f = open("/etc/sysconfig/network-scripts/ifcfg-%s" % self._team_dev_name, "w")
        f.write(
"""
DEVICE="%s"
DEVICETYPE="Team"
ONBOOT="no"
BOOTPROTO=none
NETMASK=255.255.255.0
IPADDR=192.168.241.231
TEAM_CONFIG='{"runner": {"name": "activebackup"}}'
""" % self._team_dev_name)
        f.close()
        cmd_exec("ifup %s" % self._team_dev_name)
    
    def _create_port_initscript(self, port_name):
        f = open("/etc/sysconfig/network-scripts/ifcfg-%s" % port_name, "w")
        f.write(
"""
DEVICE="%s"
DEVICETYPE="TeamPort"
ONBOOT="yes"
TEAM_MASTER="%s"
TEAM_PORT_CONFIG='{"prio": 10}'
""" % (port_name, self._team_dev_name))
        f.close()
        cmd_exec("ifup %s" % port_name)

    def _run_teamd_initscripts(self):
        os.makedirs("/tmp/team_test/")
        try:
            ifcfg_files = " ".join(["ifcfg-%s" % port_name for port_name in self._port_names])
            cmd_exec("tar --ignore-failed-read -C /etc/sysconfig/network-scripts/ -cf /tmp/team_test/initscripts_bkp.tar %s" % ifcfg_files)
            self._create_team_initscript()
            for port_name in self._port_names:
                self._create_port_initscript(port_name)
            cmd_exec("ifdown %s" % self._team_dev_name)
        except:
            cmd_exec("ifdown %s" % self._team_dev_name, cleaner=True)
            cmd_exec("ip link del %s" % self._team_dev_name, cleaner=True)
            raise
        finally:
            cmd_exec("tar -C /etc/sysconfig/network-scripts/ -xf /tmp/team_test/initscripts_bkp.tar")
            os.unlink("/tmp/team_test/initscripts_bkp.tar")
            os.removedirs("/tmp/team_test/")

    def _run_one_loop(self, run_nr):
        print "RUN #%d" % (run_nr)
        self._created_teams = []
        try:
            for mode_name in self._team_modes:
                self._run_one_mode(mode_name)
            self._run_teamd_initscripts()
        finally:
            cmd_exec("modprobe -r team_mode_loadbalance team_mode_roundrobin team_mode_activebackup team_mode_broadcast team");

    def run(self):
        for i in xrange(self._loop_count):
            self._run_one_loop(i + 1)

def main():
    try:
        opts, args = getopt.getopt(
            sys.argv[1:],
            "hc:p:",
            ["help", "loop-count=", "port="]
        )
    except getopt.GetoptError, err:
        print str(err)
        usage()

    btest = TeamBasicTest()

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
        elif opt in ("-c", "--loop-count"):
            btest.set_loop_count(int(arg))
        elif opt in ("-p", "--port"):
            btest.port_add(arg)

    btest.run()

if __name__ == "__main__":
    main()