Statistics
| Branch: | Tag: | Revision:

mininet / mininet / topo.py @ 89fb0819

History | View | Annotate | Download (10.5 KB)

1
#!/usr/bin/env python
2
"""@package topo
3

4
Network topology creation.
5

6
@author Brandon Heller (brandonh@stanford.edu)
7

8
This package includes code to represent network topologies.
9

10
A Topo object can be a topology database for NOX, can represent a physical
11
setup for testing, and can even be emulated with the Mininet package.
12
"""
13

    
14
from mininet.util import irange, natural, naturalSeq
15

    
16
class MultiGraph( object ):
17
    "Utility class to track nodes and edges - replaces networkx.MultiGraph"
18

    
19
    def __init__( self ):
20
        self.node = {}
21
        self.edge = {}
22
        self.edgeinfo = {}
23

    
24
    def add_node( self, node, attr_dict=None, **attrs):
25
        """Add node to graph
26
           attr_dict: attribute dict (optional)
27
           attrs: more attributes (optional)"""
28
        attr_dict = {} if attr_dict is None else attr_dict
29
        attr_dict.update( attrs )
30
        self.node[ node ] = attr_dict
31

    
32
    def add_edge( self, src, dst, key=None, attr_dict=None, **attrs ):
33
        """Add edge to graph
34
           key: optional key
35
           attr_dict: optional attribute dict"""
36
        attr_dict = {} if attr_dict is None else attr_dict
37
        attr_dict.update( attrs )
38
        self.node.setdefault( src, {} )
39
        self.node.setdefault( dst, {} )
40
        self.edge.setdefault( src, {} )
41
        self.edge.setdefault( dst, {} )
42
        self.edge[ src ].setdefault( dst, {} )
43
        entry = self.edge[ dst ][ src ] = self.edge[ src ][ dst ]
44
        # If no key, pick next ordinal number
45
        if key is None:
46
            keys = [ k for k in entry.keys() if type( k ) is int ]
47
            key = max( [ 0 ] + keys ) + 1
48
        entry[ key ] = attr_dict
49
        return key
50

    
51
    def nodes( self, data=False):
52
        """Return list of graph nodes
53
           data: return list of ( node, attrs)"""
54
        return self.node.items() if data else self.node.keys()
55

    
56
    def edges_iter( self, data=False ):
57
        "Iterator: return graph edges"
58
        for src, entry in self.edge.iteritems():
59
            for dst, keys in entry.iteritems():
60
                if [ src, dst ] != sorted( [ src, dst ] ):
61
                    # Skip duplicate edges
62
                    continue
63
                for key, attrs in keys.iteritems():
64
                    if data:
65
                        yield( ( src, dst, attrs ) )
66
                    else:
67
                        yield( ( src, dst ) )
68

    
69
    def edges( self, data=False ):
70
        "Return list of graph edges"
71
        return list( self.edges_iter( data ) )
72

    
73

    
74
    def __getitem__( self, node ):
75
        "Return link dict for given src node"
76
        return self.edge[ node ]
77

    
78
    def __len__( self ):
79
        "Return the number of nodes"
80
        return len( self.node )
81

    
82
    def convertTo( self, cls, data=False ):
83
        """Convert to a new object of networkx.MultiGraph-like class cls
84
           data: include node and edge data"""
85
        g = cls()
86
        g.add_nodes_from( self.nodes( data=data ) )
87
        g.add_edges_from( self.edges( data=data ) )
88
        return g
89

    
90

    
91
class Topo(object):
92
    "Data center network representation for structured multi-trees."
93

    
94
    def __init__( self, *args, **params ):
95
        """Topo object. 
96
           Optional named parameters:
97
           hinfo: default host options
98
           sopts: default switch options
99
           lopts: default link options
100
           calls build()"""
101
        self.g = MultiGraph()
102
        self.hopts = params.pop( 'hopts', {} )
103
        self.sopts = params.pop( 'sopts', {} )
