In the previous post Install NetworkX, I have introduced what is NetworkX and how to install NetworkX. This post shows how to apply NetworkX in POX to find a shortest path based on the topology mentioned in previous post Create a custom topology in Mininet (2).
This module first gets network's graph by using openflow.discovery
module mentioned in Discovery Topology in POX. The discovery module raises linkEvent if any link between two switches is added or removed. Then, this link is added to (or removed from) the network's graph. After controller got the network's graph, it calls nx.shortest_path
to find the shortest path between host1 and host2.
from pox.core import core
import pox.openflow.libopenflow_01 as of
from pox.lib.revent import *
from pox.lib.recoco import Timer
from collections import defaultdict
from pox.openflow.discovery import Discovery
from pox.lib.util import dpid_to_str
import time
import networkx as nx
class topoDiscovery(EventMixin):
G = nx.Graph()
def __init__(self):
def startup():
core.openflow.addListeners(self, priority = 0)
core.openflow_discovery.addListeners(self)
core.call_when_ready(startup, ('openflow','openflow_discovery'))
print "init completed"
def _handle_LinkEvent(self, event):
l = event.link
sw1 = l.dpid1
sw2 = l.dpid2
pt1 = l.port1
pt2 = l.port2
self.G.add_node( sw1 )
self.G.add_node( sw2 )
if event.added:
self.G.add_edge(sw1,sw2)
if event.removed:
try:
self.G.remove_edge(sw1,sw2)
except:
print "remove edge error"
print 'link added is %s'%event.added
print 'link removed is %s' %event.removed
print 'switch1 %d' %l.dpid1
print 'port1 %d' %l.port1
print 'switch2 %d' %l.dpid2
print 'port2 %d' %l.port2
print self.G.edges()
try:
print nx.shortest_path(self.G,1,6)
except:
print "no such Graph"
def launch():
core.registerNew(topoDiscovery)
run topoDiscovery and openflow.discovery
sudo ./pox/pox.py topoDiscovery openflow.discovery
Shortest path is shown as following:
[1, 2, 3, 6]
References:
Install NetworkX
Discovery Topology in POX