首页 > 解决方案 > 使用python构建拓扑时映射错误

问题描述

我正在尝试使用 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'**

似乎映射没有正确进行。作为解决方案,我能做些什么?

标签: pythonmininet

解决方案


您的问题是变量 cmap 的范围。build 方法中的这个声明只有本地范围。

cmap={}

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

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

推荐阅读