Statistics
| Branch: | Tag: | Revision:

mininet / mininet / nodelib.py @ b1ec912d

History | View | Annotate | Download (4.97 KB)

1
"""
2
Node Library for Mininet
3

4
This contains additional Node types which you may find to be useful.
5
"""
6

    
7
from mininet.node import Node, Switch
8
from mininet.log import info, warn
9
from mininet.moduledeps import pathCheck
10

    
11
import re
12

    
13
class LinuxBridge( Switch ):
14
    "Linux Bridge (with optional spanning tree)"
15

    
16
    nextPrio = 100  # next bridge priority for spanning tree
17

    
18
    def __init__( self, name, stp=False, prio=None, **kwargs ):
19
        """stp: use spanning tree protocol? (default False)
20
           prio: optional explicit bridge priority for STP"""
21
        self.stp = stp
22
        if prio:
23
            self.prio = prio
24
        else:
25
            self.prio = LinuxBridge.nextPrio
26
            LinuxBridge.nextPrio += 1
27
        Switch.__init__( self, name, **kwargs )
28

    
29
    def connected( self ):
30
        "Are we forwarding yet?"
31
        if self.stp:
32
            return 'forwarding' in self.cmd( 'brctl showstp', self )
33
        else:
34
            return True
35

    
36
    def start( self, _controllers ):
37
        "Start Linux bridge"
38
        self.cmd( 'ifconfig', self, 'down' )
39
        self.cmd( 'brctl delbr', self )
40
        self.cmd( 'brctl addbr', self )
41
        if self.stp:
42
            self.cmd( 'brctl setbridgeprio', self.prio )
43
            self.cmd( 'brctl stp', self, 'on' )
44
        for i in self.intfList():
45
            if self.name in i.name:
46
                self.cmd( 'brctl addif', self, i )
47
        self.cmd( 'ifconfig', self, 'up' )
48

    
49
    def stop( self ):
50
        "Stop Linux bridge"
51
        self.cmd( 'ifconfig', self, 'down' )
52
        self.cmd( 'brctl delbr', self )
53

    
54
    def dpctl( self, *args ):
55
        "Run brctl command"
56
        return self.cmd( 'brctl', *args )
57

    
58
    @classmethod
59
    def setup( cls ):
60
        "Make sure our class dependencies are available"
61
        pathCheck( 'brctl', moduleName='bridge-utils' )
62

    
63

    
64
class NAT( Node ):
65
    "NAT: Provides connectivity to external network"
66

    
67
    def __init__( self, name, inetIntf=None, subnet='10.0/8',
68
                  localIntf=None, **params):
69
        """Start NAT/forwarding between Mininet and external network
70
           inetIntf: interface for internet access
71
           subnet: Mininet subnet (default 10.0/8)="""
72
        super( NAT, self ).__init__( name, **params )
73

    
74
        self.inetIntf = inetIntf if inetIntf else self.getGatewayIntf()
75
        self.subnet = subnet
76
        self.localIntf = localIntf
77

    
78
    def config( self, **params ):
79
        """Configure the NAT and iptables"""
80
        super( NAT, self).config( **params )
81

    
82
        if not self.localIntf:
83
            self.localIntf =  self.defaultIntf()
84

    
85
        self.cmd( 'sysctl net.ipv4.ip_forward=0' )
86

    
87
        # Flush any currently active rules
88
        # TODO: is this safe?
89
        self.cmd( 'iptables -F' )
90
        self.cmd( 'iptables -t nat -F' )
91

    
92
        # Create default entries for unmatched traffic
93
        self.cmd( 'iptables -P INPUT ACCEPT' )
94
        self.cmd( 'iptables -P OUTPUT ACCEPT' )
95
        self.cmd( 'iptables -P FORWARD DROP' )
96

    
97
        # Configure NAT
98
        self.cmd( 'iptables -I FORWARD',
99
                  '-i', self.localIntf, '-d', self.subnet, '-j DROP' )
100
        self.cmd( 'iptables -A FORWARD',
101
                  '-i', self.localIntf, '-s', self.subnet, '-j ACCEPT' )
102
        self.cmd( 'iptables -A FORWARD',
103
                  '-i', self.inetIntf, '-d', self.subnet, '-j ACCEPT' )
104
        self.cmd( 'iptables -t nat -A POSTROUTING',
105
                  '-o', self.inetIntf, '-s', self.subnet, '-j MASQUERADE' )
106

    
107
        # Instruct the kernel to perform forwarding
108
        self.cmd( 'sysctl net.ipv4.ip_forward=1' )
109

    
110
        # Prevent network-manager from messing with our interface
111
        # by specifying manual configuration in /etc/network/interfaces
112
        intf = self.localIntf
113
        cfile = '/etc/network/interfaces'
114
        line = '\niface %s inet manual\n' % intf
115
        config = open( cfile ).read()
116
        if ( line ) not in config:
117
            info( '*** Adding "' + line.strip() + '" to ' + cfile + '\n' )
118
            with open( cfile, 'a' ) as f:
119
                f.write( line )
120
        # Probably need to restart network-manager to be safe -
121
        # hopefully this won't disconnect you
122
        self.cmd( 'service network-manager restart' )
123

    
124
    def getGatewayIntf( self, fallback='eth0' ):
125
        """Return gateway interface name
126
           fallback: default device to fall back to"""
127
        routes = self.cmd( 'ip route show' )
128
        match = re.search( r'default via \S+ dev (\S+)', routes )
129
        if match:
130
            return match.group( 1 )
131
        else:
132
            warn( 'There is no default route set.',
133
                  'Using', fallback, 'as gateway interface...\n' )
134
            return fallback
135

    
136
    def terminate( self ):
137
        """Stop NAT/forwarding between Mininet and external network"""
138
        # Flush any currently active rules
139
        # TODO: is this safe?
140
        self.cmd( 'iptables -F' )
141
        self.cmd( 'iptables -t nat -F' )
142

    
143
        # Instruct the kernel to stop forwarding
144
        self.cmd( 'sysctl net.ipv4.ip_forward=0' )
145

    
146
        super( NAT, self ).terminate()