104
        self.lopts = params.pop( 'lopts', {} )
105
        self.ports = {}  # ports[src][dst][sport] is port on dst that connects to src
106
        self.build( *args, **params )
107

    
108
    def build( self, *args, **params ):
109
        "Override this method to build your topology."
110
        pass
111

    
112
    def addNode( self, name, **opts ):
113
        """Add Node to graph.
114
           name: name
115
           opts: node options
116
           returns: node name"""
117
        self.g.add_node( name, **opts )
118
        return name
119

    
120
    def addHost( self, name, **opts ):
121
        """Convenience method: Add host to graph.
122
           name: host name
123
           opts: host options
124
           returns: host name"""
125
        if not opts and self.hopts:
126
            opts = self.hopts
127
        return self.addNode(name, **opts)
128

    
129
    def addSwitch( self, name, **opts ):
130
        """Convenience method: Add switch to graph.
131
           name: switch name
132
           opts: switch options
133
           returns: switch name"""
134
        if not opts and self.sopts:
135
            opts = self.sopts
136
        result = self.addNode(name, isSwitch=True, **opts)
137
        return result
138

    
139
    def addLink( self, node1, node2, port1=None, port2=None,
140
                key=None, **opts ):
141
        """node1, node2: nodes to link together
142
           port1, port2: ports (optional)
143
           opts: link options (optional)
144
           returns: link info key"""
145
        if not opts and self.lopts:
146
            opts = self.lopts
147
        port1, port2 = self.addPort(node1, node2, port1, port2)
148
        opts.update( node1=node1, node2=node2, port1=port1, port2=port2 )
149
        self.g.add_edge(node1, node2, key, opts )
150
        return key
151

    
152
    def nodes( self, sort=True ):
153
        "Return nodes in graph"
154
        if sort:
155
            return self.sorted( self.g.nodes() )
156
        else:
157
            return self.g.nodes()
158

    
159
    def isSwitch( self, n ):
160
        "Returns true if node is a switch."
161
        return self.g.node[ n ].get( 'isSwitch', False )
162

    
163
    def switches( self, sort=True ):
164
        """Return switches.
165
           sort: sort switches alphabetically
166
           returns: dpids list of dpids"""
167
        return [ n for n in self.nodes( sort ) if self.isSwitch( n ) ]
168

    
169
    def hosts( self, sort=True ):
170
        """Return hosts.
171
           sort: sort hosts alphabetically
172
           returns: list of hosts"""
173
        return [ n for n in self.nodes( sort ) if not self.isSwitch( n ) ]
174

    
175
    def links( self, sort=True, withKeys=False ):
176
        """Return links.
177
           sort: sort links alphabetically
178
           withKeys: return key in tuple
179
           @return links list of ( src, dst [,key ] )"""
180
        if not sort:
181
            return self.g.edges( withKeys )
182
        else:
183
            if withKeys:
184
                links = [ tuple( self.sorted( ( s, d ) ) ) + [ k ]
185
                          for s, d, k in self.g.edges( data=True ) ]
186
            else:
187
                links = [ tuple ( self.sorted( e ) ) for e in self.g.edges() ]
188
            return sorted( links, key=naturalSeq )
189

    
190
    # This legacy port management mechanism is clunky and will probably
191
    # be removed at some point.
192

    
193
    def addPort( self, src, dst, sport=None, dport=None ):
194
        """Generate port mapping for new edge.
195
            src: source switch name
196
            dst: destination switch name"""
197
        # Initialize if necessary
198
        ports = self.ports
199
        ports.setdefault( src, {} )
200
        ports.setdefault( dst, {} )
201
        # New port: number of outlinks + base
202
        if sport is None:
203
            src_base = 1 if self.isSwitch( src ) else 0
204
            sport = len( ports[ src ] ) + src_base
205
        if dport is None:
206
            dst_base = 1 if self.isSwitch( dst ) else 0
207
            dport = len( ports[ dst ] ) + dst_base
