使用python构建拓扑时发生映射错误

时间:2018-08-12 21:42:07

标签: python mininet

我正在尝试使用python在mininet中构建拓扑。我的拓扑是这样的:

         c
         |
     +--s1--+
     |      |
    s2     s3
   |  |     |
   h1 h2    h3

因此,如您所见,我有2个级别的开关,switch_L1连接到控制器,而switch_L2连接到switch_L1。这是我的代码:

from mininet.topo import Topo
from mininet.net import Mininet
from mininet.log import setLogLevel, info
from mininet.cli import CLI
from mininet.node import OVSSwitch, Controller, RemoteController
from time import sleep


n_switches = 3
n_switches_L1 = 1 #number of switches which are connected to the controller
n_switches_L2 = 2 #number of normarl switches - level 2
hosts_per_switch = [2, 1] 
sw_per_mainsw = [1, 1]
c_n = 1 #number of controllers
hosts = []
switches_L1 = []
switches_L2 = []
cmap = {}

class MyTopo(Topo):
    "Single switch connected to n hosts."
    def build(self):

        info( "*** Creating switches\n" )
        switches_L1 = [ self.addSwitch("s%s" % (n + 1)) for n in range(n_switches_L1)]
        switches_L2 = [ self.addSwitch("s%s" % (n + 1 + n_switches_L1)) for n in range(n_switches_L2)]
        .
        .
        .
        cmap1={}
        cmap2={}
        for sw1 in switches_L1:
            cmap1[sw1] = [c0]
        print(cmap1)

        for sw2 in switches_L2:
            cmap2[sw2] = []
        print(cmap2)

        cmap={}
        cmap.update(cmap1)
        cmap.update(cmap2)
        print(cmap)

c0 = RemoteController('c0', ip='127.0.0.1', port=6653)

#cmap = { **{'%s': [c0] % (sw1) for sw1 in range(switches_L1)}, **{'%s': [c1] % (sw2) for sw2 in range(switches_L2)}}

class MultiSwitch(OVSSwitch):
    "Custom Switch() subclass that connects to different controllers"
    def start(self, controllers):
        return OVSSwitch.start(self, cmap[self.name])


if __name__ == '__main__':

    setLogLevel('info')

    topo = MyTopo()

    net = Mininet(topo=topo, switch=MultiSwitch, build=False)
    net.addController(c0)
    c0.start()
    net.build()
    net.start()
    CLI(net)
    net.stop()

但是当我运行拓扑时,会遇到错误:

*** Creating network
*** Adding hosts: h1 h2 h3 
*** Adding switches: s1 s2 s3 
*** Adding links: (s1, s2) (s1, s3) (s2, h1) (s2, h2) (s3, h3) 
*** Configuring hosts h1 h2 h3 
*** Starting controller c0 
*** Starting 3 switches
**s1 Traceback (most recent call last):   File "test.py", line 91, in <module>
    net.start()   File "build/bdist.linux-x86_64/egg/mininet/net.py", line 549, in start   File "test.py", line 78, in start
    return OVSSwitch.start(self, cmap[self.name]) KeyError: 's1'**

似乎映射未正确进行。我该怎么办?

1 个答案:

答案 0 :(得分:1)

您的问题是变量cmap的范围。 build方法中的此声明仅具有局部范围。

cmap={}

如果要在函数内部使用全局变量,则需要使用关键字global

global cmap
cmap = {}
cmap.update(cmap1)
cmap.update(cmap2)