208
        ports[ src ][ sport ] = ( dst, dport )
209
        ports[ dst ][ dport ] = ( src, sport )
210
        return sport, dport
211

    
212
    def port( self, src, dst ):
213
        """Get port numbers.
214
            src: source switch name
215
            dst: destination switch name
216
            sport: optional source port (otherwise use lowest src port)
217
            returns: tuple (sport, dport), where
218
                sport = port on source switch leading to the destination switch
219
                dport = port on destination switch  leading to the source switch
220
            Note that you can also look up ports using linkInfo()"""
221
        # A bit ugly and slow vs. single-link implementation ;-(
222
        ports = [ ( sport, entry[ 1 ] )
223
                  for sport, entry in self.ports[ src ].items()
224
                  if entry[ 0 ] == dst ]
225
        return ports if len( ports ) != 1 else ports[ 0 ]
226

    
227
    def _linkEntry( self, src, dst, key=None ):
228
        "Helper function: return link entry and key"
229
        entry = self.g[ src ][ dst ]
230
        if key is None:
231
            key = min( entry )
232
        return entry, key
233
    
234
    def linkInfo( self, src, dst, key=None ):
235
        "Return link metadata dict"
236
        entry, key = self._linkEntry( src, dst, key )
237
        return entry[ key ]
238

    
239
    def setlinkInfo( self, src, dst, info, key=None ):
240
        "Set link metadata dict"
241
        entry, key = self._linkEntry( src, dst, key )
242
        entry [ key ] = info
243

    
244
    def nodeInfo( self, name ):
245
        "Return metadata (dict) for node"
246
        return self.g.node[ name ]
247

    
248
    def setNodeInfo( self, name, info ):
249
        "Set metadata (dict) for node"
250
        self.g.node[ name ] = info
251

    
252
    @staticmethod
253
    def sorted( items ):
254
        "Items sorted in natural (i.e. alphabetical) order"
255
        return sorted( items, key=natural )
256

    
257

    
258
class SingleSwitchTopo( Topo ):
259
    "Single switch connected to k hosts."
260

    
261
    def build( self, k=2, **opts ):
262
        "k: number of hosts"
263
        self.k = k
264
        switch = self.addSwitch( 's1' )
265
        for h in irange( 1, k ):
266
            host = self.addHost( 'h%s' % h )
267
            self.addLink( host, switch )
268

    
269

    
270
class SingleSwitchReversedTopo( Topo ):
271
    """Single switch connected to k hosts, with reversed ports.
272
       The lowest-numbered host is connected to the highest-numbered port.
273
       Useful to verify that Mininet properly handles custom port numberings."""
274

    
275
    def build( self, k=2 ):
276
        "k: number of hosts"
277
        self.k = k
278
        switch = self.addSwitch( 's1' )
279
        for h in irange( 1, k ):
280
            host = self.addHost( 'h%s' % h )
281
            self.addLink( host, switch,
282
                          port1=0, port2=( k - h + 1 ) )
283

    
284

    
285
class LinearTopo( Topo ):
286
    "Linear topology of k switches, with n hosts per switch."
287

    
288
    def build( self, k=2, n=1, **opts):
289
        """k: number of switches
290
           n: number of hosts per switch"""
291
        self.k = k
292
        self.n = n
293

    
294
        if n == 1:
295
            genHostName = lambda i, j: 'h%s' % i
296
        else:
297
            genHostName = lambda i, j: 'h%ss%d' % ( j, i )
298

    
299
        lastSwitch = None
300
        for i in irange( 1, k ):
301
            # Add switch
302
            switch = self.addSwitch( 's%s' % i )
303
            # Add hosts to switch
304
            for j in irange( 1, n ):
305
                host = self.addHost( genHostName( i, j ) )
306
                self.addLink( host, switch )
307
            # Connect switch to previous
308
            if lastSwitch:
309
                self.addLink( switch, lastSwitch )
310
            lastSwitch = switch