Merge branch 'master' into RAMCloud
Conflicts:
conf/onos.properties
src/main/java/net/onrc/onos/flow/FlowManagerImpl.java
src/main/java/net/onrc/onos/graph/LocalTopologyEventListener.java
src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRoute.java
src/main/java/net/onrc/onos/ofcontroller/core/ILinkStorage.java
src/main/java/net/onrc/onos/ofcontroller/core/ISwitchStorage.java
src/main/java/net/onrc/onos/ofcontroller/core/internal/DeviceStorageImpl.java
src/main/java/net/onrc/onos/ofcontroller/core/internal/LinkStorageImpl.java
src/main/java/net/onrc/onos/ofcontroller/core/internal/SwitchStorageImpl.java
src/main/java/net/onrc/onos/ofcontroller/floodlightlistener/NetworkGraphPublisher.java
src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowManager.java
src/main/java/net/onrc/onos/ofcontroller/topology/ShortestPath.java
src/main/java/net/onrc/onos/ofcontroller/topology/web/RouteResource.java
src/test/java/net/onrc/onos/ofcontroller/core/internal/SwitchStorageImplTest.java
src/test/java/net/onrc/onos/ofcontroller/core/internal/SwitchStorageImplTestBB.java
src/test/java/net/onrc/onos/ofcontroller/devicemanager/internal/DeviceStorageImplTest.java
src/test/java/net/onrc/onos/ofcontroller/topology/TopologyManagerTest.java
diff --git a/src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRoute.java b/src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRoute.java
index 52281ac..33280a6 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRoute.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRoute.java
@@ -34,15 +34,17 @@
import net.floodlightcontroller.util.MACAddress;
import net.onrc.onos.ofcontroller.bgproute.RibUpdate.Operation;
import net.onrc.onos.ofcontroller.core.INetMapTopologyService.ITopoLinkService;
-import net.onrc.onos.ofcontroller.core.INetMapTopologyService.ITopoRouteService;
+import net.onrc.onos.ofcontroller.core.config.IConfigInfoService;
import net.onrc.onos.ofcontroller.core.internal.TopoLinkServiceImpl;
import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscovery;
import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscovery.LDUpdate;
import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscoveryService;
+import net.onrc.onos.ofcontroller.proxyarp.BgpProxyArpManager;
import net.onrc.onos.ofcontroller.proxyarp.IArpRequester;
import net.onrc.onos.ofcontroller.proxyarp.IProxyArpService;
-import net.onrc.onos.ofcontroller.proxyarp.ProxyArpManager;
-import net.onrc.onos.ofcontroller.routing.TopoRouteService;
+import net.onrc.onos.ofcontroller.topology.ITopologyNetService;
+import net.onrc.onos.ofcontroller.topology.Topology;
+import net.onrc.onos.ofcontroller.topology.TopologyManager;
import net.onrc.onos.ofcontroller.util.DataPath;
import net.onrc.onos.ofcontroller.util.Dpid;
import net.onrc.onos.ofcontroller.util.FlowEntry;
@@ -76,75 +78,76 @@
public class BgpRoute implements IFloodlightModule, IBgpRouteService,
ITopologyListener, IArpRequester,
- IOFSwitchListener, ILayer3InfoService,
+ IOFSwitchListener, IConfigInfoService,
IProxyArpService {
- protected static Logger log = LoggerFactory.getLogger(BgpRoute.class);
+ private final static Logger log = LoggerFactory.getLogger(BgpRoute.class);
- protected IFloodlightProviderService floodlightProvider;
- protected ITopologyService topology;
- protected ITopoRouteService topoRouteService;
- protected ILinkDiscoveryService linkDiscoveryService;
- protected IRestApiService restApi;
+ private IFloodlightProviderService floodlightProvider;
+ private ITopologyService topologyService;
+ private ITopologyNetService topologyNetService;
+ private ILinkDiscoveryService linkDiscoveryService;
+ private IRestApiService restApi;
- protected ProxyArpManager proxyArp;
+ private BgpProxyArpManager proxyArp;
- protected IPatriciaTrie<RibEntry> ptree;
- protected IPatriciaTrie<Interface> interfacePtrie;
- protected BlockingQueue<RibUpdate> ribUpdates;
+ private IPatriciaTrie<RibEntry> ptree;
+ private IPatriciaTrie<Interface> interfacePtrie;
+ private BlockingQueue<RibUpdate> ribUpdates;
- protected String bgpdRestIp;
- protected String routerId;
- protected String configFilename = "config.json";
+ private String bgpdRestIp;
+ private String routerId;
+ private String configFilename = "config.json";
//We need to identify our flows somehow. But like it says in LearningSwitch.java,
//the controller/OS should hand out cookie IDs to prevent conflicts.
- protected final long APP_COOKIE = 0xa0000000000000L;
+ private final long APP_COOKIE = 0xa0000000000000L;
//Cookie for flows that do L2 forwarding within SDN domain to egress routers
- protected final long L2_FWD_COOKIE = APP_COOKIE + 1;
+ private final long L2_FWD_COOKIE = APP_COOKIE + 1;
//Cookie for flows in ingress switches that rewrite the MAC address
- protected final long MAC_RW_COOKIE = APP_COOKIE + 2;
+ private final long MAC_RW_COOKIE = APP_COOKIE + 2;
//Cookie for flows that setup BGP paths
- protected final long BGP_COOKIE = APP_COOKIE + 3;
+ private final long BGP_COOKIE = APP_COOKIE + 3;
//Forwarding uses priority 0, and the mac rewrite entries in ingress switches
//need to be higher priority than this otherwise the rewrite may not get done
- protected final short SDNIP_PRIORITY = 10;
- protected final short ARP_PRIORITY = 20;
+ private final short SDNIP_PRIORITY = 10;
+ private final short ARP_PRIORITY = 20;
- protected final short BGP_PORT = 179;
+ private final short BGP_PORT = 179;
- protected final int TOPO_DETECTION_WAIT = 2; //seconds
+ private final int TOPO_DETECTION_WAIT = 2; //seconds
//Configuration stuff
- protected List<String> switches;
- protected Map<String, Interface> interfaces;
- protected Map<InetAddress, BgpPeer> bgpPeers;
- protected SwitchPort bgpdAttachmentPoint;
- protected MACAddress bgpdMacAddress;
+ private List<String> switches;
+ private Map<String, Interface> interfaces;
+ private Map<InetAddress, BgpPeer> bgpPeers;
+ private SwitchPort bgpdAttachmentPoint;
+ private MACAddress bgpdMacAddress;
+ private short vlan;
//True when all switches have connected
- protected volatile boolean switchesConnected = false;
+ private volatile boolean switchesConnected = false;
//True when we have a full mesh of shortest paths between gateways
- protected volatile boolean topologyReady = false;
+ private volatile boolean topologyReady = false;
- protected ArrayList<LDUpdate> linkUpdates;
- protected SingletonTask topologyChangeDetectorTask;
+ private ArrayList<LDUpdate> linkUpdates;
+ private SingletonTask topologyChangeDetectorTask;
- protected SetMultimap<InetAddress, RibUpdate> prefixesWaitingOnArp;
+ private SetMultimap<InetAddress, RibUpdate> prefixesWaitingOnArp;
- protected Map<InetAddress, Path> pathsWaitingOnArp;
+ private Map<InetAddress, Path> pathsWaitingOnArp;
- protected ExecutorService bgpUpdatesExecutor;
+ private ExecutorService bgpUpdatesExecutor;
- protected Map<InetAddress, Path> pushedPaths;
- protected Map<Prefix, Path> prefixToPath;
- protected Multimap<Prefix, PushedFlowMod> pushedFlows;
+ private Map<InetAddress, Path> pushedPaths;
+ private Map<Prefix, Path> prefixToPath;
+ private Multimap<Prefix, PushedFlowMod> pushedFlows;
private FlowCache flowCache;
- protected volatile Map<Long, ?> topoRouteTopology = null;
+ private volatile Topology topology = null;
- protected class TopologyChangeDetector implements Runnable {
+ private class TopologyChangeDetector implements Runnable {
@Override
public void run() {
log.debug("Running topology change detection task");
@@ -182,8 +185,8 @@
}
}
- private void readGatewaysConfiguration(String gatewaysFilename){
- File gatewaysFile = new File(gatewaysFilename);
+ private void readConfiguration(String configFilename){
+ File gatewaysFile = new File(configFilename);
ObjectMapper mapper = new ObjectMapper();
try {
@@ -204,6 +207,7 @@
new Port(config.getBgpdAttachmentPort()));
bgpdMacAddress = config.getBgpdMacAddress();
+ vlan = config.getVlan();
} catch (JsonParseException e) {
log.error("Error in JSON file", e);
System.exit(1);
@@ -227,6 +231,7 @@
Collection<Class<? extends IFloodlightService>> l
= new ArrayList<Class<? extends IFloodlightService>>();
l.add(IBgpRouteService.class);
+ l.add(IConfigInfoService.class);
return l;
}
@@ -235,7 +240,7 @@
Map<Class<? extends IFloodlightService>, IFloodlightService> m
= new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
m.put(IBgpRouteService.class, this);
- m.put(IProxyArpService.class, this);
+ m.put(IConfigInfoService.class, this);
return m;
}
@@ -260,19 +265,22 @@
// Register floodlight provider and REST handler.
floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
- topology = context.getServiceImpl(ITopologyService.class);
+ topologyService = context.getServiceImpl(ITopologyService.class);
linkDiscoveryService = context.getServiceImpl(ILinkDiscoveryService.class);
restApi = context.getServiceImpl(IRestApiService.class);
//TODO We'll initialise this here for now, but it should really be done as
//part of the controller core
- proxyArp = new ProxyArpManager(floodlightProvider, topology, this, restApi);
+ //proxyArp = new ProxyArpManager(floodlightProvider, topologyService, this, restApi);
+ proxyArp = new BgpProxyArpManager();
+ proxyArp.init(floodlightProvider, topologyService, this, restApi);
+ //proxyArp = context.getServiceImpl(IProxyArpService.class);
linkUpdates = new ArrayList<LDUpdate>();
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
topologyChangeDetectorTask = new SingletonTask(executor, new TopologyChangeDetector());
- topoRouteService = new TopoRouteService("", "");
+ topologyNetService = new TopologyManager("");
pathsWaitingOnArp = new HashMap<InetAddress, Path>();
prefixesWaitingOnArp = Multimaps.synchronizedSetMultimap(
@@ -312,18 +320,18 @@
}
log.debug("Config file set to {}", configFilename);
- readGatewaysConfiguration(configFilename);
+ readConfiguration(configFilename);
}
@Override
public void startUp(FloodlightModuleContext context) {
restApi.addRestletRoutable(new BgpRouteWebRoutable());
- topology.addListener(this);
+ topologyService.addListener(this);
floodlightProvider.addOFSwitchListener(this);
proxyArp.startUp();
- floodlightProvider.addOFMessageListener(OFType.PACKET_IN, proxyArp);
+ //floodlightProvider.addOFMessageListener(OFType.PACKET_IN, proxyArp);
//Retrieve the RIB from BGPd during startup
retrieveRib();
@@ -483,14 +491,14 @@
}
private void addPrefixFlows(Prefix prefix, Interface egressInterface, MACAddress nextHopMacAddress) {
- log.debug("Adding flows for prefix {} added, next hop mac {}",
+ log.debug("Adding flows for prefix {}, next hop mac {}",
prefix, nextHopMacAddress);
//We only need one flow mod per switch, so pick one interface on each switch
Map<Long, Interface> srcInterfaces = new HashMap<Long, Interface>();
for (Interface intf : interfaces.values()) {
if (!srcInterfaces.containsKey(intf.getDpid())
- && intf != egressInterface) {
+ && !intf.equals(egressInterface)) {
srcInterfaces.put(intf.getDpid(), intf);
}
}
@@ -498,14 +506,14 @@
//Add a flow to rewrite mac for this prefix to all other border switches
for (Interface srcInterface : srcInterfaces.values()) {
DataPath shortestPath;
- if (topoRouteTopology == null) {
- shortestPath = topoRouteService.getShortestPath(
+ if (topology == null) {
+ shortestPath = topologyNetService.getDatabaseShortestPath(
srcInterface.getSwitchPort(),
egressInterface.getSwitchPort());
}
else {
- shortestPath = topoRouteService.getTopoShortestPath(
- topoRouteTopology, srcInterface.getSwitchPort(),
+ shortestPath = topologyNetService.getTopologyShortestPath(
+ topology, srcInterface.getSwitchPort(),
egressInterface.getSwitchPort());
}
@@ -692,17 +700,17 @@
List<PushedFlowMod> pushedFlows = new ArrayList<PushedFlowMod>();
for (Interface srcInterface : interfaces.values()) {
- if (dstInterface.equals(srcInterface.getName())){
+ if (dstInterface.equals(srcInterface)){
continue;
}
DataPath shortestPath;
- if (topoRouteTopology == null) {
- shortestPath = topoRouteService.getShortestPath(
+ if (topology == null) {
+ shortestPath = topologyNetService.getDatabaseShortestPath(
srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
}
else {
- shortestPath = topoRouteService.getTopoShortestPath(topoRouteTopology,
+ shortestPath = topologyNetService.getTopologyShortestPath(topology,
srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
}
@@ -771,7 +779,7 @@
for (BgpPeer bgpPeer : bgpPeers.values()){
Interface peerInterface = interfaces.get(bgpPeer.getInterfaceName());
- DataPath path = topoRouteService.getShortestPath(
+ DataPath path = topologyNetService.getDatabaseShortestPath(
peerInterface.getSwitchPort(), bgpdAttachmentPoint);
if (path == null){
@@ -1046,7 +1054,7 @@
private void beginRouting(){
log.debug("Topology is now ready, beginning routing function");
- topoRouteTopology = topoRouteService.prepareShortestPathTopo();
+ topology = topologyNetService.newDatabaseTopology();
setupArpFlows();
setupDefaultDropFlows();
@@ -1082,11 +1090,11 @@
private void checkTopologyReady(){
for (Interface dstInterface : interfaces.values()) {
for (Interface srcInterface : interfaces.values()) {
- if (dstInterface == srcInterface) {
+ if (dstInterface.equals(srcInterface)) {
continue;
}
- DataPath shortestPath = topoRouteService.getShortestPath(
+ DataPath shortestPath = topologyNetService.getDatabaseShortestPath(
srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
if (shortestPath == null){
@@ -1120,10 +1128,22 @@
RibUpdate update = ribUpdates.take();
switch (update.getOperation()){
case UPDATE:
- processRibAdd(update);
+ if (validateUpdate(update)) {
+ processRibAdd(update);
+ }
+ else {
+ log.debug("Rib UPDATE out of order: {} via {}",
+ update.getPrefix(), update.getRibEntry().getNextHop());
+ }
break;
case DELETE:
- processRibDelete(update);
+ if (validateUpdate(update)) {
+ processRibDelete(update);
+ }
+ else {
+ log.debug("Rib DELETE out of order: {} via {}",
+ update.getPrefix(), update.getRibEntry().getNextHop());
+ }
break;
}
} catch (InterruptedException e) {
@@ -1139,6 +1159,40 @@
}
}
}
+
+ private boolean validateUpdate(RibUpdate update) {
+ RibEntry newEntry = update.getRibEntry();
+ RibEntry oldEntry = ptree.lookup(update.getPrefix());
+
+ //If there is no existing entry we must assume this is the most recent
+ //update. However this might not always be the case as we might have a
+ //POST then DELETE reordering.
+ //if (oldEntry == null || !newEntry.getNextHop().equals(oldEntry.getNextHop())) {
+ if (oldEntry == null) {
+ return true;
+ }
+
+ // This handles the case where routes are gathered in the initial
+ // request because they don't have sequence number info
+ if (newEntry.getSysUpTime() == -1 && newEntry.getSequenceNum() == -1) {
+ return true;
+ }
+
+ if (newEntry.getSysUpTime() > oldEntry.getSysUpTime()) {
+ return true;
+ }
+ else if (newEntry.getSysUpTime() == oldEntry.getSysUpTime()) {
+ if (newEntry.getSequenceNum() > oldEntry.getSequenceNum()) {
+ return true;
+ }
+ else {
+ return false;
+ }
+ }
+ else {
+ return false;
+ }
+ }
@Override
public void topologyChanged() {
@@ -1147,7 +1201,7 @@
}
boolean refreshNeeded = false;
- for (LDUpdate ldu : topology.getLastLinkUpdates()){
+ for (LDUpdate ldu : topologyService.getLastLinkUpdates()){
if (!ldu.getOperation().equals(ILinkDiscovery.UpdateOperation.LINK_UPDATED)){
//We don't need to recalculate anything for just link updates
//They happen very frequently
@@ -1189,7 +1243,7 @@
}
/*
- * ILayer3InfoService methods
+ * IConfigInfoService methods
*/
@Override
@@ -1228,6 +1282,11 @@
public MACAddress getRouterMacAddress() {
return bgpdMacAddress;
}
+
+ @Override
+ public short getVlan() {
+ return vlan;
+ }
/*
* TODO This is a hack to get the REST API to work for ProxyArpManager.
diff --git a/src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRouteResource.java b/src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRouteResource.java
index 8403f71..ddc1e25 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRouteResource.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRouteResource.java
@@ -13,7 +13,7 @@
public class BgpRouteResource extends ServerResource {
- protected static Logger log = LoggerFactory.getLogger(BgpRouteResource.class);
+ protected final static Logger log = LoggerFactory.getLogger(BgpRouteResource.class);
@Get
public String get(String fmJson) {
@@ -68,19 +68,27 @@
IBgpRouteService bgpRoute = (IBgpRouteService) getContext().getAttributes().
get(IBgpRouteService.class.getCanonicalName());
+ String strSysuptime = (String) getRequestAttributes().get("sysuptime");
+ String strSequence = (String) getRequestAttributes().get("sequence");
String routerId = (String) getRequestAttributes().get("routerid");
String prefix = (String) getRequestAttributes().get("prefix");
String mask = (String) getRequestAttributes().get("mask");
String nexthop = (String) getRequestAttributes().get("nexthop");
String capability = (String) getRequestAttributes().get("capability");
+
+ log.debug("sysuptime: {}", strSysuptime);
+ log.debug("sequence: {}", strSequence);
String reply = "";
if (capability == null) {
// this is a prefix add
Prefix p;
+ long sysUpTime, sequenceNum;
try {
p = new Prefix(prefix, Integer.valueOf(mask));
+ sysUpTime = Long.parseLong(strSysuptime);
+ sequenceNum = Long.parseLong(strSequence);
} catch (NumberFormatException e) {
reply = "[POST: mask format is wrong]";
log.info(reply);
@@ -91,7 +99,7 @@
return reply + "\n";
}
- RibEntry rib = new RibEntry(routerId, nexthop);
+ RibEntry rib = new RibEntry(routerId, nexthop, sysUpTime, sequenceNum);
bgpRoute.newRibUpdate(new RibUpdate(Operation.UPDATE, p, rib));
@@ -117,19 +125,27 @@
IBgpRouteService bgpRoute = (IBgpRouteService)getContext().getAttributes().
get(IBgpRouteService.class.getCanonicalName());
+ String strSysuptime = (String) getRequestAttributes().get("sysuptime");
+ String strSequence = (String) getRequestAttributes().get("sequence");
String routerId = (String) getRequestAttributes().get("routerid");
String prefix = (String) getRequestAttributes().get("prefix");
String mask = (String) getRequestAttributes().get("mask");
String nextHop = (String) getRequestAttributes().get("nexthop");
String capability = (String) getRequestAttributes().get("capability");
+ log.debug("sysuptime: {}", strSysuptime);
+ log.debug("sequence: {}", strSequence);
+
String reply = "";
if (capability == null) {
// this is a prefix delete
Prefix p;
+ long sysUpTime, sequenceNum;
try {
p = new Prefix(prefix, Integer.valueOf(mask));
+ sysUpTime = Long.parseLong(strSysuptime);
+ sequenceNum = Long.parseLong(strSequence);
} catch (NumberFormatException e) {
reply = "[DELE: mask format is wrong]";
log.info(reply);
@@ -140,7 +156,7 @@
return reply + "\n";
}
- RibEntry r = new RibEntry(routerId, nextHop);
+ RibEntry r = new RibEntry(routerId, nextHop, sysUpTime, sequenceNum);
bgpRoute.newRibUpdate(new RibUpdate(Operation.DELETE, p, r));
diff --git a/src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRouteResourceSynch.java b/src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRouteResourceSynch.java
index 543827d..fe0ad87 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRouteResourceSynch.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRouteResourceSynch.java
@@ -10,7 +10,7 @@
public class BgpRouteResourceSynch extends ServerResource {
- protected static Logger log = LoggerFactory
+ protected final static Logger log = LoggerFactory
.getLogger(BgpRouteResource.class);
@Post
diff --git a/src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRouteWebRoutable.java b/src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRouteWebRoutable.java
index 669c385..26971b0 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRouteWebRoutable.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/bgproute/BgpRouteWebRoutable.java
@@ -12,7 +12,7 @@
Router router = new Router(context);
router.attach("/json", BgpRouteResource.class);
router.attach("/rib/{dest}", BgpRouteResource.class);
- router.attach("/{routerid}/{prefix}/{mask}/{nexthop}", BgpRouteResource.class);
+ router.attach("/{sysuptime}/{sequence}/{routerid}/{prefix}/{mask}/{nexthop}", BgpRouteResource.class);
router.attach("/{routerid}/{prefix}/{mask}/{nexthop}/synch", BgpRouteResourceSynch.class);
router.attach("/{routerid}/{capability}", BgpRouteResource.class);
return router;
diff --git a/src/main/java/net/onrc/onos/ofcontroller/bgproute/Configuration.java b/src/main/java/net/onrc/onos/ofcontroller/bgproute/Configuration.java
index 1d90edc..4c81d1b 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/bgproute/Configuration.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/bgproute/Configuration.java
@@ -12,6 +12,7 @@
private long bgpdAttachmentDpid;
private short bgpdAttachmentPort;
private MACAddress bgpdMacAddress;
+ private short vlan;
private List<String> switches;
private List<Interface> interfaces;
private List<BgpPeer> peers;
@@ -46,16 +47,25 @@
public void setBgpdMacAddress(String strMacAddress) {
this.bgpdMacAddress = MACAddress.valueOf(strMacAddress);
}
-
+
public List<String> getSwitches() {
return Collections.unmodifiableList(switches);
}
+
+ @JsonProperty("vlan")
+ public void setVlan(short vlan) {
+ this.vlan = vlan;
+ }
+
+ public short getVlan() {
+ return vlan;
+ }
@JsonProperty("switches")
public void setSwitches(List<String> switches) {
this.switches = switches;
}
-
+
public List<Interface> getInterfaces() {
return Collections.unmodifiableList(interfaces);
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/bgproute/FlowCache.java b/src/main/java/net/onrc/onos/ofcontroller/bgproute/FlowCache.java
index d1cb578..1d16eb2 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/bgproute/FlowCache.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/bgproute/FlowCache.java
@@ -19,7 +19,7 @@
import org.slf4j.LoggerFactory;
public class FlowCache {
- private static Logger log = LoggerFactory.getLogger(FlowCache.class);
+ private final static Logger log = LoggerFactory.getLogger(FlowCache.class);
private IFloodlightProviderService floodlightProvider;
diff --git a/src/main/java/net/onrc/onos/ofcontroller/bgproute/Interface.java b/src/main/java/net/onrc/onos/ofcontroller/bgproute/Interface.java
index 48b60d8..5db8f0a 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/bgproute/Interface.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/bgproute/Interface.java
@@ -59,4 +59,31 @@
public int getPrefixLength() {
return prefixLength;
}
+
+ @Override
+ public boolean equals(Object other) {
+ if (other == null || !(other instanceof Interface)) {
+ return false;
+ }
+
+ Interface otherInterface = (Interface)other;
+
+ //Don't check switchPort as it's comprised of dpid and port
+ return (name.equals(otherInterface.name)) &&
+ (dpid == otherInterface.dpid) &&
+ (port == otherInterface.port) &&
+ (ipAddress.equals(otherInterface.ipAddress)) &&
+ (prefixLength == otherInterface.prefixLength);
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 17;
+ hash = 31 * hash + name.hashCode();
+ hash = 31 * hash + (int)(dpid ^ dpid >>> 32);
+ hash = 31 * hash + (int)port;
+ hash = 31 * hash + ipAddress.hashCode();
+ hash = 31 * hash + prefixLength;
+ return hash;
+ }
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/bgproute/PtreeNode.java b/src/main/java/net/onrc/onos/ofcontroller/bgproute/PtreeNode.java
index 50b7c7d..264b0ee 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/bgproute/PtreeNode.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/bgproute/PtreeNode.java
@@ -14,7 +14,7 @@
public int refCount;
public RibEntry rib;
- protected static Logger log = LoggerFactory.getLogger(BgpRoute.class);
+ protected final static Logger log = LoggerFactory.getLogger(BgpRoute.class);
PtreeNode(byte [] key, int key_bits, int max_key_octet) {
parent = null;
diff --git a/src/main/java/net/onrc/onos/ofcontroller/bgproute/RestClient.java b/src/main/java/net/onrc/onos/ofcontroller/bgproute/RestClient.java
index f6f1a03..a9f2abe 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/bgproute/RestClient.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/bgproute/RestClient.java
@@ -13,7 +13,7 @@
public class RestClient {
- protected static Logger log = LoggerFactory.getLogger(RestClient.class);
+ protected final static Logger log = LoggerFactory.getLogger(RestClient.class);
public static String get(String str) {
StringBuilder response = new StringBuilder();
diff --git a/src/main/java/net/onrc/onos/ofcontroller/bgproute/RibEntry.java b/src/main/java/net/onrc/onos/ofcontroller/bgproute/RibEntry.java
index 1520c60..ccf8951 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/bgproute/RibEntry.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/bgproute/RibEntry.java
@@ -7,21 +7,57 @@
public class RibEntry {
private final InetAddress routerId;
private final InetAddress nextHop;
+
+ /*
+ * Store the sequence number information provided on the update here for
+ * now. I think this *should* really be in the RibUpdate, and we should
+ * store RibUpdates in the Ptrie. But, that's a bigger change to change
+ * what the Ptrie stores.
+ */
+ private final long sysUpTime;
+ private final long sequenceNum;
+
+ /*
+ * Marker for RibEntries where we don't have sequence number info.
+ * The user of this class should make sure they don't check this data
+ * if they don't provide it.
+ */
+ private final static long NULL_TIME = -1;
public RibEntry(InetAddress routerId, InetAddress nextHop) {
this.routerId = routerId;
this.nextHop = nextHop;
+ sequenceNum = NULL_TIME;
+ sysUpTime = NULL_TIME;
}
public RibEntry(String routerId, String nextHop) {
this.routerId = InetAddresses.forString(routerId);
this.nextHop = InetAddresses.forString(nextHop);
+ sequenceNum = NULL_TIME;
+ sysUpTime = NULL_TIME;
+ }
+
+ public RibEntry(String routerId, String nextHop, long sysUpTime
+ , long sequenceNum) {
+ this.routerId = InetAddresses.forString(routerId);
+ this.nextHop = InetAddresses.forString(nextHop);
+ this.sequenceNum = sequenceNum;
+ this.sysUpTime = sysUpTime;
}
public InetAddress getNextHop() {
return nextHop;
}
+ public long getSysUpTime() {
+ return sysUpTime;
+ }
+
+ public long getSequenceNum() {
+ return sequenceNum;
+ }
+
@Override
public boolean equals(Object other) {
if (other == null || !(other instanceof RibEntry)) {
diff --git a/src/main/java/net/onrc/onos/ofcontroller/core/IDeviceStorage.java b/src/main/java/net/onrc/onos/ofcontroller/core/IDeviceStorage.java
index 7310d8c..be495b9 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/core/IDeviceStorage.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/IDeviceStorage.java
@@ -9,7 +9,7 @@
public IDeviceObject updateDevice(IDevice device);
public void removeDevice(IDevice device);
public IDeviceObject getDeviceByMac(String mac);
- public IDeviceObject getDeviceByIP(String ip);
+ public IDeviceObject getDeviceByIP(int ipv4Address);
public void changeDeviceAttachments(IDevice device);
public void changeDeviceIPv4Address(IDevice device);
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/core/ILinkStorage.java b/src/main/java/net/onrc/onos/ofcontroller/core/ILinkStorage.java
index 0ea6fd5..6b285f4 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/core/ILinkStorage.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/ILinkStorage.java
@@ -8,33 +8,34 @@
public interface ILinkStorage extends INetMapStorage {
/*
- * Link creation
- */
- public void update(Link link, DM_OPERATION op);
- public void update(Link link, LinkInfo linkinfo, DM_OPERATION op);
- public void update(List<Link> List, DM_OPERATION op);
-
- /*
- * Add Linkinfo
+ * Init with Storage conf
*/
- public void updateLink (Link link, LinkInfo linkinfo, DM_OPERATION op);
+ public void init(final String dbStore, final String conf);
/*
- * Delete a single link
+ * Generic operation method
*/
- public void deleteLink(Link link);
+ public boolean update(Link link, LinkInfo linkinfo, DM_OPERATION op);
+
+ /*
+ * Link creation
+ */
+ public boolean addLink(Link link);
+ public boolean addLink(Link link, LinkInfo linfo);
+ public boolean addLinks(List<Link> links);
+
+ /*
+ * Link deletion
+ */
+ public boolean deleteLink(Link link);
+ public boolean deleteLinks(List<Link> links);
/*
- * Delete links associated with dpid and port
+ * Utility method to delete links associated with dpid and port
* If only dpid is used, All links associated for switch are removed
* Useful for port up/down and also switch join/remove events
*/
- public void deleteLinksOnPort(Long dpid, short port);
-
- /*
- * Delete a list of links
- */
- public void deleteLinks(List<Link> links);
+ public boolean deleteLinksOnPort(Long dpid, short port);
/*
* Get Links from Storage
@@ -42,12 +43,27 @@
* If only dpid is set all links associated with Switch are retrieved
*/
public List<Link> getLinks(Long dpid, short port);
- public List<Link> getLinks(String dpid);
- public List<Link> getActiveLinks();
-
- /*
- * Init with Storage conf
- */
- public void init(final String dbStore, final String conf);
+ /**
+ * Get list of all reverse links connected to the port specified by given DPID and port number.
+ * @param dpid DPID of desired port.
+ * @param port Port number of desired port.
+ * @return List of reverse links. Empty list if no port was found.
+ */
+ public List<Link> getReverseLinks(Long dpid, short port);
+
+ public List<Link> getLinks(String dpid);
+
+ /**
+ * Get list of all reverse links connected to the switch specified by
+ * given DPID.
+ * @param dpid DPID of desired switch.
+ * @return List of reverse links. Empty list if no port was found.
+ */
+
+ public List<Link> getReverseLinks(String dpid);
+
+ public List<Link> getActiveLinks();
+
+ public LinkInfo getLinkInfo(Link link);
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/core/INetMapTopologyObjects.java b/src/main/java/net/onrc/onos/ofcontroller/core/INetMapTopologyObjects.java
index 7b38fef..869333b 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/core/INetMapTopologyObjects.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/INetMapTopologyObjects.java
@@ -21,24 +21,24 @@
*/
public interface INetMapTopologyObjects {
-public interface IBaseObject extends VertexFrame {
+ public interface IBaseObject extends VertexFrame {
+
+ @JsonProperty("state")
+ @Property("state")
+ public String getState();
+
+ @Property("state")
+ public void setState(final String state);
+
+ @JsonIgnore
+ @Property("type")
+ public String getType();
+ @Property("type")
+ public void setType(final String type);
+
+ }
- @JsonProperty("state")
- @Property("state")
- public String getState();
-
- @Property("state")
- public void setState(final String state);
-
- @JsonIgnore
- @Property("type")
- public String getType();
- @Property("type")
- public void setType(final String type);
-
-}
-
-public interface ISwitchObject extends IBaseObject{
+ public interface ISwitchObject extends IBaseObject{
@JsonProperty("dpid")
@Property("dpid")
@@ -51,7 +51,7 @@
@Adjacency(label="on")
public Iterable<IPortObject> getPorts();
-// Requires Frames 2.3.0
+ // Requires Frames 2.3.0
@JsonIgnore
@GremlinGroovy("it.out('on').has('number',port_num)")
public IPortObject getPort(@GremlinParam("port_num") final short port_num);
@@ -104,7 +104,6 @@
public void setPortState(Integer s);
@JsonIgnore
-// @GremlinGroovy("it.in('on')")
@Adjacency(label="on",direction = Direction.IN)
public ISwitchObject getSwitch();
@@ -129,6 +128,10 @@
@JsonIgnore
@Adjacency(label="link")
public Iterable<IPortObject> getLinkedPorts();
+
+ @JsonIgnore
+ @Adjacency(label="link",direction = Direction.IN)
+ public Iterable<IPortObject> getReverseLinkedPorts();
@Adjacency(label="link")
public void removeLink(final IPortObject dest_port);
@@ -136,9 +139,9 @@
@Adjacency(label="link")
public void setLinkPort(final IPortObject dest_port);
-// @JsonIgnore
-// @Adjacency(label="link")
-// public Iterable<ILinkObject> getLinks();
+ // @JsonIgnore
+ // @Adjacency(label="link")
+ // public Iterable<ILinkObject> getLinks();
}
public interface IDeviceObject extends IBaseObject {
@@ -146,15 +149,10 @@
@JsonProperty("mac")
@Property("dl_addr")
public String getMACAddress();
+
@Property("dl_addr")
public void setMACAddress(String macaddr);
- @JsonProperty("ipv4")
- @Property("nw_addr")
- public String getIPAddress();
- @Property("nw_addr")
- public void setIPAddress(String ipaddr);
-
@JsonIgnore
@Adjacency(label="host",direction = Direction.IN)
public Iterable<IPortObject> getAttachedPorts();
@@ -171,6 +169,23 @@
@GremlinGroovy("it.in('host').in('on')")
public Iterable<ISwitchObject> getSwitch();
+ //
+ // IPv4 Addresses
+ //
+ @JsonProperty("ipv4addresses")
+ @Adjacency(label="hasAddress")
+ public Iterable<IIpv4Address> getIpv4Addresses();
+
+ @JsonIgnore
+ @GremlinGroovy("it.out('hasAddress').has('ipv4_address', ipv4Address)")
+ public IIpv4Address getIpv4Address(@GremlinParam("ipv4Address") final int ipv4Address);
+
+ @Adjacency(label="hasAddress")
+ public void addIpv4Address(final IIpv4Address ipv4Address);
+
+ @Adjacency(label="hasAddress")
+ public void removeIpv4Address(final IIpv4Address ipv4Address);
+
/* @JsonProperty("dpid")
@GremlinGroovy("_().in('host').in('on').next().getProperty('dpid')")
public Iterable<String> getSwitchDPID();
@@ -183,8 +198,22 @@
@GremlinGroovy("_().in('host').in('on').path(){it.number}{it.dpid}")
public Iterable<SwitchPort> getAttachmentPoints();*/
}
-
-public interface IFlowPath extends IBaseObject {
+
+ public interface IIpv4Address extends IBaseObject {
+
+ @JsonProperty("ipv4")
+ @Property("ipv4_address")
+ public int getIpv4Address();
+
+ @Property("ipv4_address")
+ public void setIpv4Address(int ipv4Address);
+
+ @JsonIgnore
+ @GremlinGroovy("it.in('hasAddress')")
+ public IDeviceObject getDevice();
+ }
+
+ public interface IFlowPath extends IBaseObject {
@JsonProperty("flowId")
@Property("flow_id")
public String getFlowId();
@@ -199,6 +228,20 @@
@Property("installer_id")
public void setInstallerId(String installerId);
+ @JsonProperty("flowPathType")
+ @Property("flow_path_type")
+ public String getFlowPathType();
+
+ @Property("flow_path_type")
+ public void setFlowPathType(String flowPathType);
+
+ @JsonProperty("flowPathUserState")
+ @Property("user_state")
+ public String getFlowPathUserState();
+
+ @Property("user_state")
+ public void setFlowPathUserState(String userState);
+
@JsonProperty("flowPathFlags")
@Property("flow_path_flags")
public Long getFlowPathFlags();
@@ -351,16 +394,9 @@
@JsonIgnore
@Property("state")
public String getState();
-
- @JsonIgnore
- @Property("user_state")
- public String getUserState();
-
- @Property("user_state")
- public void setUserState(String userState);
}
-public interface IFlowEntry extends IBaseObject {
+ public interface IFlowEntry extends IBaseObject {
@Property("flow_entry_id")
public String getFlowEntryId();
diff --git a/src/main/java/net/onrc/onos/ofcontroller/core/INetMapTopologyService.java b/src/main/java/net/onrc/onos/ofcontroller/core/INetMapTopologyService.java
index 954515b..f5ccc49 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/core/INetMapTopologyService.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/INetMapTopologyService.java
@@ -1,16 +1,11 @@
package net.onrc.onos.ofcontroller.core;
import java.util.List;
-import java.util.Map;
-import net.floodlightcontroller.core.module.IFloodlightService;
import net.floodlightcontroller.routing.Link;
-import net.floodlightcontroller.topology.NodePortTuple;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IDeviceObject;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IPortObject;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.ISwitchObject;
-import net.onrc.onos.ofcontroller.util.DataPath;
-import net.onrc.onos.ofcontroller.util.SwitchPort;
public interface INetMapTopologyService extends INetMapService {
@@ -34,90 +29,4 @@
Iterable<IDeviceObject> getDevicesOnSwitch(String dpid);
Iterable<IDeviceObject> getDevicesOnSwitch(String dpid, short port_num);
}
-
- public interface ITopoRouteService extends IFloodlightService {
- /**
- * Get the shortest path from a source to a destination.
- *
- * @param src the source in the shortest path computation.
- * @param dest the destination in the shortest path computation.
- * @return the data path with the computed shortest path if
- * found, otherwise null.
- */
- DataPath getShortestPath(SwitchPort src, SwitchPort dest);
-
- /**
- * Fetch the Switch and Ports info from the Titan Graph
- * and return it for fast access during the shortest path
- * computation.
- *
- * After fetching the state, method @ref getTopoShortestPath()
- * can be used for fast shortest path computation.
- *
- * Note: There is certain cost to fetch the state, hence it should
- * be used only when there is a large number of shortest path
- * computations that need to be done on the same topology.
- * Typically, a single call to @ref prepareShortestPathTopo()
- * should be followed by a large number of calls to
- * method @ref getTopoShortestPath().
- * After the last @ref getTopoShortestPath() call,
- * method @ref dropShortestPathTopo() should be used to release
- * the internal state that is not needed anymore:
- *
- * Map<Long, ?> shortestPathTopo;
- * shortestPathTopo = prepareShortestPathTopo();
- * for (int i = 0; i < 10000; i++) {
- * dataPath = getTopoShortestPath(shortestPathTopo, ...);
- * ...
- * }
- * dropShortestPathTopo(shortestPathTopo);
- *
- * @return the Shortest Path info handler stored in a map.
- */
- Map<Long, ?> prepareShortestPathTopo();
-
- /**
- * Release the state that was populated by
- * method @ref prepareShortestPathTopo().
- *
- * See the documentation for method @ref prepareShortestPathTopo()
- * for additional information and usage.
- *
- * @param shortestPathTopo the Shortest Path info handler to release.
- */
- void dropShortestPathTopo(Map<Long, ?> shortestPathTopo);
-
- /**
- * Get the shortest path from a source to a destination by
- * using the pre-populated local topology state prepared
- * by method @ref prepareShortestPathTopo().
- *
- * See the documentation for method @ref prepareShortestPathTopo()
- * for additional information and usage.
- *
- * @param shortestPathTopo the Shortest Path info handler
- * to use.
- * @param src the source in the shortest path computation.
- * @param dest the destination in the shortest path computation.
- * @return the data path with the computed shortest path if
- * found, otherwise null.
- */
- DataPath getTopoShortestPath(Map<Long, ?> shortestPathTopo,
- SwitchPort src, SwitchPort dest);
-
- /**
- * Test whether a route exists from a source to a destination.
- *
- * @param src the source node for the test.
- * @param dest the destination node for the test.
- * @return true if a route exists, otherwise false.
- */
- Boolean routeExists(SwitchPort src, SwitchPort dest);
- }
-
- public interface ITopoFlowService {
- Boolean flowExists(NodePortTuple src, NodePortTuple dest);
- List<NodePortTuple> getShortestFlowPath(NodePortTuple src, NodePortTuple dest);
-
- }
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/core/ISwitchStorage.java b/src/main/java/net/onrc/onos/ofcontroller/core/ISwitchStorage.java
index 4a62251..8dd2f16 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/core/ISwitchStorage.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/ISwitchStorage.java
@@ -1,5 +1,7 @@
package net.onrc.onos.ofcontroller.core;
+import java.util.List;
+
import net.floodlightcontroller.core.IOFSwitch;
import org.openflow.protocol.OFPhysicalPort;
@@ -12,33 +14,47 @@
}
/*
- * Update the switch details
- */
- public void update(String dpid,SwitchState state, DM_OPERATION op);
- /*
- * Associate a port on switch
- */
- public void addPort(String dpid, OFPhysicalPort port);
- /*
- * Add a switch and all its associated ports
- */
- public void addSwitch(IOFSwitch sw);
- /*
- * Add a switch
- */
- public void addSwitch(String dpid);
- /*
- * Delete switch and associated ports
- */
- public void deleteSwitch(String dpid);
- /*
- * Delete a port on a switch by num
- */
- public void deletePort(String dpid, short port);
- /*
* Initialize
*/
public void init(final String dbStore, final String conf);
-
+ /*
+ * Update the switch details
+ */
+ public boolean updateSwitch(String dpid, SwitchState state, DM_OPERATION op);
+ /*
+ * Add a switch and all its associated ports
+ */
+ public boolean addSwitch(IOFSwitch sw);
+ /*
+ * Add a switch
+ */
+ public boolean addSwitch(String dpid);
+ /*
+ * Delete switch and associated ports
+ */
+ public boolean deleteSwitch(String dpid);
+ /*
+ * Deactivate the switch and associated ports
+ */
+ public boolean deactivateSwitch(String dpid);
+ /*
+ * Update the port details
+ */
+ public boolean updatePort(String dpid, short port, int state, String desc);
+ /*
+ * Associate a port on switch
+ */
+ public boolean addPort(String dpid, OFPhysicalPort port);
+ /*
+ * Delete a port on a switch by num
+ */
+ public boolean deletePort(String dpid, short port);
+ /**
+ * Get list of all ports on the switch specified by given DPID.
+ *
+ * @param dpid DPID of desired switch.
+ * @return List of port IDs. Empty list if no port was found.
+ */
+ public List<Short> getPorts(String dpid);
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/core/config/DefaultConfiguration.java b/src/main/java/net/onrc/onos/ofcontroller/core/config/DefaultConfiguration.java
new file mode 100644
index 0000000..d9a291f
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/config/DefaultConfiguration.java
@@ -0,0 +1,47 @@
+package net.onrc.onos.ofcontroller.core.config;
+
+import java.net.InetAddress;
+
+import net.floodlightcontroller.util.MACAddress;
+import net.onrc.onos.ofcontroller.bgproute.Interface;
+
+import org.openflow.util.HexString;
+
+public class DefaultConfiguration implements IConfigInfoService {
+
+ @Override
+ public boolean isInterfaceAddress(InetAddress address) {
+ return false;
+ }
+
+ @Override
+ public boolean inConnectedNetwork(InetAddress address) {
+ return false;
+ }
+
+ @Override
+ public boolean fromExternalNetwork(long inDpid, short inPort) {
+ return false;
+ }
+
+ @Override
+ public Interface getOutgoingInterface(InetAddress dstIpAddress) {
+ return null;
+ }
+
+ @Override
+ public boolean hasLayer3Configuration() {
+ return false;
+ }
+
+ @Override
+ public MACAddress getRouterMacAddress() {
+ return MACAddress.valueOf(HexString.fromHexString("000000000001"));
+ }
+
+ @Override
+ public short getVlan() {
+ return 0;
+ }
+
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/bgproute/ILayer3InfoService.java b/src/main/java/net/onrc/onos/ofcontroller/core/config/IConfigInfoService.java
similarity index 67%
rename from src/main/java/net/onrc/onos/ofcontroller/bgproute/ILayer3InfoService.java
rename to src/main/java/net/onrc/onos/ofcontroller/core/config/IConfigInfoService.java
index 00ddd68..7bbf483 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/bgproute/ILayer3InfoService.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/config/IConfigInfoService.java
@@ -1,15 +1,17 @@
-package net.onrc.onos.ofcontroller.bgproute;
+package net.onrc.onos.ofcontroller.core.config;
import java.net.InetAddress;
import net.floodlightcontroller.util.MACAddress;
+import net.onrc.onos.ofcontroller.bgproute.Interface;
+import net.onrc.onos.ofcontroller.core.module.IOnosService;
/**
* Provides information about the layer 3 properties of the network.
* This is based on IP addresses configured on ports in the network.
*
*/
-public interface ILayer3InfoService {
+public interface IConfigInfoService extends IOnosService {
public boolean isInterfaceAddress(InetAddress address);
public boolean inConnectedNetwork(InetAddress address);
public boolean fromExternalNetwork(long inDpid, short inPort);
@@ -32,4 +34,15 @@
public boolean hasLayer3Configuration();
public MACAddress getRouterMacAddress();
+
+ /**
+ * We currently have basic vlan support for the situation when the contr
+ * is running within a single vlan. In this case, packets sent from the
+ * controller (e.g. ARP) need to be tagged with that vlan.
+ * @return The vlan id configured in the config file,
+ * or 0 if no vlan is configured.
+ */
+ public short getVlan();
+
+
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/core/internal/DeviceStorageImpl.java b/src/main/java/net/onrc/onos/ofcontroller/core/internal/DeviceStorageImpl.java
index 938ebeb..9ba5ecf 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/core/internal/DeviceStorageImpl.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/internal/DeviceStorageImpl.java
@@ -1,13 +1,9 @@
package net.onrc.onos.ofcontroller.core.internal;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
-import org.openflow.util.HexString;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import com.google.common.collect.Lists;
-import com.thinkaurelius.titan.core.TitanException;
import net.floodlightcontroller.devicemanager.IDevice;
import net.floodlightcontroller.devicemanager.SwitchPort;
import net.floodlightcontroller.packet.IPv4;
@@ -15,8 +11,16 @@
import net.onrc.onos.graph.GraphDBManager;
import net.onrc.onos.ofcontroller.core.IDeviceStorage;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IDeviceObject;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IIpv4Address;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IPortObject;
+import org.openflow.util.HexString;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Lists;
+import com.google.common.net.InetAddresses;
+import com.thinkaurelius.titan.core.TitanException;
/**
* This is the class for storing the information of devices into CassandraDB
*
@@ -24,125 +28,125 @@
*/
public class DeviceStorageImpl implements IDeviceStorage {
- private DBOperation ope;
- protected static Logger log = LoggerFactory.getLogger(SwitchStorageImpl.class);
+ private DBOperation ope;
+ protected final static Logger log = LoggerFactory.getLogger(SwitchStorageImpl.class);
+ /**
+ * *
+ * Initialize function. Before you use this class, please call this method
+ *
+ * @param conf configuration file for Cassandra DB
+ */
+ @Override
+ public void init(final String dbStore, final String conf) {
+ try {
+ ope = GraphDBManager.getDBOperation(dbStore, conf);
+ } catch (Exception e) {
+ log.error(e.getMessage());
+ }
+ }
- /**
- * *
- * Initialize function. Before you use this class, please call this method
- *
- * @param conf configuration file for Cassandra DB
- */
- @Override
- public void init(final String dbStore, final String conf) {
- try {
- ope = GraphDBManager.getDBOperation(dbStore, conf);
- } catch (Exception e) {
- log.error(e.getMessage());
- }
- }
+ /**
+ * *
+ * Finalize/close function. After you use this class, please call this
+ * method. It will close the DB connection.
+ */
+ @Override
+ public void close() {
+ ope.close();
+ }
- /**
- * *
- * Finalize/close function. After you use this class, please call this
- * method. It will close the DB connection.
- */
- @Override
- public void close() {
- ope.close();
- }
+ /**
+ * *
+ * Finalize/close function. After you use this class, please call this
+ * method. It will close the DB connection. This is for Java garbage
+ * collection.
+ */
+ @Override
+ public void finalize() {
+ close();
+ }
- /**
- * *
- * Finalize/close function. After you use this class, please call this
- * method. It will close the DB connection. This is for Java garbage
- * collection.
- */
- @Override
- public void finalize() {
- close();
- }
+ /**
+ * *
+ * This function is for adding the device into the DB.
+ *
+ * @param device The device you want to add into the DB.
+ * @return IDeviceObject which was added in the DB.
+ */
+ @Override
+ public IDeviceObject addDevice(IDevice device) {
+ IDeviceObject obj = null;
+ try {
+ if ((obj = ope.searchDevice(device.getMACAddressString())) != null) {
+ log.debug("Adding device {}: found existing device", device.getMACAddressString());
+ } else {
+ obj = ope.newDevice();
+ log.debug("Adding device {}: creating new device", device.getMACAddressString());
+ }
+ changeDeviceAttachments(device, obj);
- /**
- * *
- * This function is for adding the device into the DB.
- *
- * @param device The device you want to add into the DB.
- * @return IDeviceObject which was added in the DB.
- */
- @Override
- public IDeviceObject addDevice(IDevice device) {
- IDeviceObject obj = null;
- try {
- if ((obj = ope.searchDevice(device.getMACAddressString())) != null) {
- log.debug("Adding device {}: found existing device", device.getMACAddressString());
- } else {
- obj = ope.newDevice();
- log.debug("Adding device {}: creating new device", device.getMACAddressString());
- }
- changeDeviceAttachments(device, obj);
+ changeDeviceIpv4Addresses(device, obj);
- String multiIntString = "";
- for (Integer intValue : device.getIPv4Addresses()) {
- if (multiIntString == null || multiIntString.isEmpty()) {
- multiIntString = IPv4.fromIPv4Address(intValue);
- multiIntString = "[" + IPv4.fromIPv4Address(intValue);
- } else {
- multiIntString += "," + IPv4.fromIPv4Address(intValue);
- }
- }
+ obj.setMACAddress(device.getMACAddressString());
+ obj.setType("device");
+ obj.setState("ACTIVE");
+ ope.commit();
+
+ //log.debug("Adding device {}",device.getMACAddressString());
+ } catch (TitanException e) {
+ ope.rollback();
+ log.error("Adding device {} failed", device.getMACAddressString(), e);
+ obj = null;
+ }
+
+ return obj;
+ }
+ /**
+ * *
+ * This function is for updating the Device properties.
+ *
+ * @param device The device you want to add into the DB.
+ * @return IDeviceObject which was added in the DB.
+ */
+ @Override
+ public IDeviceObject updateDevice(IDevice device) {
+ return addDevice(device);
+ }
- if (multiIntString.toString() != null && !multiIntString.toString().isEmpty()) {
- obj.setIPAddress(multiIntString + "]");
- }
+ /***
+ * This function is for removing the Device from the DB.
+ * @param device The device you want to delete from the DB.
+ */
+ @Override
+ public void removeDevice(IDevice device) {
+ IDeviceObject dev;
+
+ if ((dev = ope.searchDevice(device.getMACAddressString())) != null) {
+ removeDevice(dev);
+ }
+ }
+
+ public void removeDevice(IDeviceObject deviceObject) {
+ String deviceMac = deviceObject.getMACAddress();
- obj.setMACAddress(device.getMACAddressString());
- obj.setType("device");
- obj.setState("ACTIVE");
- ope.commit();
+ removeDeviceImpl(deviceObject);
- log.debug("Adding device {}", device.getMACAddressString());
- } catch (Exception e) {
- ope.rollback();
- log.error(":addDevice mac:{} failed", device.getMACAddressString());
- obj = null;
- }
- return obj;
- }
-
- /**
- * *
- * This function is for updating the Device properties.
- *
- * @param device The device you want to add into the DB.
- * @return IDeviceObject which was added in the DB.
- */
- @Override
- public IDeviceObject updateDevice(IDevice device) {
- return addDevice(device);
- }
-
- /**
- * *
- * This function is for removing the Device from the DB.
- *
- * @param device The device you want to delete from the DB.
- */
- @Override
- public void removeDevice(IDevice device) {
- IDeviceObject dev;
- try {
- if ((dev = ope.searchDevice(device.getMACAddressString())) != null) {
- ope.removeDevice(dev);
- ope.commit();
- log.error("DeviceStorage:removeDevice mac:{} done", device.getMACAddressString());
- }
- } catch (Exception e) {
- ope.rollback();
- log.error("DeviceStorage:removeDevice mac:{} failed", device.getMACAddressString());
- }
- }
-
+ try {
+ ope.commit();
+ log.debug("DeviceStorage:removeDevice mac:{} done", deviceMac);
+ } catch (TitanException e) {
+ ope.rollback();
+ log.error("DeviceStorage:removeDevice mac:{} failed", deviceMac);
+ }
+ }
+
+ public void removeDeviceImpl(IDeviceObject deviceObject) {
+ for (IIpv4Address ipv4AddressVertex : deviceObject.getIpv4Addresses()) {
+ ope.removeIpv4Address(ipv4AddressVertex);
+ }
+
+ ope.removeDevice(deviceObject);
+ }
/**
* *
* This function is for getting the Device from the DB by Mac address of the
@@ -156,129 +160,154 @@
return ope.searchDevice(mac);
}
- /**
- * *
- * This function is for getting the Device from the DB by IP address of the
- * device.
- *
- * @param ip The device ip address you want to get from the DB.
- * @return IDeviceObject you want to get.
- */
- @Override
- public IDeviceObject getDeviceByIP(String ip) {
- try {
- for (IDeviceObject dev : ope.getDevices()) {
- String ips;
- if ((ips = dev.getIPAddress()) != null) {
- String nw_addr_wob = ips.replace("[", "").replace("]", "");
- ArrayList<String> iplists = Lists.newArrayList(nw_addr_wob.split(","));
- if (iplists.contains(ip)) {
- return dev;
- }
- }
- }
- return null;
- } catch (Exception e) {
- log.error("DeviceStorage:getDeviceByIP:{} failed");
- return null;
- }
- }
+ /***
+ * This function is for getting the Device from the DB by IP address of the device.
+ * @param ip The device ip address you want to get from the DB.
+ * @return IDeviceObject you want to get.
+ */
+ @Override
+ public IDeviceObject getDeviceByIP(int ipv4Address) {
+ try {
+ IIpv4Address ipv4AddressVertex = ope.searchIpv4Address(ipv4Address);
+ if (ipv4AddressVertex != null) {
+ return ipv4AddressVertex.getDevice();
+ }
+ return null;
+ }
+ catch (TitanException e) {
+ log.error("DeviceStorage:getDeviceByIP:{} failed");
+ return null;
+ }
+ }
- /**
- * *
- * This function is for changing the Device attachment point.
- *
- * @param device The device you want change the attachment point
- */
- @Override
- public void changeDeviceAttachments(IDevice device) {
- IDeviceObject obj = null;
- try {
- if ((obj = ope.searchDevice(device.getMACAddressString())) != null) {
- log.debug("Changing device ports {}: found existing device", device.getMACAddressString());
- changeDeviceAttachments(device, obj);
- ope.commit();
- } else {
- log.debug("failed to search device...now adding {}", device.getMACAddressString());
- addDevice(device);
- }
- } catch (Exception e) {
- ope.rollback();
- log.error(":addDevice mac:{} failed", device.getMACAddressString());
- }
- }
+ /**
+ * *
+ * This function is for changing the Device attachment point.
+ *
+ * @param device The device you want change the attachment point
+ */
+ @Override
+ public void changeDeviceAttachments(IDevice device) {
+ IDeviceObject obj = null;
+ try {
+ if ((obj = ope.searchDevice(device.getMACAddressString())) != null) {
+ log.debug("Changing device ports {}: found existing device", device.getMACAddressString());
+ changeDeviceAttachments(device, obj);
+ ope.commit();
+ } else {
+ log.debug("failed to search device...now adding {}", device.getMACAddressString());
+ addDevice(device);
+ }
+ } catch (TitanException e) {
+ ope.rollback();
+ log.error(":addDevice mac:{} failed", device.getMACAddressString());
+ }
+ }
+
+ /***
+ * This function is for changing the Device attachment point.
+ * @param device The new device you want change the attachment point
+ * @param obj The old device IDeviceObject that is going to change the attachment point.
+ */
+ public void changeDeviceAttachments(IDevice device, IDeviceObject obj) {
+ SwitchPort[] attachmentPoints = device.getAttachmentPoints();
+ List<IPortObject> attachedPorts = Lists.newArrayList(obj.getAttachedPorts());
- /**
- * *
- * This function is for changing the Device attachment point.
- *
- * @param device The new device you want change the attachment point
- * @param obj The old device IDeviceObject that is going to change the
- * attachment point.
- */
- public void changeDeviceAttachments(IDevice device, IDeviceObject obj) {
- SwitchPort[] attachmentPoints = device.getAttachmentPoints();
- List<IPortObject> attachedPorts = Lists.newArrayList(obj.getAttachedPorts());
+ for (SwitchPort ap : attachmentPoints) {
+ //Check if there is the port
+ IPortObject port = ope.searchPort(HexString.toHexString(ap.getSwitchDPID()),
+ (short) ap.getPort());
+ log.debug("New Switch Port is {},{}",
+ HexString.toHexString(ap.getSwitchDPID()), (short) ap.getPort());
- for (SwitchPort ap : attachmentPoints) {
- //Check weather there is the port
- IPortObject port = ope.searchPort(HexString.toHexString(ap.getSwitchDPID()),
- (short) ap.getPort());
- log.debug("New Switch Port is {},{}", HexString.toHexString(ap.getSwitchDPID()), (short) ap.getPort());
+ if (port != null){
+ if (attachedPorts.contains(port)) {
+ log.debug("This is the port you already attached {}: do nothing", device.getMACAddressString());
+ //This port will be remained, so remove from the removed port lists.
+ attachedPorts.remove(port);
+ } else {
+ log.debug("Adding device {}: attaching to port", device.getMACAddressString());
+ port.setDevice(obj);
+ }
- if (port != null) {
- if (attachedPorts.contains(port)) {
- log.debug("This is the port you already attached {}: do nothing", device.getMACAddressString());
- //This port will be remained, so remove from the removed port lists.
- attachedPorts.remove(port);
- } else {
- log.debug("Adding device {}: attaching to port", device.getMACAddressString());
- port.setDevice(obj);
- }
+ log.debug("port number is {}", port.getNumber().toString());
+ log.debug("port desc is {}", port.getDesc());
+ }
+ }
- log.debug("port number is {}", port.getNumber().toString());
- log.debug("port desc is {}", port.getDesc());
- }
- }
+ for (IPortObject port: attachedPorts) {
+ log.debug("Detaching the device {}: detaching from port", device.getMACAddressString());
+ port.removeDevice(obj);
+
+ if (!obj.getAttachedPorts().iterator().hasNext()) {
+ // XXX If there are no more ports attached to the device,
+ // delete it. Otherwise we have a situation where the
+ // device remains forever with an IP address attached.
+ // When we implement device probing we should get rid of this.
+ removeDevice(obj);
+ }
+ }
+ }
- for (IPortObject port : attachedPorts) {
- log.debug("Detouching the device {}: detouching from port", device.getMACAddressString());
- port.removeDevice(obj);
- }
- }
-
- /**
- * *
- * This function is for changing the Device IPv4 address.
- *
- * @param device The new device you want change the ipaddress
- */
- @Override
- public void changeDeviceIPv4Address(IDevice device) {
- IDeviceObject obj;
- try {
- if ((obj = ope.searchDevice(device.getMACAddressString())) != null) {
-
- String multiIntString = "";
- for (Integer intValue : device.getIPv4Addresses()) {
- if (multiIntString == null || multiIntString.isEmpty()) {
- multiIntString = "[" + IPv4.fromIPv4Address(intValue);
- } else {
- multiIntString += "," + IPv4.fromIPv4Address(intValue);
- }
- }
-
- if (multiIntString != null && !multiIntString.isEmpty()) {
- obj.setIPAddress(multiIntString + "]");
- }
-
- ope.commit();
- } else {
- log.error(":changeDeviceIPv4Address mac:{} failed", device.getMACAddressString());
- }
- } catch (TitanException e) {
- ope.rollback();
- log.error(":changeDeviceIPv4Address mac:{} failed due to exception {}", device.getMACAddressString(), e);
- }
- }
+ /***
+ * This function is for changing the Device IPv4 address.
+ * @param device The new device you want change the ipaddress
+ */
+ @Override
+ public void changeDeviceIPv4Address(IDevice device) {
+ log.debug("Changing IP address for {} to {}", device.getMACAddressString(),
+ device.getIPv4Addresses());
+ IDeviceObject obj;
+ try {
+ if ((obj = ope.searchDevice(device.getMACAddressString())) != null) {
+ changeDeviceIpv4Addresses(device, obj);
+ ope.commit();
+ } else {
+ log.error(":changeDeviceIPv4Address mac:{} failed", device.getMACAddressString());
+ }
+ } catch (TitanException e) {
+ ope.rollback();
+ log.error(":changeDeviceIPv4Address mac:{} failed due to exception {}", device.getMACAddressString(), e);
+ }
+ }
+
+ private void changeDeviceIpv4Addresses(IDevice device, IDeviceObject deviceObject) {
+ List<String> dbIpv4Addresses = new ArrayList<String>();
+ for (IIpv4Address ipv4Vertex : deviceObject.getIpv4Addresses()) {
+ dbIpv4Addresses.add(InetAddresses.fromInteger(ipv4Vertex.getIpv4Address()).getHostAddress());
+ }
+
+ List<String> memIpv4Addresses = new ArrayList<String>();
+ for (int addr : device.getIPv4Addresses()) {
+ memIpv4Addresses.add(InetAddresses.fromInteger(addr).getHostAddress());
+ }
+
+ log.debug("Device IP addresses {}, database IP addresses {}",
+ memIpv4Addresses, dbIpv4Addresses);
+
+ for (int ipv4Address : device.getIPv4Addresses()) {
+ if (deviceObject.getIpv4Address(ipv4Address) == null) {
+ IIpv4Address dbIpv4Address = ope.ensureIpv4Address(ipv4Address);
+
+ IDeviceObject oldDevice = dbIpv4Address.getDevice();
+ if (oldDevice != null) {
+ oldDevice.removeIpv4Address(dbIpv4Address);
+ }
+
+ log.debug("Adding IP address {}",
+ InetAddresses.fromInteger(ipv4Address).getHostAddress());
+ deviceObject.addIpv4Address(dbIpv4Address);
+ }
+ }
+
+ List<Integer> deviceIpv4Addresses = Arrays.asList(device.getIPv4Addresses());
+ for (IIpv4Address dbIpv4Address : deviceObject.getIpv4Addresses()) {
+ if (!deviceIpv4Addresses.contains(dbIpv4Address.getIpv4Address())) {
+ log.debug("Removing IP address {}",
+ InetAddresses.fromInteger(dbIpv4Address.getIpv4Address())
+ .getHostAddress());
+ deviceObject.removeIpv4Address(dbIpv4Address);
+ }
+ }
+ }
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/core/internal/LinkStorageImpl.java b/src/main/java/net/onrc/onos/ofcontroller/core/internal/LinkStorageImpl.java
index 6516bf7..84a6c9c 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/core/internal/LinkStorageImpl.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/internal/LinkStorageImpl.java
@@ -14,346 +14,507 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.thinkaurelius.titan.core.TitanException;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.pipes.PipeFunction;
import com.tinkerpop.pipes.transform.PathPipe;
import net.onrc.onos.graph.GraphDBManager;
/**
- * This is the class for storing the information of links into CassandraDB
+ * This is the class for storing the information of links into GraphDB
*/
public class LinkStorageImpl implements ILinkStorage {
- protected static Logger log = LoggerFactory.getLogger(LinkStorageImpl.class);
- protected DBOperation dbop;
+ protected final static Logger log = LoggerFactory.getLogger(LinkStorageImpl.class);
+ protected DBOperation dbop;
- /**
- * Update a record in the LinkStorage in a way provided by op.
- *
- * @param link Record of a link to be updated.
- * @param op Operation to be done.
- */
- @Override
- public void update(Link link, DM_OPERATION op) {
- update(link, (LinkInfo) null, op);
- }
+ /**
+ * Initialize the object. Open LinkStorage using given configuration file.
+ * @param conf Path (absolute path for now) to configuration file.
+ */
+ @Override
+ public void init(final String dbStore, final String conf) {
+ this.dbop = GraphDBManager.getDBOperation(dbStore, conf);
+ }
- /**
- * Update multiple records in the LinkStorage in a way provided by op.
- *
- * @param links List of records to be updated.
- * @param op Operation to be done.
- */
- @Override
- public void update(List<Link> links, DM_OPERATION op) {
- for (Link lt : links) {
- update(lt, (LinkInfo) null, op);
- }
- }
+ // Method designing policy:
+ // op.commit() and op.rollback() MUST called in public (first-class) methods.
+ // A first-class method MUST NOT call other first-class method.
+ // Routine process should be implemented in private method.
+ // A private method MUST NOT call commit or rollback.
- /**
- * Update a record of link with meta-information in the LinkStorage in a way
- * provided by op.
- *
- * @param link Record of a link to update.
- * @param linkinfo Meta-information of a link to be updated.
- * @param op Operation to be done.
- */
- @Override
- public void update(Link link, LinkInfo linkinfo, DM_OPERATION op) {
- switch (op) {
- case UPDATE:
- case CREATE:
- case INSERT:
- updateLink(link, linkinfo, op);
- break;
- case DELETE:
- deleteLink(link);
- break;
- }
- }
+
+ /**
+ * Update a record in the LinkStorage in a way provided by dmop.
+ * @param link Record of a link to be updated.
+ * @param linkinfo Meta-information of a link to be updated.
+ * @param dmop Operation to be done.
+ */
+ @Override
+ public boolean update(Link link, LinkInfo linkinfo, DM_OPERATION dmop) {
+ boolean success = false;
+
+ switch (dmop) {
+ case CREATE:
+ case INSERT:
+ if (link != null) {
+ try {
+ if (addLinkImpl(link)) {
+ dbop.commit();
+ success = true;
+ }
+ } catch (Exception e) {
+ dbop.rollback();
+ e.printStackTrace();
+ log.error("LinkStorageImpl:update {} link:{} failed", dmop, link);
+ }
+ }
+ break;
+ case UPDATE:
+ if (link != null && linkinfo != null) {
+ try {
+ if (setLinkInfoImpl(link, linkinfo)) {
+ dbop.commit();
+ success = true;
+ }
+ } catch (Exception e) {
+ dbop.rollback();
+ e.printStackTrace();
+ log.error("LinkStorageImpl:update {} link:{} failed", dmop, link);
+ }
+ }
+ break;
+ case DELETE:
+ if (link != null) {
+ try {
+ if (deleteLinkImpl(link)) {
+ dbop.commit();
+ success = true;
+ log.debug("LinkStorageImpl:update {} link:{} succeeded", dmop, link);
+ } else {
+ dbop.rollback();
+ log.debug("LinkStorageImpl:update {} link:{} failed", dmop, link);
+ }
+ } catch (Exception e) {
+ dbop.rollback();
+ e.printStackTrace();
+ log.error("LinkStorageImpl:update {} link:{} failed", dmop, link);
+ }
+ }
+ break;
+ }
+
+ return success;
+ }
- /**
- * Perform INSERT/CREATE/UPDATE operation to update the LinkStorage.
- *
- * @param lt Record of a link to be updated.
- * @param linkinfo Meta-information of a link to be updated.
- * @param op Operation to be done. (only INSERT/CREATE/UPDATE is acceptable)
- */
- public void updateLink(Link lt, LinkInfo linkinfo, DM_OPERATION op) {
- IPortObject vportSrc = null, vportDst = null;
+ @Override
+ public boolean addLink(Link link) {
+ return addLink(link, null);
+ }
- log.trace("updateLink(): op {} {} {}", new Object[]{op, lt, linkinfo});
+ @Override
+ public boolean addLink(Link link, LinkInfo linfo) {
+ boolean success = false;
+
+ try {
+ if (addLinkImpl(link)) {
+ // Set LinkInfo only if linfo is non-null.
+ if (linfo != null && (! setLinkInfoImpl(link, linfo))) {
+ log.debug("Adding linkinfo failed: {}", link);
+ dbop.rollback();
+ }
+ dbop.commit();
+ success = true;
+ } else {
+ // If we fail here that's because the ports aren't added
+ // before we try to add the link
+ log.debug("Adding link failed: {}", link);
+ dbop.rollback();
+ }
+ } catch (Exception e) {
+ dbop.rollback();
+ e.printStackTrace();
+ log.error("LinkStorageImpl:addLink link:{} linfo:{} failed", link, linfo);
+ }
+
+ return success;
+ }
+
+ /**
+ * Update multiple records in the LinkStorage in a way provided by op.
+ * @param links List of records to be updated.
+ * @param op Operation to be done.
+ */
+ @Override
+ public boolean addLinks(List<Link> links) {
+ boolean success = false;
+
+ for (Link lt: links) {
+ if (! addLinkImpl(lt)) {
+ return false;
+ }
+ }
+
+ try {
+ dbop.commit();
+ success = true;
+ } catch (Exception e) {
+ dbop.rollback();
+ e.printStackTrace();
+ log.error("LinkStorageImpl:addLinks link:s{} failed", links);
+ }
+
+ return success;
+ }
+ /**
+ * Delete a record in the LinkStorage.
+ * @param lt Record to be deleted.
+ */
+ @Override
+ public boolean deleteLink(Link lt) {
+ boolean success = false;
+
+ log.debug("LinkStorageImpl:deleteLink(): {}", lt);
+
try {
- // get source port vertex
- String dpid = HexString.toHexString(lt.getSrc());
- short port = lt.getSrcPort();
- vportSrc = dbop.searchPort(dpid, port);
-
- // get dest port vertex
- dpid = HexString.toHexString(lt.getDst());
- port = lt.getDstPort();
- vportDst = dbop.searchPort(dpid, port);
-
- if (vportSrc != null && vportDst != null) {
- // check if the link exists
-
- Iterable<IPortObject> currPorts = vportSrc.getLinkedPorts();
- List<IPortObject> currLinks = new ArrayList<IPortObject>();
- for (IPortObject V : currPorts) {
- currLinks.add(V);
- }
-
- if (currLinks.contains(vportDst)) {
- // TODO: update linkinfo
- if (op.equals(DM_OPERATION.INSERT) || op.equals(DM_OPERATION.CREATE)) {
- log.debug("addOrUpdateLink(): failed link exists {} {} src {} dst {}",
- new Object[]{op, lt, vportSrc, vportDst});
- }
- } else {
- vportSrc.setLinkPort(vportDst);
-
- dbop.commit();
- log.debug("updateLink(): link added {} {} src {} dst {}", new Object[]{op, lt, vportSrc, vportDst});
- }
+ if (deleteLinkImpl(lt)) {
+ dbop.commit();
+ success = true;
+ log.debug("LinkStorageImpl:deleteLink(): deleted edges {}", lt);
} else {
- log.error("updateLink(): failed invalid vertices {} {} src {} dst {}", new Object[]{op, lt, vportSrc, vportDst});
- dbop.rollback();
+ dbop.rollback();
+ log.error("LinkStorageImpl:deleteLink(): failed invalid vertices {}", lt);
}
- } catch (TitanException e) {
- /*
- * retry till we succeed?
- */
- e.printStackTrace();
- log.error("updateLink(): titan exception {} {} {}", new Object[]{op, lt, e.toString()});
+ } catch (Exception e) {
+ dbop.rollback();
+ log.error("LinkStorageImpl:deleteLink(): failed {} {}",
+ new Object[]{lt, e.toString()});
+ e.printStackTrace();
}
- }
+
+ return success;
+ }
- /**
- * Delete multiple records in LinkStorage.
- *
- * @param links List of records to be deleted.
- */
- @Override
- public void deleteLinks(List<Link> links) {
+ /**
+ * Delete multiple records in LinkStorage.
+ * @param links List of records to be deleted.
+ */
+ @Override
+ public boolean deleteLinks(List<Link> links) {
+ boolean success = false;
+
+ try {
+ for (Link lt : links) {
+ if (! deleteLinkImpl(lt)) {
+ dbop.rollback();
+ return false;
+ }
+ }
+ dbop.commit();
+ success = true;
+ } catch (Exception e) {
+ dbop.rollback();
+ e.printStackTrace();
+ log.error("LinkStorageImpl:deleteLinks failed invalid vertices {}", links);
+ }
+
+ return success;
+ }
- for (Link lt : links) {
- deleteLink(lt);
- }
- }
+ /**
+ * Get list of all links connected to the port specified by given DPID and port number.
+ * @param dpid DPID of desired port.
+ * @param port Port number of desired port.
+ * @return List of links. Empty list if no port was found.
+ */
+ @Override
+ public List<Link> getLinks(Long dpid, short port) {
+ List<Link> links = new ArrayList<Link>();
- /**
- * Delete a record in the LinkStorage.
- *
- * @param lt Record to be deleted.
- */
- @Override
- public void deleteLink(Link lt) {
- IPortObject vportSrc = null, vportDst = null;
- int count = 0;
+ IPortObject srcPort = dbop.searchPort(HexString.toHexString(dpid), port);
+ if (srcPort == null)
+ return links;
+ ISwitchObject srcSw = srcPort.getSwitch();
+ if (srcSw == null)
+ return links;
+
+ for(IPortObject dstPort : srcPort.getLinkedPorts()) {
+ ISwitchObject dstSw = dstPort.getSwitch();
+ if (dstSw != null) {
+ Link link = new Link(dpid, port,
+ HexString.toLong(dstSw.getDPID()),
+ dstPort.getNumber());
+ links.add(link);
+ }
+ }
+ return links;
+ }
- log.debug("deleteLink(): {}", lt);
+ /**
+ * Get list of all reverse links connected to the port specified by given DPID and port number.
+ * @param dpid DPID of desired port.
+ * @param port Port number of desired port.
+ * @return List of reverse links. Empty list if no port was found.
+ */
+ @Override
+ public List<Link> getReverseLinks(Long dpid, short port) {
+ List<Link> links = new ArrayList<Link>();
+
+ IPortObject srcPort = dbop.searchPort(HexString.toHexString(dpid), port);
+ if (srcPort == null)
+ return links;
+ ISwitchObject srcSw = srcPort.getSwitch();
+ if (srcSw == null)
+ return links;
+
+ for(IPortObject dstPort : srcPort.getReverseLinkedPorts()) {
+ ISwitchObject dstSw = dstPort.getSwitch();
+ if (dstSw != null) {
+ Link link = new Link(HexString.toLong(dstSw.getDPID()),
+ dstPort.getNumber(),
+ dpid, port);
+ links.add(link);
+ }
+ }
+ return links;
+ }
+
+ /**
+ * Delete records of the links connected to the port specified by given DPID and port number.
+ * @param dpid DPID of desired port.
+ * @param port Port number of desired port.
+ */
+ @Override
+ public boolean deleteLinksOnPort(Long dpid, short port) {
+ boolean success = false;
+
+ List<Link> linksToDelete = getLinks(dpid, port);
+ try {
+ for(Link l : linksToDelete) {
+ if (! deleteLinkImpl(l)) {
+ dbop.rollback();
+ log.error("LinkStorageImpl:deleteLinksOnPort dpid:{} port:{} failed", dpid, port);
+ return false;
+ }
+ }
+ dbop.commit();
+ success = true;
+ } catch (Exception e) {
+ dbop.rollback();
+ e.printStackTrace();
+ log.error("LinkStorageImpl:deleteLinksOnPort dpid:{} port:{} failed", dpid, port);
+ }
+
+ return success;
+ }
- try {
- // get source port vertex
- String dpid = HexString.toHexString(lt.getSrc());
- short port = lt.getSrcPort();
- vportSrc = dbop.searchPort(dpid, port);
+ /**
+ * Get list of all links connected to the switch specified by given DPID.
+ * @param dpid DPID of desired switch.
+ * @return List of links. Empty list if no port was found.
+ */
+ @Override
+ public List<Link> getLinks(String dpid) {
+ List<Link> links = new ArrayList<Link>();
- // get dst port vertex
- dpid = HexString.toHexString(lt.getDst());
- port = lt.getDstPort();
- vportDst = dbop.searchPort(dpid, port);
- // FIXME: This needs to remove all edges
+ ISwitchObject srcSw = dbop.searchSwitch(dpid);
+
+ if(srcSw != null) {
+ for(IPortObject srcPort : srcSw.getPorts()) {
+ for(IPortObject dstPort : srcPort.getLinkedPorts()) {
+ ISwitchObject dstSw = dstPort.getSwitch();
+ if(dstSw != null) {
+ Link link = new Link(HexString.toLong(dpid),
+ srcPort.getNumber(),
+ HexString.toLong(dstSw.getDPID()),
+ dstPort.getNumber());
+ links.add(link);
+ }
+ }
+ }
+ }
+
+ return links;
+ }
- if (vportSrc != null && vportDst != null) {
+ /**
+ * Get list of all reverse links connected to the switch specified by
+ * given DPID.
+ * @param dpid DPID of desired switch.
+ * @return List of reverse links. Empty list if no port was found.
+ */
+ @Override
+ public List<Link> getReverseLinks(String dpid) {
+ List<Link> links = new ArrayList<Link>();
- /* for (Edge e : vportSrc.asVertex().getEdges(Direction.OUT)) {
- log.debug("deleteLink(): {} in {} out {}",
- new Object[]{e.getLabel(), e.getVertex(Direction.IN), e.getVertex(Direction.OUT)});
- if (e.getLabel().equals("link") && e.getVertex(Direction.IN).equals(vportDst)) {
- graph.removeEdge(e);
- count++;
- }
- }*/
- vportSrc.removeLink(vportDst);
- dbop.commit();
- log.debug("deleteLink(): deleted edges src {} dst {}", new Object[]{
- lt, vportSrc, vportDst});
+ ISwitchObject srcSw = dbop.searchSwitch(dpid);
+
+ if(srcSw != null) {
+ for(IPortObject srcPort : srcSw.getPorts()) {
+ for(IPortObject dstPort : srcPort.getReverseLinkedPorts()) {
+ ISwitchObject dstSw = dstPort.getSwitch();
+ if(dstSw != null) {
+ Link link = new Link(
+ HexString.toLong(dstSw.getDPID()),
+ dstPort.getNumber(),
+
+ HexString.toLong(dpid),
+ srcPort.getNumber());
+ links.add(link);
+ }
+ }
+ }
+ }
+
+ return links;
+ }
- } else {
- log.error("deleteLink(): failed invalid vertices {} src {} dst {}", new Object[]{lt, vportSrc, vportDst});
- dbop.rollback();
- }
+ /**
+ * Get list of all links whose state is ACTIVE.
+ * @return List of active links. Empty list if no port was found.
+ */
+ public List<Link> getActiveLinks() {
+ Iterable<ISwitchObject> switches = dbop.getActiveSwitches();
- } catch (TitanException e) {
- /*
- * retry till we succeed?
- */
- log.error("deleteLink(): titan exception {} {}", new Object[]{lt, e.toString()});
- dbop.rollback();
- e.printStackTrace();
- }
- }
+ List<Link> links = new ArrayList<Link>();
+
+ for (ISwitchObject srcSw : switches) {
+ for(IPortObject srcPort : srcSw.getPorts()) {
+ for(IPortObject dstPort : srcPort.getLinkedPorts()) {
+ ISwitchObject dstSw = dstPort.getSwitch();
+
+ if(dstSw != null && dstSw.getState().equals("ACTIVE")) {
+ links.add(new Link(HexString.toLong(srcSw.getDPID()),
+ srcPort.getNumber(),
+ HexString.toLong(dstSw.getDPID()),
+ dstPort.getNumber()));
+ }
+ }
+ }
+ }
+
+ return links;
+ }
+
+ @Override
+ public LinkInfo getLinkInfo(Link link) {
+ // TODO implement this
+ return null;
+ }
- /**
- * Get list of all links connected to the port specified by given DPID and
- * port number.
- *
- * @param dpid DPID of desired port.
- * @param port Port number of desired port.
- * @return List of links. Empty list if no port was found.
- */
- // TODO: Fix me
- @Override
- public List<Link> getLinks(Long dpid, short port) {
- List<Link> links = new ArrayList<Link>();
+ /**
+ * Finalize the object.
+ */
+ public void finalize() {
+ close();
+ }
- IPortObject srcPort = dbop.searchPort(HexString.toHexString(dpid), port);
- ISwitchObject srcSw = srcPort.getSwitch();
-
- if (srcSw != null && srcPort != null) {
- for (IPortObject dstPort : srcPort.getLinkedPorts()) {
- ISwitchObject dstSw = dstPort.getSwitch();
- Link link = new Link(HexString.toLong(srcSw.getDPID()),
- srcPort.getNumber(),
- HexString.toLong(dstSw.getDPID()),
- dstPort.getNumber());
-
- links.add(link);
- }
- }
-
- return links;
- }
-
- /**
- * Initialize the object. Open LinkStorage using given configuration file.
- *
- * @param conf Path (absolute path for now) to configuration file.
- */
- @Override
- public void init(final String dbStore, final String conf) {
- this.dbop = GraphDBManager.getDBOperation(dbStore, conf);
- }
-
- /**
- * Delete records of the links connected to the port specified by given DPID
- * and port number.
- *
- * @param dpid DPID of desired port.
- * @param port Port number of desired port.
- */
- // TODO: Fix me
- @Override
- public void deleteLinksOnPort(Long dpid, short port) {
- List<Link> linksToDelete = getLinks(dpid, port);
-
- for (Link l : linksToDelete) {
- deleteLink(l);
- }
- }
-
- /**
- * Get list of all links connected to the switch specified by given DPID.
- *
- * @param dpid DPID of desired switch.
- * @return List of links. Empty list if no port was found.
- */
- // TODO: Fix me
- @Override
- public List<Link> getLinks(String dpid) {
- List<Link> links = new ArrayList<Link>();
-
- ISwitchObject srcSw = dbop.searchSwitch(dpid);
-
- if (srcSw != null) {
- for (IPortObject srcPort : srcSw.getPorts()) {
- for (IPortObject dstPort : srcPort.getLinkedPorts()) {
- ISwitchObject dstSw = dstPort.getSwitch();
- if (dstSw != null) {
- Link link = new Link(HexString.toLong(srcSw.getDPID()),
- srcPort.getNumber(),
- HexString.toLong(dstSw.getDPID()),
- dstPort.getNumber());
- links.add(link);
- }
- }
- }
- }
-
- return links;
- }
-
- /**
- * Get list of all links whose state is ACTIVE.
- *
- * @return List of active links. Empty list if no port was found.
- */
- public List<Link> getActiveLinks() {
- Iterable<ISwitchObject> switches = dbop.getActiveSwitches();
-
- List<Link> links = new ArrayList<Link>();
-
- for (ISwitchObject srcSw : switches) {
- for (IPortObject srcPort : srcSw.getPorts()) {
- for (IPortObject dstPort : srcPort.getLinkedPorts()) {
- ISwitchObject dstSw = dstPort.getSwitch();
-
- if (dstSw != null && dstSw.getState().equals("ACTIVE")) {
- links.add(new Link(HexString.toLong(srcSw.getDPID()),
- srcPort.getNumber(),
- HexString.toLong(dstSw.getDPID()),
- dstPort.getNumber()));
- }
- }
- }
- }
-
- return links;
- }
-
- static class ExtractLink implements PipeFunction<PathPipe<Vertex>, Link> {
-
- @Override
- public Link compute(PathPipe<Vertex> pipe) {
- // TODO Auto-generated method stub
- long s_dpid = 0;
- long d_dpid = 0;
- short s_port = 0;
- short d_port = 0;
- List<Vertex> V = new ArrayList<Vertex>();
- V = pipe.next();
- Vertex src_sw = V.get(0);
- Vertex dest_sw = V.get(3);
- Vertex src_port = V.get(1);
- Vertex dest_port = V.get(2);
- s_dpid = HexString.toLong((String) src_sw.getProperty("dpid"));
- d_dpid = HexString.toLong((String) dest_sw.getProperty("dpid"));
- s_port = (Short) src_port.getProperty("number");
- d_port = (Short) dest_port.getProperty("number");
-
- Link l = new Link(s_dpid, s_port, d_dpid, d_port);
-
- return l;
- }
- }
-
- /**
- * Finalize the object.
- */
- public void finalize() {
- close();
- }
-
- /**
- * Close LinkStorage.
- */
- @Override
- public void close() {
- // TODO Auto-generated method stub
+ /**
+ * Close LinkStorage.
+ */
+ @Override
+ public void close() {
+ // TODO Auto-generated method stub
// graph.shutdown();
- }
+ }
+
+ /**
+ * Update a record of link with meta-information in the LinkStorage.
+ * @param link Record of a link to update.
+ * @param linkinfo Meta-information of a link to be updated.
+ */
+ private boolean setLinkInfoImpl(Link link, LinkInfo linkinfo) {
+ // TODO implement this
+
+ return false;
+ }
+
+ private boolean addLinkImpl(Link lt) {
+ boolean success = false;
+
+ IPortObject vportSrc = null, vportDst = null;
+
+ // get source port vertex
+ String dpid = HexString.toHexString(lt.getSrc());
+ short port = lt.getSrcPort();
+ vportSrc = dbop.searchPort(dpid, port);
+
+ // get dest port vertex
+ dpid = HexString.toHexString(lt.getDst());
+ port = lt.getDstPort();
+ vportDst = dbop.searchPort(dpid, port);
+
+ if (vportSrc != null && vportDst != null) {
+ IPortObject portExist = null;
+ // check if the link exists
+ for (IPortObject V : vportSrc.getLinkedPorts()) {
+ if (V.equals(vportDst)) {
+ portExist = V;
+ break;
+ }
+ }
+
+ if (portExist == null) {
+ vportSrc.setLinkPort(vportDst);
+ success = true;
+ } else {
+ log.debug("LinkStorageImpl:addLinkImpl failed link exists {} {} src {} dst {}",
+ new Object[]{dbop, lt, vportSrc, vportDst});
+ }
+ }
+
+ return success;
+ }
+
+ private boolean deleteLinkImpl(Link lt) {
+ boolean success = false;
+ IPortObject vportSrc = null, vportDst = null;
+
+ // get source port vertex
+ String dpid = HexString.toHexString(lt.getSrc());
+ short port = lt.getSrcPort();
+ vportSrc = dbop.searchPort(dpid, port);
+
+ // get dst port vertex
+ dpid = HexString.toHexString(lt.getDst());
+ port = lt.getDstPort();
+ vportDst = dbop.searchPort(dpid, port);
+
+ // FIXME: This needs to remove all edges
+ if (vportSrc != null && vportDst != null) {
+ vportSrc.removeLink(vportDst);
+ log.debug("deleteLinkImpl(): deleted edges src {} dst {}", new Object[]{
+ lt, vportSrc, vportDst});
+ success = true;
+ }
+
+ return success;
+ }
+
+ // TODO should be moved to TopoLinkServiceImpl (never used in this class)
+ static class ExtractLink implements PipeFunction<PathPipe<Vertex>, Link> {
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Link compute(PathPipe<Vertex> pipe ) {
+ long s_dpid = 0;
+ long d_dpid = 0;
+ short s_port = 0;
+ short d_port = 0;
+ List<Vertex> V = new ArrayList<Vertex>();
+ V = (List<Vertex>)pipe.next();
+ Vertex src_sw = V.get(0);
+ Vertex dest_sw = V.get(3);
+ Vertex src_port = V.get(1);
+ Vertex dest_port = V.get(2);
+ s_dpid = HexString.toLong((String) src_sw.getProperty("dpid"));
+ d_dpid = HexString.toLong((String) dest_sw.getProperty("dpid"));
+ s_port = (Short) src_port.getProperty("number");
+ d_port = (Short) dest_port.getProperty("number");
+
+ Link l = new Link(s_dpid,s_port,d_dpid,d_port);
+
+ return l;
+ }
+ }
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/core/internal/SwitchStorageImpl.java b/src/main/java/net/onrc/onos/ofcontroller/core/internal/SwitchStorageImpl.java
index b990157..8bc4fdd 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/core/internal/SwitchStorageImpl.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/internal/SwitchStorageImpl.java
@@ -1,11 +1,16 @@
package net.onrc.onos.ofcontroller.core.internal;
+import java.util.ArrayList;
+import java.util.List;
+
import net.floodlightcontroller.core.IOFSwitch;
import net.onrc.onos.graph.DBOperation;
import net.onrc.onos.graph.GraphDBManager;
import net.onrc.onos.ofcontroller.core.ISwitchStorage;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IDeviceObject;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IPortObject;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.ISwitchObject;
+import net.onrc.onos.ofcontroller.core.ISwitchStorage;
import org.openflow.protocol.OFPhysicalPort;
import org.openflow.protocol.OFPhysicalPort.OFPortConfig;
@@ -14,253 +19,490 @@
import org.slf4j.LoggerFactory;
/**
- * This is the class for storing the information of switches into CassandraDB
+ * This is the class for storing the information of switches into GraphDB
*/
public class SwitchStorageImpl implements ISwitchStorage {
- protected DBOperation op;
- protected static Logger log = LoggerFactory.getLogger(SwitchStorageImpl.class);
+ protected DBOperation op;
+ protected final static Logger log = LoggerFactory.getLogger(SwitchStorageImpl.class);
- /**
- * *
- * Initialize function. Before you use this class, please call this method
- *
- * @param conf configuration file for Cassandra DB
- */
- @Override
- public void init(final String dbStore, final String conf) {
- op = GraphDBManager.getDBOperation(dbStore, conf);
- }
+ /**
+ * *
+ * Initialize function. Before you use this class, please call this method
+ *
+ * @param conf configuration file for Cassandra DB
+ */
+ @Override
+ public void init(final String dbStore, final String conf) {
+ op = GraphDBManager.getDBOperation(dbStore, conf);
+ }
- /**
- * *
- * Finalize/close function. After you use this class, please call this
- * method. It will close the DB connection.
- */
- public void finalize() {
- close();
- }
- /**
- * *
- * Finalize/close function. After you use this class, please call this
- * method. It will close the DB connection. This is for Java garbage
- * collection.
- */
- @Override
- public void close() {
- op.close();
- }
+ /***
+ * Finalize/close function. After you use this class, please call this method.
+ * It will close the DB connection.
+ */
+ public void finalize() {
+ close();
+ }
+
+ /***
+ * Finalize/close function. After you use this class, please call this method.
+ * It will close the DB connection. This is for Java garbage collection.
+ */
+ @Override
+ public void close() {
+ op.close();
+ }
+
+ // Method designing policy:
+ // op.commit() and op.rollback() MUST called in public (first-class) methods.
+ // A first-class method MUST NOT call other first-class method.
+ // Routine process should be implemented in private method.
+ // A private method MUST NOT call commit or rollback.
+
+ /***
+ * This function is for updating the switch into the DB.
+ * @param dpid The switch dpid you want to update from the DB
+ * @param state The state of the switch like ACTIVE, INACTIVE
+ * @param dmope The DM_OPERATION of the switch
+ */
+ /*
+ * Jono, 11/8/2013
+ * We don't need this update method that demultiplexes DM_OPERATIONS,
+ * we can have clients just call the required methods directly.
+ * We especially don't need this update method to re-implement
+ * the functions of other methods.
+ */
+ @Deprecated
+ @Override
+ public boolean updateSwitch(String dpid, SwitchState state, DM_OPERATION dmope) {
+ boolean success = false;
+ ISwitchObject sw = null;
+
+ log.info("SwitchStorage:update {} dpid:{}", dmope, dpid);
+ switch(dmope) {
+ case UPDATE:
+ try {
+ sw = op.searchSwitch(dpid);
+ if (sw != null) {
+ setSwitchStateImpl(sw, state);
+ op.commit();
+ success = true;
+ }
+ } catch (Exception e) {
+ op.rollback();
+ e.printStackTrace();
+ log.info("SwitchStorage:update {} dpid:{} failed", dmope, dpid);
+ }
+ break;
+ case INSERT:
+ case CREATE:
+ try {
+ sw = addSwitchImpl(dpid);
+ if (sw != null) {
+ if (state != SwitchState.ACTIVE) {
+ setSwitchStateImpl(sw, state);
+ }
+ op.commit();
+ success = true;
+ }
+ } catch (Exception e) {
+ op.rollback();
+ e.printStackTrace();
+ log.info("SwitchStorage:update {} dpid:{} failed", dmope, dpid);
+ }
+ break;
+ case DELETE:
+ try {
+ sw = op.searchSwitch(dpid);
+ if (sw != null) {
+ deleteSwitchImpl(sw);
+ op.commit();
+ success = true;
+ }
+ } catch (Exception e) {
+ op.rollback();
+ e.printStackTrace();
+ log.info("SwitchStorage:update {} dpid:{} failed", dmope, dpid);
+ }
+ break;
+ default:
+ }
+
+ return success;
+ }
+
+ @Override
+ public boolean addSwitch(IOFSwitch sw) {
+ boolean success = false;
+
+ String dpid = sw.getStringId();
+ log.info("SwitchStorage:addSwitch(): dpid {} ", dpid);
+
+ try {
+ ISwitchObject curr = op.searchSwitch(dpid);
+ if (curr != null) {
+ //If existing the switch. set The SW state ACTIVE.
+ log.info("SwitchStorage:addSwitch dpid:{} already exists", dpid);
+ setSwitchStateImpl(curr, SwitchState.ACTIVE);
+ } else {
+ curr = addSwitchImpl(dpid);
+ }
+
+ for (OFPhysicalPort port: sw.getPorts()) {
+ //addPort(dpid, port);
+ addPortImpl(curr, port);
- private void setStatus(String dpid, SwitchState state) {
- ISwitchObject sw = op.searchSwitch(dpid);
+ }
+
+ // XXX for now delete devices when we change a port to prevent
+ // having stale devices.
+ DeviceStorageImpl deviceStorage = new DeviceStorageImpl();
+ deviceStorage.init("","");
+ for (IPortObject portObject : curr.getPorts()) {
+ for (IDeviceObject deviceObject : portObject.getDevices()) {
+ // The deviceStorage has to remove on the object gained by its own
+ // FramedGraph, it can't use our objects from here
+ deviceStorage.removeDeviceImpl(deviceStorage.getDeviceByMac(deviceObject.getMACAddress()));
+ }
+ }
+
+ op.commit();
+ success = true;
+ } catch (Exception e) {
+ op.rollback();
+ log.error("SwitchStorage:addSwitch dpid:{} failed", dpid, e);
+ }
+
+ return success;
+ }
- try {
- if (sw != null) {
- sw.setState(state.toString());
- op.commit();
- log.info("SwitchStorage:setStatus dpid:{} state: {} done", dpid, state);
- }
- } catch (Exception e) {
- e.printStackTrace();
- op.rollback();
- log.info("SwitchStorage:setStatus dpid:{} state: {} failed: switch not found", dpid, state);
+ /***
+ * This function is for adding the switch into the DB.
+ * @param dpid The switch dpid you want to add into the DB.
+ */
+ // This method is only called by tests, so we probably don't need it.
+ // If we need both addSwitch interfaces, one should call the other
+ // rather than implementing the same logic twice.
+ @Deprecated
+ @Override
+ public boolean addSwitch(String dpid) {
+ boolean success = false;
+
+ log.info("SwitchStorage:addSwitch(): dpid {} ", dpid);
+ try {
+ ISwitchObject sw = op.searchSwitch(dpid);
+ if (sw != null) {
+ //If existing the switch. set The SW state ACTIVE.
+ log.info("SwitchStorage:addSwitch dpid:{} already exists", dpid);
+ setSwitchStateImpl(sw, SwitchState.ACTIVE);
+ } else {
+ addSwitchImpl(dpid);
+ }
+ op.commit();
+ success = true;
+ } catch (Exception e) {
+ op.rollback();
+ e.printStackTrace();
+ log.error("SwitchStorage:addSwitch dpid:{} failed", dpid, e);
+ }
+
+ return success;
+ }
+
+ /***
+ * This function is for deleting the switch into the DB.
+ * @param dpid The switch dpid you want to delete from the DB.
+ */
+ @Override
+ public boolean deleteSwitch(String dpid) {
+ boolean success = false;
+
+ try {
+ ISwitchObject sw = op.searchSwitch(dpid);
+ if (sw != null) {
+ deleteSwitchImpl(sw);
+ op.commit();
+ }
+ success = true;
+ } catch (Exception e) {
+ op.rollback();
+ e.printStackTrace();
+ log.error("SwitchStorage:deleteSwitch {} failed", dpid);
+ }
+
+ return success;
+ }
+
+ public boolean deactivateSwitch(String dpid) {
+ boolean success = false;
+
+ try {
+ ISwitchObject switchObject = op.searchSwitch(dpid);
+ if (switchObject != null) {
+ setSwitchStateImpl(switchObject, SwitchState.INACTIVE);
+
+ for (IPortObject portObject : switchObject.getPorts()) {
+ portObject.setState("INACTIVE");
+ }
+ op.commit();
+ success = true;
+ }
+ else {
+ log.warn("Switch {} not found when trying to deactivate", dpid);
+ }
+ } catch (Exception e) {
+ // TODO what type of exception is thrown when we can't commit?
+ op.rollback();
+ log.error("SwitchStorage:deactivateSwitch {} failed", dpid, e);
+ }
+
+ return success;
+ }
+
+ public boolean updatePort(String dpid, short portNum, int state, String desc) {
+ boolean success = false;
+
+ try {
+ ISwitchObject sw = op.searchSwitch(dpid);
+
+ if (sw != null) {
+ IPortObject p = sw.getPort(portNum);
+ log.info("SwitchStorage:updatePort dpid:{} port:{}", dpid, portNum);
+ if (p != null) {
+ setPortStateImpl(p, state, desc);
+ op.commit();
+ }
+ success = true;
+ } else {
+ log.error("SwitchStorage:updatePort dpid:{} port:{} : failed switch does not exist", dpid, portNum);
+ }
+ } catch (Exception e) {
+ op.rollback();
+ e.printStackTrace();
+ log.error("SwitchStorage:addPort dpid:{} port:{} failed", dpid, portNum);
+ }
+
+ return success;
+ }
+
+ /***
+ * This function is for adding the switch port into the DB.
+ * @param dpid The switch dpid that has the port.
+ * @param phport The port you want to add the switch.
+ */
+ @Override
+ public boolean addPort(String dpid, OFPhysicalPort phport) {
+ boolean success = false;
+
+ if(((OFPortConfig.OFPPC_PORT_DOWN.getValue() & phport.getConfig()) > 0) ||
+ ((OFPortState.OFPPS_LINK_DOWN.getValue() & phport.getState()) > 0)) {
+ // just dispatch to deletePort()
+ // TODO This is wrong. We need to make sure the port is in the
+ // DB with the correct info and port state.
+ return deletePort(dpid, phport.getPortNumber());
+ }
+
+ try {
+ ISwitchObject sw = op.searchSwitch(dpid);
+
+ if (sw != null) {
+ IPortObject portObject = addPortImpl(sw, phport);
+
+ // XXX for now delete devices when we change a port to prevent
+ // having stale devices.
+ DeviceStorageImpl deviceStorage = new DeviceStorageImpl();
+ deviceStorage.init("","");
+
+ for (IDeviceObject deviceObject : portObject.getDevices()) {
+ deviceStorage.removeDevice(deviceObject);
+ }
+
+ op.commit();
+ success = true;
+ } else {
+ log.error("SwitchStorage:addPort dpid:{} port:{} : failed switch does not exist", dpid, phport.getPortNumber());
+ }
+ } catch (Exception e) {
+ op.rollback();
+ e.printStackTrace();
+ log.error("SwitchStorage:addPort dpid:{} port:{} failed", dpid, phport.getPortNumber());
+ }
+
+ return success;
+ }
+
+ /***
+ * This function is for deleting the switch port from the DB.
+ * @param dpid The switch dpid that has the port.
+ * @param port The port you want to delete the switch.
+ */
+ @Override
+ public boolean deletePort(String dpid, short port) {
+ boolean success = false;
+
+ DeviceStorageImpl deviceStorage = new DeviceStorageImpl();
+ deviceStorage.init("","");
+
+ try {
+ ISwitchObject sw = op.searchSwitch(dpid);
+
+ if (sw != null) {
+ IPortObject p = sw.getPort(port);
+ if (p != null) {
+ log.info("SwitchStorage:deletePort dpid:{} port:{} found and set INACTIVE", dpid, port);
+ //deletePortImpl(p);
+ p.setState("INACTIVE");
+
+ // XXX for now delete devices when we change a port to prevent
+ // having stale devices.
+ for (IDeviceObject d : p.getDevices()) {
+ deviceStorage.removeDevice(d);
+ }
+ op.commit();
+ }
+ }
+
+ success = true;
+ } catch (Exception e) {
+ op.rollback();
+ e.printStackTrace();
+ log.error("SwitchStorage:deletePort dpid:{} port:{} failed", dpid, port);
+ }
+
+ return success;
+ }
+
+ /**
+ * Get list of all ports on the switch specified by given DPID.
+ *
+ * @param dpid DPID of desired switch.
+ * @return List of port IDs. Empty list if no port was found.
+ */
+ @Override
+ public List<Short> getPorts(String dpid) {
+ List<Short> ports = new ArrayList<Short>();
+
+ ISwitchObject srcSw = op.searchSwitch(dpid);
+ if (srcSw != null) {
+ for (IPortObject srcPort : srcSw.getPorts()) {
+ ports.add(srcPort.getNumber());
+ }
+ }
+
+ return ports;
+ }
+
+ private ISwitchObject addSwitchImpl(String dpid) {
+ if (dpid != null) {
+ ISwitchObject sw = op.newSwitch(dpid);
+ sw.setState(SwitchState.ACTIVE.toString());
+ log.info("SwitchStorage:addSwitchImpl dpid:{} added", dpid);
+ return sw;
+ } else {
+ return null;
+ }
+ }
+
+ private void setSwitchStateImpl(ISwitchObject sw, SwitchState state) {
+ if (sw != null && state != null) {
+ sw.setState(state.toString());
+ log.info("SwitchStorage:setSwitchStateImpl dpid:{} updated {}",
+ sw.getDPID(), state.toString());
+ }
+ }
+
+ private void deleteSwitchImpl(ISwitchObject sw) {
+ if (sw != null) {
+ op.removeSwitch(sw);
+ log.info("SwitchStorage:DeleteSwitchImpl dpid:{} done",
+ sw.getDPID());
}
- }
+ }
- /**
- * *
- * This function is for adding the switch into the DB.
- *
- * @param dpid The switch dpid you want to add into the DB.
- */
- @Override
- public void addSwitch(String dpid) {
+
+ private IPortObject addPortImpl(ISwitchObject sw, OFPhysicalPort phport) {
+ IPortObject portObject = op.searchPort(sw.getDPID(), phport.getPortNumber());
+
+ log.info("SwitchStorage:addPort dpid:{} port:{}",
+ sw.getDPID(), phport.getPortNumber());
+
+ if (portObject != null) {
+ setPortStateImpl(portObject, phport.getState(), phport.getName());
+ portObject.setState("ACTIVE");
+
+ // This a convoluted way of checking if the port is attached
+ // or not, but doing it this way avoids using the
+ // ISwitchObject.getPort method which uses GremlinGroovy query
+ // and takes forever.
+ boolean attached = false;
+ for (IPortObject portsOnSwitch : sw.getPorts()) {
+ if (portsOnSwitch.getPortId() == portObject.getPortId()) {
+ attached = true;
+ break;
+ }
+ }
+
+ if (!attached) {
+ sw.addPort(portObject);
+ }
+
+ /*
+ if (sw.getPort(phport.getPortNumber()) == null) {
+ // The port exists but the switch has no "on" link to it
+ sw.addPort(portObject);
+ }*/
+
+ log.info("SwitchStorage:addPort dpid:{} port:{} exists setting as ACTIVE",
+ sw.getDPID(), phport.getPortNumber());
+ } else {
+ //addPortImpl(sw, phport.getPortNumber());
+ portObject = op.newPort(sw.getDPID(), phport.getPortNumber());
+ portObject.setState("ACTIVE");
+ setPortStateImpl(portObject, phport.getState(), phport.getName());
+ sw.addPort(portObject);
+ log.info("SwitchStorage:addPort dpid:{} port:{} done",
+ sw.getDPID(), phport.getPortNumber());
+ }
+
+ return portObject;
+ }
+ // TODO There's an issue here where a port with that ID could already
+ // exist when we try to add this one (because it's left over from an
+ // old topology). We need to remove an old port with the same ID when
+ // we add the new port. Also it seems that old ports like this are
+ // never cleaned up and will remain in the DB in the ACTIVE state forever.
+ /*private IPortObject addPortImpl(ISwitchObject sw, short portNum) {
+ IPortObject p = op.newPort(sw.getDPID(), portNum);
+ p.setState("ACTIVE");
+ sw.addPort(p);
+ log.info("SwitchStorage:addPortImpl dpid:{} port:{} done",
+ sw.getDPID(), portNum);
+
+ return p;
+ }*/
- log.info("SwitchStorage:addSwitch(): dpid {} ", dpid);
- try {
- ISwitchObject sw = newSwitch(dpid);
- if (sw == null) {
- throw new RuntimeException();
- }
- op.commit();
- } catch (Exception e) {
- e.printStackTrace();
- op.rollback();
- log.info("SwitchStorage:addSwitch dpid:{} failed", dpid);
- }
- }
+ private void setPortStateImpl(IPortObject port, Integer state, String desc) {
+ if (port != null) {
+ if (state != null) {
+ port.setPortState(state);
+ }
+ if (desc != null) {
+ port.setDesc(desc);
+ }
+
+ log.info("SwitchStorage:setPortStateImpl port:{} state:{} desc:{} done",
+ new Object[] {port.getPortId(), state, desc});
+ }
+ }
+
+ private void deletePortImpl(IPortObject port) {
+ if (port != null) {
+ op.removePort(port);
+ log.info("SwitchStorage:deletePortImpl port:{} done",
+ port.getPortId());
+ }
+ }
- private ISwitchObject newSwitch(String dpid) {
- ISwitchObject sw = op.searchSwitch(dpid);
- if (sw != null) {
- //If existing the switch. set The SW state ACTIVE.
- log.info("SwitchStorage:newSwitch dpid:{} already exists", dpid);
- sw.setState(SwitchState.ACTIVE.toString());
- } else {
- sw = op.newSwitch(dpid);
- if (sw != null) {
- sw.setState(SwitchState.ACTIVE.toString());
- log.info("SwitchStorage:newSwitch dpid:{} added", dpid);
- } else {
- log.error("switchStorage:newSwitch dpid:{} failed -> newSwitch failed", dpid);
- }
- }
- return sw;
- }
-
- /**
- * *
- * This function is for updating the switch into the DB.
- *
- * @param dpid The switch dpid you want to update from the DB
- * @param state The state of the switch like ACTIVE, INACTIVE
- * @param dmope The DM_OPERATION of the switch
- */
- @Override
- public void update(String dpid, SwitchState state, DM_OPERATION dmope) {
- log.info("SwitchStorage:update dpid:{} state: {} ", dpid, state);
- switch (dmope) {
- case UPDATE:
- case INSERT:
- case CREATE:
- addSwitch(dpid);
- if (state != SwitchState.ACTIVE) {
- setStatus(dpid, state);
- }
- break;
- case DELETE:
- deleteSwitch(dpid);
- break;
- default:
- }
- }
-
- /**
- * *
- * This function is for deleting the switch into the DB.
- *
- * @param dpid The switch dpid you want to delete from the DB.
- */
- @Override
- public void deleteSwitch(String dpid) {
- try {
- ISwitchObject sw = op.searchSwitch(dpid);
- if (sw != null) {
- op.removeSwitch(sw);
- op.commit();
- log.info("SwitchStorage:DeleteSwitch dpid:{} done", dpid);
- }
- } catch (Exception e) {
- e.printStackTrace();
- op.rollback();
- log.error("SwitchStorage:deleteSwitch {} failed", dpid);
- }
-
- }
-
- /**
- * *
- * This function is for adding the switch port into the DB.
- *
- * @param dpid The switch dpid that has the port.
- * @param port The port you want to add the switch.
- */
- @Override
- public void addPort(String dpid, OFPhysicalPort port) {
-
- if (((OFPortConfig.OFPPC_PORT_DOWN.getValue() & port.getConfig()) > 0)
- || ((OFPortState.OFPPS_LINK_DOWN.getValue() & port.getState()) > 0)) {
- deletePort(dpid, port.getPortNumber());
- return;
- }
-
- try {
- ISwitchObject sw = op.searchSwitch(dpid);
-
- if (sw != null) {
- IPortObject p = op.searchPort(dpid, port.getPortNumber());
- log.info("SwitchStorage:addPort dpid:{} port:{}", dpid, port.getPortNumber());
- if (p != null) {
- log.error("SwitchStorage:addPort dpid:{} port:{} exists setting as ACTIVE", dpid, port.getPortNumber());
- p.setState("ACTIVE");
- p.setPortState(port.getState());
- p.setDesc(port.getName());
- op.commit();
- } else {
- p = op.newPort(dpid, port.getPortNumber());
- p.setState("ACTIVE");
- p.setPortState(port.getState());
- p.setDesc(port.getName());
- sw.addPort(p);
- op.commit();
- }
- } else {
- log.error("SwitchStorage:addPort dpid:{} port:{} : failed switch does not exist", dpid, port.getPortNumber());
- }
- } catch (Exception e) {
- e.printStackTrace();
- op.rollback();
- log.error("SwitchStorage:addPort dpid:{} port:{} failed", dpid, port.getPortNumber());
- }
-
- }
-
- /**
- * *
- * This function is for deleting the switch port from the DB.
- *
- * @param dpid The switch dpid that has the port.
- * @param port The port you want to delete the switch.
- */
- @Override
- public void deletePort(String dpid, short port) {
- try {
- ISwitchObject sw = op.searchSwitch(dpid);
-
- if (sw != null) {
- IPortObject p = op.searchPort(dpid, port);
- if (p != null) {
- log.info("SwitchStorage:deletePort dpid:{} port:{} found and set INACTIVE", dpid, port);
- p.setState("INACTIVE");
- op.commit();
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- op.rollback();
- log.info("SwitchStorage:deletePort dpid:{} port:{} failed", dpid, port);
- }
- }
-
- @Override
- public void addSwitch(IOFSwitch sw) {
- // TODO Auto-generated method stub
- String dpid = sw.getStringId();
- log.info("SwitchStorage:addSwitch(): dpid {} ", dpid);
- try {
- ISwitchObject switchObject = newSwitch(dpid);
- for (OFPhysicalPort port : sw.getPorts()) {
- IPortObject p = op.searchPort(dpid, port.getPortNumber());
- if (p != null) {
- log.error("SwitchStorage:addPort dpid:{} port:{} exists", dpid, port.getPortNumber());
- p.setState("ACTIVE");
- p.setPortState(port.getState());
- p.setDesc(port.getName());
- } else {
- p = op.newPort(dpid, port.getPortNumber());
- p.setState("ACTIVE");
- p.setPortState(port.getState());
- p.setDesc(port.getName());
- switchObject.addPort(p);
- }
- }
- op.commit();
- } catch (Exception e) {
- e.printStackTrace();
- op.rollback();
- log.info("SwitchStorage:addSwitch dpid:{} failed", dpid);
- }
-
- }
}
\ No newline at end of file
diff --git a/src/main/java/net/onrc/onos/ofcontroller/core/internal/TopoLinkServiceImpl.java b/src/main/java/net/onrc/onos/ofcontroller/core/internal/TopoLinkServiceImpl.java
index e810646..b692e8e 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/core/internal/TopoLinkServiceImpl.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/internal/TopoLinkServiceImpl.java
@@ -18,7 +18,7 @@
public class TopoLinkServiceImpl implements ITopoLinkService {
protected GraphDBOperation op;
- protected static Logger log = LoggerFactory.getLogger(TopoLinkServiceImpl.class);
+ protected final static Logger log = LoggerFactory.getLogger(TopoLinkServiceImpl.class);
public void finalize() {
close();
diff --git a/src/main/java/net/onrc/onos/ofcontroller/core/internal/TopoSwitchServiceImpl.java b/src/main/java/net/onrc/onos/ofcontroller/core/internal/TopoSwitchServiceImpl.java
index 978fcde..3a324b1 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/core/internal/TopoSwitchServiceImpl.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/internal/TopoSwitchServiceImpl.java
@@ -11,14 +11,14 @@
public class TopoSwitchServiceImpl implements ITopoSwitchService {
private GraphDBOperation op;
- protected static Logger log = LoggerFactory.getLogger(TopoSwitchServiceImpl.class);
+ protected final static Logger log = LoggerFactory.getLogger(TopoSwitchServiceImpl.class);
public TopoSwitchServiceImpl(String conf) {
op = new GraphDBOperation(conf);
}
public TopoSwitchServiceImpl() {
- this("/tmp/cassandra.titan");
+ this("");
}
public void finalize() {
@@ -53,7 +53,11 @@
@Override
public Iterable<IPortObject> getPortsOnSwitch(String dpid) {
- // TODO Auto-generated method stub
+ op.close(); //Commit to ensure we see latest data
+ ISwitchObject switchObject = op.searchSwitch(dpid);
+ if (switchObject != null) {
+ return switchObject.getPorts();
+ }
return null;
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/core/module/IOnosService.java b/src/main/java/net/onrc/onos/ofcontroller/core/module/IOnosService.java
new file mode 100644
index 0000000..5828366
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/module/IOnosService.java
@@ -0,0 +1,7 @@
+package net.onrc.onos.ofcontroller.core.module;
+
+import net.floodlightcontroller.core.module.IFloodlightService;
+
+public interface IOnosService extends IFloodlightService {
+
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/core/module/OnosModuleLoader.java b/src/main/java/net/onrc/onos/ofcontroller/core/module/OnosModuleLoader.java
new file mode 100644
index 0000000..6b8b514
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/module/OnosModuleLoader.java
@@ -0,0 +1,94 @@
+package net.onrc.onos.ofcontroller.core.module;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import net.floodlightcontroller.core.IFloodlightProviderService;
+import net.floodlightcontroller.core.module.FloodlightModuleContext;
+import net.floodlightcontroller.core.module.FloodlightModuleException;
+import net.floodlightcontroller.core.module.IFloodlightModule;
+import net.floodlightcontroller.core.module.IFloodlightService;
+import net.floodlightcontroller.restserver.IRestApiService;
+import net.floodlightcontroller.topology.ITopologyService;
+import net.onrc.onos.datagrid.IDatagridService;
+import net.onrc.onos.ofcontroller.core.config.DefaultConfiguration;
+import net.onrc.onos.ofcontroller.core.config.IConfigInfoService;
+import net.onrc.onos.ofcontroller.flowmanager.IFlowService;
+import net.onrc.onos.ofcontroller.forwarding.Forwarding;
+import net.onrc.onos.ofcontroller.proxyarp.IProxyArpService;
+import net.onrc.onos.ofcontroller.proxyarp.ProxyArpManager;
+
+public class OnosModuleLoader implements IFloodlightModule {
+ private IFloodlightProviderService floodlightProvider;
+ private ITopologyService topology;
+ private IConfigInfoService config;
+ private IRestApiService restApi;
+ private IFlowService flowService;
+ private IDatagridService datagrid;
+
+ private ProxyArpManager arpManager;
+ private Forwarding forwarding;
+
+ public OnosModuleLoader() {
+ arpManager = new ProxyArpManager();
+ forwarding = new Forwarding();
+ }
+
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleServices() {
+ List<Class<? extends IFloodlightService>> services =
+ new ArrayList<Class<? extends IFloodlightService>>();
+ services.add(IProxyArpService.class);
+ return services;
+ }
+
+ @Override
+ public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
+ Map<Class<? extends IFloodlightService>, IFloodlightService> impls =
+ new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
+ impls.put(IProxyArpService.class, arpManager);
+ return impls;
+ }
+
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
+ List<Class<? extends IFloodlightService>> dependencies =
+ new ArrayList<Class<? extends IFloodlightService>>();
+ dependencies.add(IFloodlightProviderService.class);
+ dependencies.add(ITopologyService.class);
+ dependencies.add(IRestApiService.class);
+ dependencies.add(IFlowService.class);
+ dependencies.add(IDatagridService.class);
+ return dependencies;
+ }
+
+ @Override
+ public void init(FloodlightModuleContext context)
+ throws FloodlightModuleException {
+ floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
+ topology = context.getServiceImpl(ITopologyService.class);
+ restApi = context.getServiceImpl(IRestApiService.class);
+ flowService = context.getServiceImpl(IFlowService.class);
+ datagrid = context.getServiceImpl(IDatagridService.class);
+
+ //This could be null because it's not mandatory to have an
+ //IConfigInfoService loaded.
+ config = context.getServiceImpl(IConfigInfoService.class);
+ if (config == null) {
+ config = new DefaultConfiguration();
+ }
+
+ arpManager.init(floodlightProvider, topology, datagrid, config, restApi);
+ forwarding.init(floodlightProvider, flowService, datagrid);
+ }
+
+ @Override
+ public void startUp(FloodlightModuleContext context) {
+ arpManager.startUp();
+ forwarding.startUp();
+ }
+
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/core/web/ClearFlowTableResource.java b/src/main/java/net/onrc/onos/ofcontroller/core/web/ClearFlowTableResource.java
index 7b1acfe..fe70877 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/core/web/ClearFlowTableResource.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/web/ClearFlowTableResource.java
@@ -16,7 +16,7 @@
import org.slf4j.LoggerFactory;
public class ClearFlowTableResource extends ServerResource {
- static Logger log = LoggerFactory.getLogger(ClearFlowTableResource.class);
+ final static Logger log = LoggerFactory.getLogger(ClearFlowTableResource.class);
@Post("json")
public List<String> ClearFlowTable(String jsonData){
diff --git a/src/main/java/net/onrc/onos/ofcontroller/floodlightlistener/INetworkGraphService.java b/src/main/java/net/onrc/onos/ofcontroller/floodlightlistener/INetworkGraphService.java
new file mode 100644
index 0000000..121eaf9
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/floodlightlistener/INetworkGraphService.java
@@ -0,0 +1,10 @@
+package net.onrc.onos.ofcontroller.floodlightlistener;
+
+import net.floodlightcontroller.core.module.IFloodlightService;
+
+/**
+ * Interface for providing Network Graph Service to other module.
+ */
+public interface INetworkGraphService extends IFloodlightService {
+ // TODO
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/floodlightlistener/NetworkGraphPublisher.java b/src/main/java/net/onrc/onos/ofcontroller/floodlightlistener/NetworkGraphPublisher.java
index 5c372fb..5a2fc7f 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/floodlightlistener/NetworkGraphPublisher.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/floodlightlistener/NetworkGraphPublisher.java
@@ -2,6 +2,8 @@
import java.util.ArrayList;
import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@@ -11,6 +13,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.common.net.InetAddresses;
+
import net.floodlightcontroller.core.IFloodlightProviderService;
import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.core.IOFSwitchListener;
@@ -27,6 +31,7 @@
import net.onrc.onos.graph.DBOperation;
import net.onrc.onos.graph.DBConnection;
import net.onrc.onos.graph.GraphDBManager;
+import net.onrc.onos.datagrid.IDatagridService;
import net.onrc.onos.graph.IDBConnection;
import net.onrc.onos.graph.LocalTopologyEventListener;
import net.onrc.onos.ofcontroller.core.IDeviceStorage;
@@ -41,17 +46,24 @@
import net.onrc.onos.ofcontroller.core.internal.SwitchStorageImpl;
import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscoveryListener;
import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscoveryService;
+import net.onrc.onos.ofcontroller.linkdiscovery.LinkInfo;
+import net.onrc.onos.ofcontroller.proxyarp.ArpMessage;
+import net.onrc.onos.ofcontroller.topology.TopologyElement;
import net.onrc.onos.registry.controller.IControllerRegistryService;
import net.onrc.onos.registry.controller.IControllerRegistryService.ControlChangeCallback;
import net.onrc.onos.registry.controller.RegistryException;
-public class NetworkGraphPublisher implements IDeviceListener, IOFSwitchListener, IOFSwitchPortListener,
- ILinkDiscoveryListener, IFloodlightModule {
+public class NetworkGraphPublisher implements IDeviceListener,
+ IOFSwitchListener,
+ IOFSwitchPortListener,
+ ILinkDiscoveryListener,
+ IFloodlightModule,
+ INetworkGraphService {
protected IDeviceStorage devStore;
protected ISwitchStorage swStore;
protected ILinkStorage linkStore;
- protected static Logger log;
+ protected final static Logger log = LoggerFactory.getLogger(NetworkGraphPublisher.class);
protected IDeviceService deviceService;
protected IControllerRegistryService registryService;
protected DBOperation op;
@@ -65,6 +77,8 @@
protected final int CLEANUP_TASK_INTERVAL = 60; // 1 min
protected SingletonTask cleanupTask;
protected ILinkDiscoveryService linkDiscovery;
+
+ protected IDatagridService datagridService;
/**
* Cleanup and synch switch state from registry
@@ -87,12 +101,50 @@
@Override
public void controlChanged(long dpid, boolean hasControl) {
- // TODO Auto-generated method stub
-
if (hasControl) {
log.debug("got control to set inactive sw {}", HexString.toHexString(dpid));
- swStore.update(HexString.toHexString(dpid),SwitchState.INACTIVE, DM_OPERATION.UPDATE);
- registryService.releaseControl(dpid);
+ try {
+ // Get the affected ports
+ List<Short> ports = swStore.getPorts(HexString.toHexString(dpid));
+ // Get the affected links
+ List<Link> links = linkStore.getLinks(HexString.toHexString(dpid));
+ // Get the affected reverse links
+ List<Link> reverseLinks = linkStore.getReverseLinks(HexString.toHexString(dpid));
+ links.addAll(reverseLinks);
+
+ //if (swStore.updateSwitch(HexString.toHexString(dpid), SwitchState.INACTIVE, DM_OPERATION.UPDATE)) {
+ if (swStore.deactivateSwitch(HexString.toHexString(dpid))) {
+ registryService.releaseControl(dpid);
+
+ // TODO publish UPDATE_SWITCH event here
+ //
+ // NOTE: Here we explicitly send
+ // notification to remove the
+ // switch, because it is inactive
+ //
+ TopologyElement topologyElement =
+ new TopologyElement(dpid);
+ datagridService.notificationSendTopologyElementRemoved(topologyElement);
+
+ // Publish: remove the affected ports
+ for (Short port : ports) {
+ TopologyElement topologyElementPort =
+ new TopologyElement(dpid, port);
+ datagridService.notificationSendTopologyElementRemoved(topologyElementPort);
+ }
+ // Publish: remove the affected links
+ for (Link link : links) {
+ TopologyElement topologyElementLink =
+ new TopologyElement(link.getSrc(),
+ link.getSrcPort(),
+ link.getDst(),
+ link.getDstPort());
+ datagridService.notificationSendTopologyElementRemoved(topologyElementLink);
+ }
+ }
+ } catch (Exception e) {
+ log.error("Error in SwitchCleanup:controlChanged ", e);
+ }
}
}
}
@@ -115,39 +167,67 @@
// log.debug("sw {} is controlled by controller: {}",HexString.toHexString(dpid),controller);
}
} catch (NumberFormatException e) {
- // TODO Auto-generated catch block
+ log.debug("Caught NumberFormatException trying to requestControl in cleanup thread");
e.printStackTrace();
} catch (RegistryException e) {
log.debug("Caught RegistryException trying to requestControl in cleanup thread");
e.printStackTrace();
- }
+ }
}
op.close();
}
@Override
public void linkDiscoveryUpdate(LDUpdate update) {
- // TODO Auto-generated method stub
Link lt = new Link(update.getSrc(),update.getSrcPort(),update.getDst(),update.getDstPort());
//log.debug("{}:LinkDicoveryUpdate(): Updating Link {}",this.getClass(), lt);
switch (update.getOperation()) {
case LINK_REMOVED:
log.debug("LinkDiscoveryUpdate(): Removing link {}", lt);
- linkStore.update(lt, DM_OPERATION.DELETE);
- // TODO: Move network map link removal here
- // reconcile paths here
-// IPortObject srcPort = conn.utils().searchPort(conn, HexString.toHexString(update.getSrc()), update.getSrcPort());
+
+ if (linkStore.deleteLink(lt)) {
+ // TODO publish DELETE_LINK event here
+ TopologyElement topologyElement =
+ new TopologyElement(update.getSrc(),
+ update.getSrcPort(),
+ update.getDst(),
+ update.getDstPort());
+ datagridService.notificationSendTopologyElementRemoved(topologyElement);
+ }
break;
case LINK_UPDATED:
log.debug("LinkDiscoveryUpdate(): Updating link {}", lt);
- linkStore.update(lt, DM_OPERATION.UPDATE);
+
+ LinkInfo linfo = linkStore.getLinkInfo(lt);
+ // TODO update "linfo" using portState derived using "update"
+ if (linkStore.update(lt, linfo, DM_OPERATION.UPDATE)) {
+ // TODO publish UPDATE_LINK event here
+ //
+ // TODO NOTE: Here we assume that updated
+ // link is UP.
+ //
+ TopologyElement topologyElement =
+ new TopologyElement(update.getSrc(),
+ update.getSrcPort(),
+ update.getDst(),
+ update.getDstPort());
+ datagridService.notificationSendTopologyElementUpdated(topologyElement);
+ }
break;
case LINK_ADDED:
log.debug("LinkDiscoveryUpdate(): Adding link {}", lt);
- linkStore.update(lt, DM_OPERATION.INSERT);
+
+ if (linkStore.addLink(lt)) {
+ // TODO publish ADD_LINK event here
+ TopologyElement topologyElement =
+ new TopologyElement(update.getSrc(),
+ update.getSrcPort(),
+ update.getDst(),
+ update.getDstPort());
+ datagridService.notificationSendTopologyElementAdded(topologyElement);
+ }
break;
-
default:
break;
}
@@ -156,36 +236,135 @@
@Override
public void addedSwitch(IOFSwitch sw) {
-
if (registryService.hasControl(sw.getId())) {
- swStore.addSwitch(sw);
- }
+ if (swStore.addSwitch(sw)) {
+ // TODO publish ADD_SWITCH event here
+ TopologyElement topologyElement =
+ new TopologyElement(sw.getId());
+ datagridService.notificationSendTopologyElementAdded(topologyElement);
+ // Publish: add the ports
+ // TODO: Add only ports that are UP?
+ for (OFPhysicalPort port : sw.getPorts()) {
+ TopologyElement topologyElementPort =
+ new TopologyElement(sw.getId(),
+ port.getPortNumber());
+ datagridService.notificationSendTopologyElementAdded(topologyElementPort);
+ }
+
+ // Add all links that might be connected already
+ List<Link> links = linkStore.getLinks(HexString.toHexString(sw.getId()));
+ // Add all reverse links as well
+ List<Link> reverseLinks = linkStore.getReverseLinks(HexString.toHexString(sw.getId()));
+ links.addAll(reverseLinks);
+
+ // Publish: add the links
+ for (Link link : links) {
+ TopologyElement topologyElementLink =
+ new TopologyElement(link.getSrc(),
+ link.getSrcPort(),
+ link.getDst(),
+ link.getDstPort());
+ datagridService.notificationSendTopologyElementAdded(topologyElementLink);
+ }
+ }
+ }
}
@Override
public void removedSwitch(IOFSwitch sw) {
- // TODO Auto-generated method stub
+ /*
+ if (registryService.hasControl(sw.getId())) {
+ // Get the affected ports
+ List<Short> ports = swStore.getPorts(HexString.toHexString(sw.getId()));
+ // Get the affected links
+ List<Link> links = linkStore.getLinks(HexString.toHexString(sw.getId()));
+ // Get the affected reverse links
+ List<Link> reverseLinks = linkStore.getReverseLinks(HexString.toHexString(sw.getId()));
+ links.addAll(reverseLinks);
+ if (swStore.deleteSwitch(sw.getStringId())) {
+ // TODO publish DELETE_SWITCH event here
+ TopologyElement topologyElement =
+ new TopologyElement(sw.getId());
+ datagridService.notificationSendTopologyElementRemoved(topologyElement);
+
+ // Publish: remove the affected ports
+ for (Short port : ports) {
+ TopologyElement topologyElementPort =
+ new TopologyElement(sw.getId(), port);
+ datagridService.notificationSendTopologyElementRemoved(topologyElementPort);
+ }
+ // Publish: remove the affected links
+ for (Link link : links) {
+ TopologyElement topologyElementLink =
+ new TopologyElement(link.getSrc(),
+ link.getSrcPort(),
+ link.getDst(),
+ link.getDstPort());
+ datagridService.notificationSendTopologyElementRemoved(topologyElementLink);
+ }
+ }
+ }
+ */
}
@Override
public void switchPortChanged(Long switchId) {
- // TODO Auto-generated method stub
-
+ // NOTE: Event not needed here. This callback always coincide with add/remove callback.
}
@Override
public void switchPortAdded(Long switchId, OFPhysicalPort port) {
- // TODO Auto-generated method stub
- swStore.addPort(HexString.toHexString(switchId), port);
+ if (swStore.addPort(HexString.toHexString(switchId), port)) {
+ // TODO publish ADD_PORT event here
+ TopologyElement topologyElement =
+ new TopologyElement(switchId, port.getPortNumber());
+ datagridService.notificationSendTopologyElementAdded(topologyElement);
+
+ // Add all links that might be connected already
+ List<Link> links = linkStore.getLinks(switchId, port.getPortNumber());
+ // Add all reverse links as well
+ List<Link> reverseLinks = linkStore.getReverseLinks(switchId, port.getPortNumber());
+ links.addAll(reverseLinks);
+
+ // Publish: add the links
+ for (Link link : links) {
+ TopologyElement topologyElementLink =
+ new TopologyElement(link.getSrc(),
+ link.getSrcPort(),
+ link.getDst(),
+ link.getDstPort());
+ datagridService.notificationSendTopologyElementAdded(topologyElementLink);
+ }
+ }
}
@Override
public void switchPortRemoved(Long switchId, OFPhysicalPort port) {
- // TODO Auto-generated method stub
- swStore.deletePort(HexString.toHexString(switchId), port.getPortNumber());
+ // Remove all links that might be connected already
+ List<Link> links = linkStore.getLinks(switchId, port.getPortNumber());
+ // Remove all reverse links as well
+ List<Link> reverseLinks = linkStore.getReverseLinks(switchId, port.getPortNumber());
+ links.addAll(reverseLinks);
+
+ if (swStore.deletePort(HexString.toHexString(switchId), port.getPortNumber())) {
+ // TODO publish DELETE_PORT event here
+ TopologyElement topologyElement =
+ new TopologyElement(switchId, port.getPortNumber());
+ datagridService.notificationSendTopologyElementRemoved(topologyElement);
+
+ // Publish: remove the links
+ for (Link link : links) {
+ TopologyElement topologyElementLink =
+ new TopologyElement(link.getSrc(),
+ link.getSrcPort(),
+ link.getDst(),
+ link.getDstPort());
+ datagridService.notificationSendTopologyElementRemoved(topologyElementLink);
+ }
+ }
}
@Override
@@ -195,29 +374,28 @@
@Override
public void deviceAdded(IDevice device) {
- // TODO Auto-generated method stub
log.debug("{}:deviceAdded(): Adding device {}",this.getClass(),device.getMACAddressString());
devStore.addDevice(device);
+ for (int intIpv4Address : device.getIPv4Addresses()) {
+ datagridService.sendArpRequest(
+ ArpMessage.newReply(InetAddresses.fromInteger(intIpv4Address)));
+ }
}
@Override
public void deviceRemoved(IDevice device) {
// TODO Auto-generated method stub
-
+ devStore.removeDevice(device);
}
@Override
public void deviceMoved(IDevice device) {
- // TODO Auto-generated method stub
devStore.changeDeviceAttachments(device);
-
}
@Override
public void deviceIPV4AddrChanged(IDevice device) {
- // TODO Auto-generated method stub
devStore.changeDeviceIPv4Address(device);
-
}
@Override
@@ -228,14 +406,20 @@
@Override
public Collection<Class<? extends IFloodlightService>> getModuleServices() {
- // TODO Auto-generated method stub
- return null;
+ Collection<Class<? extends IFloodlightService>> l =
+ new ArrayList<Class<? extends IFloodlightService>>();
+ l.add(INetworkGraphService.class);
+ return l;
}
@Override
public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
- // TODO Auto-generated method stub
- return null;
+ Map<Class<? extends IFloodlightService>,
+ IFloodlightService> m =
+ new HashMap<Class<? extends IFloodlightService>,
+ IFloodlightService>();
+ m.put(INetworkGraphService.class, this);
+ return m;
}
@Override
@@ -244,6 +428,7 @@
new ArrayList<Class<? extends IFloodlightService>>();
l.add(IFloodlightProviderService.class);
l.add(IDeviceService.class);
+ l.add(IDatagridService.class);
l.add(IThreadPoolService.class);
return l;
}
@@ -251,19 +436,18 @@
@Override
public void init(FloodlightModuleContext context)
throws FloodlightModuleException {
- // TODO Auto-generated method stub
Map<String, String> configMap = context.getConfigParams(this);
String conf = configMap.get(DBConfigFile);
String dbStore = configMap.get(GraphDBStore);
op = GraphDBManager.getDBOperation(dbStore, conf);
- log = LoggerFactory.getLogger(NetworkGraphPublisher.class);
floodlightProvider =
context.getServiceImpl(IFloodlightProviderService.class);
deviceService = context.getServiceImpl(IDeviceService.class);
linkDiscovery = context.getServiceImpl(ILinkDiscoveryService.class);
threadPool = context.getServiceImpl(IThreadPoolService.class);
registryService = context.getServiceImpl(IControllerRegistryService.class);
+ datagridService = context.getServiceImpl(IDatagridService.class);
devStore = new DeviceStorageImpl();
devStore.init(dbStore, conf);
@@ -280,7 +464,6 @@
@Override
public void startUp(FloodlightModuleContext context) {
- // TODO Auto-generated method stub
Map<String, String> configMap = context.getConfigParams(this);
String cleanupNeeded = configMap.get(CleanupEnabled);
@@ -297,6 +480,11 @@
cleanupTask = new SingletonTask(ses, new SwitchCleanup());
cleanupTask.reschedule(CLEANUP_TASK_INTERVAL, TimeUnit.SECONDS);
}
+
+ //
+ // NOTE: No need to register with the Datagrid Service,
+ // because we don't need to receive any notifications from it.
+ //
}
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowDatabaseOperation.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowDatabaseOperation.java
new file mode 100644
index 0000000..73c4e51
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowDatabaseOperation.java
@@ -0,0 +1,850 @@
+package net.onrc.onos.ofcontroller.flowmanager;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+import net.floodlightcontroller.util.MACAddress;
+
+import net.onrc.onos.graph.GraphDBOperation;
+
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowEntry;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowPath;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IPortObject;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.ISwitchObject;
+import net.onrc.onos.ofcontroller.util.*;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Class for performing Flow-related operations on the Database.
+ */
+class FlowDatabaseOperation {
+ private final static Logger log = LoggerFactory.getLogger(FlowDatabaseOperation.class);
+
+ /**
+ * Add a flow.
+ *
+ * @param flowManager the Flow Manager to use.
+ * @param dbHandler the Graph Database handler to use.
+ * @param flowPath the Flow Path to install.
+ * @param flowId the return-by-reference Flow ID as assigned internally.
+ * @return true on success, otherwise false.
+ */
+ static boolean addFlow(FlowManager flowManager,
+ GraphDBOperation dbHandler,
+ FlowPath flowPath, FlowId flowId) {
+ IFlowPath flowObj = null;
+ boolean found = false;
+ try {
+ if ((flowObj = dbHandler.searchFlowPath(flowPath.flowId())) != null) {
+ found = true;
+ } else {
+ flowObj = dbHandler.newFlowPath();
+ }
+ } catch (Exception e) {
+ dbHandler.rollback();
+
+ StringWriter sw = new StringWriter();
+ e.printStackTrace(new PrintWriter(sw));
+ String stacktrace = sw.toString();
+
+ log.error(":addFlow FlowId:{} failed: {}",
+ flowPath.flowId().toString(),
+ stacktrace);
+ return false;
+ }
+ if (flowObj == null) {
+ log.error(":addFlow FlowId:{} failed: Flow object not created",
+ flowPath.flowId().toString());
+ dbHandler.rollback();
+ return false;
+ }
+
+ //
+ // Set the Flow key:
+ // - flowId
+ //
+ flowObj.setFlowId(flowPath.flowId().toString());
+ flowObj.setType("flow");
+
+ //
+ // Set the Flow attributes:
+ // - flowPath.installerId()
+ // - flowPath.flowPathType()
+ // - flowPath.flowPathUserState()
+ // - flowPath.flowPathFlags()
+ // - flowPath.dataPath().srcPort()
+ // - flowPath.dataPath().dstPort()
+ // - flowPath.matchSrcMac()
+ // - flowPath.matchDstMac()
+ // - flowPath.matchEthernetFrameType()
+ // - flowPath.matchVlanId()
+ // - flowPath.matchVlanPriority()
+ // - flowPath.matchSrcIPv4Net()
+ // - flowPath.matchDstIPv4Net()
+ // - flowPath.matchIpProto()
+ // - flowPath.matchIpToS()
+ // - flowPath.matchSrcTcpUdpPort()
+ // - flowPath.matchDstTcpUdpPort()
+ // - flowPath.flowEntryActions()
+ //
+ flowObj.setInstallerId(flowPath.installerId().toString());
+ flowObj.setFlowPathType(flowPath.flowPathType().toString());
+ flowObj.setFlowPathUserState(flowPath.flowPathUserState().toString());
+ flowObj.setFlowPathFlags(flowPath.flowPathFlags().flags());
+ flowObj.setSrcSwitch(flowPath.dataPath().srcPort().dpid().toString());
+ flowObj.setSrcPort(flowPath.dataPath().srcPort().port().value());
+ flowObj.setDstSwitch(flowPath.dataPath().dstPort().dpid().toString());
+ flowObj.setDstPort(flowPath.dataPath().dstPort().port().value());
+ if (flowPath.flowEntryMatch().matchSrcMac()) {
+ flowObj.setMatchSrcMac(flowPath.flowEntryMatch().srcMac().toString());
+ }
+ if (flowPath.flowEntryMatch().matchDstMac()) {
+ flowObj.setMatchDstMac(flowPath.flowEntryMatch().dstMac().toString());
+ }
+ if (flowPath.flowEntryMatch().matchEthernetFrameType()) {
+ flowObj.setMatchEthernetFrameType(flowPath.flowEntryMatch().ethernetFrameType());
+ }
+ if (flowPath.flowEntryMatch().matchVlanId()) {
+ flowObj.setMatchVlanId(flowPath.flowEntryMatch().vlanId());
+ }
+ if (flowPath.flowEntryMatch().matchVlanPriority()) {
+ flowObj.setMatchVlanPriority(flowPath.flowEntryMatch().vlanPriority());
+ }
+ if (flowPath.flowEntryMatch().matchSrcIPv4Net()) {
+ flowObj.setMatchSrcIPv4Net(flowPath.flowEntryMatch().srcIPv4Net().toString());
+ }
+ if (flowPath.flowEntryMatch().matchDstIPv4Net()) {
+ flowObj.setMatchDstIPv4Net(flowPath.flowEntryMatch().dstIPv4Net().toString());
+ }
+ if (flowPath.flowEntryMatch().matchIpProto()) {
+ flowObj.setMatchIpProto(flowPath.flowEntryMatch().ipProto());
+ }
+ if (flowPath.flowEntryMatch().matchIpToS()) {
+ flowObj.setMatchIpToS(flowPath.flowEntryMatch().ipToS());
+ }
+ if (flowPath.flowEntryMatch().matchSrcTcpUdpPort()) {
+ flowObj.setMatchSrcTcpUdpPort(flowPath.flowEntryMatch().srcTcpUdpPort());
+ }
+ if (flowPath.flowEntryMatch().matchDstTcpUdpPort()) {
+ flowObj.setMatchDstTcpUdpPort(flowPath.flowEntryMatch().dstTcpUdpPort());
+ }
+ if (! flowPath.flowEntryActions().actions().isEmpty()) {
+ flowObj.setActions(flowPath.flowEntryActions().toString());
+ }
+ flowObj.setDataPathSummary(flowPath.dataPath().dataPathSummary());
+
+ if (found)
+ flowObj.setFlowPathUserState("FP_USER_MODIFY");
+ else
+ flowObj.setFlowPathUserState("FP_USER_ADD");
+
+ // Flow edges:
+ // HeadFE
+
+
+ //
+ // Flow Entries:
+ // flowPath.dataPath().flowEntries()
+ //
+ for (FlowEntry flowEntry : flowPath.dataPath().flowEntries()) {
+ if (addFlowEntry(flowManager, dbHandler, flowObj, flowEntry) == null) {
+ dbHandler.rollback();
+ return false;
+ }
+ }
+ dbHandler.commit();
+
+ //
+ // TODO: We need a proper Flow ID allocation mechanism.
+ //
+ flowId.setValue(flowPath.flowId().value());
+
+ return true;
+ }
+
+ /**
+ * Add a flow entry to the Network MAP.
+ *
+ * @param flowManager the Flow Manager to use.
+ * @param dbHandler the Graph Database handler to use.
+ * @param flowObj the corresponding Flow Path object for the Flow Entry.
+ * @param flowEntry the Flow Entry to install.
+ * @return the added Flow Entry object on success, otherwise null.
+ */
+ static IFlowEntry addFlowEntry(FlowManager flowManager,
+ GraphDBOperation dbHandler,
+ IFlowPath flowObj,
+ FlowEntry flowEntry) {
+ // Flow edges
+ // HeadFE (TODO)
+
+ //
+ // Assign the FlowEntry ID.
+ //
+ if ((flowEntry.flowEntryId() == null) ||
+ (flowEntry.flowEntryId().value() == 0)) {
+ long id = flowManager.getNextFlowEntryId();
+ flowEntry.setFlowEntryId(new FlowEntryId(id));
+ }
+
+ IFlowEntry flowEntryObj = null;
+ boolean found = false;
+ try {
+ if ((flowEntryObj =
+ dbHandler.searchFlowEntry(flowEntry.flowEntryId())) != null) {
+ found = true;
+ } else {
+ flowEntryObj = dbHandler.newFlowEntry();
+ }
+ } catch (Exception e) {
+ log.error(":addFlow FlowEntryId:{} failed",
+ flowEntry.flowEntryId().toString());
+ return null;
+ }
+ if (flowEntryObj == null) {
+ log.error(":addFlow FlowEntryId:{} failed: FlowEntry object not created",
+ flowEntry.flowEntryId().toString());
+ return null;
+ }
+
+ //
+ // Set the Flow Entry key:
+ // - flowEntry.flowEntryId()
+ //
+ flowEntryObj.setFlowEntryId(flowEntry.flowEntryId().toString());
+ flowEntryObj.setType("flow_entry");
+
+ //
+ // Set the Flow Entry Edges and attributes:
+ // - Switch edge
+ // - InPort edge
+ // - OutPort edge
+ //
+ // - flowEntry.dpid()
+ // - flowEntry.flowEntryUserState()
+ // - flowEntry.flowEntrySwitchState()
+ // - flowEntry.flowEntryErrorState()
+ // - flowEntry.matchInPort()
+ // - flowEntry.matchSrcMac()
+ // - flowEntry.matchDstMac()
+ // - flowEntry.matchEthernetFrameType()
+ // - flowEntry.matchVlanId()
+ // - flowEntry.matchVlanPriority()
+ // - flowEntry.matchSrcIPv4Net()
+ // - flowEntry.matchDstIPv4Net()
+ // - flowEntry.matchIpProto()
+ // - flowEntry.matchIpToS()
+ // - flowEntry.matchSrcTcpUdpPort()
+ // - flowEntry.matchDstTcpUdpPort()
+ // - flowEntry.actionOutputPort()
+ // - flowEntry.actions()
+ //
+ ISwitchObject sw = dbHandler.searchSwitch(flowEntry.dpid().toString());
+ flowEntryObj.setSwitchDpid(flowEntry.dpid().toString());
+ flowEntryObj.setSwitch(sw);
+ if (flowEntry.flowEntryMatch().matchInPort()) {
+ IPortObject inport =
+ dbHandler.searchPort(flowEntry.dpid().toString(),
+ flowEntry.flowEntryMatch().inPort().value());
+ flowEntryObj.setMatchInPort(flowEntry.flowEntryMatch().inPort().value());
+ flowEntryObj.setInPort(inport);
+ }
+ if (flowEntry.flowEntryMatch().matchSrcMac()) {
+ flowEntryObj.setMatchSrcMac(flowEntry.flowEntryMatch().srcMac().toString());
+ }
+ if (flowEntry.flowEntryMatch().matchDstMac()) {
+ flowEntryObj.setMatchDstMac(flowEntry.flowEntryMatch().dstMac().toString());
+ }
+ if (flowEntry.flowEntryMatch().matchEthernetFrameType()) {
+ flowEntryObj.setMatchEthernetFrameType(flowEntry.flowEntryMatch().ethernetFrameType());
+ }
+ if (flowEntry.flowEntryMatch().matchVlanId()) {
+ flowEntryObj.setMatchVlanId(flowEntry.flowEntryMatch().vlanId());
+ }
+ if (flowEntry.flowEntryMatch().matchVlanPriority()) {
+ flowEntryObj.setMatchVlanPriority(flowEntry.flowEntryMatch().vlanPriority());
+ }
+ if (flowEntry.flowEntryMatch().matchSrcIPv4Net()) {
+ flowEntryObj.setMatchSrcIPv4Net(flowEntry.flowEntryMatch().srcIPv4Net().toString());
+ }
+ if (flowEntry.flowEntryMatch().matchDstIPv4Net()) {
+ flowEntryObj.setMatchDstIPv4Net(flowEntry.flowEntryMatch().dstIPv4Net().toString());
+ }
+ if (flowEntry.flowEntryMatch().matchIpProto()) {
+ flowEntryObj.setMatchIpProto(flowEntry.flowEntryMatch().ipProto());
+ }
+ if (flowEntry.flowEntryMatch().matchIpToS()) {
+ flowEntryObj.setMatchIpToS(flowEntry.flowEntryMatch().ipToS());
+ }
+ if (flowEntry.flowEntryMatch().matchSrcTcpUdpPort()) {
+ flowEntryObj.setMatchSrcTcpUdpPort(flowEntry.flowEntryMatch().srcTcpUdpPort());
+ }
+ if (flowEntry.flowEntryMatch().matchDstTcpUdpPort()) {
+ flowEntryObj.setMatchDstTcpUdpPort(flowEntry.flowEntryMatch().dstTcpUdpPort());
+ }
+
+ for (FlowEntryAction fa : flowEntry.flowEntryActions().actions()) {
+ if (fa.actionOutput() != null) {
+ IPortObject outport =
+ dbHandler.searchPort(flowEntry.dpid().toString(),
+ fa.actionOutput().port().value());
+ flowEntryObj.setActionOutputPort(fa.actionOutput().port().value());
+ flowEntryObj.setOutPort(outport);
+ }
+ }
+ if (! flowEntry.flowEntryActions().isEmpty()) {
+ flowEntryObj.setActions(flowEntry.flowEntryActions().toString());
+ }
+
+ // TODO: Hacks with hard-coded state names!
+ if (found)
+ flowEntryObj.setUserState("FE_USER_MODIFY");
+ else
+ flowEntryObj.setUserState("FE_USER_ADD");
+ flowEntryObj.setSwitchState(flowEntry.flowEntrySwitchState().toString());
+ //
+ // TODO: Take care of the FlowEntryErrorState.
+ //
+
+ // Flow Entries edges:
+ // Flow
+ // NextFE (TODO)
+ if (! found) {
+ flowObj.addFlowEntry(flowEntryObj);
+ flowEntryObj.setFlow(flowObj);
+ }
+
+ return flowEntryObj;
+ }
+
+ /**
+ * Delete a flow entry from the Network MAP.
+ *
+ * @param dbHandler the Graph Database handler to use.
+ * @param flowObj the corresponding Flow Path object for the Flow Entry.
+ * @param flowEntry the Flow Entry to delete.
+ * @return true on success, otherwise false.
+ */
+ static boolean deleteFlowEntry(GraphDBOperation dbHandler,
+ IFlowPath flowObj,
+ FlowEntry flowEntry) {
+ IFlowEntry flowEntryObj = null;
+ try {
+ flowEntryObj = dbHandler.searchFlowEntry(flowEntry.flowEntryId());
+ } catch (Exception e) {
+ log.error(":deleteFlowEntry FlowEntryId:{} failed",
+ flowEntry.flowEntryId().toString());
+ return false;
+ }
+ //
+ // TODO: Don't print an error for now, because multiple controller
+ // instances might be deleting the same flow entry.
+ //
+ /*
+ if (flowEntryObj == null) {
+ log.error(":deleteFlowEntry FlowEntryId:{} failed: FlowEntry object not found",
+ flowEntry.flowEntryId().toString());
+ return false;
+ }
+ */
+ if (flowEntryObj == null)
+ return true;
+
+ flowObj.removeFlowEntry(flowEntryObj);
+ dbHandler.removeFlowEntry(flowEntryObj);
+ return true;
+ }
+
+ /**
+ * Delete all previously added flows.
+ *
+ * @param dbHandler the Graph Database handler to use.
+ * @return true on success, otherwise false.
+ */
+ static boolean deleteAllFlows(GraphDBOperation dbHandler) {
+ List<FlowId> allFlowIds = new LinkedList<FlowId>();
+
+ // Get all Flow IDs
+ Iterable<IFlowPath> allFlowPaths = dbHandler.getAllFlowPaths();
+ for (IFlowPath flowPathObj : allFlowPaths) {
+ if (flowPathObj == null)
+ continue;
+ String flowIdStr = flowPathObj.getFlowId();
+ if (flowIdStr == null)
+ continue;
+ FlowId flowId = new FlowId(flowIdStr);
+ allFlowIds.add(flowId);
+ }
+
+ // Delete all flows one-by-one
+ for (FlowId flowId : allFlowIds) {
+ deleteFlow(dbHandler, flowId);
+ }
+
+ return true;
+ }
+
+ /**
+ * Delete a previously added flow.
+ *
+ * @param dbHandler the Graph Database handler to use.
+ * @param flowId the Flow ID of the flow to delete.
+ * @return true on success, otherwise false.
+ */
+ static boolean deleteFlow(GraphDBOperation dbHandler, FlowId flowId) {
+ IFlowPath flowObj = null;
+ try {
+ flowObj = dbHandler.searchFlowPath(flowId);
+ } catch (Exception e) {
+ // TODO: handle exceptions
+ dbHandler.rollback();
+ log.error(":deleteFlow FlowId:{} failed", flowId.toString());
+ return false;
+ }
+ if (flowObj == null) {
+ dbHandler.commit();
+ return true; // OK: No such flow
+ }
+
+ //
+ // Remove all Flow Entries
+ //
+ Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries();
+ for (IFlowEntry flowEntryObj : flowEntries) {
+ flowObj.removeFlowEntry(flowEntryObj);
+ dbHandler.removeFlowEntry(flowEntryObj);
+ }
+ // Remove the Flow itself
+ dbHandler.removeFlowPath(flowObj);
+ dbHandler.commit();
+
+ return true;
+ }
+
+ /**
+ * Get a previously added flow.
+ *
+ * @param dbHandler the Graph Database handler to use.
+ * @param flowId the Flow ID of the flow to get.
+ * @return the Flow Path if found, otherwise null.
+ */
+ static FlowPath getFlow(GraphDBOperation dbHandler, FlowId flowId) {
+ IFlowPath flowObj = null;
+ try {
+ flowObj = dbHandler.searchFlowPath(flowId);
+ } catch (Exception e) {
+ // TODO: handle exceptions
+ dbHandler.rollback();
+ log.error(":getFlow FlowId:{} failed", flowId.toString());
+ return null;
+ }
+ if (flowObj == null) {
+ dbHandler.commit();
+ return null; // Flow not found
+ }
+
+ //
+ // Extract the Flow state
+ //
+ FlowPath flowPath = extractFlowPath(flowObj);
+ dbHandler.commit();
+
+ return flowPath;
+ }
+
+ /**
+ * Get all installed flows by all installers.
+ *
+ * @param dbHandler the Graph Database handler to use.
+ * @return the Flow Paths if found, otherwise null.
+ */
+ static ArrayList<FlowPath> getAllFlows(GraphDBOperation dbHandler) {
+ Iterable<IFlowPath> flowPathsObj = null;
+ ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>();
+
+ try {
+ flowPathsObj = dbHandler.getAllFlowPaths();
+ } catch (Exception e) {
+ // TODO: handle exceptions
+ dbHandler.rollback();
+ log.error(":getAllFlowPaths failed");
+ return flowPaths;
+ }
+ if ((flowPathsObj == null) || (flowPathsObj.iterator().hasNext() == false)) {
+ dbHandler.commit();
+ return flowPaths; // No Flows found
+ }
+
+ for (IFlowPath flowObj : flowPathsObj) {
+ //
+ // Extract the Flow state
+ //
+ FlowPath flowPath = extractFlowPath(flowObj);
+ if (flowPath != null)
+ flowPaths.add(flowPath);
+ }
+
+ dbHandler.commit();
+
+ return flowPaths;
+ }
+
+ /**
+ * Get all previously added flows by a specific installer for a given
+ * data path endpoints.
+ *
+ * @param dbHandler the Graph Database handler to use.
+ * @param installerId the Caller ID of the installer of the flow to get.
+ * @param dataPathEndpoints the data path endpoints of the flow to get.
+ * @return the Flow Paths if found, otherwise null.
+ */
+ static ArrayList<FlowPath> getAllFlows(GraphDBOperation dbHandler,
+ CallerId installerId,
+ DataPathEndpoints dataPathEndpoints) {
+ //
+ // TODO: The implementation below is not optimal:
+ // We fetch all flows, and then return only the subset that match
+ // the query conditions.
+ // We should use the appropriate Titan/Gremlin query to filter-out
+ // the flows as appropriate.
+ //
+ ArrayList<FlowPath> allFlows = getAllFlows(dbHandler);
+ ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>();
+
+ if (allFlows == null)
+ return flowPaths;
+
+ for (FlowPath flow : allFlows) {
+ //
+ // TODO: String-based comparison is sub-optimal.
+ // We are using it for now to save us the extra work of
+ // implementing the "equals()" and "hashCode()" methods.
+ //
+ if (! flow.installerId().toString().equals(installerId.toString()))
+ continue;
+ if (! flow.dataPath().srcPort().toString().equals(dataPathEndpoints.srcPort().toString())) {
+ continue;
+ }
+ if (! flow.dataPath().dstPort().toString().equals(dataPathEndpoints.dstPort().toString())) {
+ continue;
+ }
+ flowPaths.add(flow);
+ }
+
+ return flowPaths;
+ }
+
+ /**
+ * Get all installed flows by all installers for given data path endpoints.
+ *
+ * @param dbHandler the Graph Database handler to use.
+ * @param dataPathEndpoints the data path endpoints of the flows to get.
+ * @return the Flow Paths if found, otherwise null.
+ */
+ static ArrayList<FlowPath> getAllFlows(GraphDBOperation dbHandler,
+ DataPathEndpoints dataPathEndpoints) {
+ //
+ // TODO: The implementation below is not optimal:
+ // We fetch all flows, and then return only the subset that match
+ // the query conditions.
+ // We should use the appropriate Titan/Gremlin query to filter-out
+ // the flows as appropriate.
+ //
+ ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>();
+ ArrayList<FlowPath> allFlows = getAllFlows(dbHandler);
+
+ if (allFlows == null)
+ return flowPaths;
+
+ for (FlowPath flow : allFlows) {
+ //
+ // TODO: String-based comparison is sub-optimal.
+ // We are using it for now to save us the extra work of
+ // implementing the "equals()" and "hashCode()" methods.
+ //
+ if (! flow.dataPath().srcPort().toString().equals(dataPathEndpoints.srcPort().toString())) {
+ continue;
+ }
+ if (! flow.dataPath().dstPort().toString().equals(dataPathEndpoints.dstPort().toString())) {
+ continue;
+ }
+ flowPaths.add(flow);
+ }
+
+ return flowPaths;
+ }
+
+ /**
+ * Get summary of all installed flows by all installers in a given range.
+ *
+ * @param dbHandler the Graph Database handler to use.
+ * @param flowId the Flow ID of the first flow in the flow range to get.
+ * @param maxFlows the maximum number of flows to be returned.
+ * @return the Flow Paths if found, otherwise null.
+ */
+ static ArrayList<IFlowPath> getAllFlowsSummary(GraphDBOperation dbHandler,
+ FlowId flowId,
+ int maxFlows) {
+ //
+ // TODO: The implementation below is not optimal:
+ // We fetch all flows, and then return only the subset that match
+ // the query conditions.
+ // We should use the appropriate Titan/Gremlin query to filter-out
+ // the flows as appropriate.
+ //
+ ArrayList<IFlowPath> flowPathsWithoutFlowEntries =
+ getAllFlowsWithoutFlowEntries(dbHandler);
+
+ Collections.sort(flowPathsWithoutFlowEntries,
+ new Comparator<IFlowPath>() {
+ @Override
+ public int compare(IFlowPath first, IFlowPath second) {
+ long result =
+ new FlowId(first.getFlowId()).value()
+ - new FlowId(second.getFlowId()).value();
+ if (result > 0) {
+ return 1;
+ } else if (result < 0) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ }
+ );
+
+ return flowPathsWithoutFlowEntries;
+ }
+
+ /**
+ * Get all Flows information, without the associated Flow Entries.
+ *
+ * @param dbHandler the Graph Database handler to use.
+ * @return all Flows information, without the associated Flow Entries.
+ */
+ static ArrayList<IFlowPath> getAllFlowsWithoutFlowEntries(GraphDBOperation dbHandler) {
+ Iterable<IFlowPath> flowPathsObj = null;
+ ArrayList<IFlowPath> flowPathsObjArray = new ArrayList<IFlowPath>();
+
+ // TODO: Remove this op.commit() flow, because it is not needed?
+ dbHandler.commit();
+
+ try {
+ flowPathsObj = dbHandler.getAllFlowPaths();
+ } catch (Exception e) {
+ // TODO: handle exceptions
+ dbHandler.rollback();
+ log.error(":getAllFlowPaths failed");
+ return flowPathsObjArray; // No Flows found
+ }
+ if ((flowPathsObj == null) || (flowPathsObj.iterator().hasNext() == false)) {
+ return flowPathsObjArray; // No Flows found
+ }
+
+ for (IFlowPath flowObj : flowPathsObj)
+ flowPathsObjArray.add(flowObj);
+
+ // conn.endTx(Transaction.COMMIT);
+
+ return flowPathsObjArray;
+ }
+
+ /**
+ * Extract Flow Path State from a Titan Database Object @ref IFlowPath.
+ *
+ * @param flowObj the object to extract the Flow Path State from.
+ * @return the extracted Flow Path State.
+ */
+ private static FlowPath extractFlowPath(IFlowPath flowObj) {
+ //
+ // Extract the Flow state
+ //
+ String flowIdStr = flowObj.getFlowId();
+ String installerIdStr = flowObj.getInstallerId();
+ String flowPathType = flowObj.getFlowPathType();
+ String flowPathUserState = flowObj.getFlowPathUserState();
+ Long flowPathFlags = flowObj.getFlowPathFlags();
+ String srcSwitchStr = flowObj.getSrcSwitch();
+ Short srcPortShort = flowObj.getSrcPort();
+ String dstSwitchStr = flowObj.getDstSwitch();
+ Short dstPortShort = flowObj.getDstPort();
+
+ if ((flowIdStr == null) ||
+ (installerIdStr == null) ||
+ (flowPathType == null) ||
+ (flowPathUserState == null) ||
+ (flowPathFlags == null) ||
+ (srcSwitchStr == null) ||
+ (srcPortShort == null) ||
+ (dstSwitchStr == null) ||
+ (dstPortShort == null)) {
+ // TODO: A work-around, becauuse of some bogus database objects
+ return null;
+ }
+
+ FlowPath flowPath = new FlowPath();
+ flowPath.setFlowId(new FlowId(flowIdStr));
+ flowPath.setInstallerId(new CallerId(installerIdStr));
+ flowPath.setFlowPathType(FlowPathType.valueOf(flowPathType));
+ flowPath.setFlowPathUserState(FlowPathUserState.valueOf(flowPathUserState));
+ flowPath.setFlowPathFlags(new FlowPathFlags(flowPathFlags));
+ flowPath.dataPath().srcPort().setDpid(new Dpid(srcSwitchStr));
+ flowPath.dataPath().srcPort().setPort(new Port(srcPortShort));
+ flowPath.dataPath().dstPort().setDpid(new Dpid(dstSwitchStr));
+ flowPath.dataPath().dstPort().setPort(new Port(dstPortShort));
+ //
+ // Extract the match conditions common for all Flow Entries
+ //
+ {
+ FlowEntryMatch match = new FlowEntryMatch();
+ String matchSrcMac = flowObj.getMatchSrcMac();
+ if (matchSrcMac != null)
+ match.enableSrcMac(MACAddress.valueOf(matchSrcMac));
+ String matchDstMac = flowObj.getMatchDstMac();
+ if (matchDstMac != null)
+ match.enableDstMac(MACAddress.valueOf(matchDstMac));
+ Short matchEthernetFrameType = flowObj.getMatchEthernetFrameType();
+ if (matchEthernetFrameType != null)
+ match.enableEthernetFrameType(matchEthernetFrameType);
+ Short matchVlanId = flowObj.getMatchVlanId();
+ if (matchVlanId != null)
+ match.enableVlanId(matchVlanId);
+ Byte matchVlanPriority = flowObj.getMatchVlanPriority();
+ if (matchVlanPriority != null)
+ match.enableVlanPriority(matchVlanPriority);
+ String matchSrcIPv4Net = flowObj.getMatchSrcIPv4Net();
+ if (matchSrcIPv4Net != null)
+ match.enableSrcIPv4Net(new IPv4Net(matchSrcIPv4Net));
+ String matchDstIPv4Net = flowObj.getMatchDstIPv4Net();
+ if (matchDstIPv4Net != null)
+ match.enableDstIPv4Net(new IPv4Net(matchDstIPv4Net));
+ Byte matchIpProto = flowObj.getMatchIpProto();
+ if (matchIpProto != null)
+ match.enableIpProto(matchIpProto);
+ Byte matchIpToS = flowObj.getMatchIpToS();
+ if (matchIpToS != null)
+ match.enableIpToS(matchIpToS);
+ Short matchSrcTcpUdpPort = flowObj.getMatchSrcTcpUdpPort();
+ if (matchSrcTcpUdpPort != null)
+ match.enableSrcTcpUdpPort(matchSrcTcpUdpPort);
+ Short matchDstTcpUdpPort = flowObj.getMatchDstTcpUdpPort();
+ if (matchDstTcpUdpPort != null)
+ match.enableDstTcpUdpPort(matchDstTcpUdpPort);
+
+ flowPath.setFlowEntryMatch(match);
+ }
+ //
+ // Extract the actions for the first Flow Entry
+ //
+ {
+ String actionsStr = flowObj.getActions();
+ if (actionsStr != null) {
+ FlowEntryActions flowEntryActions = new FlowEntryActions(actionsStr);
+ flowPath.setFlowEntryActions(flowEntryActions);
+ }
+ }
+
+ //
+ // Extract all Flow Entries
+ //
+ Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries();
+ for (IFlowEntry flowEntryObj : flowEntries) {
+ FlowEntry flowEntry = extractFlowEntry(flowEntryObj);
+ if (flowEntry == null)
+ continue;
+ flowPath.dataPath().flowEntries().add(flowEntry);
+ }
+
+ return flowPath;
+ }
+
+ /**
+ * Extract Flow Entry State from a Titan Database Object @ref IFlowEntry.
+ *
+ * @param flowEntryObj the object to extract the Flow Entry State from.
+ * @return the extracted Flow Entry State.
+ */
+ public static FlowEntry extractFlowEntry(IFlowEntry flowEntryObj) {
+ String flowEntryIdStr = flowEntryObj.getFlowEntryId();
+ String switchDpidStr = flowEntryObj.getSwitchDpid();
+ String userState = flowEntryObj.getUserState();
+ String switchState = flowEntryObj.getSwitchState();
+
+ if ((flowEntryIdStr == null) ||
+ (switchDpidStr == null) ||
+ (userState == null) ||
+ (switchState == null)) {
+ // TODO: A work-around, because of some bogus database objects
+ return null;
+ }
+
+ FlowEntry flowEntry = new FlowEntry();
+ flowEntry.setFlowEntryId(new FlowEntryId(flowEntryIdStr));
+ flowEntry.setDpid(new Dpid(switchDpidStr));
+
+ //
+ // Extract the match conditions
+ //
+ FlowEntryMatch match = new FlowEntryMatch();
+ Short matchInPort = flowEntryObj.getMatchInPort();
+ if (matchInPort != null)
+ match.enableInPort(new Port(matchInPort));
+ String matchSrcMac = flowEntryObj.getMatchSrcMac();
+ if (matchSrcMac != null)
+ match.enableSrcMac(MACAddress.valueOf(matchSrcMac));
+ String matchDstMac = flowEntryObj.getMatchDstMac();
+ if (matchDstMac != null)
+ match.enableDstMac(MACAddress.valueOf(matchDstMac));
+ Short matchEthernetFrameType = flowEntryObj.getMatchEthernetFrameType();
+ if (matchEthernetFrameType != null)
+ match.enableEthernetFrameType(matchEthernetFrameType);
+ Short matchVlanId = flowEntryObj.getMatchVlanId();
+ if (matchVlanId != null)
+ match.enableVlanId(matchVlanId);
+ Byte matchVlanPriority = flowEntryObj.getMatchVlanPriority();
+ if (matchVlanPriority != null)
+ match.enableVlanPriority(matchVlanPriority);
+ String matchSrcIPv4Net = flowEntryObj.getMatchSrcIPv4Net();
+ if (matchSrcIPv4Net != null)
+ match.enableSrcIPv4Net(new IPv4Net(matchSrcIPv4Net));
+ String matchDstIPv4Net = flowEntryObj.getMatchDstIPv4Net();
+ if (matchDstIPv4Net != null)
+ match.enableDstIPv4Net(new IPv4Net(matchDstIPv4Net));
+ Byte matchIpProto = flowEntryObj.getMatchIpProto();
+ if (matchIpProto != null)
+ match.enableIpProto(matchIpProto);
+ Byte matchIpToS = flowEntryObj.getMatchIpToS();
+ if (matchIpToS != null)
+ match.enableIpToS(matchIpToS);
+ Short matchSrcTcpUdpPort = flowEntryObj.getMatchSrcTcpUdpPort();
+ if (matchSrcTcpUdpPort != null)
+ match.enableSrcTcpUdpPort(matchSrcTcpUdpPort);
+ Short matchDstTcpUdpPort = flowEntryObj.getMatchDstTcpUdpPort();
+ if (matchDstTcpUdpPort != null)
+ match.enableDstTcpUdpPort(matchDstTcpUdpPort);
+ flowEntry.setFlowEntryMatch(match);
+
+ //
+ // Extract the actions
+ //
+ FlowEntryActions actions = new FlowEntryActions();
+ String actionsStr = flowEntryObj.getActions();
+ if (actionsStr != null)
+ actions = new FlowEntryActions(actionsStr);
+ flowEntry.setFlowEntryActions(actions);
+ flowEntry.setFlowEntryUserState(FlowEntryUserState.valueOf(userState));
+ flowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.valueOf(switchState));
+ //
+ // TODO: Take care of FlowEntryErrorState.
+ //
+ return flowEntry;
+ }
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowEventHandler.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowEventHandler.java
new file mode 100644
index 0000000..0e9887a
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowEventHandler.java
@@ -0,0 +1,867 @@
+package net.onrc.onos.ofcontroller.flowmanager;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+
+import net.floodlightcontroller.core.IOFSwitch;
+import net.onrc.onos.datagrid.IDatagridService;
+import net.onrc.onos.ofcontroller.topology.Topology;
+import net.onrc.onos.ofcontroller.topology.TopologyElement;
+import net.onrc.onos.ofcontroller.topology.TopologyManager;
+import net.onrc.onos.ofcontroller.util.DataPath;
+import net.onrc.onos.ofcontroller.util.EventEntry;
+import net.onrc.onos.ofcontroller.util.FlowEntry;
+import net.onrc.onos.ofcontroller.util.FlowEntryAction;
+import net.onrc.onos.ofcontroller.util.FlowEntryActions;
+import net.onrc.onos.ofcontroller.util.FlowEntryId;
+import net.onrc.onos.ofcontroller.util.FlowEntryMatch;
+import net.onrc.onos.ofcontroller.util.FlowEntrySwitchState;
+import net.onrc.onos.ofcontroller.util.FlowEntryUserState;
+import net.onrc.onos.ofcontroller.util.FlowId;
+import net.onrc.onos.ofcontroller.util.FlowPath;
+import net.onrc.onos.ofcontroller.util.FlowPathUserState;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A class for storing a pair of Flow Path and a Flow Entry.
+ */
+class FlowPathEntryPair {
+ protected FlowPath flowPath;
+ protected FlowEntry flowEntry;
+
+ protected FlowPathEntryPair(FlowPath flowPath, FlowEntry flowEntry) {
+ this.flowPath = flowPath;
+ this.flowEntry = flowEntry;
+ }
+}
+
+/**
+ * Class for FlowPath Maintenance.
+ * This class listens for FlowEvents to:
+ * - Maintain a local cache of the Network Topology.
+ * - Detect FlowPaths impacted by Topology change.
+ * - Recompute impacted FlowPath using cached Topology.
+ */
+class FlowEventHandler extends Thread implements IFlowEventHandlerService {
+ /** The logger. */
+ private final static Logger log = LoggerFactory.getLogger(FlowEventHandler.class);
+
+ private FlowManager flowManager; // The Flow Manager to use
+ private IDatagridService datagridService; // The Datagrid Service to use
+ private Topology topology; // The network topology
+ private Map<Long, FlowPath> allFlowPaths = new HashMap<Long, FlowPath>();
+ private Map<Long, FlowEntry> unmatchedFlowEntryAdd =
+ new HashMap<Long, FlowEntry>();
+
+ // The queue with Flow Path and Topology Element updates
+ private BlockingQueue<EventEntry<?>> networkEvents =
+ new LinkedBlockingQueue<EventEntry<?>>();
+
+ // The pending Topology, FlowPath, and FlowEntry events
+ private List<EventEntry<TopologyElement>> topologyEvents =
+ new LinkedList<EventEntry<TopologyElement>>();
+ private List<EventEntry<FlowPath>> flowPathEvents =
+ new LinkedList<EventEntry<FlowPath>>();
+ private List<EventEntry<FlowEntry>> flowEntryEvents =
+ new LinkedList<EventEntry<FlowEntry>>();
+
+ //
+ // Transient state for processing the Flow Paths:
+ // - The new Flow Paths
+ // - The Flow Paths that should be recomputed
+ // - The Flow Paths with modified Flow Entries
+ // - The Flow Entries that were updated
+ //
+ private List<FlowPath> newFlowPaths = new LinkedList<FlowPath>();
+ private List<FlowPath> recomputeFlowPaths = new LinkedList<FlowPath>();
+ private List<FlowPath> modifiedFlowPaths = new LinkedList<FlowPath>();
+ private List<FlowPathEntryPair> updatedFlowEntries =
+ new LinkedList<FlowPathEntryPair>();
+ private List<FlowPathEntryPair> unmatchedDeleteFlowEntries =
+ new LinkedList<FlowPathEntryPair>();
+
+
+ /**
+ * Constructor for a given Flow Manager and Datagrid Service.
+ *
+ * @param flowManager the Flow Manager to use.
+ * @param datagridService the Datagrid Service to use.
+ */
+ FlowEventHandler(FlowManager flowManager,
+ IDatagridService datagridService) {
+ this.flowManager = flowManager;
+ this.datagridService = datagridService;
+ this.topology = new Topology();
+ }
+
+ /**
+ * Get the network topology.
+ *
+ * @return the network topology.
+ */
+ protected Topology getTopology() { return this.topology; }
+
+ /**
+ * Startup processing.
+ */
+ private void startup() {
+ //
+ // Obtain the initial Topology state
+ //
+ Collection<TopologyElement> topologyElements =
+ datagridService.getAllTopologyElements();
+ for (TopologyElement topologyElement : topologyElements) {
+ EventEntry<TopologyElement> eventEntry =
+ new EventEntry<TopologyElement>(EventEntry.Type.ENTRY_ADD, topologyElement);
+ topologyEvents.add(eventEntry);
+ }
+ //
+ // Obtain the initial Flow Path state
+ //
+ Collection<FlowPath> flowPaths = datagridService.getAllFlows();
+ for (FlowPath flowPath : flowPaths) {
+ EventEntry<FlowPath> eventEntry =
+ new EventEntry<FlowPath>(EventEntry.Type.ENTRY_ADD, flowPath);
+ flowPathEvents.add(eventEntry);
+ }
+ //
+ // Obtain the initial FlowEntry state
+ //
+ Collection<FlowEntry> flowEntries = datagridService.getAllFlowEntries();
+ for (FlowEntry flowEntry : flowEntries) {
+ EventEntry<FlowEntry> eventEntry =
+ new EventEntry<FlowEntry>(EventEntry.Type.ENTRY_ADD, flowEntry);
+ flowEntryEvents.add(eventEntry);
+ }
+
+ // Process the initial events (if any)
+ processEvents();
+ }
+
+ /**
+ * Run the thread.
+ */
+ @Override
+ public void run() {
+ startup();
+
+ //
+ // The main loop
+ //
+ Collection<EventEntry<?>> collection = new LinkedList<EventEntry<?>>();
+ try {
+ while (true) {
+ EventEntry<?> eventEntry = networkEvents.take();
+ collection.add(eventEntry);
+ networkEvents.drainTo(collection);
+
+ //
+ // Demultiplex all events:
+ // - EventEntry<TopologyElement>
+ // - EventEntry<FlowPath>
+ // - EventEntry<FlowEntry>
+ //
+ for (EventEntry<?> event : collection) {
+ if (event.eventData() instanceof TopologyElement) {
+ EventEntry<TopologyElement> topologyEventEntry =
+ (EventEntry<TopologyElement>)event;
+ topologyEvents.add(topologyEventEntry);
+ } else if (event.eventData() instanceof FlowPath) {
+ EventEntry<FlowPath> flowPathEventEntry =
+ (EventEntry<FlowPath>)event;
+ flowPathEvents.add(flowPathEventEntry);
+ } else if (event.eventData() instanceof FlowEntry) {
+ EventEntry<FlowEntry> flowEntryEventEntry =
+ (EventEntry<FlowEntry>)event;
+ flowEntryEvents.add(flowEntryEventEntry);
+ }
+ }
+ collection.clear();
+
+ // Process the events (if any)
+ processEvents();
+ }
+ } catch (Exception exception) {
+ log.debug("Exception processing Network Events: ", exception);
+ }
+ }
+
+ /**
+ * Process the events (if any)
+ */
+ private void processEvents() {
+ List<FlowPathEntryPair> modifiedFlowEntries;
+
+ if (topologyEvents.isEmpty() && flowPathEvents.isEmpty() &&
+ flowEntryEvents.isEmpty()) {
+ return; // Nothing to do
+ }
+
+ processFlowPathEvents();
+ processTopologyEvents();
+ //
+ // Add all new Flows: should be done after processing the Flow Path
+ // and Topology events.
+ //
+ for (FlowPath flowPath : newFlowPaths) {
+ allFlowPaths.put(flowPath.flowId().value(), flowPath);
+ }
+
+ processFlowEntryEvents();
+
+ // Recompute all affected Flow Paths and keep only the modified
+ for (FlowPath flowPath : recomputeFlowPaths) {
+ if (recomputeFlowPath(flowPath))
+ modifiedFlowPaths.add(flowPath);
+ }
+
+ modifiedFlowEntries = extractModifiedFlowEntries(modifiedFlowPaths);
+
+ // Assign missing Flow Entry IDs
+ assignFlowEntryId(modifiedFlowEntries);
+
+ //
+ // Push the modified Flow Entries to switches, datagrid and database
+ //
+ flowManager.pushModifiedFlowEntriesToSwitches(modifiedFlowEntries);
+ flowManager.pushModifiedFlowEntriesToDatagrid(modifiedFlowEntries);
+ flowManager.pushModifiedFlowEntriesToDatabase(modifiedFlowEntries);
+ flowManager.pushModifiedFlowEntriesToDatabase(updatedFlowEntries);
+ flowManager.pushModifiedFlowEntriesToDatabase(unmatchedDeleteFlowEntries);
+
+ //
+ // Remove Flow Entries that were deleted
+ //
+ for (FlowPath flowPath : modifiedFlowPaths)
+ flowPath.dataPath().removeDeletedFlowEntries();
+
+ // Cleanup
+ topologyEvents.clear();
+ flowPathEvents.clear();
+ flowEntryEvents.clear();
+ //
+ newFlowPaths.clear();
+ recomputeFlowPaths.clear();
+ modifiedFlowPaths.clear();
+ updatedFlowEntries.clear();
+ unmatchedDeleteFlowEntries.clear();
+ }
+
+ /**
+ * Extract the modified Flow Entries.
+ */
+ private List<FlowPathEntryPair> extractModifiedFlowEntries(
+ List<FlowPath> modifiedFlowPaths) {
+ List<FlowPathEntryPair> modifiedFlowEntries =
+ new LinkedList<FlowPathEntryPair>();
+
+ // Extract only the modified Flow Entries
+ for (FlowPath flowPath : modifiedFlowPaths) {
+ for (FlowEntry flowEntry : flowPath.flowEntries()) {
+ if (flowEntry.flowEntrySwitchState() ==
+ FlowEntrySwitchState.FE_SWITCH_NOT_UPDATED) {
+ FlowPathEntryPair flowPair =
+ new FlowPathEntryPair(flowPath, flowEntry);
+ modifiedFlowEntries.add(flowPair);
+ }
+ }
+ }
+ return modifiedFlowEntries;
+ }
+
+ /**
+ * Assign the Flow Entry ID as needed.
+ */
+ private void assignFlowEntryId(List<FlowPathEntryPair> modifiedFlowEntries) {
+ if (modifiedFlowEntries.isEmpty())
+ return;
+
+ Map<Long, IOFSwitch> mySwitches = flowManager.getMySwitches();
+
+ //
+ // Assign the Flow Entry ID only for Flow Entries for my switches
+ //
+ for (FlowPathEntryPair flowPair : modifiedFlowEntries) {
+ FlowEntry flowEntry = flowPair.flowEntry;
+ // Update the Flow Entries only for my switches
+ IOFSwitch mySwitch = mySwitches.get(flowEntry.dpid().value());
+ if (mySwitch == null)
+ continue;
+ if (! flowEntry.isValidFlowEntryId()) {
+ long id = flowManager.getNextFlowEntryId();
+ flowEntry.setFlowEntryId(new FlowEntryId(id));
+ }
+ }
+ }
+
+ /**
+ * Process the Flow Path events.
+ */
+ private void processFlowPathEvents() {
+ //
+ // Process all Flow Path events and update the appropriate state
+ //
+ for (EventEntry<FlowPath> eventEntry : flowPathEvents) {
+ FlowPath flowPath = eventEntry.eventData();
+
+ log.debug("Flow Event: {} {}", eventEntry.eventType(),
+ flowPath.toString());
+
+ switch (eventEntry.eventType()) {
+ case ENTRY_ADD: {
+ //
+ // Add a new Flow Path
+ //
+ if (allFlowPaths.get(flowPath.flowId().value()) != null) {
+ //
+ // TODO: What to do if the Flow Path already exists?
+ // Remove and then re-add it, or merge the info?
+ // For now, we don't have to do anything.
+ //
+ break;
+ }
+
+ switch (flowPath.flowPathType()) {
+ case FP_TYPE_SHORTEST_PATH:
+ //
+ // Reset the Data Path, in case it was set already, because
+ // we are going to recompute it anyway.
+ //
+ flowPath.flowEntries().clear();
+ recomputeFlowPaths.add(flowPath);
+ break;
+ case FP_TYPE_EXPLICIT_PATH:
+ //
+ // Mark all Flow Entries for installation in the switches.
+ //
+ for (FlowEntry flowEntry : flowPath.flowEntries()) {
+ flowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.FE_SWITCH_NOT_UPDATED);
+ }
+ modifiedFlowPaths.add(flowPath);
+ break;
+ }
+ newFlowPaths.add(flowPath);
+
+ break;
+ }
+
+ case ENTRY_REMOVE: {
+ //
+ // Remove an existing Flow Path.
+ //
+ // Find the Flow Path, and mark the Flow and its Flow Entries
+ // for deletion.
+ //
+ FlowPath existingFlowPath =
+ allFlowPaths.get(flowPath.flowId().value());
+ if (existingFlowPath == null)
+ continue; // Nothing to do
+
+ existingFlowPath.setFlowPathUserState(FlowPathUserState.FP_USER_DELETE);
+ for (FlowEntry flowEntry : existingFlowPath.flowEntries()) {
+ flowEntry.setFlowEntryUserState(FlowEntryUserState.FE_USER_DELETE);
+ flowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.FE_SWITCH_NOT_UPDATED);
+ }
+
+ allFlowPaths.remove(existingFlowPath.flowId().value());
+ modifiedFlowPaths.add(existingFlowPath);
+
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Process the Topology events.
+ */
+ private void processTopologyEvents() {
+ //
+ // Process all Topology events and update the appropriate state
+ //
+ boolean isTopologyModified = false;
+ for (EventEntry<TopologyElement> eventEntry : topologyEvents) {
+ TopologyElement topologyElement = eventEntry.eventData();
+
+ log.debug("Topology Event: {} {}", eventEntry.eventType(),
+ topologyElement.toString());
+
+ switch (eventEntry.eventType()) {
+ case ENTRY_ADD:
+ isTopologyModified |= topology.addTopologyElement(topologyElement);
+ break;
+ case ENTRY_REMOVE:
+ isTopologyModified |= topology.removeTopologyElement(topologyElement);
+ break;
+ }
+ }
+ if (isTopologyModified) {
+ // TODO: For now, if the topology changes, we recompute all Flows
+ recomputeFlowPaths.addAll(allFlowPaths.values());
+ }
+ }
+
+ /**
+ * Process the Flow Entry events.
+ */
+ private void processFlowEntryEvents() {
+ FlowPathEntryPair flowPair;
+ FlowPath flowPath;
+ FlowEntry updatedFlowEntry;
+
+ //
+ // Update Flow Entries with previously unmatched Flow Entry updates
+ //
+ if (! unmatchedFlowEntryAdd.isEmpty()) {
+ Map<Long, FlowEntry> remainingUpdates = new HashMap<Long, FlowEntry>();
+ for (FlowEntry flowEntry : unmatchedFlowEntryAdd.values()) {
+ flowPath = allFlowPaths.get(flowEntry.flowId().value());
+ if (flowPath == null)
+ continue;
+ updatedFlowEntry = updateFlowEntryAdd(flowPath, flowEntry);
+ if (updatedFlowEntry == null) {
+ remainingUpdates.put(flowEntry.flowEntryId().value(),
+ flowEntry);
+ continue;
+ }
+ flowPair = new FlowPathEntryPair(flowPath, updatedFlowEntry);
+ updatedFlowEntries.add(flowPair);
+ }
+ unmatchedFlowEntryAdd = remainingUpdates;
+ }
+
+ //
+ // Process all Flow Entry events and update the appropriate state
+ //
+ for (EventEntry<FlowEntry> eventEntry : flowEntryEvents) {
+ FlowEntry flowEntry = eventEntry.eventData();
+
+ log.debug("Flow Entry Event: {} {}", eventEntry.eventType(),
+ flowEntry.toString());
+
+ if ((! flowEntry.isValidFlowId()) ||
+ (! flowEntry.isValidFlowEntryId())) {
+ continue;
+ }
+
+ switch (eventEntry.eventType()) {
+ case ENTRY_ADD:
+ flowPath = allFlowPaths.get(flowEntry.flowId().value());
+ if (flowPath == null) {
+ // Flow Path not found: keep the entry for later matching
+ unmatchedFlowEntryAdd.put(flowEntry.flowEntryId().value(),
+ flowEntry);
+ break;
+ }
+ updatedFlowEntry = updateFlowEntryAdd(flowPath, flowEntry);
+ if (updatedFlowEntry == null) {
+ // Flow Entry not found: keep the entry for later matching
+ unmatchedFlowEntryAdd.put(flowEntry.flowEntryId().value(),
+ flowEntry);
+ break;
+ }
+ // Add the updated entry to the list of updated Flow Entries
+ flowPair = new FlowPathEntryPair(flowPath, updatedFlowEntry);
+ updatedFlowEntries.add(flowPair);
+ break;
+
+ case ENTRY_REMOVE:
+ flowEntry.setFlowEntryUserState(FlowEntryUserState.FE_USER_DELETE);
+ if (unmatchedFlowEntryAdd.remove(flowEntry.flowEntryId().value()) != null) {
+ continue; // Match found
+ }
+
+ flowPath = allFlowPaths.get(flowEntry.flowId().value());
+ if (flowPath == null) {
+ // Flow Path not found: ignore the update
+ break;
+ }
+ updatedFlowEntry = updateFlowEntryRemove(flowPath, flowEntry);
+ if (updatedFlowEntry == null) {
+ // Flow Entry not found: add to list of deleted entries
+ flowPair = new FlowPathEntryPair(flowPath, flowEntry);
+ unmatchedDeleteFlowEntries.add(flowPair);
+ break;
+ }
+ flowPair = new FlowPathEntryPair(flowPath, updatedFlowEntry);
+ updatedFlowEntries.add(flowPair);
+ break;
+ }
+ }
+ }
+
+ /**
+ * Update a Flow Entry because of an external ENTRY_ADD event.
+ *
+ * @param flowPath the FlowPath for the Flow Entry to update.
+ * @param flowEntry the FlowEntry with the new state.
+ * @return the updated Flow Entry if found, otherwise null.
+ */
+ private FlowEntry updateFlowEntryAdd(FlowPath flowPath,
+ FlowEntry flowEntry) {
+ //
+ // Iterate over all Flow Entries and find a match.
+ //
+ for (FlowEntry localFlowEntry : flowPath.flowEntries()) {
+ if (! TopologyManager.isSameFlowEntryDataPath(localFlowEntry,
+ flowEntry)) {
+ continue;
+ }
+
+ //
+ // Local Flow Entry match found
+ //
+ if (localFlowEntry.isValidFlowEntryId()) {
+ if (localFlowEntry.flowEntryId().value() !=
+ flowEntry.flowEntryId().value()) {
+ //
+ // Find a local Flow Entry, but the Flow Entry ID doesn't
+ // match. Keep looking.
+ //
+ continue;
+ }
+ } else {
+ // Update the Flow Entry ID
+ FlowEntryId flowEntryId =
+ new FlowEntryId(flowEntry.flowEntryId().value());
+ localFlowEntry.setFlowEntryId(flowEntryId);
+ }
+
+ //
+ // Update the local Flow Entry.
+ //
+ localFlowEntry.setFlowEntryUserState(flowEntry.flowEntryUserState());
+ localFlowEntry.setFlowEntrySwitchState(flowEntry.flowEntrySwitchState());
+ return localFlowEntry;
+ }
+
+ return null; // Entry not found
+ }
+
+ /**
+ * Update a Flow Entry because of an external ENTRY_REMOVE event.
+ *
+ * @param flowPath the FlowPath for the Flow Entry to update.
+ * @param flowEntry the FlowEntry with the new state.
+ * @return the updated Flow Entry if found, otherwise null.
+ */
+ private FlowEntry updateFlowEntryRemove(FlowPath flowPath,
+ FlowEntry flowEntry) {
+ //
+ // Iterate over all Flow Entries and find a match based on
+ // the Flow Entry ID.
+ //
+ for (FlowEntry localFlowEntry : flowPath.flowEntries()) {
+ if (! localFlowEntry.isValidFlowEntryId())
+ continue;
+ if (localFlowEntry.flowEntryId().value() !=
+ flowEntry.flowEntryId().value()) {
+ continue;
+ }
+ //
+ // Update the local Flow Entry.
+ //
+ localFlowEntry.setFlowEntryUserState(flowEntry.flowEntryUserState());
+ localFlowEntry.setFlowEntrySwitchState(flowEntry.flowEntrySwitchState());
+ return localFlowEntry;
+ }
+
+ return null; // Entry not found
+ }
+
+ /**
+ * Recompute a Flow Path.
+ *
+ * @param flowPath the Flow Path to recompute.
+ * @return true if the recomputed Flow Path has changed, otherwise false.
+ */
+ private boolean recomputeFlowPath(FlowPath flowPath) {
+ boolean hasChanged = false;
+
+ //
+ // Test whether the Flow Path needs to be recomputed
+ //
+ switch (flowPath.flowPathType()) {
+ case FP_TYPE_UNKNOWN:
+ return false; // Can't recompute on Unknown FlowType
+ case FP_TYPE_SHORTEST_PATH:
+ break;
+ case FP_TYPE_EXPLICIT_PATH:
+ return false; // An explicit path never changes
+ }
+
+ DataPath oldDataPath = flowPath.dataPath();
+
+ // Compute the new path
+ DataPath newDataPath = TopologyManager.computeNetworkPath(topology,
+ flowPath);
+ if (newDataPath == null) {
+ // We need the DataPath to compare the paths
+ newDataPath = new DataPath();
+ }
+ newDataPath.applyFlowPathFlags(flowPath.flowPathFlags());
+
+ //
+ // Test whether the new path is same
+ //
+ if (oldDataPath.flowEntries().size() !=
+ newDataPath.flowEntries().size()) {
+ hasChanged = true;
+ } else {
+ Iterator<FlowEntry> oldIter = oldDataPath.flowEntries().iterator();
+ Iterator<FlowEntry> newIter = newDataPath.flowEntries().iterator();
+ while (oldIter.hasNext() && newIter.hasNext()) {
+ FlowEntry oldFlowEntry = oldIter.next();
+ FlowEntry newFlowEntry = newIter.next();
+ if (! TopologyManager.isSameFlowEntryDataPath(oldFlowEntry,
+ newFlowEntry)) {
+ hasChanged = true;
+ break;
+ }
+ }
+ }
+ if (! hasChanged)
+ return hasChanged;
+
+ //
+ // Merge the changes in the path:
+ // - If a Flow Entry for a switch is in the old data path, but not
+ // in the new data path, then mark it for deletion.
+ // - If a Flow Entry for a switch is in the new data path, but not
+ // in the old data path, then mark it for addition.
+ // - If a Flow Entry for a switch is in both the old and the new
+ // data path, but it has changed, e.g., the incoming and/or outgoing
+ // port(s), then mark the old Flow Entry for deletion, and mark
+ // the new Flow Entry for addition.
+ // - If a Flow Entry for a switch is in both the old and the new
+ // data path, and it hasn't changed, then just keep it.
+ //
+ // NOTE: We use the Switch DPID of each entry to match the entries
+ //
+ Map<Long, FlowEntry> oldFlowEntriesMap = new HashMap<Long, FlowEntry>();
+ Map<Long, FlowEntry> newFlowEntriesMap = new HashMap<Long, FlowEntry>();
+ ArrayList<FlowEntry> finalFlowEntries = new ArrayList<FlowEntry>();
+ List<FlowEntry> deletedFlowEntries = new LinkedList<FlowEntry>();
+
+ // Prepare maps with the Flow Entries, so they are fast to lookup
+ for (FlowEntry flowEntry : oldDataPath.flowEntries())
+ oldFlowEntriesMap.put(flowEntry.dpid().value(), flowEntry);
+ for (FlowEntry flowEntry : newDataPath.flowEntries())
+ newFlowEntriesMap.put(flowEntry.dpid().value(), flowEntry);
+
+ //
+ // Find the old Flow Entries that should be deleted
+ //
+ for (FlowEntry oldFlowEntry : oldDataPath.flowEntries()) {
+ FlowEntry newFlowEntry =
+ newFlowEntriesMap.get(oldFlowEntry.dpid().value());
+ if (newFlowEntry == null) {
+ // The old Flow Entry should be deleted: not on the path
+ oldFlowEntry.setFlowEntryUserState(FlowEntryUserState.FE_USER_DELETE);
+ oldFlowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.FE_SWITCH_NOT_UPDATED);
+ deletedFlowEntries.add(oldFlowEntry);
+ }
+ }
+
+ //
+ // Find the new Flow Entries that should be added or updated
+ //
+ int idx = 0;
+ for (FlowEntry newFlowEntry : newDataPath.flowEntries()) {
+ FlowEntry oldFlowEntry =
+ oldFlowEntriesMap.get(newFlowEntry.dpid().value());
+
+ if ((oldFlowEntry != null) &&
+ TopologyManager.isSameFlowEntryDataPath(oldFlowEntry,
+ newFlowEntry)) {
+ //
+ // Both Flow Entries are same
+ //
+ finalFlowEntries.add(oldFlowEntry);
+ idx++;
+ continue;
+ }
+
+ if (oldFlowEntry != null) {
+ //
+ // The old Flow Entry should be deleted: path diverges
+ //
+ oldFlowEntry.setFlowEntryUserState(FlowEntryUserState.FE_USER_DELETE);
+ oldFlowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.FE_SWITCH_NOT_UPDATED);
+ deletedFlowEntries.add(oldFlowEntry);
+ }
+
+ //
+ // Add the new Flow Entry
+ //
+ //
+ // NOTE: Assign only the Flow ID.
+ // The Flow Entry ID is assigned later only for the Flow Entries
+ // this instance is responsible for.
+ //
+ newFlowEntry.setFlowId(new FlowId(flowPath.flowId().value()));
+
+ // Set the incoming port matching
+ FlowEntryMatch flowEntryMatch = new FlowEntryMatch();
+ newFlowEntry.setFlowEntryMatch(flowEntryMatch);
+ flowEntryMatch.enableInPort(newFlowEntry.inPort());
+
+ //
+ // Set the actions:
+ // If the first Flow Entry, copy the Flow Path actions to it.
+ //
+ FlowEntryActions flowEntryActions = newFlowEntry.flowEntryActions();
+ if ((idx == 0) && (flowPath.flowEntryActions() != null)) {
+ FlowEntryActions flowActions =
+ new FlowEntryActions(flowPath.flowEntryActions());
+ for (FlowEntryAction action : flowActions.actions())
+ flowEntryActions.addAction(action);
+ }
+ idx++;
+
+ //
+ // Add the outgoing port output action
+ //
+ FlowEntryAction flowEntryAction = new FlowEntryAction();
+ flowEntryAction.setActionOutput(newFlowEntry.outPort());
+ flowEntryActions.addAction(flowEntryAction);
+
+ //
+ // Set the state of the new Flow Entry
+ //
+ newFlowEntry.setFlowEntryUserState(FlowEntryUserState.FE_USER_ADD);
+ newFlowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.FE_SWITCH_NOT_UPDATED);
+ finalFlowEntries.add(newFlowEntry);
+ }
+
+ //
+ // Replace the old Flow Entries with the new Flow Entries.
+ // Note that the Flow Entries that will be deleted are added at
+ // the end.
+ //
+ finalFlowEntries.addAll(deletedFlowEntries);
+ flowPath.dataPath().setFlowEntries(finalFlowEntries);
+
+ return hasChanged;
+ }
+
+ /**
+ * Receive a notification that a Flow is added.
+ *
+ * @param flowPath the Flow that is added.
+ */
+ @Override
+ public void notificationRecvFlowAdded(FlowPath flowPath) {
+ EventEntry<FlowPath> eventEntry =
+ new EventEntry<FlowPath>(EventEntry.Type.ENTRY_ADD, flowPath);
+ networkEvents.add(eventEntry);
+ }
+
+ /**
+ * Receive a notification that a Flow is removed.
+ *
+ * @param flowPath the Flow that is removed.
+ */
+ @Override
+ public void notificationRecvFlowRemoved(FlowPath flowPath) {
+ EventEntry<FlowPath> eventEntry =
+ new EventEntry<FlowPath>(EventEntry.Type.ENTRY_REMOVE, flowPath);
+ networkEvents.add(eventEntry);
+ }
+
+ /**
+ * Receive a notification that a Flow is updated.
+ *
+ * @param flowPath the Flow that is updated.
+ */
+ @Override
+ public void notificationRecvFlowUpdated(FlowPath flowPath) {
+ // NOTE: The ADD and UPDATE events are processed in same way
+ EventEntry<FlowPath> eventEntry =
+ new EventEntry<FlowPath>(EventEntry.Type.ENTRY_ADD, flowPath);
+ networkEvents.add(eventEntry);
+ }
+
+ /**
+ * Receive a notification that a FlowEntry is added.
+ *
+ * @param flowEntry the FlowEntry that is added.
+ */
+ @Override
+ public void notificationRecvFlowEntryAdded(FlowEntry flowEntry) {
+ EventEntry<FlowEntry> eventEntry =
+ new EventEntry<FlowEntry>(EventEntry.Type.ENTRY_ADD, flowEntry);
+ networkEvents.add(eventEntry);
+ }
+
+ /**
+ * Receive a notification that a FlowEntry is removed.
+ *
+ * @param flowEntry the FlowEntry that is removed.
+ */
+ @Override
+ public void notificationRecvFlowEntryRemoved(FlowEntry flowEntry) {
+ EventEntry<FlowEntry> eventEntry =
+ new EventEntry<FlowEntry>(EventEntry.Type.ENTRY_REMOVE, flowEntry);
+ networkEvents.add(eventEntry);
+ }
+
+ /**
+ * Receive a notification that a FlowEntry is updated.
+ *
+ * @param flowEntry the FlowEntry that is updated.
+ */
+ @Override
+ public void notificationRecvFlowEntryUpdated(FlowEntry flowEntry) {
+ // NOTE: The ADD and UPDATE events are processed in same way
+ EventEntry<FlowEntry> eventEntry =
+ new EventEntry<FlowEntry>(EventEntry.Type.ENTRY_ADD, flowEntry);
+ networkEvents.add(eventEntry);
+ }
+
+ /**
+ * Receive a notification that a Topology Element is added.
+ *
+ * @param topologyElement the Topology Element that is added.
+ */
+ @Override
+ public void notificationRecvTopologyElementAdded(TopologyElement topologyElement) {
+ EventEntry<TopologyElement> eventEntry =
+ new EventEntry<TopologyElement>(EventEntry.Type.ENTRY_ADD, topologyElement);
+ networkEvents.add(eventEntry);
+ }
+
+ /**
+ * Receive a notification that a Topology Element is removed.
+ *
+ * @param topologyElement the Topology Element that is removed.
+ */
+ @Override
+ public void notificationRecvTopologyElementRemoved(TopologyElement topologyElement) {
+ EventEntry<TopologyElement> eventEntry =
+ new EventEntry<TopologyElement>(EventEntry.Type.ENTRY_REMOVE, topologyElement);
+ networkEvents.add(eventEntry);
+ }
+
+ /**
+ * Receive a notification that a Topology Element is updated.
+ *
+ * @param topologyElement the Topology Element that is updated.
+ */
+ @Override
+ public void notificationRecvTopologyElementUpdated(TopologyElement topologyElement) {
+ // NOTE: The ADD and UPDATE events are processed in same way
+ EventEntry<TopologyElement> eventEntry =
+ new EventEntry<TopologyElement>(EventEntry.Type.ENTRY_ADD, topologyElement);
+ networkEvents.add(eventEntry);
+ }
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowManager.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowManager.java
index cd6f5eb..db1e588 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowManager.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowManager.java
@@ -1,20 +1,14 @@
package net.onrc.onos.ofcontroller.flowmanager;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedList;
-import java.util.List;
import java.util.Map;
import java.util.Random;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.Executors;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@@ -25,43 +19,20 @@
import net.floodlightcontroller.core.module.IFloodlightModule;
import net.floodlightcontroller.core.module.IFloodlightService;
import net.floodlightcontroller.restserver.IRestApiService;
-import net.floodlightcontroller.util.MACAddress;
import net.floodlightcontroller.util.OFMessageDamper;
import net.onrc.onos.graph.DBOperation;
import net.onrc.onos.graph.GraphDBManager;
+import net.onrc.onos.datagrid.IDatagridService;
import net.onrc.onos.ofcontroller.core.INetMapStorage;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowEntry;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowPath;
-import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IPortObject;
-import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.ISwitchObject;
-import net.onrc.onos.ofcontroller.core.INetMapTopologyService.ITopoRouteService;
+import net.onrc.onos.ofcontroller.floodlightlistener.INetworkGraphService;
import net.onrc.onos.ofcontroller.flowmanager.web.FlowWebRoutable;
-import net.onrc.onos.ofcontroller.routing.TopoRouteService;
-import net.onrc.onos.ofcontroller.util.CallerId;
-import net.onrc.onos.ofcontroller.util.DataPath;
-import net.onrc.onos.ofcontroller.util.DataPathEndpoints;
-import net.onrc.onos.ofcontroller.util.Dpid;
-import net.onrc.onos.ofcontroller.util.FlowEntry;
-import net.onrc.onos.ofcontroller.util.FlowEntryAction;
-import net.onrc.onos.ofcontroller.util.FlowEntryAction.*;
-import net.onrc.onos.ofcontroller.util.FlowEntryActions;
-import net.onrc.onos.ofcontroller.util.FlowEntryId;
-import net.onrc.onos.ofcontroller.util.FlowEntryMatch;
-import net.onrc.onos.ofcontroller.util.FlowEntrySwitchState;
-import net.onrc.onos.ofcontroller.util.FlowEntryUserState;
-import net.onrc.onos.ofcontroller.util.FlowId;
-import net.onrc.onos.ofcontroller.util.FlowPath;
-import net.onrc.onos.ofcontroller.util.FlowPathFlags;
-import net.onrc.onos.ofcontroller.util.IPv4Net;
-import net.onrc.onos.ofcontroller.util.Port;
-import net.onrc.onos.ofcontroller.util.SwitchPort;
+import net.onrc.onos.ofcontroller.flowprogrammer.IFlowPusherService;
+import net.onrc.onos.ofcontroller.topology.Topology;
+import net.onrc.onos.ofcontroller.util.*;
-import org.openflow.protocol.OFFlowMod;
-import org.openflow.protocol.OFMatch;
-import org.openflow.protocol.OFPacketOut;
-import org.openflow.protocol.OFPort;
import org.openflow.protocol.OFType;
-import org.openflow.protocol.action.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -69,362 +40,40 @@
* Flow Manager class for handling the network flows.
*/
public class FlowManager implements IFloodlightModule, IFlowService, INetMapStorage {
+ // flag to use FlowPusher instead of FlowSwitchOperation/MessageDamper
+ private final static boolean enableFlowPusher = false;
protected DBOperation op;
- protected IRestApiService restApi;
protected volatile IFloodlightProviderService floodlightProvider;
- protected volatile ITopoRouteService topoRouteService;
+ protected volatile IDatagridService datagridService;
+ protected IRestApiService restApi;
protected FloodlightModuleContext context;
+ protected FlowEventHandler flowEventHandler;
+ protected IFlowPusherService pusher;
+
protected OFMessageDamper messageDamper;
-
+
//
// TODO: Values copied from elsewhere (class LearningSwitch).
// The local copy should go away!
//
protected static final int OFMESSAGE_DAMPER_CAPACITY = 50000; // TODO: find sweet spot
protected static final int OFMESSAGE_DAMPER_TIMEOUT = 250; // ms
- public static final short FLOWMOD_DEFAULT_IDLE_TIMEOUT = 0; // infinity
- public static final short FLOWMOD_DEFAULT_HARD_TIMEOUT = 0; // infinite
- public static final short PRIORITY_DEFAULT = 100;
// Flow Entry ID generation state
private static Random randomGenerator = new Random();
private static int nextFlowEntryIdPrefix = 0;
private static int nextFlowEntryIdSuffix = 0;
- private static long nextFlowEntryId = 0;
-
- // State for measurement purpose
- private static long measurementFlowId = 100000;
- private static String measurementFlowIdStr = "0x186a0"; // 100000
- private long modifiedMeasurementFlowTime = 0;
- //
/** The logger. */
- private static Logger log = LoggerFactory.getLogger(FlowManager.class);
+ private final static Logger log = LoggerFactory.getLogger(FlowManager.class);
- // The periodic task(s)
- private ScheduledExecutorService mapReaderScheduler;
- private ScheduledExecutorService shortestPathReconcileScheduler;
-
- /**
- * Periodic task for reading the Flow Entries and pushing changes
- * into the switches.
- */
- final Runnable mapReader = new Runnable() {
- public void run() {
- try {
- runImpl();
- } catch (Exception e) {
- log.debug("Exception processing All Flow Entries from the Network MAP: ", e);
- op.rollback();
- return;
- }
- }
-
- private void runImpl() {
- long startTime = System.nanoTime();
- int counterAllFlowEntries = 0;
- int counterMyNotUpdatedFlowEntries = 0;
-
- if (floodlightProvider == null) {
- log.debug("FloodlightProvider service not found!");
- return;
- }
- Map<Long, IOFSwitch> mySwitches =
- floodlightProvider.getSwitches();
- if (mySwitches.isEmpty()) {
- log.trace("No switches controlled");
- return;
- }
- LinkedList<IFlowEntry> addFlowEntries =
- new LinkedList<IFlowEntry>();
- LinkedList<IFlowEntry> deleteFlowEntries =
- new LinkedList<IFlowEntry>();
-
- //
- // Fetch all Flow Entries which need to be updated and select only my Flow Entries
- // that need to be updated into the switches.
- //
- boolean processed_measurement_flow = false;
- Iterable<IFlowEntry> allFlowEntries =
- op.getAllSwitchNotUpdatedFlowEntries();
- for (IFlowEntry flowEntryObj : allFlowEntries) {
- counterAllFlowEntries++;
-
- String dpidStr = flowEntryObj.getSwitchDpid();
- if (dpidStr == null)
- continue;
- Dpid dpid = new Dpid(dpidStr);
- IOFSwitch mySwitch = mySwitches.get(dpid.value());
- if (mySwitch == null)
- continue; // Ignore the entry: not my switch
-
- IFlowPath flowObj =
- op.getFlowPathByFlowEntry(flowEntryObj);
- if (flowObj == null)
- continue; // Should NOT happen
- if (flowObj.getFlowId() == null)
- continue; // Invalid entry
-
- //
- // NOTE: For now we process the DELETE before the ADD
- // to cover the more common scenario.
- // TODO: This is error prone and needs to be fixed!
- //
- String userState = flowEntryObj.getUserState();
- if (userState == null)
- continue;
- if (userState.equals("FE_USER_DELETE")) {
- // An entry that needs to be deleted.
- deleteFlowEntries.add(flowEntryObj);
- installFlowEntry(mySwitch, flowObj, flowEntryObj);
- } else {
- addFlowEntries.add(flowEntryObj);
- }
- counterMyNotUpdatedFlowEntries++;
- // Code for measurement purpose
- // TODO: Commented-out for now
- /*
- {
- if (flowObj.getFlowId().equals(measurementFlowIdStr)) {
- processed_measurement_flow = true;
- }
- }
- */
- }
-
- //
- // Process the Flow Entries that need to be added
- //
- for (IFlowEntry flowEntryObj : addFlowEntries) {
- IFlowPath flowObj =
- op.getFlowPathByFlowEntry(flowEntryObj);
- if (flowObj == null)
- continue; // Should NOT happen
- if (flowObj.getFlowId() == null)
- continue; // Invalid entry
-
- Dpid dpid = new Dpid(flowEntryObj.getSwitchDpid());
- IOFSwitch mySwitch = mySwitches.get(dpid.value());
- if (mySwitch == null)
- continue; // Shouldn't happen
- installFlowEntry(mySwitch, flowObj, flowEntryObj);
- }
-
- //
- // Delete all Flow Entries marked for deletion from the
- // Network MAP.
- //
- // TODO: We should use the OpenFlow Barrier mechanism
- // to check for errors, and delete the Flow Entries after the
- // Barrier message is received.
- //
- while (! deleteFlowEntries.isEmpty()) {
- IFlowEntry flowEntryObj = deleteFlowEntries.poll();
- IFlowPath flowObj =
- op.getFlowPathByFlowEntry(flowEntryObj);
- if (flowObj == null) {
- log.debug("Did not find FlowPath to be deleted");
- continue;
- }
- flowObj.removeFlowEntry(flowEntryObj);
- op.removeFlowEntry(flowEntryObj);
- }
-
- op.commit();
-
- if (processed_measurement_flow) {
- long estimatedTime =
- System.nanoTime() - modifiedMeasurementFlowTime;
- String logMsg = "MEASUREMENT: Pushed Flow delay: " +
- (double)estimatedTime / 1000000000 + " sec";
- log.debug(logMsg);
- }
-
- long estimatedTime = System.nanoTime() - startTime;
- double rate = 0.0;
- if (estimatedTime > 0)
- rate = ((double)counterAllFlowEntries * 1000000000) / estimatedTime;
- String logMsg = "MEASUREMENT: Processed AllFlowEntries: " +
- counterAllFlowEntries + " MyNotUpdatedFlowEntries: " +
- counterMyNotUpdatedFlowEntries + " in " +
- (double)estimatedTime / 1000000000 + " sec: " +
- rate + " paths/s";
- log.debug(logMsg);
- }
- };
-
- /**
- * Periodic task for reading the Flow Paths and recomputing the
- * shortest paths.
- */
- final Runnable shortestPathReconcile = new Runnable() {
- public void run() {
- try {
- runImpl();
- } catch (Exception e) {
- log.debug("Exception processing All Flows from the Network MAP: ", e);
- op.rollback();
- return;
- }
- }
-
- private void runImpl() {
- long startTime = System.nanoTime();
- int counterAllFlowPaths = 0;
- int counterMyFlowPaths = 0;
-
- if (floodlightProvider == null) {
- log.debug("FloodlightProvider service not found!");
- return;
- }
- Map<Long, IOFSwitch> mySwitches =
- floodlightProvider.getSwitches();
- if (mySwitches.isEmpty()) {
- log.trace("No switches controlled");
- return;
- }
- LinkedList<IFlowPath> deleteFlows = new LinkedList<IFlowPath>();
-
- boolean processed_measurement_flow = false;
-
- //
- // Fetch and recompute the Shortest Path for those
- // Flow Paths this controller is responsible for.
- //
- Map<Long, ?> shortestPathTopo =
- topoRouteService.prepareShortestPathTopo();
- Iterable<IFlowPath> allFlowPaths = op.getAllFlowPaths();
- for (IFlowPath flowPathObj : allFlowPaths) {
- counterAllFlowPaths++;
- if (flowPathObj == null)
- continue;
-
- String srcDpidStr = flowPathObj.getSrcSwitch();
- if (srcDpidStr == null)
- continue;
- Dpid srcDpid = new Dpid(srcDpidStr);
- //
- // Use the source DPID as a heuristic to decide
- // which controller is responsible for maintaining the
- // shortest path.
- // NOTE: This heuristic is error-prone: if the switch
- // goes away and no controller is responsible for that
- // switch, then the original Flow Path is not cleaned-up
- //
- IOFSwitch mySwitch = mySwitches.get(srcDpid.value());
- if (mySwitch == null)
- continue; // Ignore: not my responsibility
-
- // Test the Data Path Summary string
- String dataPathSummaryStr = flowPathObj.getDataPathSummary();
- if (dataPathSummaryStr == null)
- continue; // Could be invalid entry?
- if (dataPathSummaryStr.isEmpty())
- continue; // No need to maintain this flow
-
- //
- // Test whether we need to complete the Flow cleanup,
- // if the Flow has been deleted by the user.
- //
- String flowUserState = flowPathObj.getUserState();
- if ((flowUserState != null)
- && flowUserState.equals("FE_USER_DELETE")) {
- Iterable<IFlowEntry> flowEntries = flowPathObj.getFlowEntries();
- boolean empty = true; // TODO: an ugly hack
- for (IFlowEntry flowEntryObj : flowEntries) {
- empty = false;
- break;
- }
- if (empty)
- deleteFlows.add(flowPathObj);
- }
-
- // Fetch the fields needed to recompute the shortest path
- Short srcPortShort = flowPathObj.getSrcPort();
- String dstDpidStr = flowPathObj.getDstSwitch();
- Short dstPortShort = flowPathObj.getDstPort();
- Long flowPathFlagsLong = flowPathObj.getFlowPathFlags();
- if ((srcPortShort == null) ||
- (dstDpidStr == null) ||
- (dstPortShort == null) ||
- (flowPathFlagsLong == null)) {
- continue;
- }
-
- Port srcPort = new Port(srcPortShort);
- Dpid dstDpid = new Dpid(dstDpidStr);
- Port dstPort = new Port(dstPortShort);
- SwitchPort srcSwitchPort = new SwitchPort(srcDpid, srcPort);
- SwitchPort dstSwitchPort = new SwitchPort(dstDpid, dstPort);
- FlowPathFlags flowPathFlags = new FlowPathFlags(flowPathFlagsLong);
-
- counterMyFlowPaths++;
-
- //
- // NOTE: Using here the regular getShortestPath() method
- // won't work here, because that method calls internally
- // "conn.endTx(Transaction.COMMIT)", and that will
- // invalidate all handlers to the Titan database.
- // If we want to experiment with calling here
- // getShortestPath(), we need to refactor that code
- // to avoid closing the transaction.
- //
- DataPath dataPath =
- topoRouteService.getTopoShortestPath(shortestPathTopo,
- srcSwitchPort,
- dstSwitchPort);
- if (dataPath == null) {
- // We need the DataPath to compare the paths
- dataPath = new DataPath();
- dataPath.setSrcPort(srcSwitchPort);
- dataPath.setDstPort(dstSwitchPort);
- }
- dataPath.applyFlowPathFlags(flowPathFlags);
-
- String newDataPathSummaryStr = dataPath.dataPathSummary();
- if (dataPathSummaryStr.equals(newDataPathSummaryStr))
- continue; // Nothing changed
-
- reconcileFlow(flowPathObj, dataPath);
- }
-
- //
- // Delete all leftover Flows marked for deletion from the
- // Network MAP.
- //
- while (! deleteFlows.isEmpty()) {
- IFlowPath flowPathObj = deleteFlows.poll();
- op.removeFlowPath(flowPathObj);
- }
-
- topoRouteService.dropShortestPathTopo(shortestPathTopo);
-
- op.commit();
-
- if (processed_measurement_flow) {
- long estimatedTime =
- System.nanoTime() - modifiedMeasurementFlowTime;
- String logMsg = "MEASUREMENT: Pushed Flow delay: " +
- (double)estimatedTime / 1000000000 + " sec";
- log.debug(logMsg);
- }
-
- long estimatedTime = System.nanoTime() - startTime;
- double rate = 0.0;
- if (estimatedTime > 0)
- rate = ((double)counterAllFlowPaths * 1000000000) / estimatedTime;
- String logMsg = "MEASUREMENT: Processed AllFlowPaths: " +
- counterAllFlowPaths + " MyFlowPaths: " +
- counterMyFlowPaths + " in " +
- (double)estimatedTime / 1000000000 + " sec: " +
- rate + " paths/s";
- log.debug(logMsg);
- }
- };
-
+ // The queue to write Flow Entries to the database
+ private BlockingQueue<FlowPathEntryPair> flowEntriesToDatabaseQueue =
+ new LinkedBlockingQueue<FlowPathEntryPair>();
+ FlowDatabaseWriter flowDatabaseWriter;
/**
* Initialize the Flow Manager.
@@ -449,7 +98,9 @@
*/
@Override
public void close() {
- op.close();
+ datagridService.deregisterFlowEventHandlerService(flowEventHandler);
+ dbHandlerApi.close();
+ dbHandlerInner.close();
}
/**
@@ -474,9 +125,9 @@
public Map<Class<? extends IFloodlightService>, IFloodlightService>
getServiceImpls() {
Map<Class<? extends IFloodlightService>,
- IFloodlightService> m =
- new HashMap<Class<? extends IFloodlightService>,
- IFloodlightService>();
+ IFloodlightService> m =
+ new HashMap<Class<? extends IFloodlightService>,
+ IFloodlightService>();
m.put(IFlowService.class, this);
return m;
}
@@ -488,10 +139,12 @@
*/
@Override
public Collection<Class<? extends IFloodlightService>>
- getModuleDependencies() {
+ getModuleDependencies() {
Collection<Class<? extends IFloodlightService>> l =
new ArrayList<Class<? extends IFloodlightService>>();
l.add(IFloodlightProviderService.class);
+ l.add(INetworkGraphService.class);
+ l.add(IDatagridService.class);
l.add(IRestApiService.class);
return l;
}
@@ -506,17 +159,18 @@
throws FloodlightModuleException {
this.context = context;
floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
+ datagridService = context.getServiceImpl(IDatagridService.class);
restApi = context.getServiceImpl(IRestApiService.class);
- messageDamper = new OFMessageDamper(OFMESSAGE_DAMPER_CAPACITY,
- EnumSet.of(OFType.FLOW_MOD),
- OFMESSAGE_DAMPER_TIMEOUT);
- // TODO: An ugly hack!
- String conf = "/tmp/cassandra.titan";
- this.init("titan", conf);
-
- mapReaderScheduler = Executors.newScheduledThreadPool(1);
- shortestPathReconcileScheduler = Executors.newScheduledThreadPool(1);
+ if (enableFlowPusher) {
+ pusher = context.getServiceImpl(IFlowPusherService.class);
+ } else {
+ messageDamper = new OFMessageDamper(OFMESSAGE_DAMPER_CAPACITY,
+ EnumSet.of(OFType.FLOW_MOD),
+ OFMESSAGE_DAMPER_TIMEOUT);
+ }
+
+ this.init("","");
}
/**
@@ -524,7 +178,8 @@
*
* @return the next Flow Entry ID to use.
*/
- private synchronized long getNextFlowEntryId() {
+ @Override
+ public synchronized long getNextFlowEntryId() {
//
// Generate the next Flow Entry ID.
// NOTE: For now, the higher 32 bits are random, and
@@ -550,172 +205,55 @@
@Override
public void startUp(FloodlightModuleContext context) {
restApi.addRestletRoutable(new FlowWebRoutable());
-
+
// Initialize the Flow Entry ID generator
nextFlowEntryIdPrefix = randomGenerator.nextInt();
-
- mapReaderScheduler.scheduleAtFixedRate(
- mapReader, 3, 3, TimeUnit.SECONDS);
- shortestPathReconcileScheduler.scheduleAtFixedRate(
- shortestPathReconcile, 3, 3, TimeUnit.SECONDS);
+
+ //
+ // The thread to write to the database
+ //
+ flowDatabaseWriter = new FlowDatabaseWriter(this,
+ flowEntriesToDatabaseQueue);
+ flowDatabaseWriter.start();
+
+ //
+ // The Flow Event Handler thread:
+ // - create
+ // - register with the Datagrid Service
+ // - startup
+ //
+ flowEventHandler = new FlowEventHandler(this, datagridService);
+ datagridService.registerFlowEventHandlerService(flowEventHandler);
+ flowEventHandler.start();
}
/**
* Add a flow.
*
- * Internally, ONOS will automatically register the installer for
- * receiving Flow Path Notifications for that path.
- *
* @param flowPath the Flow Path to install.
* @param flowId the return-by-reference Flow ID as assigned internally.
- * @param dataPathSummaryStr the data path summary string if the added
- * flow will be maintained internally, otherwise null.
* @return true on success, otherwise false.
*/
@Override
- public boolean addFlow(FlowPath flowPath, FlowId flowId,
- String dataPathSummaryStr) {
- /*
- * TODO: Commented-out for now
- if (flowPath.flowId().value() == measurementFlowId) {
- modifiedMeasurementFlowTime = System.nanoTime();
- }
- */
-
- IFlowPath flowObj = null;
- boolean found = false;
- try {
- if ((flowObj = op.searchFlowPath(flowPath.flowId()))
- != null) {
- log.debug("Adding FlowPath with FlowId {}: found existing FlowPath",
- flowPath.flowId().toString());
- found = true;
- } else {
- flowObj = op.newFlowPath();
- log.debug("Adding FlowPath with FlowId {}: creating new FlowPath",
- flowPath.flowId().toString());
+ public boolean addFlow(FlowPath flowPath, FlowId flowId) {
+ //
+ // NOTE: We need to explicitly initialize some of the state,
+ // in case the application didn't do it.
+ //
+ for (FlowEntry flowEntry : flowPath.flowEntries()) {
+ if (flowEntry.flowEntrySwitchState() ==
+ FlowEntrySwitchState.FE_SWITCH_UNKNOWN) {
+ flowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.FE_SWITCH_NOT_UPDATED);
}
- } catch (Exception e) {
- // TODO: handle exceptions
- op.rollback();
-
- StringWriter sw = new StringWriter();
- e.printStackTrace(new PrintWriter(sw));
- String stacktrace = sw.toString();
-
- log.error(":addFlow FlowId:{} failed: {}",
- flowPath.flowId().toString(),
- stacktrace);
- }
- if (flowObj == null) {
- log.error(":addFlow FlowId:{} failed: Flow object not created",
- flowPath.flowId().toString());
- op.rollback();
- return false;
+ if (! flowEntry.isValidFlowId())
+ flowEntry.setFlowId(new FlowId(flowPath.flowId().value()));
}
- //
- // Set the Flow key:
- // - flowId
- //
- flowObj.setFlowId(flowPath.flowId().toString());
- flowObj.setType("flow");
-
- //
- // Set the Flow attributes:
- // - flowPath.installerId()
- // - flowPath.flowPathFlags()
- // - flowPath.dataPath().srcPort()
- // - flowPath.dataPath().dstPort()
- // - flowPath.matchSrcMac()
- // - flowPath.matchDstMac()
- // - flowPath.matchEthernetFrameType()
- // - flowPath.matchVlanId()
- // - flowPath.matchVlanPriority()
- // - flowPath.matchSrcIPv4Net()
- // - flowPath.matchDstIPv4Net()
- // - flowPath.matchIpProto()
- // - flowPath.matchIpToS()
- // - flowPath.matchSrcTcpUdpPort()
- // - flowPath.matchDstTcpUdpPort()
- // - flowPath.flowEntryActions()
- //
- flowObj.setInstallerId(flowPath.installerId().toString());
- flowObj.setFlowPathFlags(flowPath.flowPathFlags().flags());
- flowObj.setSrcSwitch(flowPath.dataPath().srcPort().dpid().toString());
- flowObj.setSrcPort(flowPath.dataPath().srcPort().port().value());
- flowObj.setDstSwitch(flowPath.dataPath().dstPort().dpid().toString());
- flowObj.setDstPort(flowPath.dataPath().dstPort().port().value());
- if (flowPath.flowEntryMatch().matchSrcMac()) {
- flowObj.setMatchSrcMac(flowPath.flowEntryMatch().srcMac().toString());
+ if (FlowDatabaseOperation.addFlow(this, dbHandlerApi, flowPath, flowId)) {
+ datagridService.notificationSendFlowAdded(flowPath);
+ return true;
}
- if (flowPath.flowEntryMatch().matchDstMac()) {
- flowObj.setMatchDstMac(flowPath.flowEntryMatch().dstMac().toString());
- }
- if (flowPath.flowEntryMatch().matchEthernetFrameType()) {
- flowObj.setMatchEthernetFrameType(flowPath.flowEntryMatch().ethernetFrameType());
- }
- if (flowPath.flowEntryMatch().matchVlanId()) {
- flowObj.setMatchVlanId(flowPath.flowEntryMatch().vlanId());
- }
- if (flowPath.flowEntryMatch().matchVlanPriority()) {
- flowObj.setMatchVlanPriority(flowPath.flowEntryMatch().vlanPriority());
- }
- if (flowPath.flowEntryMatch().matchSrcIPv4Net()) {
- flowObj.setMatchSrcIPv4Net(flowPath.flowEntryMatch().srcIPv4Net().toString());
- }
- if (flowPath.flowEntryMatch().matchDstIPv4Net()) {
- flowObj.setMatchDstIPv4Net(flowPath.flowEntryMatch().dstIPv4Net().toString());
- }
- if (flowPath.flowEntryMatch().matchIpProto()) {
- flowObj.setMatchIpProto(flowPath.flowEntryMatch().ipProto());
- }
- if (flowPath.flowEntryMatch().matchIpToS()) {
- flowObj.setMatchIpToS(flowPath.flowEntryMatch().ipToS());
- }
- if (flowPath.flowEntryMatch().matchSrcTcpUdpPort()) {
- flowObj.setMatchSrcTcpUdpPort(flowPath.flowEntryMatch().srcTcpUdpPort());
- }
- if (flowPath.flowEntryMatch().matchDstTcpUdpPort()) {
- flowObj.setMatchDstTcpUdpPort(flowPath.flowEntryMatch().dstTcpUdpPort());
- }
- if (! flowPath.flowEntryActions().actions().isEmpty()) {
- flowObj.setActions(flowPath.flowEntryActions().toString());
- }
-
- if (dataPathSummaryStr != null) {
- flowObj.setDataPathSummary(dataPathSummaryStr);
- } else {
- flowObj.setDataPathSummary("");
- }
-
- if (found)
- flowObj.setUserState("FE_USER_MODIFY");
- else
- flowObj.setUserState("FE_USER_ADD");
-
- // Flow edges:
- // HeadFE
-
-
- //
- // Flow Entries:
- // flowPath.dataPath().flowEntries()
- //
- for (FlowEntry flowEntry : flowPath.dataPath().flowEntries()) {
- if (addFlowEntry(flowObj, flowEntry) == null) {
- op.rollback();
- return false;
- }
- }
- op.commit();
-
- //
- // TODO: We need a proper Flow ID allocation mechanism.
- //
- flowId.setValue(flowPath.flowId().value());
-
- return true;
+ return false;
}
/**
@@ -726,150 +264,20 @@
* @return the added Flow Entry object on success, otherwise null.
*/
private IFlowEntry addFlowEntry(IFlowPath flowObj, FlowEntry flowEntry) {
- // Flow edges
- // HeadFE (TODO)
+ return FlowDatabaseOperation.addFlowEntry(this, dbHandlerInner,
+ flowObj, flowEntry);
+ }
- //
- // Assign the FlowEntry ID.
- //
- if ((flowEntry.flowEntryId() == null) ||
- (flowEntry.flowEntryId().value() == 0)) {
- long id = getNextFlowEntryId();
- flowEntry.setFlowEntryId(new FlowEntryId(id));
- }
-
- IFlowEntry flowEntryObj = null;
- boolean found = false;
- try {
- if ((flowEntryObj =
- op.searchFlowEntry(flowEntry.flowEntryId())) != null) {
- log.debug("Adding FlowEntry with FlowEntryId {}: found existing FlowEntry",
- flowEntry.flowEntryId().toString());
- found = true;
- } else {
- flowEntryObj = op.newFlowEntry();
- log.debug("Adding FlowEntry with FlowEntryId {}: creating new FlowEntry",
- flowEntry.flowEntryId().toString());
- }
- } catch (Exception e) {
- log.error(":addFlow FlowEntryId:{} failed",
- flowEntry.flowEntryId().toString());
- return null;
- }
- if (flowEntryObj == null) {
- log.error(":addFlow FlowEntryId:{} failed: FlowEntry object not created",
- flowEntry.flowEntryId().toString());
- return null;
- }
-
- //
- // Set the Flow Entry key:
- // - flowEntry.flowEntryId()
- //
- flowEntryObj.setFlowEntryId(flowEntry.flowEntryId().toString());
- flowEntryObj.setType("flow_entry");
-
- //
- // Set the Flow Entry Edges and attributes:
- // - Switch edge
- // - InPort edge
- // - OutPort edge
- //
- // - flowEntry.dpid()
- // - flowEntry.flowEntryUserState()
- // - flowEntry.flowEntrySwitchState()
- // - flowEntry.flowEntryErrorState()
- // - flowEntry.matchInPort()
- // - flowEntry.matchSrcMac()
- // - flowEntry.matchDstMac()
- // - flowEntry.matchEthernetFrameType()
- // - flowEntry.matchVlanId()
- // - flowEntry.matchVlanPriority()
- // - flowEntry.matchSrcIPv4Net()
- // - flowEntry.matchDstIPv4Net()
- // - flowEntry.matchIpProto()
- // - flowEntry.matchIpToS()
- // - flowEntry.matchSrcTcpUdpPort()
- // - flowEntry.matchDstTcpUdpPort()
- // - flowEntry.actionOutputPort()
- // - flowEntry.actions()
- //
- ISwitchObject sw = op.searchSwitch(flowEntry.dpid().toString());
- flowEntryObj.setSwitchDpid(flowEntry.dpid().toString());
- flowEntryObj.setSwitch(sw);
- if (flowEntry.flowEntryMatch().matchInPort()) {
- IPortObject inport =
- op.searchPort(flowEntry.dpid().toString(),
- flowEntry.flowEntryMatch().inPort().value());
- flowEntryObj.setMatchInPort(flowEntry.flowEntryMatch().inPort().value());
- flowEntryObj.setInPort(inport);
- }
- if (flowEntry.flowEntryMatch().matchSrcMac()) {
- flowEntryObj.setMatchSrcMac(flowEntry.flowEntryMatch().srcMac().toString());
- }
- if (flowEntry.flowEntryMatch().matchDstMac()) {
- flowEntryObj.setMatchDstMac(flowEntry.flowEntryMatch().dstMac().toString());
- }
- if (flowEntry.flowEntryMatch().matchEthernetFrameType()) {
- flowEntryObj.setMatchEthernetFrameType(flowEntry.flowEntryMatch().ethernetFrameType());
- }
- if (flowEntry.flowEntryMatch().matchVlanId()) {
- flowEntryObj.setMatchVlanId(flowEntry.flowEntryMatch().vlanId());
- }
- if (flowEntry.flowEntryMatch().matchVlanPriority()) {
- flowEntryObj.setMatchVlanPriority(flowEntry.flowEntryMatch().vlanPriority());
- }
- if (flowEntry.flowEntryMatch().matchSrcIPv4Net()) {
- flowEntryObj.setMatchSrcIPv4Net(flowEntry.flowEntryMatch().srcIPv4Net().toString());
- }
- if (flowEntry.flowEntryMatch().matchDstIPv4Net()) {
- flowEntryObj.setMatchDstIPv4Net(flowEntry.flowEntryMatch().dstIPv4Net().toString());
- }
- if (flowEntry.flowEntryMatch().matchIpProto()) {
- flowEntryObj.setMatchIpProto(flowEntry.flowEntryMatch().ipProto());
- }
- if (flowEntry.flowEntryMatch().matchIpToS()) {
- flowEntryObj.setMatchIpToS(flowEntry.flowEntryMatch().ipToS());
- }
- if (flowEntry.flowEntryMatch().matchSrcTcpUdpPort()) {
- flowEntryObj.setMatchSrcTcpUdpPort(flowEntry.flowEntryMatch().srcTcpUdpPort());
- }
- if (flowEntry.flowEntryMatch().matchDstTcpUdpPort()) {
- flowEntryObj.setMatchDstTcpUdpPort(flowEntry.flowEntryMatch().dstTcpUdpPort());
- }
-
- for (FlowEntryAction fa : flowEntry.flowEntryActions().actions()) {
- if (fa.actionOutput() != null) {
- IPortObject outport =
- op.searchPort(flowEntry.dpid().toString(),
- fa.actionOutput().port().value());
- flowEntryObj.setActionOutputPort(fa.actionOutput().port().value());
- flowEntryObj.setOutPort(outport);
- }
- }
- if (! flowEntry.flowEntryActions().isEmpty()) {
- flowEntryObj.setActions(flowEntry.flowEntryActions().toString());
- }
-
- // TODO: Hacks with hard-coded state names!
- if (found)
- flowEntryObj.setUserState("FE_USER_MODIFY");
- else
- flowEntryObj.setUserState("FE_USER_ADD");
- flowEntryObj.setSwitchState("FE_SWITCH_NOT_UPDATED");
- //
- // TODO: Take care of the FlowEntryErrorState.
- //
-
- // Flow Entries edges:
- // Flow
- // NextFE (TODO)
- if (! found) {
- flowObj.addFlowEntry(flowEntryObj);
- flowEntryObj.setFlow(flowObj);
- }
-
- return flowEntryObj;
+ /**
+ * Delete a flow entry from the Network MAP.
+ *
+ * @param flowObj the corresponding Flow Path object for the Flow Entry.
+ * @param flowEntry the Flow Entry to delete.
+ * @return true on success, otherwise false.
+ */
+ private boolean deleteFlowEntry(IFlowPath flowObj, FlowEntry flowEntry) {
+ return FlowDatabaseOperation.deleteFlowEntry(dbHandlerInner,
+ flowObj, flowEntry);
}
/**
@@ -879,64 +287,11 @@
*/
@Override
public boolean deleteAllFlows() {
- List<Thread> threads = new LinkedList<Thread>();
- final ConcurrentLinkedQueue<FlowId> concurrentAllFlowIds =
- new ConcurrentLinkedQueue<FlowId>();
-
- // Get all Flow IDs
- Iterable<IFlowPath> allFlowPaths = op.getAllFlowPaths();
- for (IFlowPath flowPathObj : allFlowPaths) {
- if (flowPathObj == null)
- continue;
- String flowIdStr = flowPathObj.getFlowId();
- if (flowIdStr == null)
- continue;
- FlowId flowId = new FlowId(flowIdStr);
- concurrentAllFlowIds.add(flowId);
+ if (FlowDatabaseOperation.deleteAllFlows(dbHandlerApi)) {
+ datagridService.notificationSendAllFlowsRemoved();
+ return true;
}
-
- // Delete all flows one-by-one
- for (FlowId flowId : concurrentAllFlowIds)
- deleteFlow(flowId);
-
- /*
- * TODO: A faster mechanism to delete the Flow Paths by using
- * a number of threads. Commented-out for now.
- */
- /*
- //
- // Create the threads to delete the Flow Paths
- //
- for (int i = 0; i < 10; i++) {
- Thread thread = new Thread(new Runnable() {
- @Override
- public void run() {
- while (true) {
- FlowId flowId = concurrentAllFlowIds.poll();
- if (flowId == null)
- return;
- deleteFlow(flowId);
- }
- }}, "Delete All Flow Paths");
- threads.add(thread);
- }
-
- // Start processing
- for (Thread thread : threads) {
- thread.start();
- }
-
- // Wait for all threads to complete
- for (Thread thread : threads) {
- try {
- thread.join();
- } catch (InterruptedException e) {
- log.debug("Exception waiting for a thread to delete a Flow Path: ", e);
- }
- }
- */
-
- return true;
+ return false;
}
/**
@@ -947,130 +302,11 @@
*/
@Override
public boolean deleteFlow(FlowId flowId) {
- /*
- * TODO: Commented-out for now
- if (flowId.value() == measurementFlowId) {
- modifiedMeasurementFlowTime = System.nanoTime();
+ if (FlowDatabaseOperation.deleteFlow(dbHandlerApi, flowId)) {
+ datagridService.notificationSendFlowRemoved(flowId);
+ return true;
}
- */
-
- IFlowPath flowObj = null;
- //
- // We just mark the entries for deletion,
- // and let the switches remove each individual entry after
- // it has been removed from the switches.
- //
- try {
- if ((flowObj = op.searchFlowPath(flowId))
- != null) {
- log.debug("Deleting FlowPath with FlowId {}: found existing FlowPath",
- flowId.toString());
- } else {
- log.debug("Deleting FlowPath with FlowId {}: FlowPath not found",
- flowId.toString());
- }
- } catch (Exception e) {
- // TODO: handle exceptions
- op.rollback();
- log.error(":deleteFlow FlowId:{} failed", flowId.toString());
- }
- if (flowObj == null) {
- op.commit();
- return true; // OK: No such flow
- }
-
- //
- // Find and mark for deletion all Flow Entries,
- // and the Flow itself.
- //
- flowObj.setUserState("FE_USER_DELETE");
- Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries();
- boolean empty = true; // TODO: an ugly hack
- for (IFlowEntry flowEntryObj : flowEntries) {
- empty = false;
- // flowObj.removeFlowEntry(flowEntryObj);
- // conn.utils().removeFlowEntry(conn, flowEntryObj);
- flowEntryObj.setUserState("FE_USER_DELETE");
- flowEntryObj.setSwitchState("FE_SWITCH_NOT_UPDATED");
- }
- // Remove from the database empty flows
- if (empty)
- op.removeFlowPath(flowObj);
- op.commit();
-
- return true;
- }
-
- /**
- * Clear the state for all previously added flows.
- *
- * @return true on success, otherwise false.
- */
- @Override
- public boolean clearAllFlows() {
- List<FlowId> allFlowIds = new LinkedList<FlowId>();
-
- // Get all Flow IDs
- Iterable<IFlowPath> allFlowPaths = op.getAllFlowPaths();
- for (IFlowPath flowPathObj : allFlowPaths) {
- if (flowPathObj == null)
- continue;
- String flowIdStr = flowPathObj.getFlowId();
- if (flowIdStr == null)
- continue;
- FlowId flowId = new FlowId(flowIdStr);
- allFlowIds.add(flowId);
- }
-
- // Clear all flows one-by-one
- for (FlowId flowId : allFlowIds) {
- clearFlow(flowId);
- }
-
- return true;
- }
-
- /**
- * Clear the state for a previously added flow.
- *
- * @param flowId the Flow ID of the flow to clear.
- * @return true on success, otherwise false.
- */
- @Override
- public boolean clearFlow(FlowId flowId) {
- IFlowPath flowObj = null;
- try {
- if ((flowObj = op.searchFlowPath(flowId))
- != null) {
- log.debug("Clearing FlowPath with FlowId {}: found existing FlowPath",
- flowId.toString());
- } else {
- log.debug("Clearing FlowPath with FlowId {}: FlowPath not found",
- flowId.toString());
- }
- } catch (Exception e) {
- // TODO: handle exceptions
- op.rollback();
- log.error(":clearFlow FlowId:{} failed", flowId.toString());
- }
- if (flowObj == null) {
- op.commit();
- return true; // OK: No such flow
- }
-
- //
- // Remove all Flow Entries
- //
- Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries();
- for (IFlowEntry flowEntryObj : flowEntries) {
- flowObj.removeFlowEntry(flowEntryObj);
- op.removeFlowEntry(flowEntryObj);
- }
- // Remove the Flow itself
- op.removeFlowPath(flowObj);
- op.commit();
-
- return true;
+ return false;
}
/**
@@ -1081,33 +317,17 @@
*/
@Override
public FlowPath getFlow(FlowId flowId) {
- IFlowPath flowObj = null;
- try {
- if ((flowObj = op.searchFlowPath(flowId))
- != null) {
- log.debug("Get FlowPath with FlowId {}: found existing FlowPath",
- flowId.toString());
- } else {
- log.debug("Get FlowPath with FlowId {}: FlowPath not found",
- flowId.toString());
- }
- } catch (Exception e) {
- // TODO: handle exceptions
- op.rollback();
- log.error(":getFlow FlowId:{} failed", flowId.toString());
- }
- if (flowObj == null) {
- op.commit();
- return null; // Flow not found
- }
+ return FlowDatabaseOperation.getFlow(dbHandlerApi, flowId);
+ }
- //
- // Extract the Flow state
- //
- FlowPath flowPath = extractFlowPath(flowObj);
- op.commit();
-
- return flowPath;
+ /**
+ * Get all installed flows by all installers.
+ *
+ * @return the Flow Paths if found, otherwise null.
+ */
+ @Override
+ public ArrayList<FlowPath> getAllFlows() {
+ return FlowDatabaseOperation.getAllFlows(dbHandlerApi);
}
/**
@@ -1121,45 +341,8 @@
@Override
public ArrayList<FlowPath> getAllFlows(CallerId installerId,
DataPathEndpoints dataPathEndpoints) {
- //
- // TODO: The implementation below is not optimal:
- // We fetch all flows, and then return only the subset that match
- // the query conditions.
- // We should use the appropriate Titan/Gremlin query to filter-out
- // the flows as appropriate.
- //
- ArrayList<FlowPath> allFlows = getAllFlows();
- ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>();
-
- if (allFlows == null) {
- log.debug("Get FlowPaths for installerId{} and dataPathEndpoints{}: no FlowPaths found", installerId, dataPathEndpoints);
- return flowPaths;
- }
-
- for (FlowPath flow : allFlows) {
- //
- // TODO: String-based comparison is sub-optimal.
- // We are using it for now to save us the extra work of
- // implementing the "equals()" and "hashCode()" methods.
- //
- if (! flow.installerId().toString().equals(installerId.toString()))
- continue;
- if (! flow.dataPath().srcPort().toString().equals(dataPathEndpoints.srcPort().toString())) {
- continue;
- }
- if (! flow.dataPath().dstPort().toString().equals(dataPathEndpoints.dstPort().toString())) {
- continue;
- }
- flowPaths.add(flow);
- }
-
- if (flowPaths.isEmpty()) {
- log.debug("Get FlowPaths for installerId{} and dataPathEndpoints{}: no FlowPaths found", installerId, dataPathEndpoints);
- } else {
- log.debug("Get FlowPaths for installerId{} and dataPathEndpoints{}: FlowPaths are found", installerId, dataPathEndpoints);
- }
-
- return flowPaths;
+ return FlowDatabaseOperation.getAllFlows(dbHandlerApi, installerId,
+ dataPathEndpoints);
}
/**
@@ -1170,43 +353,8 @@
*/
@Override
public ArrayList<FlowPath> getAllFlows(DataPathEndpoints dataPathEndpoints) {
- //
- // TODO: The implementation below is not optimal:
- // We fetch all flows, and then return only the subset that match
- // the query conditions.
- // We should use the appropriate Titan/Gremlin query to filter-out
- // the flows as appropriate.
- //
- ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>();
- ArrayList<FlowPath> allFlows = getAllFlows();
-
- if (allFlows == null) {
- log.debug("Get FlowPaths for dataPathEndpoints{}: no FlowPaths found", dataPathEndpoints);
- return flowPaths;
- }
-
- for (FlowPath flow : allFlows) {
- //
- // TODO: String-based comparison is sub-optimal.
- // We are using it for now to save us the extra work of
- // implementing the "equals()" and "hashCode()" methods.
- //
- if (! flow.dataPath().srcPort().toString().equals(dataPathEndpoints.srcPort().toString())) {
- continue;
- }
- if (! flow.dataPath().dstPort().toString().equals(dataPathEndpoints.dstPort().toString())) {
- continue;
- }
- flowPaths.add(flow);
- }
-
- if (flowPaths.isEmpty()) {
- log.debug("Get FlowPaths for dataPathEndpoints{}: no FlowPaths found", dataPathEndpoints);
- } else {
- log.debug("Get FlowPaths for dataPathEndpoints{}: FlowPaths are found", dataPathEndpoints);
- }
-
- return flowPaths;
+ return FlowDatabaseOperation.getAllFlows(dbHandlerApi,
+ dataPathEndpoints);
}
/**
@@ -1217,344 +365,19 @@
* @return the Flow Paths if found, otherwise null.
*/
@Override
- public ArrayList<IFlowPath> getAllFlowsSummary(FlowId flowId, int maxFlows) {
-
- //
- // TODO: The implementation below is not optimal:
- // We fetch all flows, and then return only the subset that match
- // the query conditions.
- // We should use the appropriate Titan/Gremlin query to filter-out
- // the flows as appropriate.
- //
- //ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>();
-
- ArrayList<IFlowPath> flowPathsWithoutFlowEntries = getAllFlowsWithoutFlowEntries();
-
- Collections.sort(flowPathsWithoutFlowEntries,
- new Comparator<IFlowPath>(){
- @Override
- public int compare(IFlowPath first, IFlowPath second) {
- // TODO Auto-generated method stub
- long result = new FlowId(first.getFlowId()).value()
- - new FlowId(second.getFlowId()).value();
- if (result > 0) return 1;
- else if (result < 0) return -1;
- else return 0;
- }
- }
- );
-
- return flowPathsWithoutFlowEntries;
-
- /*
- ArrayList<FlowPath> allFlows = getAllFlows();
-
- if (allFlows == null) {
- log.debug("Get FlowPathsSummary for {} {}: no FlowPaths found", flowId, maxFlows);
- return flowPaths;
- }
-
- Collections.sort(allFlows);
-
- for (FlowPath flow : allFlows) {
- flow.setFlowEntryMatch(null);
-
- // start from desired flowId
- if (flow.flowId().value() < flowId.value()) {
- continue;
- }
-
- // Summarize by making null flow entry fields that are not relevant to report
- for (FlowEntry flowEntry : flow.dataPath().flowEntries()) {
- flowEntry.setFlowEntryActions(null);
- flowEntry.setFlowEntryMatch(null);
- }
-
- flowPaths.add(flow);
- if (maxFlows != 0 && flowPaths.size() >= maxFlows) {
- break;
- }
- }
-
- if (flowPaths.isEmpty()) {
- log.debug("Get FlowPathsSummary {} {}: no FlowPaths found", flowId, maxFlows);
- } else {
- log.debug("Get FlowPathsSummary for {} {}: FlowPaths were found", flowId, maxFlows);
- }
-
- return flowPaths;
- */
+ public ArrayList<IFlowPath> getAllFlowsSummary(FlowId flowId,
+ int maxFlows) {
+ return FlowDatabaseOperation.getAllFlowsSummary(dbHandlerApi, flowId,
+ maxFlows);
}
/**
- * Get all installed flows by all installers.
- *
- * @return the Flow Paths if found, otherwise null.
- */
- @Override
- public ArrayList<FlowPath> getAllFlows() {
- Iterable<IFlowPath> flowPathsObj = null;
- ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>();
-
- try {
- if ((flowPathsObj = op.getAllFlowPaths()) != null) {
- log.debug("Get all FlowPaths: found FlowPaths");
- } else {
- log.debug("Get all FlowPaths: no FlowPaths found");
- }
- } catch (Exception e) {
- // TODO: handle exceptions
- op.rollback();
- log.error(":getAllFlowPaths failed");
- }
- if ((flowPathsObj == null) || (flowPathsObj.iterator().hasNext() == false)) {
- op.commit();
- return flowPaths; // No Flows found
- }
-
- for (IFlowPath flowObj : flowPathsObj) {
- //
- // Extract the Flow state
- //
- FlowPath flowPath = extractFlowPath(flowObj);
- if (flowPath != null)
- flowPaths.add(flowPath);
- }
-
- op.commit();
-
- return flowPaths;
- }
-
- /**
* Get all Flows information, without the associated Flow Entries.
*
* @return all Flows information, without the associated Flow Entries.
*/
public ArrayList<IFlowPath> getAllFlowsWithoutFlowEntries() {
- Iterable<IFlowPath> flowPathsObj = null;
- ArrayList<IFlowPath> flowPathsObjArray = new ArrayList<IFlowPath>();
- ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>();
-
- op.commit();
-
- try {
- if ((flowPathsObj = op.getAllFlowPaths()) != null) {
- log.debug("Get all FlowPaths: found FlowPaths");
- } else {
- log.debug("Get all FlowPaths: no FlowPaths found");
- }
- } catch (Exception e) {
- // TODO: handle exceptions
- op.rollback();
- log.error(":getAllFlowPaths failed");
- }
- if ((flowPathsObj == null) || (flowPathsObj.iterator().hasNext() == false)) {
- return new ArrayList<IFlowPath>(); // No Flows found
- }
-
- for (IFlowPath flowObj : flowPathsObj){
- flowPathsObjArray.add(flowObj);
- }
- /*
- for (IFlowPath flowObj : flowPathsObj) {
- //
- // Extract the Flow state
- //
- FlowPath flowPath = extractFlowPath(flowObj);
- if (flowPath != null)
- flowPaths.add(flowPath);
- }
- */
-
- //conn.endTx(Transaction.COMMIT);
-
- return flowPathsObjArray;
- }
-
- /**
- * Extract Flow Path State from a Titan Database Object @ref IFlowPath.
- *
- * @param flowObj the object to extract the Flow Path State from.
- * @return the extracted Flow Path State.
- */
- private FlowPath extractFlowPath(IFlowPath flowObj) {
- //
- // Extract the Flow state
- //
- String flowIdStr = flowObj.getFlowId();
- String installerIdStr = flowObj.getInstallerId();
- Long flowPathFlags = flowObj.getFlowPathFlags();
- String srcSwitchStr = flowObj.getSrcSwitch();
- Short srcPortShort = flowObj.getSrcPort();
- String dstSwitchStr = flowObj.getDstSwitch();
- Short dstPortShort = flowObj.getDstPort();
-
- if ((flowIdStr == null) ||
- (installerIdStr == null) ||
- (flowPathFlags == null) ||
- (srcSwitchStr == null) ||
- (srcPortShort == null) ||
- (dstSwitchStr == null) ||
- (dstPortShort == null)) {
- // TODO: A work-around, becauuse of some bogus database objects
- return null;
- }
-
- FlowPath flowPath = new FlowPath();
- flowPath.setFlowId(new FlowId(flowIdStr));
- flowPath.setInstallerId(new CallerId(installerIdStr));
- flowPath.setFlowPathFlags(new FlowPathFlags(flowPathFlags));
- flowPath.dataPath().srcPort().setDpid(new Dpid(srcSwitchStr));
- flowPath.dataPath().srcPort().setPort(new Port(srcPortShort));
- flowPath.dataPath().dstPort().setDpid(new Dpid(dstSwitchStr));
- flowPath.dataPath().dstPort().setPort(new Port(dstPortShort));
- //
- // Extract the match conditions common for all Flow Entries
- //
- {
- FlowEntryMatch match = new FlowEntryMatch();
- String matchSrcMac = flowObj.getMatchSrcMac();
- if (matchSrcMac != null)
- match.enableSrcMac(MACAddress.valueOf(matchSrcMac));
- String matchDstMac = flowObj.getMatchDstMac();
- if (matchDstMac != null)
- match.enableDstMac(MACAddress.valueOf(matchDstMac));
- Short matchEthernetFrameType = flowObj.getMatchEthernetFrameType();
- if (matchEthernetFrameType != null)
- match.enableEthernetFrameType(matchEthernetFrameType);
- Short matchVlanId = flowObj.getMatchVlanId();
- if (matchVlanId != null)
- match.enableVlanId(matchVlanId);
- Byte matchVlanPriority = flowObj.getMatchVlanPriority();
- if (matchVlanPriority != null)
- match.enableVlanPriority(matchVlanPriority);
- String matchSrcIPv4Net = flowObj.getMatchSrcIPv4Net();
- if (matchSrcIPv4Net != null)
- match.enableSrcIPv4Net(new IPv4Net(matchSrcIPv4Net));
- String matchDstIPv4Net = flowObj.getMatchDstIPv4Net();
- if (matchDstIPv4Net != null)
- match.enableDstIPv4Net(new IPv4Net(matchDstIPv4Net));
- Byte matchIpProto = flowObj.getMatchIpProto();
- if (matchIpProto != null)
- match.enableIpProto(matchIpProto);
- Byte matchIpToS = flowObj.getMatchIpToS();
- if (matchIpToS != null)
- match.enableIpToS(matchIpToS);
- Short matchSrcTcpUdpPort = flowObj.getMatchSrcTcpUdpPort();
- if (matchSrcTcpUdpPort != null)
- match.enableSrcTcpUdpPort(matchSrcTcpUdpPort);
- Short matchDstTcpUdpPort = flowObj.getMatchDstTcpUdpPort();
- if (matchDstTcpUdpPort != null)
- match.enableDstTcpUdpPort(matchDstTcpUdpPort);
-
- flowPath.setFlowEntryMatch(match);
- }
- //
- // Extract the actions for the first Flow Entry
- //
- {
- String actionsStr = flowObj.getActions();
- if (actionsStr != null) {
- FlowEntryActions flowEntryActions = new FlowEntryActions(actionsStr);
- flowPath.setFlowEntryActions(flowEntryActions);
- }
- }
-
- //
- // Extract all Flow Entries
- //
- Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries();
- for (IFlowEntry flowEntryObj : flowEntries) {
- FlowEntry flowEntry = extractFlowEntry(flowEntryObj);
- if (flowEntry == null)
- continue;
- flowPath.dataPath().flowEntries().add(flowEntry);
- }
-
- return flowPath;
- }
-
- /**
- * Extract Flow Entry State from a Titan Database Object @ref IFlowEntry.
- *
- * @param flowEntryObj the object to extract the Flow Entry State from.
- * @return the extracted Flow Entry State.
- */
- private FlowEntry extractFlowEntry(IFlowEntry flowEntryObj) {
- String flowEntryIdStr = flowEntryObj.getFlowEntryId();
- String switchDpidStr = flowEntryObj.getSwitchDpid();
- String userState = flowEntryObj.getUserState();
- String switchState = flowEntryObj.getSwitchState();
-
- if ((flowEntryIdStr == null) ||
- (switchDpidStr == null) ||
- (userState == null) ||
- (switchState == null)) {
- // TODO: A work-around, becauuse of some bogus database objects
- return null;
- }
-
- FlowEntry flowEntry = new FlowEntry();
- flowEntry.setFlowEntryId(new FlowEntryId(flowEntryIdStr));
- flowEntry.setDpid(new Dpid(switchDpidStr));
-
- //
- // Extract the match conditions
- //
- FlowEntryMatch match = new FlowEntryMatch();
- Short matchInPort = flowEntryObj.getMatchInPort();
- if (matchInPort != null)
- match.enableInPort(new Port(matchInPort));
- String matchSrcMac = flowEntryObj.getMatchSrcMac();
- if (matchSrcMac != null)
- match.enableSrcMac(MACAddress.valueOf(matchSrcMac));
- String matchDstMac = flowEntryObj.getMatchDstMac();
- if (matchDstMac != null)
- match.enableDstMac(MACAddress.valueOf(matchDstMac));
- Short matchEthernetFrameType = flowEntryObj.getMatchEthernetFrameType();
- if (matchEthernetFrameType != null)
- match.enableEthernetFrameType(matchEthernetFrameType);
- Short matchVlanId = flowEntryObj.getMatchVlanId();
- if (matchVlanId != null)
- match.enableVlanId(matchVlanId);
- Byte matchVlanPriority = flowEntryObj.getMatchVlanPriority();
- if (matchVlanPriority != null)
- match.enableVlanPriority(matchVlanPriority);
- String matchSrcIPv4Net = flowEntryObj.getMatchSrcIPv4Net();
- if (matchSrcIPv4Net != null)
- match.enableSrcIPv4Net(new IPv4Net(matchSrcIPv4Net));
- String matchDstIPv4Net = flowEntryObj.getMatchDstIPv4Net();
- if (matchDstIPv4Net != null)
- match.enableDstIPv4Net(new IPv4Net(matchDstIPv4Net));
- Byte matchIpProto = flowEntryObj.getMatchIpProto();
- if (matchIpProto != null)
- match.enableIpProto(matchIpProto);
- Byte matchIpToS = flowEntryObj.getMatchIpToS();
- if (matchIpToS != null)
- match.enableIpToS(matchIpToS);
- Short matchSrcTcpUdpPort = flowEntryObj.getMatchSrcTcpUdpPort();
- if (matchSrcTcpUdpPort != null)
- match.enableSrcTcpUdpPort(matchSrcTcpUdpPort);
- Short matchDstTcpUdpPort = flowEntryObj.getMatchDstTcpUdpPort();
- if (matchDstTcpUdpPort != null)
- match.enableDstTcpUdpPort(matchDstTcpUdpPort);
- flowEntry.setFlowEntryMatch(match);
-
- //
- // Extract the actions
- //
- FlowEntryActions actions = new FlowEntryActions();
- String actionsStr = flowEntryObj.getActions();
- if (actionsStr != null)
- actions = new FlowEntryActions(actionsStr);
- flowEntry.setFlowEntryActions(actions);
- flowEntry.setFlowEntryUserState(FlowEntryUserState.valueOf(userState));
- flowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.valueOf(switchState));
- //
- // TODO: Take care of FlowEntryErrorState.
- //
- return flowEntry;
+ return FlowDatabaseOperation.getAllFlowsWithoutFlowEntries(dbHandlerApi);
}
/**
@@ -1573,108 +396,29 @@
// Instead, let the Flow reconciliation thread take care of it.
//
- // We need the DataPath to populate the Network MAP
- DataPath dataPath = new DataPath();
- dataPath.setSrcPort(flowPath.dataPath().srcPort());
- dataPath.setDstPort(flowPath.dataPath().dstPort());
-
- //
- // Prepare the computed Flow Path
- //
- FlowPath computedFlowPath = new FlowPath();
- computedFlowPath.setFlowId(new FlowId(flowPath.flowId().value()));
- computedFlowPath.setInstallerId(new CallerId(flowPath.installerId().value()));
- computedFlowPath.setFlowPathFlags(new FlowPathFlags(flowPath.flowPathFlags().flags()));
- computedFlowPath.setDataPath(dataPath);
- computedFlowPath.setFlowEntryMatch(new FlowEntryMatch(flowPath.flowEntryMatch()));
- computedFlowPath.setFlowEntryActions(new FlowEntryActions(flowPath.flowEntryActions()));
-
FlowId flowId = new FlowId();
- String dataPathSummaryStr = dataPath.dataPathSummary();
- if (! addFlow(computedFlowPath, flowId, dataPathSummaryStr))
+ if (! addFlow(flowPath, flowId))
return null;
- // TODO: Mark the flow for maintenance purpose
-
- return (computedFlowPath);
+ return (flowPath);
}
/**
- * Reconcile a flow.
+ * Get the collection of my switches.
*
- * @param flowObj the flow that needs to be reconciliated.
- * @param newDataPath the new data path to use.
- * @return true on success, otherwise false.
+ * @return the collection of my switches.
*/
- public boolean reconcileFlow(IFlowPath flowObj, DataPath newDataPath) {
- Map<Long, IOFSwitch> mySwitches = floodlightProvider.getSwitches();
-
- //
- // Set the incoming port matching and the outgoing port output
- // actions for each flow entry.
- //
- int idx = 0;
- for (FlowEntry flowEntry : newDataPath.flowEntries()) {
- // Set the incoming port matching
- FlowEntryMatch flowEntryMatch = new FlowEntryMatch();
- flowEntry.setFlowEntryMatch(flowEntryMatch);
- flowEntryMatch.enableInPort(flowEntry.inPort());
-
- //
- // Set the actions
- //
- FlowEntryActions flowEntryActions = flowEntry.flowEntryActions();
- //
- // If the first Flow Entry, copy the Flow Path actions to it
- //
- if (idx == 0) {
- String actionsStr = flowObj.getActions();
- if (actionsStr != null) {
- FlowEntryActions flowActions = new FlowEntryActions(actionsStr);
- for (FlowEntryAction action : flowActions.actions())
- flowEntryActions.addAction(action);
- }
- }
- idx++;
- //
- // Add the outgoing port output action
- //
- FlowEntryAction flowEntryAction = new FlowEntryAction();
- flowEntryAction.setActionOutput(flowEntry.outPort());
- flowEntryActions.addAction(flowEntryAction);
- }
-
- //
- // Remove the old Flow Entries, and add the new Flow Entries
- //
- Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries();
- LinkedList<IFlowEntry> deleteFlowEntries = new LinkedList<IFlowEntry>();
- for (IFlowEntry flowEntryObj : flowEntries) {
- flowEntryObj.setUserState("FE_USER_DELETE");
- flowEntryObj.setSwitchState("FE_SWITCH_NOT_UPDATED");
- }
- for (FlowEntry flowEntry : newDataPath.flowEntries()) {
- addFlowEntry(flowObj, flowEntry);
- }
-
- //
- // Set the Data Path Summary
- //
- String dataPathSummaryStr = newDataPath.dataPathSummary();
- flowObj.setDataPathSummary(dataPathSummaryStr);
-
- return true;
+ public Map<Long, IOFSwitch> getMySwitches() {
+ return floodlightProvider.getSwitches();
}
/**
- * Reconcile all flows in a set.
+ * Get the network topology.
*
- * @param flowObjSet the set of flows that need to be reconciliated.
+ * @return the network topology.
*/
- public void reconcileFlows(Iterable<IFlowPath> flowObjSet) {
- if (! flowObjSet.iterator().hasNext())
- return;
- // TODO: Not implemented/used yet.
+ public Topology getTopology() {
+ return flowEventHandler.getTopology();
}
/**
@@ -1685,313 +429,15 @@
* @param flowEntryObj the flow entry object to install.
* @return true on success, otherwise false.
*/
- public boolean installFlowEntry(IOFSwitch mySwitch, IFlowPath flowObj,
+ private boolean installFlowEntry(IOFSwitch mySwitch, IFlowPath flowObj,
IFlowEntry flowEntryObj) {
- String flowEntryIdStr = flowEntryObj.getFlowEntryId();
- if (flowEntryIdStr == null)
- return false;
- FlowEntryId flowEntryId = new FlowEntryId(flowEntryIdStr);
- String userState = flowEntryObj.getUserState();
- if (userState == null)
- return false;
-
- //
- // Create the Open Flow Flow Modification Entry to push
- //
- OFFlowMod fm = (OFFlowMod) floodlightProvider.getOFMessageFactory()
- .getMessage(OFType.FLOW_MOD);
- long cookie = flowEntryId.value();
-
- short flowModCommand = OFFlowMod.OFPFC_ADD;
- if (userState.equals("FE_USER_ADD")) {
- flowModCommand = OFFlowMod.OFPFC_ADD;
- } else if (userState.equals("FE_USER_MODIFY")) {
- flowModCommand = OFFlowMod.OFPFC_MODIFY_STRICT;
- } else if (userState.equals("FE_USER_DELETE")) {
- flowModCommand = OFFlowMod.OFPFC_DELETE_STRICT;
- } else {
- // Unknown user state. Ignore the entry
- log.debug("Flow Entry ignored (FlowEntryId = {}): unknown user state {}",
- flowEntryId.toString(), userState);
- return false;
- }
-
- //
- // Fetch the match conditions.
- //
- // NOTE: The Flow matching conditions common for all Flow Entries are
- // used ONLY if a Flow Entry does NOT have the corresponding matching
- // condition set.
- //
- OFMatch match = new OFMatch();
- match.setWildcards(OFMatch.OFPFW_ALL);
-
- // Match the Incoming Port
- Short matchInPort = flowEntryObj.getMatchInPort();
- if (matchInPort != null) {
- match.setInputPort(matchInPort);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_IN_PORT);
- }
-
- // Match the Source MAC address
- String matchSrcMac = flowEntryObj.getMatchSrcMac();
- if (matchSrcMac == null)
- matchSrcMac = flowObj.getMatchSrcMac();
- if (matchSrcMac != null) {
- match.setDataLayerSource(matchSrcMac);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_SRC);
- }
-
- // Match the Destination MAC address
- String matchDstMac = flowEntryObj.getMatchDstMac();
- if (matchDstMac == null)
- matchDstMac = flowObj.getMatchDstMac();
- if (matchDstMac != null) {
- match.setDataLayerDestination(matchDstMac);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_DST);
- }
-
- // Match the Ethernet Frame Type
- Short matchEthernetFrameType = flowEntryObj.getMatchEthernetFrameType();
- if (matchEthernetFrameType == null)
- matchEthernetFrameType = flowObj.getMatchEthernetFrameType();
- if (matchEthernetFrameType != null) {
- match.setDataLayerType(matchEthernetFrameType);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
- }
-
- // Match the VLAN ID
- Short matchVlanId = flowEntryObj.getMatchVlanId();
- if (matchVlanId == null)
- matchVlanId = flowObj.getMatchVlanId();
- if (matchVlanId != null) {
- match.setDataLayerVirtualLan(matchVlanId);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_VLAN);
- }
-
- // Match the VLAN priority
- Byte matchVlanPriority = flowEntryObj.getMatchVlanPriority();
- if (matchVlanPriority == null)
- matchVlanPriority = flowObj.getMatchVlanPriority();
- if (matchVlanPriority != null) {
- match.setDataLayerVirtualLanPriorityCodePoint(matchVlanPriority);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_VLAN_PCP);
- }
-
- // Match the Source IPv4 Network prefix
- String matchSrcIPv4Net = flowEntryObj.getMatchSrcIPv4Net();
- if (matchSrcIPv4Net == null)
- matchSrcIPv4Net = flowObj.getMatchSrcIPv4Net();
- if (matchSrcIPv4Net != null) {
- match.setFromCIDR(matchSrcIPv4Net, OFMatch.STR_NW_SRC);
- }
-
- // Natch the Destination IPv4 Network prefix
- String matchDstIPv4Net = flowEntryObj.getMatchDstIPv4Net();
- if (matchDstIPv4Net == null)
- matchDstIPv4Net = flowObj.getMatchDstIPv4Net();
- if (matchDstIPv4Net != null) {
- match.setFromCIDR(matchDstIPv4Net, OFMatch.STR_NW_DST);
- }
-
- // Match the IP protocol
- Byte matchIpProto = flowEntryObj.getMatchIpProto();
- if (matchIpProto == null)
- matchIpProto = flowObj.getMatchIpProto();
- if (matchIpProto != null) {
- match.setNetworkProtocol(matchIpProto);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_NW_PROTO);
- }
-
- // Match the IP ToS (DSCP field, 6 bits)
- Byte matchIpToS = flowEntryObj.getMatchIpToS();
- if (matchIpToS == null)
- matchIpToS = flowObj.getMatchIpToS();
- if (matchIpToS != null) {
- match.setNetworkTypeOfService(matchIpToS);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_NW_TOS);
- }
-
- // Match the Source TCP/UDP port
- Short matchSrcTcpUdpPort = flowEntryObj.getMatchSrcTcpUdpPort();
- if (matchSrcTcpUdpPort == null)
- matchSrcTcpUdpPort = flowObj.getMatchSrcTcpUdpPort();
- if (matchSrcTcpUdpPort != null) {
- match.setTransportSource(matchSrcTcpUdpPort);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_TP_SRC);
- }
-
- // Match the Destination TCP/UDP port
- Short matchDstTcpUdpPort = flowEntryObj.getMatchDstTcpUdpPort();
- if (matchDstTcpUdpPort == null)
- matchDstTcpUdpPort = flowObj.getMatchDstTcpUdpPort();
- if (matchDstTcpUdpPort != null) {
- match.setTransportDestination(matchDstTcpUdpPort);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_TP_DST);
- }
-
- //
- // Fetch the actions
- //
- Short actionOutputPort = null;
- List<OFAction> openFlowActions = new ArrayList<OFAction>();
- int actionsLen = 0;
- FlowEntryActions flowEntryActions = null;
- String actionsStr = flowEntryObj.getActions();
- if (actionsStr != null)
- flowEntryActions = new FlowEntryActions(actionsStr);
- for (FlowEntryAction action : flowEntryActions.actions()) {
- ActionOutput actionOutput = action.actionOutput();
- ActionSetVlanId actionSetVlanId = action.actionSetVlanId();
- ActionSetVlanPriority actionSetVlanPriority = action.actionSetVlanPriority();
- ActionStripVlan actionStripVlan = action.actionStripVlan();
- ActionSetEthernetAddr actionSetEthernetSrcAddr = action.actionSetEthernetSrcAddr();
- ActionSetEthernetAddr actionSetEthernetDstAddr = action.actionSetEthernetDstAddr();
- ActionSetIPv4Addr actionSetIPv4SrcAddr = action.actionSetIPv4SrcAddr();
- ActionSetIPv4Addr actionSetIPv4DstAddr = action.actionSetIPv4DstAddr();
- ActionSetIpToS actionSetIpToS = action.actionSetIpToS();
- ActionSetTcpUdpPort actionSetTcpUdpSrcPort = action.actionSetTcpUdpSrcPort();
- ActionSetTcpUdpPort actionSetTcpUdpDstPort = action.actionSetTcpUdpDstPort();
- ActionEnqueue actionEnqueue = action.actionEnqueue();
-
- if (actionOutput != null) {
- actionOutputPort = actionOutput.port().value();
- // XXX: The max length is hard-coded for now
- OFActionOutput ofa =
- new OFActionOutput(actionOutput.port().value(),
- (short)0xffff);
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionSetVlanId != null) {
- OFActionVirtualLanIdentifier ofa =
- new OFActionVirtualLanIdentifier(actionSetVlanId.vlanId());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionSetVlanPriority != null) {
- OFActionVirtualLanPriorityCodePoint ofa =
- new OFActionVirtualLanPriorityCodePoint(actionSetVlanPriority.vlanPriority());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionStripVlan != null) {
- if (actionStripVlan.stripVlan() == true) {
- OFActionStripVirtualLan ofa = new OFActionStripVirtualLan();
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
- }
-
- if (actionSetEthernetSrcAddr != null) {
- OFActionDataLayerSource ofa =
- new OFActionDataLayerSource(actionSetEthernetSrcAddr.addr().toBytes());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionSetEthernetDstAddr != null) {
- OFActionDataLayerDestination ofa =
- new OFActionDataLayerDestination(actionSetEthernetDstAddr.addr().toBytes());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionSetIPv4SrcAddr != null) {
- OFActionNetworkLayerSource ofa =
- new OFActionNetworkLayerSource(actionSetIPv4SrcAddr.addr().value());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionSetIPv4DstAddr != null) {
- OFActionNetworkLayerDestination ofa =
- new OFActionNetworkLayerDestination(actionSetIPv4DstAddr.addr().value());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionSetIpToS != null) {
- OFActionNetworkTypeOfService ofa =
- new OFActionNetworkTypeOfService(actionSetIpToS.ipToS());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionSetTcpUdpSrcPort != null) {
- OFActionTransportLayerSource ofa =
- new OFActionTransportLayerSource(actionSetTcpUdpSrcPort.port());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionSetTcpUdpDstPort != null) {
- OFActionTransportLayerDestination ofa =
- new OFActionTransportLayerDestination(actionSetTcpUdpDstPort.port());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionEnqueue != null) {
- OFActionEnqueue ofa =
- new OFActionEnqueue(actionEnqueue.port().value(),
- actionEnqueue.queueId());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
- }
-
- fm.setIdleTimeout(FLOWMOD_DEFAULT_IDLE_TIMEOUT)
- .setHardTimeout(FLOWMOD_DEFAULT_HARD_TIMEOUT)
- .setPriority(PRIORITY_DEFAULT)
- .setBufferId(OFPacketOut.BUFFER_ID_NONE)
- .setCookie(cookie)
- .setCommand(flowModCommand)
- .setMatch(match)
- .setActions(openFlowActions)
- .setLengthU(OFFlowMod.MINIMUM_LENGTH + actionsLen);
- fm.setOutPort(OFPort.OFPP_NONE.getValue());
- if ((flowModCommand == OFFlowMod.OFPFC_DELETE) ||
- (flowModCommand == OFFlowMod.OFPFC_DELETE_STRICT)) {
- if (actionOutputPort != null)
- fm.setOutPort(actionOutputPort);
- }
-
- //
- // TODO: Set the following flag
- // fm.setFlags(OFFlowMod.OFPFF_SEND_FLOW_REM);
- // See method ForwardingBase::pushRoute()
- //
-
- //
- // Write the message to the switch
- //
- log.debug("MEASUREMENT: Installing flow entry " + userState +
- " into switch DPID: " +
- mySwitch.getStringId() +
- " flowEntryId: " + flowEntryId.toString() +
- " srcMac: " + matchSrcMac + " dstMac: " + matchDstMac +
- " inPort: " + matchInPort + " outPort: " + actionOutputPort
- );
- try {
- messageDamper.write(mySwitch, fm, null);
- mySwitch.flush();
- //
- // TODO: We should use the OpenFlow Barrier mechanism
- // to check for errors, and update the SwitchState
- // for a flow entry after the Barrier message is
- // is received.
- //
- flowEntryObj.setSwitchState("FE_SWITCH_UPDATED");
- } catch (IOException e) {
- log.error("Failure writing flow mod from network map", e);
- return false;
- }
-
- return true;
+ if (enableFlowPusher) {
+ return pusher.add(mySwitch, flowObj, flowEntryObj);
+ } else {
+ return FlowSwitchOperation.installFlowEntry(
+ floodlightProvider.getOFMessageFactory(),
+ messageDamper, mySwitch, flowObj, flowEntryObj);
+ }
}
/**
@@ -2002,311 +448,15 @@
* @param flowEntry the flow entry to install.
* @return true on success, otherwise false.
*/
- public boolean installFlowEntry(IOFSwitch mySwitch, FlowPath flowPath,
+ private boolean installFlowEntry(IOFSwitch mySwitch, FlowPath flowPath,
FlowEntry flowEntry) {
- //
- // Create the OpenFlow Flow Modification Entry to push
- //
- OFFlowMod fm = (OFFlowMod) floodlightProvider.getOFMessageFactory()
- .getMessage(OFType.FLOW_MOD);
- long cookie = flowEntry.flowEntryId().value();
-
- short flowModCommand = OFFlowMod.OFPFC_ADD;
- if (flowEntry.flowEntryUserState() == FlowEntryUserState.FE_USER_ADD) {
- flowModCommand = OFFlowMod.OFPFC_ADD;
- } else if (flowEntry.flowEntryUserState() == FlowEntryUserState.FE_USER_MODIFY) {
- flowModCommand = OFFlowMod.OFPFC_MODIFY_STRICT;
- } else if (flowEntry.flowEntryUserState() == FlowEntryUserState.FE_USER_DELETE) {
- flowModCommand = OFFlowMod.OFPFC_DELETE_STRICT;
- } else {
- // Unknown user state. Ignore the entry
- log.debug("Flow Entry ignored (FlowEntryId = {}): unknown user state {}",
- flowEntry.flowEntryId().toString(),
- flowEntry.flowEntryUserState());
- return false;
- }
-
- //
- // Fetch the match conditions.
- //
- // NOTE: The Flow matching conditions common for all Flow Entries are
- // used ONLY if a Flow Entry does NOT have the corresponding matching
- // condition set.
- //
- OFMatch match = new OFMatch();
- match.setWildcards(OFMatch.OFPFW_ALL);
- FlowEntryMatch flowPathMatch = flowPath.flowEntryMatch();
- FlowEntryMatch flowEntryMatch = flowEntry.flowEntryMatch();
-
- // Match the Incoming Port
- Port matchInPort = flowEntryMatch.inPort();
- if (matchInPort != null) {
- match.setInputPort(matchInPort.value());
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_IN_PORT);
- }
-
- // Match the Source MAC address
- MACAddress matchSrcMac = flowEntryMatch.srcMac();
- if ((matchSrcMac == null) && (flowPathMatch != null)) {
- matchSrcMac = flowPathMatch.srcMac();
- }
- if (matchSrcMac != null) {
- match.setDataLayerSource(matchSrcMac.toString());
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_SRC);
- }
-
- // Match the Destination MAC address
- MACAddress matchDstMac = flowEntryMatch.dstMac();
- if ((matchDstMac == null) && (flowPathMatch != null)) {
- matchDstMac = flowPathMatch.dstMac();
- }
- if (matchDstMac != null) {
- match.setDataLayerDestination(matchDstMac.toString());
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_DST);
- }
-
- // Match the Ethernet Frame Type
- Short matchEthernetFrameType = flowEntryMatch.ethernetFrameType();
- if ((matchEthernetFrameType == null) && (flowPathMatch != null)) {
- matchEthernetFrameType = flowPathMatch.ethernetFrameType();
- }
- if (matchEthernetFrameType != null) {
- match.setDataLayerType(matchEthernetFrameType);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
- }
-
- // Match the VLAN ID
- Short matchVlanId = flowEntryMatch.vlanId();
- if ((matchVlanId == null) && (flowPathMatch != null)) {
- matchVlanId = flowPathMatch.vlanId();
- }
- if (matchVlanId != null) {
- match.setDataLayerVirtualLan(matchVlanId);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_VLAN);
- }
-
- // Match the VLAN priority
- Byte matchVlanPriority = flowEntryMatch.vlanPriority();
- if ((matchVlanPriority == null) && (flowPathMatch != null)) {
- matchVlanPriority = flowPathMatch.vlanPriority();
- }
- if (matchVlanPriority != null) {
- match.setDataLayerVirtualLanPriorityCodePoint(matchVlanPriority);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_VLAN_PCP);
- }
-
- // Match the Source IPv4 Network prefix
- IPv4Net matchSrcIPv4Net = flowEntryMatch.srcIPv4Net();
- if ((matchSrcIPv4Net == null) && (flowPathMatch != null)) {
- matchSrcIPv4Net = flowPathMatch.srcIPv4Net();
- }
- if (matchSrcIPv4Net != null) {
- match.setFromCIDR(matchSrcIPv4Net.toString(), OFMatch.STR_NW_SRC);
- }
-
- // Natch the Destination IPv4 Network prefix
- IPv4Net matchDstIPv4Net = flowEntryMatch.dstIPv4Net();
- if ((matchDstIPv4Net == null) && (flowPathMatch != null)) {
- matchDstIPv4Net = flowPathMatch.dstIPv4Net();
- }
- if (matchDstIPv4Net != null) {
- match.setFromCIDR(matchDstIPv4Net.toString(), OFMatch.STR_NW_DST);
- }
-
- // Match the IP protocol
- Byte matchIpProto = flowEntryMatch.ipProto();
- if ((matchIpProto == null) && (flowPathMatch != null)) {
- matchIpProto = flowPathMatch.ipProto();
- }
- if (matchIpProto != null) {
- match.setNetworkProtocol(matchIpProto);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_NW_PROTO);
- }
-
- // Match the IP ToS (DSCP field, 6 bits)
- Byte matchIpToS = flowEntryMatch.ipToS();
- if ((matchIpToS == null) && (flowPathMatch != null)) {
- matchIpToS = flowPathMatch.ipToS();
- }
- if (matchIpToS != null) {
- match.setNetworkTypeOfService(matchIpToS);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_NW_TOS);
- }
-
- // Match the Source TCP/UDP port
- Short matchSrcTcpUdpPort = flowEntryMatch.srcTcpUdpPort();
- if ((matchSrcTcpUdpPort == null) && (flowPathMatch != null)) {
- matchSrcTcpUdpPort = flowPathMatch.srcTcpUdpPort();
- }
- if (matchSrcTcpUdpPort != null) {
- match.setTransportSource(matchSrcTcpUdpPort);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_TP_SRC);
- }
-
- // Match the Destination TCP/UDP port
- Short matchDstTcpUdpPort = flowEntryMatch.dstTcpUdpPort();
- if ((matchDstTcpUdpPort == null) && (flowPathMatch != null)) {
- matchDstTcpUdpPort = flowPathMatch.dstTcpUdpPort();
- }
- if (matchDstTcpUdpPort != null) {
- match.setTransportDestination(matchDstTcpUdpPort);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_TP_DST);
- }
-
- //
- // Fetch the actions
- //
- Short actionOutputPort = null;
- List<OFAction> openFlowActions = new ArrayList<OFAction>();
- int actionsLen = 0;
- FlowEntryActions flowEntryActions = flowEntry.flowEntryActions();
- //
- for (FlowEntryAction action : flowEntryActions.actions()) {
- ActionOutput actionOutput = action.actionOutput();
- ActionSetVlanId actionSetVlanId = action.actionSetVlanId();
- ActionSetVlanPriority actionSetVlanPriority = action.actionSetVlanPriority();
- ActionStripVlan actionStripVlan = action.actionStripVlan();
- ActionSetEthernetAddr actionSetEthernetSrcAddr = action.actionSetEthernetSrcAddr();
- ActionSetEthernetAddr actionSetEthernetDstAddr = action.actionSetEthernetDstAddr();
- ActionSetIPv4Addr actionSetIPv4SrcAddr = action.actionSetIPv4SrcAddr();
- ActionSetIPv4Addr actionSetIPv4DstAddr = action.actionSetIPv4DstAddr();
- ActionSetIpToS actionSetIpToS = action.actionSetIpToS();
- ActionSetTcpUdpPort actionSetTcpUdpSrcPort = action.actionSetTcpUdpSrcPort();
- ActionSetTcpUdpPort actionSetTcpUdpDstPort = action.actionSetTcpUdpDstPort();
- ActionEnqueue actionEnqueue = action.actionEnqueue();
-
- if (actionOutput != null) {
- actionOutputPort = actionOutput.port().value();
- // XXX: The max length is hard-coded for now
- OFActionOutput ofa =
- new OFActionOutput(actionOutput.port().value(),
- (short)0xffff);
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionSetVlanId != null) {
- OFActionVirtualLanIdentifier ofa =
- new OFActionVirtualLanIdentifier(actionSetVlanId.vlanId());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionSetVlanPriority != null) {
- OFActionVirtualLanPriorityCodePoint ofa =
- new OFActionVirtualLanPriorityCodePoint(actionSetVlanPriority.vlanPriority());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionStripVlan != null) {
- if (actionStripVlan.stripVlan() == true) {
- OFActionStripVirtualLan ofa = new OFActionStripVirtualLan();
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
- }
-
- if (actionSetEthernetSrcAddr != null) {
- OFActionDataLayerSource ofa =
- new OFActionDataLayerSource(actionSetEthernetSrcAddr.addr().toBytes());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionSetEthernetDstAddr != null) {
- OFActionDataLayerDestination ofa =
- new OFActionDataLayerDestination(actionSetEthernetDstAddr.addr().toBytes());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionSetIPv4SrcAddr != null) {
- OFActionNetworkLayerSource ofa =
- new OFActionNetworkLayerSource(actionSetIPv4SrcAddr.addr().value());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionSetIPv4DstAddr != null) {
- OFActionNetworkLayerDestination ofa =
- new OFActionNetworkLayerDestination(actionSetIPv4DstAddr.addr().value());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionSetIpToS != null) {
- OFActionNetworkTypeOfService ofa =
- new OFActionNetworkTypeOfService(actionSetIpToS.ipToS());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionSetTcpUdpSrcPort != null) {
- OFActionTransportLayerSource ofa =
- new OFActionTransportLayerSource(actionSetTcpUdpSrcPort.port());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionSetTcpUdpDstPort != null) {
- OFActionTransportLayerDestination ofa =
- new OFActionTransportLayerDestination(actionSetTcpUdpDstPort.port());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
-
- if (actionEnqueue != null) {
- OFActionEnqueue ofa =
- new OFActionEnqueue(actionEnqueue.port().value(),
- actionEnqueue.queueId());
- openFlowActions.add(ofa);
- actionsLen += ofa.getLength();
- }
- }
-
- fm.setIdleTimeout(FLOWMOD_DEFAULT_IDLE_TIMEOUT)
- .setHardTimeout(FLOWMOD_DEFAULT_HARD_TIMEOUT)
- .setPriority(PRIORITY_DEFAULT)
- .setBufferId(OFPacketOut.BUFFER_ID_NONE)
- .setCookie(cookie)
- .setCommand(flowModCommand)
- .setMatch(match)
- .setActions(openFlowActions)
- .setLengthU(OFFlowMod.MINIMUM_LENGTH + actionsLen);
- fm.setOutPort(OFPort.OFPP_NONE.getValue());
- if ((flowModCommand == OFFlowMod.OFPFC_DELETE) ||
- (flowModCommand == OFFlowMod.OFPFC_DELETE_STRICT)) {
- if (actionOutputPort != null)
- fm.setOutPort(actionOutputPort);
- }
-
- //
- // TODO: Set the following flag
- // fm.setFlags(OFFlowMod.OFPFF_SEND_FLOW_REM);
- // See method ForwardingBase::pushRoute()
- //
-
- //
- // Write the message to the switch
- //
- try {
- messageDamper.write(mySwitch, fm, null);
- mySwitch.flush();
- //
- // TODO: We should use the OpenFlow Barrier mechanism
- // to check for errors, and update the SwitchState
- // for a flow entry after the Barrier message is
- // is received.
- //
- // TODO: The FlowEntry Object in Titan should be set
- // to FE_SWITCH_UPDATED.
- //
- } catch (IOException e) {
- log.error("Failure writing flow mod from network map", e);
- return false;
- }
- return true;
+ if (enableFlowPusher) {
+ return pusher.add(mySwitch, flowPath, flowEntry);
+ } else {
+ return FlowSwitchOperation.installFlowEntry(
+ floodlightProvider.getOFMessageFactory(),
+ messageDamper, mySwitch, flowPath, flowEntry);
+ }
}
/**
@@ -2317,7 +467,7 @@
* @param flowEntry the flow entry to remove.
* @return true on success, otherwise false.
*/
- public boolean removeFlowEntry(IOFSwitch mySwitch, FlowPath flowPath,
+ private boolean removeFlowEntry(IOFSwitch mySwitch, FlowPath flowPath,
FlowEntry flowEntry) {
//
// The installFlowEntry() method implements both installation
@@ -2327,37 +477,266 @@
}
/**
- * Install a Flow Entry on a remote controller.
+ * Push modified Flow Entries to switches.
*
- * TODO: We need it now: Jono
- * - For now it will make a REST call to the remote controller.
- * - Internally, it needs to know the name of the remote controller.
+ * NOTE: Only the Flow Entries to switches controlled by this instance
+ * are pushed.
*
- * @param flowPath the flow path for the flow entry to install.
- * @param flowEntry the flow entry to install.
- * @return true on success, otherwise false.
+ * @param modifiedFlowEntries the collection of modified Flow Entries.
*/
- public boolean installRemoteFlowEntry(FlowPath flowPath,
- FlowEntry flowEntry) {
- // TODO: We need it now: Jono
- // - For now it will make a REST call to the remote controller.
- // - Internally, it needs to know the name of the remote controller.
- return true;
+ public void pushModifiedFlowEntriesToSwitches(
+ Collection<FlowPathEntryPair> modifiedFlowEntries) {
+ if (modifiedFlowEntries.isEmpty())
+ return;
+
+ Map<Long, IOFSwitch> mySwitches = getMySwitches();
+
+ for (FlowPathEntryPair flowPair : modifiedFlowEntries) {
+ FlowPath flowPath = flowPair.flowPath;
+ FlowEntry flowEntry = flowPair.flowEntry;
+
+ IOFSwitch mySwitch = mySwitches.get(flowEntry.dpid().value());
+ if (mySwitch == null)
+ continue;
+
+ log.debug("Pushing Flow Entry To Switch: {}", flowEntry.toString());
+
+ //
+ // Install the Flow Entry into the switch
+ //
+ if (! installFlowEntry(mySwitch, flowPath, flowEntry)) {
+ String logMsg = "Cannot install Flow Entry " +
+ flowEntry.flowEntryId() +
+ " from Flow Path " + flowPath.flowId() +
+ " on switch " + flowEntry.dpid();
+ log.error(logMsg);
+ continue;
+ }
+
+ //
+ // NOTE: Here we assume that the switch has been
+ // successfully updated.
+ //
+ flowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.FE_SWITCH_UPDATED);
+ }
}
/**
- * Remove a flow entry on a remote controller.
+ * Push modified Flow Entries to the datagrid.
*
- * @param flowPath the flow path for the flow entry to remove.
- * @param flowEntry the flow entry to remove.
- * @return true on success, otherwise false.
+ * @param modifiedFlowEntries the collection of modified Flow Entries.
*/
- public boolean removeRemoteFlowEntry(FlowPath flowPath,
- FlowEntry flowEntry) {
+ public void pushModifiedFlowEntriesToDatagrid(
+ Collection<FlowPathEntryPair> modifiedFlowEntries) {
+ if (modifiedFlowEntries.isEmpty())
+ return;
+
+ Map<Long, IOFSwitch> mySwitches = getMySwitches();
+
+ for (FlowPathEntryPair flowPair : modifiedFlowEntries) {
+ FlowEntry flowEntry = flowPair.flowEntry;
+
+ IOFSwitch mySwitch = mySwitches.get(flowEntry.dpid().value());
+
+ //
+ // TODO: For now Flow Entries are removed by all instances,
+ // even if this Flow Entry is not for our switches.
+ //
+ // This is needed to handle the case a switch going down:
+ // it has no Master controller instance, hence no
+ // controller instance will cleanup its flow entries.
+ // This is sub-optimal: we need to elect a controller
+ // instance to handle the cleanup of such orphaned flow
+ // entries.
+ //
+ if (mySwitch == null) {
+ if (flowEntry.flowEntryUserState() !=
+ FlowEntryUserState.FE_USER_DELETE) {
+ continue;
+ }
+ if (! flowEntry.isValidFlowEntryId())
+ continue;
+ }
+
+ log.debug("Pushing Flow Entry To Datagrid: {}", flowEntry.toString());
+ //
+ // Write the Flow Entry to the Datagrid
+ //
+ switch (flowEntry.flowEntryUserState()) {
+ case FE_USER_ADD:
+ if (mySwitch == null)
+ break; // Install only flow entries for my switches
+ datagridService.notificationSendFlowEntryAdded(flowEntry);
+ break;
+ case FE_USER_MODIFY:
+ if (mySwitch == null)
+ break; // Install only flow entries for my switches
+ datagridService.notificationSendFlowEntryUpdated(flowEntry);
+ break;
+ case FE_USER_DELETE:
+ datagridService.notificationSendFlowEntryRemoved(flowEntry.flowEntryId());
+ break;
+ }
+ }
+ }
+
+ /**
+ * Class to implement writing to the database in a separate thread.
+ */
+ class FlowDatabaseWriter extends Thread {
+ private FlowManager flowManager;
+ private BlockingQueue<FlowPathEntryPair> blockingQueue;
+
+ /**
+ * Constructor.
+ *
+ * @param flowManager the Flow Manager to use.
+ * @param blockingQueue the blocking queue to use.
+ */
+ FlowDatabaseWriter(FlowManager flowManager,
+ BlockingQueue<FlowPathEntryPair> blockingQueue) {
+ this.flowManager = flowManager;
+ this.blockingQueue = blockingQueue;
+ }
+
+ /**
+ * Run the thread.
+ */
+ @Override
+ public void run() {
+ //
+ // The main loop
+ //
+ Collection<FlowPathEntryPair> collection =
+ new LinkedList<FlowPathEntryPair>();
+ try {
+ while (true) {
+ FlowPathEntryPair entryPair = blockingQueue.take();
+ collection.add(entryPair);
+ blockingQueue.drainTo(collection);
+ flowManager.writeModifiedFlowEntriesToDatabase(collection);
+ collection.clear();
+ }
+ } catch (Exception exception) {
+ log.debug("Exception writing to the Database: ", exception);
+ }
+ }
+ }
+
+ /**
+ * Push Flow Entries to the Network MAP.
+ *
+ * NOTE: The Flow Entries are pushed only on the instance responsible
+ * for the first switch. This is to avoid database errors when multiple
+ * instances are writing Flow Entries for the same Flow Path.
+ *
+ * @param modifiedFlowEntries the collection of Flow Entries to push.
+ */
+ void pushModifiedFlowEntriesToDatabase(
+ Collection<FlowPathEntryPair> modifiedFlowEntries) {
//
- // The installRemoteFlowEntry() method implements both installation
- // and removal of flow entries.
+ // We only add the Flow Entries to the Database Queue.
+ // The FlowDatabaseWriter thread is responsible for the actual writing.
//
- return (installRemoteFlowEntry(flowPath, flowEntry));
+ flowEntriesToDatabaseQueue.addAll(modifiedFlowEntries);
+ }
+
+ /**
+ * Write Flow Entries to the Network MAP.
+ *
+ * NOTE: The Flow Entries are written only on the instance responsible
+ * for the first switch. This is to avoid database errors when multiple
+ * instances are writing Flow Entries for the same Flow Path.
+ *
+ * @param modifiedFlowEntries the collection of Flow Entries to write.
+ */
+ private void writeModifiedFlowEntriesToDatabase(
+ Collection<FlowPathEntryPair> modifiedFlowEntries) {
+ if (modifiedFlowEntries.isEmpty())
+ return;
+
+ Map<Long, IOFSwitch> mySwitches = getMySwitches();
+
+ for (FlowPathEntryPair flowPair : modifiedFlowEntries) {
+ FlowPath flowPath = flowPair.flowPath;
+ FlowEntry flowEntry = flowPair.flowEntry;
+
+ if (! flowEntry.isValidFlowEntryId())
+ continue;
+
+ //
+ // Push the changes only on the instance responsible for the
+ // first switch.
+ //
+ Dpid srcDpid = flowPath.dataPath().srcPort().dpid();
+ IOFSwitch mySrcSwitch = mySwitches.get(srcDpid.value());
+ if (mySrcSwitch == null)
+ continue;
+
+ log.debug("Pushing Flow Entry To Database: {}", flowEntry.toString());
+ //
+ // Write the Flow Entry to the Network Map
+ //
+ // NOTE: We try a number of times, in case somehow some other
+ // instances are writing at the same time.
+ // Apparently, if other instances are writing at the same time
+ // this will trigger an error.
+ //
+ for (int i = 0; i < 6; i++) {
+ try {
+ //
+ // Find the Flow Path in the Network MAP.
+ //
+ // NOTE: The Flow Path might not be found if the Flow was
+ // just removed by some other controller instance.
+ //
+ IFlowPath flowObj =
+ dbHandlerInner.searchFlowPath(flowEntry.flowId());
+ if (flowObj == null) {
+ String logMsg = "Cannot find Network MAP entry for Flow Path " + flowEntry.flowId();
+ log.error(logMsg);
+ break;
+ }
+
+ // Write the Flow Entry
+ switch (flowEntry.flowEntryUserState()) {
+ case FE_USER_ADD:
+ // FALLTHROUGH
+ case FE_USER_MODIFY:
+ if (addFlowEntry(flowObj, flowEntry) == null) {
+ String logMsg = "Cannot write to Network MAP Flow Entry " +
+ flowEntry.flowEntryId() +
+ " from Flow Path " + flowEntry.flowId() +
+ " on switch " + flowEntry.dpid();
+ log.error(logMsg);
+ }
+ break;
+ case FE_USER_DELETE:
+ if (deleteFlowEntry(flowObj, flowEntry) == false) {
+ String logMsg = "Cannot remove from Network MAP Flow Entry " +
+ flowEntry.flowEntryId() +
+ " from Flow Path " + flowEntry.flowId() +
+ " on switch " + flowEntry.dpid();
+ log.error(logMsg);
+ }
+ break;
+ }
+
+ // Commit to the database
+ dbHandlerInner.commit();
+ break; // Success
+
+ } catch (Exception e) {
+ log.debug("Exception writing Flow Entry to Network MAP: ", e);
+ dbHandlerInner.rollback();
+ // Wait a bit (random value [1ms, 20ms] and try again
+ int delay = 1 + randomGenerator.nextInt() % 20;
+ try {
+ Thread.sleep(delay);
+ } catch (Exception e0) {
+ }
+ }
+ }
+ }
}
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowSwitchOperation.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowSwitchOperation.java
new file mode 100644
index 0000000..8bed120
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowSwitchOperation.java
@@ -0,0 +1,689 @@
+package net.onrc.onos.ofcontroller.flowmanager;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import net.floodlightcontroller.core.IOFSwitch;
+import net.floodlightcontroller.util.MACAddress;
+import net.floodlightcontroller.util.OFMessageDamper;
+
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowEntry;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowPath;
+import net.onrc.onos.ofcontroller.util.*;
+import net.onrc.onos.ofcontroller.util.FlowEntryAction.*;
+
+import org.openflow.protocol.OFFlowMod;
+import org.openflow.protocol.OFMatch;
+import org.openflow.protocol.OFPacketOut;
+import org.openflow.protocol.OFPort;
+import org.openflow.protocol.OFType;
+import org.openflow.protocol.action.*;
+import org.openflow.protocol.factory.BasicFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Class for performing Flow-related operations on the Switch.
+ */
+class FlowSwitchOperation {
+ private final static Logger log = LoggerFactory.getLogger(FlowSwitchOperation.class);
+ //
+ // TODO: Values copied from elsewhere (class LearningSwitch).
+ // The local copy should go away!
+ //
+ public static final short PRIORITY_DEFAULT = 100;
+ public static final short FLOWMOD_DEFAULT_IDLE_TIMEOUT = 0; // infinity
+ public static final short FLOWMOD_DEFAULT_HARD_TIMEOUT = 0; // infinite
+
+ // TODO add Pusher instance member
+ //
+
+ /**
+ * Install a Flow Entry on a switch.
+ *
+ * @param messageFactory the OpenFlow message factory to use.
+ * @param messageDamper the OpenFlow message damper to use.
+ * @param mySwitch the switch to install the Flow Entry into.
+ * @param flowObj the flow path object for the flow entry to install.
+ * @param flowEntryObj the flow entry object to install.
+ * @return true on success, otherwise false.
+ */
+ static boolean installFlowEntry(BasicFactory messageFactory,
+ OFMessageDamper messageDamper,
+ IOFSwitch mySwitch, IFlowPath flowObj,
+ IFlowEntry flowEntryObj) {
+ String flowEntryIdStr = flowEntryObj.getFlowEntryId();
+ if (flowEntryIdStr == null)
+ return false;
+ FlowEntryId flowEntryId = new FlowEntryId(flowEntryIdStr);
+ String userState = flowEntryObj.getUserState();
+ if (userState == null)
+ return false;
+
+ //
+ // Create the Open Flow Flow Modification Entry to push
+ //
+ OFFlowMod fm = (OFFlowMod)messageFactory.getMessage(OFType.FLOW_MOD);
+ long cookie = flowEntryId.value();
+
+ short flowModCommand = OFFlowMod.OFPFC_ADD;
+ if (userState.equals("FE_USER_ADD")) {
+ flowModCommand = OFFlowMod.OFPFC_ADD;
+ } else if (userState.equals("FE_USER_MODIFY")) {
+ flowModCommand = OFFlowMod.OFPFC_MODIFY_STRICT;
+ } else if (userState.equals("FE_USER_DELETE")) {
+ flowModCommand = OFFlowMod.OFPFC_DELETE_STRICT;
+ } else {
+ // Unknown user state. Ignore the entry
+ log.debug("Flow Entry ignored (FlowEntryId = {}): unknown user state {}",
+ flowEntryId.toString(), userState);
+ return false;
+ }
+
+ //
+ // Fetch the match conditions.
+ //
+ // NOTE: The Flow matching conditions common for all Flow Entries are
+ // used ONLY if a Flow Entry does NOT have the corresponding matching
+ // condition set.
+ //
+ OFMatch match = new OFMatch();
+ match.setWildcards(OFMatch.OFPFW_ALL);
+
+ // Match the Incoming Port
+ Short matchInPort = flowEntryObj.getMatchInPort();
+ if (matchInPort != null) {
+ match.setInputPort(matchInPort);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_IN_PORT);
+ }
+
+ // Match the Source MAC address
+ String matchSrcMac = flowEntryObj.getMatchSrcMac();
+ if (matchSrcMac == null)
+ matchSrcMac = flowObj.getMatchSrcMac();
+ if (matchSrcMac != null) {
+ match.setDataLayerSource(matchSrcMac);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_SRC);
+ }
+
+ // Match the Destination MAC address
+ String matchDstMac = flowEntryObj.getMatchDstMac();
+ if (matchDstMac == null)
+ matchDstMac = flowObj.getMatchDstMac();
+ if (matchDstMac != null) {
+ match.setDataLayerDestination(matchDstMac);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_DST);
+ }
+
+ // Match the Ethernet Frame Type
+ Short matchEthernetFrameType = flowEntryObj.getMatchEthernetFrameType();
+ if (matchEthernetFrameType == null)
+ matchEthernetFrameType = flowObj.getMatchEthernetFrameType();
+ if (matchEthernetFrameType != null) {
+ match.setDataLayerType(matchEthernetFrameType);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
+ }
+
+ // Match the VLAN ID
+ Short matchVlanId = flowEntryObj.getMatchVlanId();
+ if (matchVlanId == null)
+ matchVlanId = flowObj.getMatchVlanId();
+ if (matchVlanId != null) {
+ match.setDataLayerVirtualLan(matchVlanId);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_VLAN);
+ }
+
+ // Match the VLAN priority
+ Byte matchVlanPriority = flowEntryObj.getMatchVlanPriority();
+ if (matchVlanPriority == null)
+ matchVlanPriority = flowObj.getMatchVlanPriority();
+ if (matchVlanPriority != null) {
+ match.setDataLayerVirtualLanPriorityCodePoint(matchVlanPriority);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_VLAN_PCP);
+ }
+
+ // Match the Source IPv4 Network prefix
+ String matchSrcIPv4Net = flowEntryObj.getMatchSrcIPv4Net();
+ if (matchSrcIPv4Net == null)
+ matchSrcIPv4Net = flowObj.getMatchSrcIPv4Net();
+ if (matchSrcIPv4Net != null) {
+ match.setFromCIDR(matchSrcIPv4Net, OFMatch.STR_NW_SRC);
+ }
+
+ // Natch the Destination IPv4 Network prefix
+ String matchDstIPv4Net = flowEntryObj.getMatchDstIPv4Net();
+ if (matchDstIPv4Net == null)
+ matchDstIPv4Net = flowObj.getMatchDstIPv4Net();
+ if (matchDstIPv4Net != null) {
+ match.setFromCIDR(matchDstIPv4Net, OFMatch.STR_NW_DST);
+ }
+
+ // Match the IP protocol
+ Byte matchIpProto = flowEntryObj.getMatchIpProto();
+ if (matchIpProto == null)
+ matchIpProto = flowObj.getMatchIpProto();
+ if (matchIpProto != null) {
+ match.setNetworkProtocol(matchIpProto);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_NW_PROTO);
+ }
+
+ // Match the IP ToS (DSCP field, 6 bits)
+ Byte matchIpToS = flowEntryObj.getMatchIpToS();
+ if (matchIpToS == null)
+ matchIpToS = flowObj.getMatchIpToS();
+ if (matchIpToS != null) {
+ match.setNetworkTypeOfService(matchIpToS);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_NW_TOS);
+ }
+
+ // Match the Source TCP/UDP port
+ Short matchSrcTcpUdpPort = flowEntryObj.getMatchSrcTcpUdpPort();
+ if (matchSrcTcpUdpPort == null)
+ matchSrcTcpUdpPort = flowObj.getMatchSrcTcpUdpPort();
+ if (matchSrcTcpUdpPort != null) {
+ match.setTransportSource(matchSrcTcpUdpPort);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_TP_SRC);
+ }
+
+ // Match the Destination TCP/UDP port
+ Short matchDstTcpUdpPort = flowEntryObj.getMatchDstTcpUdpPort();
+ if (matchDstTcpUdpPort == null)
+ matchDstTcpUdpPort = flowObj.getMatchDstTcpUdpPort();
+ if (matchDstTcpUdpPort != null) {
+ match.setTransportDestination(matchDstTcpUdpPort);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_TP_DST);
+ }
+
+ //
+ // Fetch the actions
+ //
+ Short actionOutputPort = null;
+ List<OFAction> openFlowActions = new ArrayList<OFAction>();
+ int actionsLen = 0;
+ FlowEntryActions flowEntryActions = null;
+ String actionsStr = flowEntryObj.getActions();
+ if (actionsStr != null)
+ flowEntryActions = new FlowEntryActions(actionsStr);
+ else
+ flowEntryActions = new FlowEntryActions();
+ for (FlowEntryAction action : flowEntryActions.actions()) {
+ ActionOutput actionOutput = action.actionOutput();
+ ActionSetVlanId actionSetVlanId = action.actionSetVlanId();
+ ActionSetVlanPriority actionSetVlanPriority = action.actionSetVlanPriority();
+ ActionStripVlan actionStripVlan = action.actionStripVlan();
+ ActionSetEthernetAddr actionSetEthernetSrcAddr = action.actionSetEthernetSrcAddr();
+ ActionSetEthernetAddr actionSetEthernetDstAddr = action.actionSetEthernetDstAddr();
+ ActionSetIPv4Addr actionSetIPv4SrcAddr = action.actionSetIPv4SrcAddr();
+ ActionSetIPv4Addr actionSetIPv4DstAddr = action.actionSetIPv4DstAddr();
+ ActionSetIpToS actionSetIpToS = action.actionSetIpToS();
+ ActionSetTcpUdpPort actionSetTcpUdpSrcPort = action.actionSetTcpUdpSrcPort();
+ ActionSetTcpUdpPort actionSetTcpUdpDstPort = action.actionSetTcpUdpDstPort();
+ ActionEnqueue actionEnqueue = action.actionEnqueue();
+
+ if (actionOutput != null) {
+ actionOutputPort = actionOutput.port().value();
+ // XXX: The max length is hard-coded for now
+ OFActionOutput ofa =
+ new OFActionOutput(actionOutput.port().value(),
+ (short)0xffff);
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetVlanId != null) {
+ OFActionVirtualLanIdentifier ofa =
+ new OFActionVirtualLanIdentifier(actionSetVlanId.vlanId());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetVlanPriority != null) {
+ OFActionVirtualLanPriorityCodePoint ofa =
+ new OFActionVirtualLanPriorityCodePoint(actionSetVlanPriority.vlanPriority());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionStripVlan != null) {
+ if (actionStripVlan.stripVlan() == true) {
+ OFActionStripVirtualLan ofa = new OFActionStripVirtualLan();
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+ }
+
+ if (actionSetEthernetSrcAddr != null) {
+ OFActionDataLayerSource ofa =
+ new OFActionDataLayerSource(actionSetEthernetSrcAddr.addr().toBytes());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetEthernetDstAddr != null) {
+ OFActionDataLayerDestination ofa =
+ new OFActionDataLayerDestination(actionSetEthernetDstAddr.addr().toBytes());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetIPv4SrcAddr != null) {
+ OFActionNetworkLayerSource ofa =
+ new OFActionNetworkLayerSource(actionSetIPv4SrcAddr.addr().value());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetIPv4DstAddr != null) {
+ OFActionNetworkLayerDestination ofa =
+ new OFActionNetworkLayerDestination(actionSetIPv4DstAddr.addr().value());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetIpToS != null) {
+ OFActionNetworkTypeOfService ofa =
+ new OFActionNetworkTypeOfService(actionSetIpToS.ipToS());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetTcpUdpSrcPort != null) {
+ OFActionTransportLayerSource ofa =
+ new OFActionTransportLayerSource(actionSetTcpUdpSrcPort.port());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetTcpUdpDstPort != null) {
+ OFActionTransportLayerDestination ofa =
+ new OFActionTransportLayerDestination(actionSetTcpUdpDstPort.port());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionEnqueue != null) {
+ OFActionEnqueue ofa =
+ new OFActionEnqueue(actionEnqueue.port().value(),
+ actionEnqueue.queueId());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+ }
+
+ fm.setIdleTimeout(FLOWMOD_DEFAULT_IDLE_TIMEOUT)
+ .setHardTimeout(FLOWMOD_DEFAULT_HARD_TIMEOUT)
+ .setPriority(PRIORITY_DEFAULT)
+ .setBufferId(OFPacketOut.BUFFER_ID_NONE)
+ .setCookie(cookie)
+ .setCommand(flowModCommand)
+ .setMatch(match)
+ .setActions(openFlowActions)
+ .setLengthU(OFFlowMod.MINIMUM_LENGTH + actionsLen);
+ fm.setOutPort(OFPort.OFPP_NONE.getValue());
+ if ((flowModCommand == OFFlowMod.OFPFC_DELETE) ||
+ (flowModCommand == OFFlowMod.OFPFC_DELETE_STRICT)) {
+ if (actionOutputPort != null)
+ fm.setOutPort(actionOutputPort);
+ }
+
+ //
+ // TODO: Set the following flag
+ // fm.setFlags(OFFlowMod.OFPFF_SEND_FLOW_REM);
+ // See method ForwardingBase::pushRoute()
+ //
+
+ //
+ // Write the message to the switch
+ //
+ log.debug("MEASUREMENT: Installing flow entry " + userState +
+ " into switch DPID: " +
+ mySwitch.getStringId() +
+ " flowEntryId: " + flowEntryId.toString() +
+ " srcMac: " + matchSrcMac + " dstMac: " + matchDstMac +
+ " inPort: " + matchInPort + " outPort: " + actionOutputPort
+ );
+ try {
+ messageDamper.write(mySwitch, fm, null);
+ mySwitch.flush();
+ //
+ // TODO: We should use the OpenFlow Barrier mechanism
+ // to check for errors, and update the SwitchState
+ // for a flow entry after the Barrier message is
+ // is received.
+ //
+ flowEntryObj.setSwitchState("FE_SWITCH_UPDATED");
+ } catch (IOException e) {
+ log.error("Failure writing flow mod from network map", e);
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Install a Flow Entry on a switch.
+ *
+ * @param messageFactory the OpenFlow message factory to use.
+ * @maram messageDamper the OpenFlow message damper to use.
+ * @param mySwitch the switch to install the Flow Entry into.
+ * @param flowPath the flow path for the flow entry to install.
+ * @param flowEntry the flow entry to install.
+ * @return true on success, otherwise false.
+ */
+ static boolean installFlowEntry(BasicFactory messageFactory,
+ OFMessageDamper messageDamper,
+ IOFSwitch mySwitch, FlowPath flowPath,
+ FlowEntry flowEntry) {
+ //
+ // Create the OpenFlow Flow Modification Entry to push
+ //
+ OFFlowMod fm = (OFFlowMod)messageFactory.getMessage(OFType.FLOW_MOD);
+ long cookie = flowEntry.flowEntryId().value();
+
+ short flowModCommand = OFFlowMod.OFPFC_ADD;
+ if (flowEntry.flowEntryUserState() == FlowEntryUserState.FE_USER_ADD) {
+ flowModCommand = OFFlowMod.OFPFC_ADD;
+ } else if (flowEntry.flowEntryUserState() == FlowEntryUserState.FE_USER_MODIFY) {
+ flowModCommand = OFFlowMod.OFPFC_MODIFY_STRICT;
+ } else if (flowEntry.flowEntryUserState() == FlowEntryUserState.FE_USER_DELETE) {
+ flowModCommand = OFFlowMod.OFPFC_DELETE_STRICT;
+ } else {
+ // Unknown user state. Ignore the entry
+ log.debug("Flow Entry ignored (FlowEntryId = {}): unknown user state {}",
+ flowEntry.flowEntryId().toString(),
+ flowEntry.flowEntryUserState());
+ return false;
+ }
+
+ //
+ // Fetch the match conditions.
+ //
+ // NOTE: The Flow matching conditions common for all Flow Entries are
+ // used ONLY if a Flow Entry does NOT have the corresponding matching
+ // condition set.
+ //
+ OFMatch match = new OFMatch();
+ match.setWildcards(OFMatch.OFPFW_ALL);
+ FlowEntryMatch flowPathMatch = flowPath.flowEntryMatch();
+ FlowEntryMatch flowEntryMatch = flowEntry.flowEntryMatch();
+
+ // Match the Incoming Port
+ Port matchInPort = flowEntryMatch.inPort();
+ if (matchInPort != null) {
+ match.setInputPort(matchInPort.value());
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_IN_PORT);
+ }
+
+ // Match the Source MAC address
+ MACAddress matchSrcMac = flowEntryMatch.srcMac();
+ if ((matchSrcMac == null) && (flowPathMatch != null)) {
+ matchSrcMac = flowPathMatch.srcMac();
+ }
+ if (matchSrcMac != null) {
+ match.setDataLayerSource(matchSrcMac.toString());
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_SRC);
+ }
+
+ // Match the Destination MAC address
+ MACAddress matchDstMac = flowEntryMatch.dstMac();
+ if ((matchDstMac == null) && (flowPathMatch != null)) {
+ matchDstMac = flowPathMatch.dstMac();
+ }
+ if (matchDstMac != null) {
+ match.setDataLayerDestination(matchDstMac.toString());
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_DST);
+ }
+
+ // Match the Ethernet Frame Type
+ Short matchEthernetFrameType = flowEntryMatch.ethernetFrameType();
+ if ((matchEthernetFrameType == null) && (flowPathMatch != null)) {
+ matchEthernetFrameType = flowPathMatch.ethernetFrameType();
+ }
+ if (matchEthernetFrameType != null) {
+ match.setDataLayerType(matchEthernetFrameType);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
+ }
+
+ // Match the VLAN ID
+ Short matchVlanId = flowEntryMatch.vlanId();
+ if ((matchVlanId == null) && (flowPathMatch != null)) {
+ matchVlanId = flowPathMatch.vlanId();
+ }
+ if (matchVlanId != null) {
+ match.setDataLayerVirtualLan(matchVlanId);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_VLAN);
+ }
+
+ // Match the VLAN priority
+ Byte matchVlanPriority = flowEntryMatch.vlanPriority();
+ if ((matchVlanPriority == null) && (flowPathMatch != null)) {
+ matchVlanPriority = flowPathMatch.vlanPriority();
+ }
+ if (matchVlanPriority != null) {
+ match.setDataLayerVirtualLanPriorityCodePoint(matchVlanPriority);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_VLAN_PCP);
+ }
+
+ // Match the Source IPv4 Network prefix
+ IPv4Net matchSrcIPv4Net = flowEntryMatch.srcIPv4Net();
+ if ((matchSrcIPv4Net == null) && (flowPathMatch != null)) {
+ matchSrcIPv4Net = flowPathMatch.srcIPv4Net();
+ }
+ if (matchSrcIPv4Net != null) {
+ match.setFromCIDR(matchSrcIPv4Net.toString(), OFMatch.STR_NW_SRC);
+ }
+
+ // Natch the Destination IPv4 Network prefix
+ IPv4Net matchDstIPv4Net = flowEntryMatch.dstIPv4Net();
+ if ((matchDstIPv4Net == null) && (flowPathMatch != null)) {
+ matchDstIPv4Net = flowPathMatch.dstIPv4Net();
+ }
+ if (matchDstIPv4Net != null) {
+ match.setFromCIDR(matchDstIPv4Net.toString(), OFMatch.STR_NW_DST);
+ }
+
+ // Match the IP protocol
+ Byte matchIpProto = flowEntryMatch.ipProto();
+ if ((matchIpProto == null) && (flowPathMatch != null)) {
+ matchIpProto = flowPathMatch.ipProto();
+ }
+ if (matchIpProto != null) {
+ match.setNetworkProtocol(matchIpProto);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_NW_PROTO);
+ }
+
+ // Match the IP ToS (DSCP field, 6 bits)
+ Byte matchIpToS = flowEntryMatch.ipToS();
+ if ((matchIpToS == null) && (flowPathMatch != null)) {
+ matchIpToS = flowPathMatch.ipToS();
+ }
+ if (matchIpToS != null) {
+ match.setNetworkTypeOfService(matchIpToS);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_NW_TOS);
+ }
+
+ // Match the Source TCP/UDP port
+ Short matchSrcTcpUdpPort = flowEntryMatch.srcTcpUdpPort();
+ if ((matchSrcTcpUdpPort == null) && (flowPathMatch != null)) {
+ matchSrcTcpUdpPort = flowPathMatch.srcTcpUdpPort();
+ }
+ if (matchSrcTcpUdpPort != null) {
+ match.setTransportSource(matchSrcTcpUdpPort);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_TP_SRC);
+ }
+
+ // Match the Destination TCP/UDP port
+ Short matchDstTcpUdpPort = flowEntryMatch.dstTcpUdpPort();
+ if ((matchDstTcpUdpPort == null) && (flowPathMatch != null)) {
+ matchDstTcpUdpPort = flowPathMatch.dstTcpUdpPort();
+ }
+ if (matchDstTcpUdpPort != null) {
+ match.setTransportDestination(matchDstTcpUdpPort);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_TP_DST);
+ }
+
+ //
+ // Fetch the actions
+ //
+ Short actionOutputPort = null;
+ List<OFAction> openFlowActions = new ArrayList<OFAction>();
+ int actionsLen = 0;
+ FlowEntryActions flowEntryActions = flowEntry.flowEntryActions();
+ //
+ for (FlowEntryAction action : flowEntryActions.actions()) {
+ ActionOutput actionOutput = action.actionOutput();
+ ActionSetVlanId actionSetVlanId = action.actionSetVlanId();
+ ActionSetVlanPriority actionSetVlanPriority = action.actionSetVlanPriority();
+ ActionStripVlan actionStripVlan = action.actionStripVlan();
+ ActionSetEthernetAddr actionSetEthernetSrcAddr = action.actionSetEthernetSrcAddr();
+ ActionSetEthernetAddr actionSetEthernetDstAddr = action.actionSetEthernetDstAddr();
+ ActionSetIPv4Addr actionSetIPv4SrcAddr = action.actionSetIPv4SrcAddr();
+ ActionSetIPv4Addr actionSetIPv4DstAddr = action.actionSetIPv4DstAddr();
+ ActionSetIpToS actionSetIpToS = action.actionSetIpToS();
+ ActionSetTcpUdpPort actionSetTcpUdpSrcPort = action.actionSetTcpUdpSrcPort();
+ ActionSetTcpUdpPort actionSetTcpUdpDstPort = action.actionSetTcpUdpDstPort();
+ ActionEnqueue actionEnqueue = action.actionEnqueue();
+
+ if (actionOutput != null) {
+ actionOutputPort = actionOutput.port().value();
+ // XXX: The max length is hard-coded for now
+ OFActionOutput ofa =
+ new OFActionOutput(actionOutput.port().value(),
+ (short)0xffff);
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetVlanId != null) {
+ OFActionVirtualLanIdentifier ofa =
+ new OFActionVirtualLanIdentifier(actionSetVlanId.vlanId());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetVlanPriority != null) {
+ OFActionVirtualLanPriorityCodePoint ofa =
+ new OFActionVirtualLanPriorityCodePoint(actionSetVlanPriority.vlanPriority());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionStripVlan != null) {
+ if (actionStripVlan.stripVlan() == true) {
+ OFActionStripVirtualLan ofa = new OFActionStripVirtualLan();
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+ }
+
+ if (actionSetEthernetSrcAddr != null) {
+ OFActionDataLayerSource ofa =
+ new OFActionDataLayerSource(actionSetEthernetSrcAddr.addr().toBytes());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetEthernetDstAddr != null) {
+ OFActionDataLayerDestination ofa =
+ new OFActionDataLayerDestination(actionSetEthernetDstAddr.addr().toBytes());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetIPv4SrcAddr != null) {
+ OFActionNetworkLayerSource ofa =
+ new OFActionNetworkLayerSource(actionSetIPv4SrcAddr.addr().value());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetIPv4DstAddr != null) {
+ OFActionNetworkLayerDestination ofa =
+ new OFActionNetworkLayerDestination(actionSetIPv4DstAddr.addr().value());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetIpToS != null) {
+ OFActionNetworkTypeOfService ofa =
+ new OFActionNetworkTypeOfService(actionSetIpToS.ipToS());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetTcpUdpSrcPort != null) {
+ OFActionTransportLayerSource ofa =
+ new OFActionTransportLayerSource(actionSetTcpUdpSrcPort.port());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetTcpUdpDstPort != null) {
+ OFActionTransportLayerDestination ofa =
+ new OFActionTransportLayerDestination(actionSetTcpUdpDstPort.port());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionEnqueue != null) {
+ OFActionEnqueue ofa =
+ new OFActionEnqueue(actionEnqueue.port().value(),
+ actionEnqueue.queueId());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+ }
+
+ fm.setIdleTimeout(FLOWMOD_DEFAULT_IDLE_TIMEOUT)
+ .setHardTimeout(FLOWMOD_DEFAULT_HARD_TIMEOUT)
+ .setPriority(PRIORITY_DEFAULT)
+ .setBufferId(OFPacketOut.BUFFER_ID_NONE)
+ .setCookie(cookie)
+ .setCommand(flowModCommand)
+ .setMatch(match)
+ .setActions(openFlowActions)
+ .setLengthU(OFFlowMod.MINIMUM_LENGTH + actionsLen);
+ fm.setOutPort(OFPort.OFPP_NONE.getValue());
+ if ((flowModCommand == OFFlowMod.OFPFC_DELETE) ||
+ (flowModCommand == OFFlowMod.OFPFC_DELETE_STRICT)) {
+ if (actionOutputPort != null)
+ fm.setOutPort(actionOutputPort);
+ }
+
+ //
+ // TODO: Set the following flag
+ // fm.setFlags(OFFlowMod.OFPFF_SEND_FLOW_REM);
+ // See method ForwardingBase::pushRoute()
+ //
+
+ //
+ // Write the message to the switch
+ //
+ log.debug("MEASUREMENT: Installing flow entry " +
+ flowEntry.flowEntryUserState() +
+ " into switch DPID: " +
+ mySwitch.getStringId() +
+ " flowEntryId: " + flowEntry.flowEntryId().toString() +
+ " srcMac: " + matchSrcMac + " dstMac: " + matchDstMac +
+ " inPort: " + matchInPort + " outPort: " + actionOutputPort
+ );
+ try {
+ messageDamper.write(mySwitch, fm, null);
+ mySwitch.flush();
+ //
+ // TODO: We should use the OpenFlow Barrier mechanism
+ // to check for errors, and update the SwitchState
+ // for a flow entry after the Barrier message is
+ // is received.
+ //
+ // TODO: The FlowEntry Object in Titan should be set
+ // to FE_SWITCH_UPDATED.
+ //
+ } catch (IOException e) {
+ log.error("Failure writing flow mod from network map", e);
+ return false;
+ }
+ return true;
+ }
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/IFlowEventHandlerService.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/IFlowEventHandlerService.java
new file mode 100644
index 0000000..78562e1
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/IFlowEventHandlerService.java
@@ -0,0 +1,73 @@
+package net.onrc.onos.ofcontroller.flowmanager;
+
+import net.onrc.onos.ofcontroller.topology.TopologyElement;
+import net.onrc.onos.ofcontroller.util.FlowEntry;
+import net.onrc.onos.ofcontroller.util.FlowPath;
+
+/**
+ * Interface for providing Flow Event Handler Service to other modules.
+ */
+public interface IFlowEventHandlerService {
+ /**
+ * Receive a notification that a Flow is added.
+ *
+ * @param flowPath the Flow that is added.
+ */
+ void notificationRecvFlowAdded(FlowPath flowPath);
+
+ /**
+ * Receive a notification that a Flow is removed.
+ *
+ * @param flowPath the Flow that is removed.
+ */
+ void notificationRecvFlowRemoved(FlowPath flowPath);
+
+ /**
+ * Receive a notification that a Flow is updated.
+ *
+ * @param flowPath the Flow that is updated.
+ */
+ void notificationRecvFlowUpdated(FlowPath flowPath);
+
+ /**
+ * Receive a notification that a FlowEntry is added.
+ *
+ * @param flowEntry the FlowEntry that is added.
+ */
+ void notificationRecvFlowEntryAdded(FlowEntry flowEntry);
+
+ /**
+ * Receive a notification that a FlowEntry is removed.
+ *
+ * @param flowEntry the FlowEntry that is removed.
+ */
+ void notificationRecvFlowEntryRemoved(FlowEntry flowEntry);
+
+ /**
+ * Receive a notification that a FlowEntry is updated.
+ *
+ * @param flowEntry the FlowEntry that is updated.
+ */
+ void notificationRecvFlowEntryUpdated(FlowEntry flowEntry);
+
+ /**
+ * Receive a notification that a Topology Element is added.
+ *
+ * @param topologyElement the Topology Element that is added.
+ */
+ void notificationRecvTopologyElementAdded(TopologyElement topologyElement);
+
+ /**
+ * Receive a notification that a Topology Element is removed.
+ *
+ * @param topologyElement the Topology Element that is removed.
+ */
+ void notificationRecvTopologyElementRemoved(TopologyElement topologyElement);
+
+ /**
+ * Receive a notification that a Topology Element is updated.
+ *
+ * @param topologyElement the Topology Element that is updated.
+ */
+ void notificationRecvTopologyElementUpdated(TopologyElement topologyElement);
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/IFlowService.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/IFlowService.java
index df11d6b..b06d844 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/IFlowService.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/IFlowService.java
@@ -4,6 +4,7 @@
import net.floodlightcontroller.core.module.IFloodlightService;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowPath;
+import net.onrc.onos.ofcontroller.topology.Topology;
import net.onrc.onos.ofcontroller.util.CallerId;
import net.onrc.onos.ofcontroller.util.DataPathEndpoints;
import net.onrc.onos.ofcontroller.util.FlowId;
@@ -21,12 +22,9 @@
*
* @param flowPath the Flow Path to install.
* @param flowId the return-by-reference Flow ID as assigned internally.
- * @param dataPathSummaryStr the data path summary string if the added
- * flow will be maintained internally, otherwise null.
* @return true on success, otherwise false.
*/
- boolean addFlow(FlowPath flowPath, FlowId flowId,
- String dataPathSummaryStr);
+ boolean addFlow(FlowPath flowPath, FlowId flowId);
/**
* Delete all previously added flows.
@@ -44,21 +42,6 @@
boolean deleteFlow(FlowId flowId);
/**
- * Clear the state for all previously added flows.
- *
- * @return true on success, otherwise false.
- */
- boolean clearAllFlows();
-
- /**
- * Clear the state for a previously added flow.
- *
- * @param flowId the Flow ID of the flow to clear.
- * @return true on success, otherwise false.
- */
- boolean clearFlow(FlowId flowId);
-
- /**
* Get a previously added flow.
*
* @param flowId the Flow ID of the flow to get.
@@ -67,6 +50,13 @@
FlowPath getFlow(FlowId flowId);
/**
+ * Get all installed flows by all installers.
+ *
+ * @return the Flow Paths if found, otherwise null.
+ */
+ ArrayList<FlowPath> getAllFlows();
+
+ /**
* Get all previously added flows by a specific installer for a given
* data path endpoints.
*
@@ -95,13 +85,6 @@
ArrayList<IFlowPath> getAllFlowsSummary(FlowId flowId, int maxFlows);
/**
- * Get all installed flows by all installers.
- *
- * @return the Flow Paths if found, otherwise null.
- */
- ArrayList<FlowPath> getAllFlows();
-
- /**
* Add and maintain a shortest-path flow.
*
* NOTE: The Flow Path argument does NOT contain all flow entries.
@@ -114,5 +97,20 @@
* conditions to install.
* @return the added shortest-path flow on success, otherwise null.
*/
- public FlowPath addAndMaintainShortestPathFlow(FlowPath flowPath);
+ FlowPath addAndMaintainShortestPathFlow(FlowPath flowPath);
+
+ /**
+ * Get the network topology.
+ *
+ * @return the network topology.
+ */
+ Topology getTopology();
+
+ /**
+ * Get a globally unique flow ID from the flow service.
+ * NOTE: Not currently guaranteed to be globally unique.
+ *
+ * @return unique flow ID
+ */
+ public long getNextFlowEntryId();
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/AddFlowResource.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/AddFlowResource.java
index 7464ec5..0926f91 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/AddFlowResource.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/AddFlowResource.java
@@ -22,7 +22,7 @@
*/
public class AddFlowResource extends ServerResource {
- protected static Logger log = LoggerFactory.getLogger(AddFlowResource.class);
+ protected final static Logger log = LoggerFactory.getLogger(AddFlowResource.class);
/**
* Implement the API.
@@ -64,7 +64,7 @@
// Process the request
if (flowPath != null) {
- if (flowService.addFlow(flowPath, result, null) != true) {
+ if (flowService.addFlow(flowPath, result) != true) {
result = new FlowId(); // Error: Return empty Flow Id
}
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/AddShortestPathFlowResource.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/AddShortestPathFlowResource.java
index c454b0f..7a4e88c 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/AddShortestPathFlowResource.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/AddShortestPathFlowResource.java
@@ -22,7 +22,7 @@
*/
public class AddShortestPathFlowResource extends ServerResource {
- protected static Logger log = LoggerFactory.getLogger(AddShortestPathFlowResource.class);
+ protected final static Logger log = LoggerFactory.getLogger(AddShortestPathFlowResource.class);
/**
* Implement the API.
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/ClearFlowResource.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/ClearFlowResource.java
deleted file mode 100644
index db591ae..0000000
--- a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/ClearFlowResource.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package net.onrc.onos.ofcontroller.flowmanager.web;
-
-import net.onrc.onos.ofcontroller.flowmanager.IFlowService;
-import net.onrc.onos.ofcontroller.util.FlowId;
-
-import org.restlet.resource.Get;
-import org.restlet.resource.ServerResource;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Flow Manager REST API implementation: Clear internal Flow state.
- *
- * The "{flow-id}" request attribute value can be either a specific Flow ID,
- * or the keyword "all" to clear all Flows:
- *
- * GET /wm/flow/clear/{flow-id}/json
- */
-public class ClearFlowResource extends ServerResource {
- protected static Logger log = LoggerFactory.getLogger(ClearFlowResource.class);
-
- /**
- * Implement the API.
- *
- * @return true on success, otehrwise false.
- */
- @Get("json")
- public Boolean retrieve() {
- Boolean result = false;
-
- IFlowService flowService =
- (IFlowService)getContext().getAttributes().
- get(IFlowService.class.getCanonicalName());
-
- if (flowService == null) {
- log.debug("ONOS Flow Service not found");
- return result;
- }
-
- // Extract the arguments
- String flowIdStr = (String) getRequestAttributes().get("flow-id");
-
- // Process the request
- if (flowIdStr.equals("all")) {
- log.debug("Clear All Flows");
- result = flowService.clearAllFlows();
- } else {
- FlowId flowId = new FlowId(flowIdStr);
- log.debug("Clear Flow Id: " + flowIdStr);
- result = flowService.clearFlow(flowId);
- }
- return result;
- }
-}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/DatapathSummarySerializer.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/DatapathSummarySerializer.java
index 9133077..5fa472f 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/DatapathSummarySerializer.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/DatapathSummarySerializer.java
@@ -10,7 +10,7 @@
import org.slf4j.LoggerFactory;
public class DatapathSummarySerializer extends JsonSerializer<String>{
- static Logger log = LoggerFactory.getLogger(DatapathSummarySerializer.class);
+ protected final static Logger log = LoggerFactory.getLogger(DatapathSummarySerializer.class);
@Override
public void serialize(String datapathSummary, JsonGenerator jGen,
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/DeleteFlowResource.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/DeleteFlowResource.java
index 5b2bad4..f4e23b8 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/DeleteFlowResource.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/DeleteFlowResource.java
@@ -17,7 +17,7 @@
* GET /wm/flow/delete/{flow-id}/json
*/
public class DeleteFlowResource extends ServerResource {
- protected static Logger log = LoggerFactory.getLogger(DeleteFlowResource.class);
+ protected final static Logger log = LoggerFactory.getLogger(DeleteFlowResource.class);
/**
* Implement the API.
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/FlowWebRoutable.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/FlowWebRoutable.java
index e027270..81d26dd 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/FlowWebRoutable.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/FlowWebRoutable.java
@@ -18,7 +18,6 @@
Router router = new Router(context);
router.attach("/add/json", AddFlowResource.class);
router.attach("/add-shortest-path/json", AddShortestPathFlowResource.class);
- router.attach("/clear/{flow-id}/json", ClearFlowResource.class);
router.attach("/delete/{flow-id}/json", DeleteFlowResource.class);
router.attach("/get/{flow-id}/json", GetFlowByIdResource.class);
router.attach("/getall-by-installer-id/{installer-id}/{src-dpid}/{src-port}/{dst-dpid}/{dst-port}/json", GetAllFlowsByInstallerIdResource.class);
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetAllFlowsByEndpointsResource.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetAllFlowsByEndpointsResource.java
index 0308e89..1ac98c0 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetAllFlowsByEndpointsResource.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetAllFlowsByEndpointsResource.java
@@ -30,7 +30,7 @@
* GET /wm/flow/getall-by-endpoints/{src-dpid}/{src-port}/{dst-dpid}/{dst-port}/json"
*/
public class GetAllFlowsByEndpointsResource extends ServerResource {
- protected static Logger log = LoggerFactory.getLogger(GetAllFlowsByEndpointsResource.class);
+ protected final static Logger log = LoggerFactory.getLogger(GetAllFlowsByEndpointsResource.class);
/**
* Implement the API.
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetAllFlowsByInstallerIdResource.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetAllFlowsByInstallerIdResource.java
index 43f1618..870548e 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetAllFlowsByInstallerIdResource.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetAllFlowsByInstallerIdResource.java
@@ -33,7 +33,7 @@
* GET /wm/flow/getall-by-installer-id/{installer-id}/{src-dpid}/{src-port}/{dst-dpid}/{dst-port}/json"
*/
public class GetAllFlowsByInstallerIdResource extends ServerResource {
- protected static Logger log = LoggerFactory.getLogger(GetAllFlowsByInstallerIdResource.class);
+ protected final static Logger log = LoggerFactory.getLogger(GetAllFlowsByInstallerIdResource.class);
/**
* Implement the API.
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetAllFlowsResource.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetAllFlowsResource.java
index ab88348..a4ea960 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetAllFlowsResource.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetAllFlowsResource.java
@@ -16,7 +16,7 @@
* GET /wm/flow/getall/json"
*/
public class GetAllFlowsResource extends ServerResource {
- protected static Logger log = LoggerFactory.getLogger(GetAllFlowsResource.class);
+ protected final static Logger log = LoggerFactory.getLogger(GetAllFlowsResource.class);
/**
* Implement the API.
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetFlowByIdResource.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetFlowByIdResource.java
index 77a898c..9ceef6e 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetFlowByIdResource.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetFlowByIdResource.java
@@ -17,7 +17,7 @@
* GET /wm/flow/get/{flow-id}/json
*/
public class GetFlowByIdResource extends ServerResource {
- protected static Logger log = LoggerFactory.getLogger(GetFlowByIdResource.class);
+ protected final static Logger log = LoggerFactory.getLogger(GetFlowByIdResource.class);
/**
* Implement the API.
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetSummaryFlowsResource.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetSummaryFlowsResource.java
index 67e1ad6..89e5b01 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetSummaryFlowsResource.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/web/GetSummaryFlowsResource.java
@@ -23,7 +23,7 @@
* GET /wm/flow/getsummary/{flow-id}/{max-flows}/json"
*/
public class GetSummaryFlowsResource extends ServerResource {
- protected static Logger log = LoggerFactory.getLogger(GetSummaryFlowsResource.class);
+ protected final static Logger log = LoggerFactory.getLogger(GetSummaryFlowsResource.class);
/**
* Implement the API.
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/FlowProgrammer.java b/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/FlowProgrammer.java
new file mode 100644
index 0000000..b567a87
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/FlowProgrammer.java
@@ -0,0 +1,87 @@
+package net.onrc.onos.ofcontroller.flowprogrammer;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import net.floodlightcontroller.core.IFloodlightProviderService;
+import net.floodlightcontroller.core.module.FloodlightModuleContext;
+import net.floodlightcontroller.core.module.FloodlightModuleException;
+import net.floodlightcontroller.core.module.IFloodlightModule;
+import net.floodlightcontroller.core.module.IFloodlightService;
+
+public class FlowProgrammer implements IFloodlightModule {
+ @SuppressWarnings("unused")
+ private final static Logger log = LoggerFactory.getLogger(FlowProgrammer.class);
+
+ private static final boolean enableFlowSync = false;
+
+ protected volatile IFloodlightProviderService floodlightProvider;
+
+ protected FlowPusher pusher;
+ private static final int NUM_PUSHER_THREAD = 1;
+
+ protected FlowSynchronizer synchronizer;
+
+ public FlowProgrammer() {
+ pusher = new FlowPusher(NUM_PUSHER_THREAD);
+ if (enableFlowSync) {
+ synchronizer = new FlowSynchronizer();
+ }
+ }
+
+ @Override
+ public void init(FloodlightModuleContext context)
+ throws FloodlightModuleException {
+ floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
+ pusher.init(null, context, floodlightProvider.getOFMessageFactory(), null);
+ if (enableFlowSync) {
+ synchronizer.init(context);
+ }
+ }
+
+ @Override
+ public void startUp(FloodlightModuleContext context) {
+ pusher.start();
+ if (enableFlowSync) {
+ synchronizer.startUp(context);
+ }
+ }
+
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleServices() {
+ Collection<Class<? extends IFloodlightService>> l =
+ new ArrayList<Class<? extends IFloodlightService>>();
+ l.add(IFlowPusherService.class);
+ if (enableFlowSync) {
+ l.add(IFlowSyncService.class);
+ }
+ return l;
+ }
+
+ @Override
+ public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
+ Map<Class<? extends IFloodlightService>,
+ IFloodlightService> m =
+ new HashMap<Class<? extends IFloodlightService>,
+ IFloodlightService>();
+ m.put(IFlowPusherService.class, pusher);
+ if (enableFlowSync) {
+ m.put(IFlowSyncService.class, synchronizer);
+ }
+ return m;
+ }
+
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
+ Collection<Class<? extends IFloodlightService>> l =
+ new ArrayList<Class<? extends IFloodlightService>>();
+ l.add(IFloodlightProviderService.class);
+ return l;
+ }
+
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/FlowPusher.java b/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/FlowPusher.java
new file mode 100644
index 0000000..f43a83e
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/FlowPusher.java
@@ -0,0 +1,1122 @@
+package net.onrc.onos.ofcontroller.flowprogrammer;
+
+import java.io.IOException;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Semaphore;
+
+import org.openflow.protocol.*;
+import org.openflow.protocol.action.*;
+import org.openflow.protocol.factory.BasicFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import net.floodlightcontroller.core.FloodlightContext;
+import net.floodlightcontroller.core.IFloodlightProviderService;
+import net.floodlightcontroller.core.IOFMessageListener;
+import net.floodlightcontroller.core.IOFSwitch;
+import net.floodlightcontroller.core.internal.OFMessageFuture;
+import net.floodlightcontroller.core.module.FloodlightModuleContext;
+import net.floodlightcontroller.threadpool.IThreadPoolService;
+import net.floodlightcontroller.util.MACAddress;
+import net.floodlightcontroller.util.OFMessageDamper;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowEntry;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowPath;
+import net.onrc.onos.ofcontroller.util.FlowEntryAction;
+import net.onrc.onos.ofcontroller.util.FlowEntryAction.*;
+import net.onrc.onos.ofcontroller.util.FlowEntry;
+import net.onrc.onos.ofcontroller.util.FlowEntryActions;
+import net.onrc.onos.ofcontroller.util.FlowEntryId;
+import net.onrc.onos.ofcontroller.util.FlowEntryMatch;
+import net.onrc.onos.ofcontroller.util.FlowEntryUserState;
+import net.onrc.onos.ofcontroller.util.FlowPath;
+import net.onrc.onos.ofcontroller.util.IPv4Net;
+import net.onrc.onos.ofcontroller.util.Port;
+
+/**
+ * FlowPusher intermediates FlowManager/FlowSynchronizer and switches to push OpenFlow
+ * messages to switches in proper rate.
+ * @author Naoki Shiota
+ *
+ */
+public class FlowPusher implements IFlowPusherService, IOFMessageListener {
+ private final static Logger log = LoggerFactory.getLogger(FlowPusher.class);
+
+ private static boolean barrierIfEmpty = false;
+
+ // NOTE: Below are moved from FlowManager.
+ // TODO: Values copied from elsewhere (class LearningSwitch).
+ // The local copy should go away!
+ //
+ protected static final int OFMESSAGE_DAMPER_CAPACITY = 50000; // TODO: find sweet spot
+ protected static final int OFMESSAGE_DAMPER_TIMEOUT = 250; // ms
+
+ // Interval of sleep when queue is empty
+ protected static final long SLEEP_MILLI_SEC = 10;
+ protected static final int SLEEP_NANO_SEC = 0;
+
+ // Number of messages sent to switch at once
+ protected static final int MAX_MESSAGE_SEND = 100;
+
+ public static final short PRIORITY_DEFAULT = 100;
+ public static final short FLOWMOD_DEFAULT_IDLE_TIMEOUT = 0; // infinity
+ public static final short FLOWMOD_DEFAULT_HARD_TIMEOUT = 0; // infinite
+
+ public enum QueueState {
+ READY,
+ SUSPENDED,
+ }
+
+ /**
+ * Message queue attached to a switch.
+ * This consists of queue itself and variables used for limiting sending rate.
+ * @author Naoki Shiota
+ *
+ */
+ @SuppressWarnings("serial")
+ private class SwitchQueue extends ArrayDeque<OFMessage> {
+ QueueState state;
+
+ // Max rate of sending message (bytes/sec). 0 implies no limitation.
+ long max_rate = 0; // 0 indicates no limitation
+ long last_sent_time = 0;
+ long last_sent_size = 0;
+
+ /**
+ * Check if sending rate is within the rate
+ * @param current Current time
+ * @return true if within the rate
+ */
+ boolean isSendable(long current) {
+ if (max_rate == 0) {
+ // no limitation
+ return true;
+ }
+
+ if (current == last_sent_time) {
+ return false;
+ }
+
+ // Check if sufficient time (from aspect of rate) elapsed or not.
+ long rate = last_sent_size / (current - last_sent_time);
+ return (rate < max_rate);
+ }
+
+ /**
+ * Log time and size of last sent data.
+ * @param current Time to be sent.
+ * @param size Size of sent data (in bytes).
+ */
+ void logSentData(long current, long size) {
+ last_sent_time = current;
+ last_sent_size = size;
+ }
+
+ }
+
+ private OFMessageDamper messageDamper = null;
+ private IThreadPoolService threadPool = null;
+
+ private FloodlightContext context = null;
+ private BasicFactory factory = null;
+ private Map<Long, FlowPusherThread> threadMap = null;
+ private Map<Long, Map<Integer, OFBarrierReplyFuture>>
+ barrierFutures = new HashMap<Long, Map<Integer, OFBarrierReplyFuture>>();
+
+ private int number_thread = 1;
+
+ /**
+ * Main thread that reads messages from queues and sends them to switches.
+ * @author Naoki Shiota
+ *
+ */
+ private class FlowPusherThread extends Thread {
+ private Map<IOFSwitch,SwitchQueue> queues
+ = new HashMap<IOFSwitch,SwitchQueue>();
+
+ private Semaphore mutex = new Semaphore(0);
+
+ @Override
+ public void run() {
+ log.debug("Begin Flow Pusher Process");
+
+ while (true) {
+ try {
+ // wait for message pushed to queue
+ mutex.acquire();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ log.debug("FlowPusherThread is interrupted");
+ return;
+ }
+
+ Set< Map.Entry<IOFSwitch,SwitchQueue> > entries;
+ synchronized (queues) {
+ entries = queues.entrySet();
+ }
+
+ for (Map.Entry<IOFSwitch,SwitchQueue> entry : entries) {
+ IOFSwitch sw = entry.getKey();
+ SwitchQueue queue = entry.getValue();
+
+ // Skip if queue is suspended
+ if (sw == null || queue == null ||
+ queue.state != QueueState.READY) {
+ continue;
+ }
+
+ // check sending rate and determine it to be sent or not
+ long current_time = System.nanoTime();
+ long size = 0;
+
+ synchronized (queue) {
+ if (queue.isSendable(current_time)) {
+ int i = 0;
+ while (! queue.isEmpty()) {
+ // Number of messages excess the limit
+ if (i >= MAX_MESSAGE_SEND) {
+ // Messages remains in queue
+ mutex.release();
+ break;
+ }
+ ++i;
+
+ OFMessage msg = queue.poll();
+ try {
+ messageDamper.write(sw, msg, context);
+ log.debug("Pusher sends message : {}", msg);
+ size += msg.getLength();
+ } catch (IOException e) {
+ e.printStackTrace();
+ log.error("Exception in sending message ({}) : {}", msg, e);
+ }
+ }
+ sw.flush();
+ queue.logSentData(current_time, size);
+
+ if (queue.isEmpty() && barrierIfEmpty) {
+ barrier(sw);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Initialize object with one thread.
+ */
+ public FlowPusher() {
+ }
+
+ /**
+ * Initialize object with threads of given number.
+ * @param number_thread Number of threads to handle messages.
+ */
+ public FlowPusher(int number_thread) {
+ this.number_thread = number_thread;
+ }
+
+ /**
+ * Set parameters needed for sending messages.
+ * @param context FloodlightContext used for sending messages.
+ * If null, FlowPusher uses default context.
+ * @param modContext FloodlightModuleContext used for acquiring
+ * ThreadPoolService and registering MessageListener.
+ * @param factory Factory object to create OFMessage objects.
+ * @param damper Message damper used for sending messages.
+ * If null, FlowPusher creates its own damper object.
+ */
+ public void init(FloodlightContext context,
+ FloodlightModuleContext modContext,
+ BasicFactory factory,
+ OFMessageDamper damper) {
+ this.context = context;
+ this.factory = factory;
+ this.threadPool = modContext.getServiceImpl(IThreadPoolService.class);
+ IFloodlightProviderService flservice = modContext.getServiceImpl(IFloodlightProviderService.class);
+ flservice.addOFMessageListener(OFType.BARRIER_REPLY, this);
+
+ if (damper != null) {
+ messageDamper = damper;
+ } else {
+ // use default value
+ messageDamper = new OFMessageDamper(OFMESSAGE_DAMPER_CAPACITY,
+ EnumSet.of(OFType.FLOW_MOD),
+ OFMESSAGE_DAMPER_TIMEOUT);
+ }
+ }
+
+ /**
+ * Begin processing queue.
+ */
+ public void start() {
+ if (factory == null) {
+ log.error("FlowPusher not yet initialized.");
+ return;
+ }
+
+ threadMap = new HashMap<Long,FlowPusherThread>();
+ for (long i = 0; i < number_thread; ++i) {
+ FlowPusherThread thread = new FlowPusherThread();
+
+ threadMap.put(i, thread);
+ thread.start();
+ }
+ }
+
+ /**
+ * Suspend sending messages to switch.
+ * @param sw
+ */
+ @Override
+ public boolean suspend(IOFSwitch sw) {
+ SwitchQueue queue = getQueue(sw);
+
+ if (queue == null) {
+ return false;
+ }
+
+ synchronized (queue) {
+ if (queue.state == QueueState.READY) {
+ queue.state = QueueState.SUSPENDED;
+ return true;
+ }
+ return false;
+ }
+ }
+
+ /**
+ * Resume sending messages to switch.
+ */
+ @Override
+ public boolean resume(IOFSwitch sw) {
+ SwitchQueue queue = getQueue(sw);
+
+ if (queue == null) {
+ return false;
+ }
+
+ synchronized (queue) {
+ if (queue.state == QueueState.SUSPENDED) {
+ queue.state = QueueState.READY;
+ return true;
+ }
+ return false;
+ }
+ }
+
+ /**
+ * Check if given switch is suspended.
+ */
+ @Override
+ public boolean isSuspended(IOFSwitch sw) {
+ SwitchQueue queue = getQueue(sw);
+
+ if (queue == null) {
+ // TODO Is true suitable for this case?
+ return true;
+ }
+
+ return (queue.state == QueueState.SUSPENDED);
+ }
+
+ /**
+ * Stop processing queue and exit thread.
+ */
+ public void stop() {
+ if (threadMap == null) {
+ return;
+ }
+
+ for (FlowPusherThread t : threadMap.values()) {
+ t.interrupt();
+ }
+ }
+
+ /**
+ * Set sending rate to a switch.
+ * @param sw Switch.
+ * @param rate Rate in bytes/sec.
+ */
+ public void setRate(IOFSwitch sw, long rate) {
+ SwitchQueue queue = getQueue(sw);
+ if (queue == null) {
+ return;
+ }
+
+ if (rate > 0) {
+ queue.max_rate = rate;
+ }
+ }
+
+ /**
+ * Add OFMessage to queue of the switch.
+ * @param sw Switch to which message is sent.
+ * @param msg Message to be sent.
+ * @return true if succeed.
+ */
+ @Override
+ public boolean add(IOFSwitch sw, OFMessage msg) {
+ FlowPusherThread proc = getProcess(sw);
+ SwitchQueue queue = proc.queues.get(sw);
+
+ if (queue == null) {
+ queue = new SwitchQueue();
+ queue.state = QueueState.READY;
+ synchronized (proc) {
+ proc.queues.put(sw, queue);
+ }
+ }
+
+ synchronized (queue) {
+ queue.add(msg);
+ log.debug("Message is pushed : {}", msg);
+ }
+
+ if (proc.mutex.availablePermits() == 0) {
+ proc.mutex.release();
+ }
+
+ return true;
+ }
+
+ /**
+ * Create OFMessage from given flow information and add it to the queue.
+ * @param sw Switch to which message is sent.
+ * @param flowObj FlowPath.
+ * @param flowEntryObj FlowEntry.
+ * @return true if succeed.
+ */
+ @Override
+ public boolean add(IOFSwitch sw, IFlowPath flowObj, IFlowEntry flowEntryObj) {
+ log.debug("sending : {}, {}", sw, flowObj);
+ String flowEntryIdStr = flowEntryObj.getFlowEntryId();
+ if (flowEntryIdStr == null)
+ return false;
+ FlowEntryId flowEntryId = new FlowEntryId(flowEntryIdStr);
+ String userState = flowEntryObj.getUserState();
+ if (userState == null)
+ return false;
+
+ //
+ // Create the Open Flow Flow Modification Entry to push
+ //
+ OFFlowMod fm = (OFFlowMod)factory.getMessage(OFType.FLOW_MOD);
+ long cookie = flowEntryId.value();
+
+ short flowModCommand = OFFlowMod.OFPFC_ADD;
+ if (userState.equals("FE_USER_ADD")) {
+ flowModCommand = OFFlowMod.OFPFC_ADD;
+ } else if (userState.equals("FE_USER_MODIFY")) {
+ flowModCommand = OFFlowMod.OFPFC_MODIFY_STRICT;
+ } else if (userState.equals("FE_USER_DELETE")) {
+ flowModCommand = OFFlowMod.OFPFC_DELETE_STRICT;
+ } else {
+ // Unknown user state. Ignore the entry
+ log.debug("Flow Entry ignored (FlowEntryId = {}): unknown user state {}",
+ flowEntryId.toString(), userState);
+ return false;
+ }
+
+ //
+ // Fetch the match conditions.
+ //
+ // NOTE: The Flow matching conditions common for all Flow Entries are
+ // used ONLY if a Flow Entry does NOT have the corresponding matching
+ // condition set.
+ //
+ OFMatch match = new OFMatch();
+ match.setWildcards(OFMatch.OFPFW_ALL);
+
+ // Match the Incoming Port
+ Short matchInPort = flowEntryObj.getMatchInPort();
+ if (matchInPort != null) {
+ match.setInputPort(matchInPort);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_IN_PORT);
+ }
+
+ // Match the Source MAC address
+ String matchSrcMac = flowEntryObj.getMatchSrcMac();
+ if (matchSrcMac == null)
+ matchSrcMac = flowObj.getMatchSrcMac();
+ if (matchSrcMac != null) {
+ match.setDataLayerSource(matchSrcMac);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_SRC);
+ }
+
+ // Match the Destination MAC address
+ String matchDstMac = flowEntryObj.getMatchDstMac();
+ if (matchDstMac == null)
+ matchDstMac = flowObj.getMatchDstMac();
+ if (matchDstMac != null) {
+ match.setDataLayerDestination(matchDstMac);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_DST);
+ }
+
+ // Match the Ethernet Frame Type
+ Short matchEthernetFrameType = flowEntryObj.getMatchEthernetFrameType();
+ if (matchEthernetFrameType == null)
+ matchEthernetFrameType = flowObj.getMatchEthernetFrameType();
+ if (matchEthernetFrameType != null) {
+ match.setDataLayerType(matchEthernetFrameType);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
+ }
+
+ // Match the VLAN ID
+ Short matchVlanId = flowEntryObj.getMatchVlanId();
+ if (matchVlanId == null)
+ matchVlanId = flowObj.getMatchVlanId();
+ if (matchVlanId != null) {
+ match.setDataLayerVirtualLan(matchVlanId);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_VLAN);
+ }
+
+ // Match the VLAN priority
+ Byte matchVlanPriority = flowEntryObj.getMatchVlanPriority();
+ if (matchVlanPriority == null)
+ matchVlanPriority = flowObj.getMatchVlanPriority();
+ if (matchVlanPriority != null) {
+ match.setDataLayerVirtualLanPriorityCodePoint(matchVlanPriority);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_VLAN_PCP);
+ }
+
+ // Match the Source IPv4 Network prefix
+ String matchSrcIPv4Net = flowEntryObj.getMatchSrcIPv4Net();
+ if (matchSrcIPv4Net == null)
+ matchSrcIPv4Net = flowObj.getMatchSrcIPv4Net();
+ if (matchSrcIPv4Net != null) {
+ match.setFromCIDR(matchSrcIPv4Net, OFMatch.STR_NW_SRC);
+ }
+
+ // Match the Destination IPv4 Network prefix
+ String matchDstIPv4Net = flowEntryObj.getMatchDstIPv4Net();
+ if (matchDstIPv4Net == null)
+ matchDstIPv4Net = flowObj.getMatchDstIPv4Net();
+ if (matchDstIPv4Net != null) {
+ match.setFromCIDR(matchDstIPv4Net, OFMatch.STR_NW_DST);
+ }
+
+ // Match the IP protocol
+ Byte matchIpProto = flowEntryObj.getMatchIpProto();
+ if (matchIpProto == null)
+ matchIpProto = flowObj.getMatchIpProto();
+ if (matchIpProto != null) {
+ match.setNetworkProtocol(matchIpProto);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_NW_PROTO);
+ }
+
+ // Match the IP ToS (DSCP field, 6 bits)
+ Byte matchIpToS = flowEntryObj.getMatchIpToS();
+ if (matchIpToS == null)
+ matchIpToS = flowObj.getMatchIpToS();
+ if (matchIpToS != null) {
+ match.setNetworkTypeOfService(matchIpToS);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_NW_TOS);
+ }
+
+ // Match the Source TCP/UDP port
+ Short matchSrcTcpUdpPort = flowEntryObj.getMatchSrcTcpUdpPort();
+ if (matchSrcTcpUdpPort == null)
+ matchSrcTcpUdpPort = flowObj.getMatchSrcTcpUdpPort();
+ if (matchSrcTcpUdpPort != null) {
+ match.setTransportSource(matchSrcTcpUdpPort);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_TP_SRC);
+ }
+
+ // Match the Destination TCP/UDP port
+ Short matchDstTcpUdpPort = flowEntryObj.getMatchDstTcpUdpPort();
+ if (matchDstTcpUdpPort == null)
+ matchDstTcpUdpPort = flowObj.getMatchDstTcpUdpPort();
+ if (matchDstTcpUdpPort != null) {
+ match.setTransportDestination(matchDstTcpUdpPort);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_TP_DST);
+ }
+
+ //
+ // Fetch the actions
+ //
+ Short actionOutputPort = null;
+ List<OFAction> openFlowActions = new ArrayList<OFAction>();
+ int actionsLen = 0;
+ FlowEntryActions flowEntryActions = null;
+ String actionsStr = flowEntryObj.getActions();
+ if (actionsStr != null)
+ flowEntryActions = new FlowEntryActions(actionsStr);
+ else
+ flowEntryActions = new FlowEntryActions();
+ for (FlowEntryAction action : flowEntryActions.actions()) {
+ ActionOutput actionOutput = action.actionOutput();
+ ActionSetVlanId actionSetVlanId = action.actionSetVlanId();
+ ActionSetVlanPriority actionSetVlanPriority = action.actionSetVlanPriority();
+ ActionStripVlan actionStripVlan = action.actionStripVlan();
+ ActionSetEthernetAddr actionSetEthernetSrcAddr = action.actionSetEthernetSrcAddr();
+ ActionSetEthernetAddr actionSetEthernetDstAddr = action.actionSetEthernetDstAddr();
+ ActionSetIPv4Addr actionSetIPv4SrcAddr = action.actionSetIPv4SrcAddr();
+ ActionSetIPv4Addr actionSetIPv4DstAddr = action.actionSetIPv4DstAddr();
+ ActionSetIpToS actionSetIpToS = action.actionSetIpToS();
+ ActionSetTcpUdpPort actionSetTcpUdpSrcPort = action.actionSetTcpUdpSrcPort();
+ ActionSetTcpUdpPort actionSetTcpUdpDstPort = action.actionSetTcpUdpDstPort();
+ ActionEnqueue actionEnqueue = action.actionEnqueue();
+
+ if (actionOutput != null) {
+ actionOutputPort = actionOutput.port().value();
+ // XXX: The max length is hard-coded for now
+ OFActionOutput ofa =
+ new OFActionOutput(actionOutput.port().value(),
+ (short)0xffff);
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetVlanId != null) {
+ OFActionVirtualLanIdentifier ofa =
+ new OFActionVirtualLanIdentifier(actionSetVlanId.vlanId());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetVlanPriority != null) {
+ OFActionVirtualLanPriorityCodePoint ofa =
+ new OFActionVirtualLanPriorityCodePoint(actionSetVlanPriority.vlanPriority());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionStripVlan != null) {
+ if (actionStripVlan.stripVlan() == true) {
+ OFActionStripVirtualLan ofa = new OFActionStripVirtualLan();
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+ }
+
+ if (actionSetEthernetSrcAddr != null) {
+ OFActionDataLayerSource ofa =
+ new OFActionDataLayerSource(actionSetEthernetSrcAddr.addr().toBytes());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetEthernetDstAddr != null) {
+ OFActionDataLayerDestination ofa =
+ new OFActionDataLayerDestination(actionSetEthernetDstAddr.addr().toBytes());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetIPv4SrcAddr != null) {
+ OFActionNetworkLayerSource ofa =
+ new OFActionNetworkLayerSource(actionSetIPv4SrcAddr.addr().value());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetIPv4DstAddr != null) {
+ OFActionNetworkLayerDestination ofa =
+ new OFActionNetworkLayerDestination(actionSetIPv4DstAddr.addr().value());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetIpToS != null) {
+ OFActionNetworkTypeOfService ofa =
+ new OFActionNetworkTypeOfService(actionSetIpToS.ipToS());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetTcpUdpSrcPort != null) {
+ OFActionTransportLayerSource ofa =
+ new OFActionTransportLayerSource(actionSetTcpUdpSrcPort.port());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetTcpUdpDstPort != null) {
+ OFActionTransportLayerDestination ofa =
+ new OFActionTransportLayerDestination(actionSetTcpUdpDstPort.port());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionEnqueue != null) {
+ OFActionEnqueue ofa =
+ new OFActionEnqueue(actionEnqueue.port().value(),
+ actionEnqueue.queueId());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+ }
+
+ fm.setIdleTimeout(FLOWMOD_DEFAULT_IDLE_TIMEOUT)
+ .setHardTimeout(FLOWMOD_DEFAULT_HARD_TIMEOUT)
+ .setPriority(PRIORITY_DEFAULT)
+ .setBufferId(OFPacketOut.BUFFER_ID_NONE)
+ .setCookie(cookie)
+ .setCommand(flowModCommand)
+ .setMatch(match)
+ .setActions(openFlowActions)
+ .setLengthU(OFFlowMod.MINIMUM_LENGTH + actionsLen);
+ fm.setOutPort(OFPort.OFPP_NONE.getValue());
+ if ((flowModCommand == OFFlowMod.OFPFC_DELETE) ||
+ (flowModCommand == OFFlowMod.OFPFC_DELETE_STRICT)) {
+ if (actionOutputPort != null)
+ fm.setOutPort(actionOutputPort);
+ }
+
+ //
+ // TODO: Set the following flag
+ // fm.setFlags(OFFlowMod.OFPFF_SEND_FLOW_REM);
+ // See method ForwardingBase::pushRoute()
+ //
+
+ //
+ // Write the message to the switch
+ //
+ log.debug("MEASUREMENT: Installing flow entry " + userState +
+ " into switch DPID: " +
+ sw.getStringId() +
+ " flowEntryId: " + flowEntryId.toString() +
+ " srcMac: " + matchSrcMac + " dstMac: " + matchDstMac +
+ " inPort: " + matchInPort + " outPort: " + actionOutputPort
+ );
+ add(sw,fm);
+ //
+ // TODO: We should use the OpenFlow Barrier mechanism
+ // to check for errors, and update the SwitchState
+ // for a flow entry after the Barrier message is
+ // is received.
+ //
+ flowEntryObj.setSwitchState("FE_SWITCH_UPDATED");
+
+ return true;
+ }
+
+ /**
+ * Create OFMessage from given flow information and add it to the queue.
+ * @param sw Switch to which message is sent.
+ * @param flowPath FlowPath.
+ * @param flowEntry FlowEntry.
+ * @return true if secceed.
+ */
+ @Override
+ public boolean add(IOFSwitch sw, FlowPath flowPath, FlowEntry flowEntry) {
+ //
+ // Create the OpenFlow Flow Modification Entry to push
+ //
+ OFFlowMod fm = (OFFlowMod) factory.getMessage(OFType.FLOW_MOD);
+ long cookie = flowEntry.flowEntryId().value();
+
+ short flowModCommand = OFFlowMod.OFPFC_ADD;
+ if (flowEntry.flowEntryUserState() == FlowEntryUserState.FE_USER_ADD) {
+ flowModCommand = OFFlowMod.OFPFC_ADD;
+ } else if (flowEntry.flowEntryUserState() == FlowEntryUserState.FE_USER_MODIFY) {
+ flowModCommand = OFFlowMod.OFPFC_MODIFY_STRICT;
+ } else if (flowEntry.flowEntryUserState() == FlowEntryUserState.FE_USER_DELETE) {
+ flowModCommand = OFFlowMod.OFPFC_DELETE_STRICT;
+ } else {
+ // Unknown user state. Ignore the entry
+ log.debug(
+ "Flow Entry ignored (FlowEntryId = {}): unknown user state {}",
+ flowEntry.flowEntryId().toString(),
+ flowEntry.flowEntryUserState());
+ return false;
+ }
+
+ //
+ // Fetch the match conditions.
+ //
+ // NOTE: The Flow matching conditions common for all Flow Entries are
+ // used ONLY if a Flow Entry does NOT have the corresponding matching
+ // condition set.
+ //
+ OFMatch match = new OFMatch();
+ match.setWildcards(OFMatch.OFPFW_ALL);
+ FlowEntryMatch flowPathMatch = flowPath.flowEntryMatch();
+ FlowEntryMatch flowEntryMatch = flowEntry.flowEntryMatch();
+
+ // Match the Incoming Port
+ Port matchInPort = flowEntryMatch.inPort();
+ if (matchInPort != null) {
+ match.setInputPort(matchInPort.value());
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_IN_PORT);
+ }
+
+ // Match the Source MAC address
+ MACAddress matchSrcMac = flowEntryMatch.srcMac();
+ if ((matchSrcMac == null) && (flowPathMatch != null)) {
+ matchSrcMac = flowPathMatch.srcMac();
+ }
+ if (matchSrcMac != null) {
+ match.setDataLayerSource(matchSrcMac.toString());
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_SRC);
+ }
+
+ // Match the Destination MAC address
+ MACAddress matchDstMac = flowEntryMatch.dstMac();
+ if ((matchDstMac == null) && (flowPathMatch != null)) {
+ matchDstMac = flowPathMatch.dstMac();
+ }
+ if (matchDstMac != null) {
+ match.setDataLayerDestination(matchDstMac.toString());
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_DST);
+ }
+
+ // Match the Ethernet Frame Type
+ Short matchEthernetFrameType = flowEntryMatch.ethernetFrameType();
+ if ((matchEthernetFrameType == null) && (flowPathMatch != null)) {
+ matchEthernetFrameType = flowPathMatch.ethernetFrameType();
+ }
+ if (matchEthernetFrameType != null) {
+ match.setDataLayerType(matchEthernetFrameType);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
+ }
+
+ // Match the VLAN ID
+ Short matchVlanId = flowEntryMatch.vlanId();
+ if ((matchVlanId == null) && (flowPathMatch != null)) {
+ matchVlanId = flowPathMatch.vlanId();
+ }
+ if (matchVlanId != null) {
+ match.setDataLayerVirtualLan(matchVlanId);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_VLAN);
+ }
+
+ // Match the VLAN priority
+ Byte matchVlanPriority = flowEntryMatch.vlanPriority();
+ if ((matchVlanPriority == null) && (flowPathMatch != null)) {
+ matchVlanPriority = flowPathMatch.vlanPriority();
+ }
+ if (matchVlanPriority != null) {
+ match.setDataLayerVirtualLanPriorityCodePoint(matchVlanPriority);
+ match.setWildcards(match.getWildcards()
+ & ~OFMatch.OFPFW_DL_VLAN_PCP);
+ }
+
+ // Match the Source IPv4 Network prefix
+ IPv4Net matchSrcIPv4Net = flowEntryMatch.srcIPv4Net();
+ if ((matchSrcIPv4Net == null) && (flowPathMatch != null)) {
+ matchSrcIPv4Net = flowPathMatch.srcIPv4Net();
+ }
+ if (matchSrcIPv4Net != null) {
+ match.setFromCIDR(matchSrcIPv4Net.toString(), OFMatch.STR_NW_SRC);
+ }
+
+ // Natch the Destination IPv4 Network prefix
+ IPv4Net matchDstIPv4Net = flowEntryMatch.dstIPv4Net();
+ if ((matchDstIPv4Net == null) && (flowPathMatch != null)) {
+ matchDstIPv4Net = flowPathMatch.dstIPv4Net();
+ }
+ if (matchDstIPv4Net != null) {
+ match.setFromCIDR(matchDstIPv4Net.toString(), OFMatch.STR_NW_DST);
+ }
+
+ // Match the IP protocol
+ Byte matchIpProto = flowEntryMatch.ipProto();
+ if ((matchIpProto == null) && (flowPathMatch != null)) {
+ matchIpProto = flowPathMatch.ipProto();
+ }
+ if (matchIpProto != null) {
+ match.setNetworkProtocol(matchIpProto);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_NW_PROTO);
+ }
+
+ // Match the IP ToS (DSCP field, 6 bits)
+ Byte matchIpToS = flowEntryMatch.ipToS();
+ if ((matchIpToS == null) && (flowPathMatch != null)) {
+ matchIpToS = flowPathMatch.ipToS();
+ }
+ if (matchIpToS != null) {
+ match.setNetworkTypeOfService(matchIpToS);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_NW_TOS);
+ }
+
+ // Match the Source TCP/UDP port
+ Short matchSrcTcpUdpPort = flowEntryMatch.srcTcpUdpPort();
+ if ((matchSrcTcpUdpPort == null) && (flowPathMatch != null)) {
+ matchSrcTcpUdpPort = flowPathMatch.srcTcpUdpPort();
+ }
+ if (matchSrcTcpUdpPort != null) {
+ match.setTransportSource(matchSrcTcpUdpPort);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_TP_SRC);
+ }
+
+ // Match the Destination TCP/UDP port
+ Short matchDstTcpUdpPort = flowEntryMatch.dstTcpUdpPort();
+ if ((matchDstTcpUdpPort == null) && (flowPathMatch != null)) {
+ matchDstTcpUdpPort = flowPathMatch.dstTcpUdpPort();
+ }
+ if (matchDstTcpUdpPort != null) {
+ match.setTransportDestination(matchDstTcpUdpPort);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_TP_DST);
+ }
+
+ //
+ // Fetch the actions
+ //
+ Short actionOutputPort = null;
+ List<OFAction> openFlowActions = new ArrayList<OFAction>();
+ int actionsLen = 0;
+ FlowEntryActions flowEntryActions = flowEntry.flowEntryActions();
+ //
+ for (FlowEntryAction action : flowEntryActions.actions()) {
+ ActionOutput actionOutput = action.actionOutput();
+ ActionSetVlanId actionSetVlanId = action.actionSetVlanId();
+ ActionSetVlanPriority actionSetVlanPriority = action
+ .actionSetVlanPriority();
+ ActionStripVlan actionStripVlan = action.actionStripVlan();
+ ActionSetEthernetAddr actionSetEthernetSrcAddr = action
+ .actionSetEthernetSrcAddr();
+ ActionSetEthernetAddr actionSetEthernetDstAddr = action
+ .actionSetEthernetDstAddr();
+ ActionSetIPv4Addr actionSetIPv4SrcAddr = action
+ .actionSetIPv4SrcAddr();
+ ActionSetIPv4Addr actionSetIPv4DstAddr = action
+ .actionSetIPv4DstAddr();
+ ActionSetIpToS actionSetIpToS = action.actionSetIpToS();
+ ActionSetTcpUdpPort actionSetTcpUdpSrcPort = action
+ .actionSetTcpUdpSrcPort();
+ ActionSetTcpUdpPort actionSetTcpUdpDstPort = action
+ .actionSetTcpUdpDstPort();
+ ActionEnqueue actionEnqueue = action.actionEnqueue();
+
+ if (actionOutput != null) {
+ actionOutputPort = actionOutput.port().value();
+ // XXX: The max length is hard-coded for now
+ OFActionOutput ofa = new OFActionOutput(actionOutput.port()
+ .value(), (short) 0xffff);
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetVlanId != null) {
+ OFActionVirtualLanIdentifier ofa = new OFActionVirtualLanIdentifier(
+ actionSetVlanId.vlanId());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetVlanPriority != null) {
+ OFActionVirtualLanPriorityCodePoint ofa = new OFActionVirtualLanPriorityCodePoint(
+ actionSetVlanPriority.vlanPriority());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionStripVlan != null) {
+ if (actionStripVlan.stripVlan() == true) {
+ OFActionStripVirtualLan ofa = new OFActionStripVirtualLan();
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+ }
+
+ if (actionSetEthernetSrcAddr != null) {
+ OFActionDataLayerSource ofa = new OFActionDataLayerSource(
+ actionSetEthernetSrcAddr.addr().toBytes());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetEthernetDstAddr != null) {
+ OFActionDataLayerDestination ofa = new OFActionDataLayerDestination(
+ actionSetEthernetDstAddr.addr().toBytes());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetIPv4SrcAddr != null) {
+ OFActionNetworkLayerSource ofa = new OFActionNetworkLayerSource(
+ actionSetIPv4SrcAddr.addr().value());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetIPv4DstAddr != null) {
+ OFActionNetworkLayerDestination ofa = new OFActionNetworkLayerDestination(
+ actionSetIPv4DstAddr.addr().value());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetIpToS != null) {
+ OFActionNetworkTypeOfService ofa = new OFActionNetworkTypeOfService(
+ actionSetIpToS.ipToS());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetTcpUdpSrcPort != null) {
+ OFActionTransportLayerSource ofa = new OFActionTransportLayerSource(
+ actionSetTcpUdpSrcPort.port());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionSetTcpUdpDstPort != null) {
+ OFActionTransportLayerDestination ofa = new OFActionTransportLayerDestination(
+ actionSetTcpUdpDstPort.port());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+
+ if (actionEnqueue != null) {
+ OFActionEnqueue ofa = new OFActionEnqueue(actionEnqueue.port()
+ .value(), actionEnqueue.queueId());
+ openFlowActions.add(ofa);
+ actionsLen += ofa.getLength();
+ }
+ }
+
+ fm.setIdleTimeout(FLOWMOD_DEFAULT_IDLE_TIMEOUT)
+ .setHardTimeout(FLOWMOD_DEFAULT_HARD_TIMEOUT)
+ .setPriority(PRIORITY_DEFAULT)
+ .setBufferId(OFPacketOut.BUFFER_ID_NONE).setCookie(cookie)
+ .setCommand(flowModCommand).setMatch(match)
+ .setActions(openFlowActions)
+ .setLengthU(OFFlowMod.MINIMUM_LENGTH + actionsLen);
+ fm.setOutPort(OFPort.OFPP_NONE.getValue());
+ if ((flowModCommand == OFFlowMod.OFPFC_DELETE)
+ || (flowModCommand == OFFlowMod.OFPFC_DELETE_STRICT)) {
+ if (actionOutputPort != null)
+ fm.setOutPort(actionOutputPort);
+ }
+
+ //
+ // TODO: Set the following flag
+ // fm.setFlags(OFFlowMod.OFPFF_SEND_FLOW_REM);
+ // See method ForwardingBase::pushRoute()
+ //
+
+ //
+ // Write the message to the switch
+ //
+ log.debug("MEASUREMENT: Installing flow entry "
+ + flowEntry.flowEntryUserState() + " into switch DPID: "
+ + sw.getStringId() + " flowEntryId: "
+ + flowEntry.flowEntryId().toString() + " srcMac: "
+ + matchSrcMac + " dstMac: " + matchDstMac + " inPort: "
+ + matchInPort + " outPort: " + actionOutputPort);
+
+ //
+ // TODO: We should use the OpenFlow Barrier mechanism
+ // to check for errors, and update the SwitchState
+ // for a flow entry after the Barrier message is
+ // is received.
+ //
+ // TODO: The FlowEntry Object in Titan should be set
+ // to FE_SWITCH_UPDATED.
+ //
+
+ return add(sw,fm);
+ }
+
+ @Override
+ public OFBarrierReply barrier(IOFSwitch sw) {
+ OFMessageFuture<OFBarrierReply> future = barrierAsync(sw);
+ if (future == null) {
+ return null;
+ }
+
+ try {
+ return future.get();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ log.error("InterruptedException: {}", e);
+ return null;
+ } catch (ExecutionException e) {
+ e.printStackTrace();
+ log.error("ExecutionException: {}", e);
+ return null;
+ }
+ }
+
+ @Override
+ public OFBarrierReplyFuture barrierAsync(IOFSwitch sw) {
+ // TODO creation of message and future should be moved to OFSwitchImpl
+
+ if (sw == null) {
+ return null;
+ }
+
+ OFBarrierRequest msg = (OFBarrierRequest) factory.getMessage(OFType.BARRIER_REQUEST);
+ msg.setXid(sw.getNextTransactionId());
+ add(sw, msg);
+
+ // TODO create Future object of message
+ OFBarrierReplyFuture future = new OFBarrierReplyFuture(threadPool, sw, msg.getXid());
+
+ synchronized (barrierFutures) {
+ Map<Integer,OFBarrierReplyFuture> map = barrierFutures.get(sw.getId());
+ if (map == null) {
+ map = new HashMap<Integer,OFBarrierReplyFuture>();
+ barrierFutures.put(sw.getId(), map);
+ }
+ map.put(msg.getXid(), future);
+ log.debug("Inserted future for {}", msg.getXid());
+ }
+
+ return future;
+ }
+
+ protected SwitchQueue getQueue(IOFSwitch sw) {
+ if (sw == null) {
+ return null;
+ }
+
+ return getProcess(sw).queues.get(sw);
+ }
+
+ protected long getHash(IOFSwitch sw) {
+ // This code assumes DPID is sequentially assigned.
+ // TODO consider equalization algorithm
+ return sw.getId() % number_thread;
+ }
+
+ protected FlowPusherThread getProcess(IOFSwitch sw) {
+ long hash = getHash(sw);
+
+ return threadMap.get(hash);
+ }
+
+ @Override
+ public String getName() {
+ return "flowpusher";
+ }
+
+ @Override
+ public boolean isCallbackOrderingPrereq(OFType type, String name) {
+ return false;
+ }
+
+ @Override
+ public boolean isCallbackOrderingPostreq(OFType type, String name) {
+ return false;
+ }
+
+ @Override
+ public Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx) {
+ Map<Integer,OFBarrierReplyFuture> map = barrierFutures.get(sw.getId());
+ if (map == null) {
+ return Command.CONTINUE;
+ }
+
+ OFBarrierReplyFuture future = map.get(msg.getXid());
+ if (future == null) {
+ return Command.CONTINUE;
+ }
+
+ log.debug("Received BARRIER_REPLY : {}", msg);
+ future.deliverFuture(sw, msg);
+
+ return Command.CONTINUE;
+ }
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/FlowSynchronizer.java b/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/FlowSynchronizer.java
new file mode 100644
index 0000000..f3f5c50
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/FlowSynchronizer.java
@@ -0,0 +1,270 @@
+package net.onrc.onos.ofcontroller.flowprogrammer;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+import org.openflow.protocol.OFFlowMod;
+import org.openflow.protocol.OFMatch;
+import org.openflow.protocol.OFPort;
+import org.openflow.protocol.OFStatisticsRequest;
+import org.openflow.protocol.statistics.OFFlowStatisticsReply;
+import org.openflow.protocol.statistics.OFFlowStatisticsRequest;
+import org.openflow.protocol.statistics.OFStatistics;
+import org.openflow.protocol.statistics.OFStatisticsType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import net.floodlightcontroller.core.IFloodlightProviderService;
+import net.floodlightcontroller.core.IOFSwitch;
+import net.floodlightcontroller.core.IOFSwitchListener;
+import net.floodlightcontroller.core.module.FloodlightModuleContext;
+import net.floodlightcontroller.core.module.FloodlightModuleException;
+import net.onrc.onos.graph.GraphDBOperation;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowEntry;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.ISwitchObject;
+import net.onrc.onos.ofcontroller.util.Dpid;
+import net.onrc.onos.ofcontroller.util.FlowEntryId;
+import net.onrc.onos.registry.controller.IControllerRegistryService;
+
+public class FlowSynchronizer implements IFlowSyncService, IOFSwitchListener {
+
+ protected static Logger log = LoggerFactory.getLogger(FlowSynchronizer.class);
+ protected IFloodlightProviderService floodlightProvider;
+ protected IControllerRegistryService registryService;
+ protected IFlowPusherService pusher;
+
+ private GraphDBOperation dbHandler;
+ private Map<IOFSwitch, Thread> switchThread = new HashMap<IOFSwitch, Thread>();
+
+ public FlowSynchronizer() {
+ dbHandler = new GraphDBOperation("");
+ }
+
+ public void synchronize(IOFSwitch sw) {
+ Synchroizer sync = new Synchroizer(sw);
+ Thread t = new Thread(sync);
+ switchThread.put(sw, t);
+ t.start();
+ }
+
+ @Override
+ public void addedSwitch(IOFSwitch sw) {
+ log.debug("Switch added: {}", sw.getId());
+
+ if (registryService.hasControl(sw.getId())) {
+ synchronize(sw);
+ }
+ }
+
+ @Override
+ public void removedSwitch(IOFSwitch sw) {
+ log.debug("Switch removed: {}", sw.getId());
+
+ Thread t = switchThread.remove(sw);
+ if(t != null) {
+ t.interrupt();
+ }
+
+ }
+
+ @Override
+ public void switchPortChanged(Long switchId) {
+ // TODO Auto-generated method stub
+ }
+
+ @Override
+ public String getName() {
+ return "FlowSynchronizer";
+ }
+
+ //@Override
+ public void init(FloodlightModuleContext context)
+ throws FloodlightModuleException {
+ floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
+ registryService = context.getServiceImpl(IControllerRegistryService.class);
+ pusher = context.getServiceImpl(IFlowPusherService.class);
+ }
+
+ //@Override
+ public void startUp(FloodlightModuleContext context) {
+ floodlightProvider.addOFSwitchListener(this);
+ }
+
+ protected class Synchroizer implements Runnable {
+ IOFSwitch sw;
+ ISwitchObject swObj;
+
+ public Synchroizer(IOFSwitch sw) {
+ this.sw = sw;
+ Dpid dpid = new Dpid(sw.getId());
+ this.swObj = dbHandler.searchSwitch(dpid.toString());
+ }
+
+ @Override
+ public void run() {
+ Set<FlowEntryWrapper> graphEntries = getFlowEntriesFromGraph();
+ Set<FlowEntryWrapper> switchEntries = getFlowEntriesFromSwitch();
+ compare(graphEntries, switchEntries);
+ }
+
+ private void compare(Set<FlowEntryWrapper> graphEntries, Set<FlowEntryWrapper> switchEntries) {
+ int added = 0, removed = 0, skipped = 0;
+ for(FlowEntryWrapper entry : switchEntries) {
+ if(graphEntries.contains(entry)) {
+ graphEntries.remove(entry);
+ skipped++;
+ }
+ else {
+ // remove flow entry from the switch
+ entry.removeFromSwitch(sw);
+ removed++;
+ }
+ }
+ for(FlowEntryWrapper entry : graphEntries) {
+ // add flow entry to switch
+ entry.addToSwitch(sw);
+ added++;
+ }
+ log.debug("Flow entries added "+ added + ", " +
+ "Flow entries removed "+ removed + ", " +
+ "Flow entries skipped " + skipped);
+ }
+
+ private Set<FlowEntryWrapper> getFlowEntriesFromGraph() {
+ Set<FlowEntryWrapper> entries = new HashSet<FlowEntryWrapper>();
+ for(IFlowEntry entry : swObj.getFlowEntries()) {
+ FlowEntryWrapper fe = new FlowEntryWrapper(entry);
+ entries.add(fe);
+ }
+ return entries;
+ }
+
+ private Set<FlowEntryWrapper> getFlowEntriesFromSwitch() {
+
+ int lengthU = 0;
+ OFMatch match = new OFMatch();
+ match.setWildcards(OFMatch.OFPFW_ALL);
+
+ OFFlowStatisticsRequest stat = new OFFlowStatisticsRequest();
+ stat.setOutPort((short) 0xffff); //TODO: OFPort.OFPP_NONE
+ stat.setTableId((byte) 0xff); // TODO: fix this with enum (ALL TABLES)
+ stat.setMatch(match);
+ List<OFStatistics> stats = new ArrayList<OFStatistics>();
+ stats.add(stat);
+ lengthU += stat.getLength();
+
+ OFStatisticsRequest req = new OFStatisticsRequest();
+ req.setStatisticType(OFStatisticsType.FLOW);
+ req.setStatistics(stats);
+ lengthU += req.getLengthU();
+ req.setLengthU(lengthU);
+
+ List<OFStatistics> entries = null;
+ try {
+ Future<List<OFStatistics>> dfuture = sw.getStatistics(req);
+ entries = dfuture.get();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (ExecutionException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ Set<FlowEntryWrapper> results = new HashSet<FlowEntryWrapper>();
+ for(OFStatistics result : entries){
+ OFFlowStatisticsReply entry = (OFFlowStatisticsReply) result;
+ FlowEntryWrapper fe = new FlowEntryWrapper(entry);
+ results.add(fe);
+ }
+ return results;
+ }
+
+ }
+
+ class FlowEntryWrapper {
+ FlowEntryId id;
+ IFlowEntry iflowEntry;
+ OFFlowStatisticsReply statisticsReply;
+
+ public FlowEntryWrapper(IFlowEntry entry) {
+ iflowEntry = entry;
+ id = new FlowEntryId(entry.getFlowEntryId());
+ }
+
+ public FlowEntryWrapper(OFFlowStatisticsReply entry) {
+ statisticsReply = entry;
+ id = new FlowEntryId(entry.getCookie());
+ }
+
+ public void addToSwitch(IOFSwitch sw) {
+ if(iflowEntry != null) {
+ pusher.add(sw, iflowEntry.getFlow(), iflowEntry);
+ }
+ else if(statisticsReply != null) {
+ log.error("Adding existing flow entry {} to sw {}",
+ statisticsReply.getCookie(), sw.getId());
+ }
+ }
+
+ public void removeFromSwitch(IOFSwitch sw){
+ if(iflowEntry != null) {
+ log.error("Removing non-existent flow entry {} from sw {}",
+ iflowEntry.getFlowEntryId(), sw.getId());
+
+ }
+ else if(statisticsReply != null) {
+ // Convert Statistics Reply to Flow Mod, then write it
+ OFFlowMod fm = new OFFlowMod();
+ fm.setCookie(statisticsReply.getCookie());
+ fm.setCommand(OFFlowMod.OFPFC_DELETE_STRICT);
+ fm.setLengthU(OFFlowMod.MINIMUM_LENGTH);
+ fm.setMatch(statisticsReply.getMatch());
+ fm.setPriority(statisticsReply.getPriority());
+ fm.setOutPort(OFPort.OFPP_NONE);
+ pusher.add(sw, fm);
+ }
+ }
+
+ /**
+ * Return the hash code of the Flow Entry ID
+ */
+ @Override
+ public int hashCode() {
+ return id.hashCode();
+ }
+
+ /**
+ * Returns true of the object is another Flow Entry ID with
+ * the same value; otherwise, returns false.
+ *
+ * @param Object to compare
+ */
+ @Override
+ public boolean equals(Object obj){
+ if(obj.getClass() == this.getClass()) {
+ FlowEntryWrapper entry = (FlowEntryWrapper) obj;
+ // TODO: we need to actually compare the match + actions
+ return this.id.equals(entry.id);
+ }
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return id.toString();
+ }
+ }
+}
+
+
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/IFlowPusherService.java b/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/IFlowPusherService.java
new file mode 100644
index 0000000..94d6e35
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/IFlowPusherService.java
@@ -0,0 +1,75 @@
+package net.onrc.onos.ofcontroller.flowprogrammer;
+
+import org.openflow.protocol.OFBarrierReply;
+import org.openflow.protocol.OFMessage;
+
+import net.floodlightcontroller.core.IOFSwitch;
+import net.floodlightcontroller.core.internal.OFMessageFuture;
+import net.floodlightcontroller.core.module.IFloodlightService;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowEntry;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowPath;
+import net.onrc.onos.ofcontroller.util.FlowEntry;
+import net.onrc.onos.ofcontroller.util.FlowPath;
+
+public interface IFlowPusherService extends IFloodlightService {
+ /**
+ * Add a message to the queue of the switch.
+ * @param sw Switch to which message is pushed.
+ * @param msg Message object to be added.
+ * @return true if message is successfully added to a queue.
+ */
+ boolean add(IOFSwitch sw, OFMessage msg);
+
+ /**
+ * Create a message from FlowEntry and add it to the queue of the switch.
+ * @param sw Switch to which message is pushed.
+ * @param flowPath FlowPath object used for creating message.
+ * @param flowEntry FlowEntry object used for creating message.
+ * @return true if message is successfully added to a queue.
+ */
+ boolean add(IOFSwitch sw, FlowPath flowPath, FlowEntry flowEntry);
+
+ /**
+ * Create a message from IFlowEntry and add it to the queue of the switch.
+ * @param sw Switch to which message is pushed.
+ * @param flowObj IFlowPath object used for creating message.
+ * @param flowEntryObj IFlowEntry object used for creating message.
+ * @return true if message is successfully added to a queue.
+ */
+ boolean add(IOFSwitch sw, IFlowPath flowObj, IFlowEntry flowEntryObj);
+
+ /**
+ * Add BARRIER message to queue and wait for reply.
+ * @param sw Switch to which barrier message is pushed.
+ * @return BARRIER_REPLY message sent from switch.
+ */
+ OFBarrierReply barrier(IOFSwitch sw);
+
+ /**
+ * Add BARRIER message to queue asynchronously.
+ * @param sw Switch to which barrier message is pushed.
+ * @return Future object of BARRIER_REPLY message which will be sent from switch.
+ */
+ OFMessageFuture<OFBarrierReply> barrierAsync(IOFSwitch sw);
+
+ /**
+ * Suspend pushing message to a switch.
+ * @param sw Switch to be suspended pushing message.
+ * @return true if success
+ */
+ boolean suspend(IOFSwitch sw);
+
+ /**
+ * Resume pushing message to a switch.
+ * @param sw Switch to be resumed pushing message.
+ * @return true if success
+ */
+ boolean resume(IOFSwitch sw);
+
+ /**
+ * Get whether pushing of message is suspended or not.
+ * @param sw Switch to be checked.
+ * @return true if suspended.
+ */
+ boolean isSuspended(IOFSwitch sw);
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/IFlowSyncService.java b/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/IFlowSyncService.java
new file mode 100644
index 0000000..1e71f6a
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/IFlowSyncService.java
@@ -0,0 +1,13 @@
+package net.onrc.onos.ofcontroller.flowprogrammer;
+
+import net.floodlightcontroller.core.IOFSwitch;
+import net.floodlightcontroller.core.IOFSwitchListener;
+import net.floodlightcontroller.core.module.IFloodlightService;
+
+/**
+ * @author bocon
+ *
+ */
+public interface IFlowSyncService extends IFloodlightService {
+ public void synchronize(IOFSwitch sw);
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/OFBarrierReplyFuture.java b/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/OFBarrierReplyFuture.java
new file mode 100644
index 0000000..3013f5a
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowprogrammer/OFBarrierReplyFuture.java
@@ -0,0 +1,49 @@
+package net.onrc.onos.ofcontroller.flowprogrammer;
+
+import java.util.concurrent.TimeUnit;
+
+import org.openflow.protocol.OFBarrierReply;
+import org.openflow.protocol.OFMessage;
+import org.openflow.protocol.OFType;
+
+import net.floodlightcontroller.core.IOFSwitch;
+import net.floodlightcontroller.core.internal.OFMessageFuture;
+import net.floodlightcontroller.threadpool.IThreadPoolService;
+
+public class OFBarrierReplyFuture extends OFMessageFuture<OFBarrierReply> {
+
+ protected volatile boolean finished;
+
+ public OFBarrierReplyFuture(IThreadPoolService tp,
+ IOFSwitch sw, int transactionId) {
+ super(tp, sw, OFType.FEATURES_REPLY, transactionId);
+ init();
+ }
+
+ public OFBarrierReplyFuture(IThreadPoolService tp,
+ IOFSwitch sw, int transactionId, long timeout, TimeUnit unit) {
+ super(tp, sw, OFType.FEATURES_REPLY, transactionId, timeout, unit);
+ init();
+ }
+
+ private void init() {
+ this.finished = false;
+ this.result = null;
+ }
+
+ @Override
+ protected void handleReply(IOFSwitch sw, OFMessage msg) {
+ this.result = (OFBarrierReply) msg;
+ this.finished = true;
+ }
+
+ @Override
+ protected boolean isFinished() {
+ return finished;
+ }
+
+ @Override
+ protected void unRegister() {
+ super.unRegister();
+ }
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/forwarding/Forwarding.java b/src/main/java/net/onrc/onos/ofcontroller/forwarding/Forwarding.java
new file mode 100644
index 0000000..686bee0
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/forwarding/Forwarding.java
@@ -0,0 +1,197 @@
+package net.onrc.onos.ofcontroller.forwarding;
+
+import java.util.Iterator;
+
+import net.floodlightcontroller.core.FloodlightContext;
+import net.floodlightcontroller.core.IFloodlightProviderService;
+import net.floodlightcontroller.core.IOFMessageListener;
+import net.floodlightcontroller.core.IOFSwitch;
+import net.floodlightcontroller.packet.Ethernet;
+import net.floodlightcontroller.util.MACAddress;
+import net.onrc.onos.datagrid.IDatagridService;
+import net.onrc.onos.ofcontroller.core.IDeviceStorage;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IDeviceObject;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IPortObject;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.ISwitchObject;
+import net.onrc.onos.ofcontroller.core.internal.DeviceStorageImpl;
+import net.onrc.onos.ofcontroller.flowmanager.IFlowService;
+import net.onrc.onos.ofcontroller.topology.TopologyManager;
+import net.onrc.onos.ofcontroller.util.CallerId;
+import net.onrc.onos.ofcontroller.util.DataPath;
+import net.onrc.onos.ofcontroller.util.Dpid;
+import net.onrc.onos.ofcontroller.util.FlowEntryMatch;
+import net.onrc.onos.ofcontroller.util.FlowId;
+import net.onrc.onos.ofcontroller.util.FlowPath;
+import net.onrc.onos.ofcontroller.util.FlowPathType;
+import net.onrc.onos.ofcontroller.util.FlowPathUserState;
+import net.onrc.onos.ofcontroller.util.Port;
+import net.onrc.onos.ofcontroller.util.SwitchPort;
+
+import org.openflow.protocol.OFMessage;
+import org.openflow.protocol.OFPacketIn;
+import org.openflow.protocol.OFType;
+import org.openflow.util.HexString;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class Forwarding implements IOFMessageListener {
+ private final static Logger log = LoggerFactory.getLogger(Forwarding.class);
+
+ private IFloodlightProviderService floodlightProvider;
+ private IFlowService flowService;
+ private IDatagridService datagridService;
+
+ private IDeviceStorage deviceStorage;
+ private TopologyManager topologyService;
+
+ public Forwarding() {
+
+ }
+
+ public void init(IFloodlightProviderService floodlightProvider,
+ IFlowService flowService, IDatagridService datagridService) {
+ this.floodlightProvider = floodlightProvider;
+ this.flowService = flowService;
+ this.datagridService = datagridService;
+
+ floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
+
+ deviceStorage = new DeviceStorageImpl();
+ deviceStorage.init("");
+ topologyService = new TopologyManager();
+ topologyService.init("");
+ }
+
+ public void startUp() {
+ // no-op
+ }
+
+ @Override
+ public String getName() {
+ return "onosforwarding";
+ }
+
+ @Override
+ public boolean isCallbackOrderingPrereq(OFType type, String name) {
+ return (type == OFType.PACKET_IN) &&
+ (name.equals("devicemanager") || name.equals("proxyarpmanager"));
+ }
+
+ @Override
+ public boolean isCallbackOrderingPostreq(OFType type, String name) {
+ return false;
+ }
+
+ @Override
+ public Command receive(
+ IOFSwitch sw, OFMessage msg, FloodlightContext cntx) {
+
+ if (msg.getType() != OFType.PACKET_IN) {
+ return Command.CONTINUE;
+ }
+
+ OFPacketIn pi = (OFPacketIn) msg;
+
+ Ethernet eth = IFloodlightProviderService.bcStore.
+ get(cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
+
+ // We only want to handle unicast IPv4
+ if (eth.isBroadcast() || eth.isMulticast() ||
+ eth.getEtherType() != Ethernet.TYPE_IPv4) {
+ return Command.CONTINUE;
+ }
+
+ handlePacketIn(sw, pi, eth);
+
+ return Command.STOP;
+ }
+
+ private void handlePacketIn(IOFSwitch sw, OFPacketIn pi, Ethernet eth) {
+ String destinationMac = HexString.toHexString(eth.getDestinationMACAddress());
+
+ IDeviceObject deviceObject = deviceStorage.getDeviceByMac(
+ destinationMac);
+
+ if (deviceObject == null) {
+ log.debug("No device entry found for {}", destinationMac);
+ return;
+ }
+
+ Iterator<IPortObject> ports = deviceObject.getAttachedPorts().iterator();
+ if (!ports.hasNext()) {
+ log.debug("No attachment point found for device {}", destinationMac);
+ return;
+ }
+ IPortObject portObject = ports.next();
+ short destinationPort = portObject.getNumber();
+ ISwitchObject switchObject = portObject.getSwitch();
+ long destinationDpid = HexString.toLong(switchObject.getDPID());
+
+ SwitchPort srcSwitchPort = new SwitchPort(
+ new Dpid(sw.getId()), new Port(pi.getInPort()));
+ SwitchPort dstSwitchPort = new SwitchPort(
+ new Dpid(destinationDpid), new Port(destinationPort));
+
+ MACAddress srcMacAddress = MACAddress.valueOf(eth.getSourceMACAddress());
+ MACAddress dstMacAddress = MACAddress.valueOf(eth.getDestinationMACAddress());
+
+ if (flowExists(srcSwitchPort, srcMacAddress,
+ dstSwitchPort, dstMacAddress)) {
+ log.debug("Not adding flow because it already exists");
+
+ // Don't do anything if the flow already exists
+ return;
+ }
+
+ log.debug("Adding new flow between {} at {} and {} at {}",
+ new Object[]{srcMacAddress, srcSwitchPort, dstMacAddress, dstSwitchPort});
+
+
+ DataPath dataPath = new DataPath();
+ dataPath.setSrcPort(srcSwitchPort);
+ dataPath.setDstPort(dstSwitchPort);
+
+ FlowId flowId = new FlowId(flowService.getNextFlowEntryId());
+ FlowPath flowPath = new FlowPath();
+ flowPath.setFlowId(flowId);
+ flowPath.setInstallerId(new CallerId("Forwarding"));
+ flowPath.setFlowPathType(FlowPathType.FP_TYPE_SHORTEST_PATH);
+ flowPath.setFlowPathUserState(FlowPathUserState.FP_USER_ADD);
+ flowPath.setFlowEntryMatch(new FlowEntryMatch());
+ flowPath.flowEntryMatch().enableSrcMac(srcMacAddress);
+ flowPath.flowEntryMatch().enableDstMac(dstMacAddress);
+ // For now just forward IPv4 packets. This prevents accidentally
+ // other stuff like ARP.
+ flowPath.flowEntryMatch().enableEthernetFrameType(Ethernet.TYPE_IPv4);
+ flowPath.setDataPath(dataPath);
+
+ flowService.addFlow(flowPath, flowId);
+ }
+
+ private boolean flowExists(SwitchPort srcPort, MACAddress srcMac,
+ SwitchPort dstPort, MACAddress dstMac) {
+ for (FlowPath flow : datagridService.getAllFlows()) {
+ FlowEntryMatch match = flow.flowEntryMatch();
+ // TODO implement FlowEntryMatch.equals();
+ // This is painful to do properly without support in the FlowEntryMatch
+ boolean same = true;
+ if (!match.srcMac().equals(srcMac) ||
+ !match.dstMac().equals(dstMac)) {
+ same = false;
+ }
+ if (!flow.dataPath().srcPort().equals(srcPort) ||
+ !flow.dataPath().dstPort().equals(dstPort)) {
+ same = false;
+ }
+
+ if (same) {
+ log.debug("found flow entry that's the same {}-{}:::{}-{}",
+ new Object[] {srcPort, srcMac, dstPort, dstMac});
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/linkdiscovery/internal/LinkDiscoveryManager.java b/src/main/java/net/onrc/onos/ofcontroller/linkdiscovery/internal/LinkDiscoveryManager.java
index c9f3d5e..c03b266 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/linkdiscovery/internal/LinkDiscoveryManager.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/linkdiscovery/internal/LinkDiscoveryManager.java
@@ -127,7 +127,7 @@
IStorageSourceListener, ILinkDiscoveryService,
IFloodlightModule, IInfoProvider, IHAListener {
protected IFloodlightProviderService controller;
- protected static Logger log = LoggerFactory.getLogger(LinkDiscoveryManager.class);
+ protected final static Logger log = LoggerFactory.getLogger(LinkDiscoveryManager.class);
// Names of table/fields for links in the storage API
private static final String LINK_TABLE_NAME = "controller_link";
diff --git a/src/main/java/net/onrc/onos/ofcontroller/linkdiscovery/web/AutoPortFast.java b/src/main/java/net/onrc/onos/ofcontroller/linkdiscovery/web/AutoPortFast.java
index 29dc890..ce1be94 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/linkdiscovery/web/AutoPortFast.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/linkdiscovery/web/AutoPortFast.java
@@ -9,7 +9,7 @@
import org.slf4j.LoggerFactory;
public class AutoPortFast extends ServerResource {
- protected static Logger log = LoggerFactory.getLogger(AutoPortFast.class);
+ protected final static Logger log = LoggerFactory.getLogger(AutoPortFast.class);
@Get("json")
public String retrieve() {
diff --git a/src/main/java/net/onrc/onos/ofcontroller/linkdiscovery/web/LinksResource.java b/src/main/java/net/onrc/onos/ofcontroller/linkdiscovery/web/LinksResource.java
index c522a05..3c97e6a 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/linkdiscovery/web/LinksResource.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/linkdiscovery/web/LinksResource.java
@@ -3,6 +3,7 @@
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Set;
import net.floodlightcontroller.routing.Link;
@@ -23,8 +24,9 @@
if (ld != null) {
links.putAll(ld.getLinks());
- for (Link link: links.keySet()) {
- LinkInfo info = links.get(link);
+ for(Entry<Link, LinkInfo> e : links.entrySet()) {
+ Link link = e.getKey();
+ LinkInfo info = e.getValue();
LinkWithType lwt = new LinkWithType(link,
info.getSrcPortState(),
info.getDstPortState(),
diff --git a/src/main/java/net/onrc/onos/ofcontroller/proxyarp/ArpMessage.java b/src/main/java/net/onrc/onos/ofcontroller/proxyarp/ArpMessage.java
new file mode 100644
index 0000000..53891ef
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/proxyarp/ArpMessage.java
@@ -0,0 +1,60 @@
+package net.onrc.onos.ofcontroller.proxyarp;
+
+import java.io.Serializable;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.List;
+
+import net.onrc.onos.ofcontroller.util.SwitchPort;
+
+public class ArpMessage implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ private final Type type;
+ private final InetAddress forAddress;
+ private final byte[] packetData;
+
+ private final List<SwitchPort> switchPorts = new ArrayList<SwitchPort>();
+
+ public enum Type {
+ REQUEST,
+ REPLY
+ }
+
+ private ArpMessage(Type type, InetAddress address, byte[] eth) {
+ // TODO Auto-generated constructor stub
+ this.type = type;
+ this.forAddress = address;
+ this.packetData = eth;
+ }
+
+ private ArpMessage(Type type, InetAddress address) {
+ this.type = type;
+ this.forAddress = address;
+ this.packetData = null;
+ }
+
+ public static ArpMessage newRequest(InetAddress forAddress, byte[] arpRequest) {
+ return new ArpMessage(Type.REQUEST, forAddress, arpRequest);
+ }
+
+ public static ArpMessage newReply(InetAddress forAddress) {
+ return new ArpMessage(Type.REPLY, forAddress);
+ }
+
+ public Type getType() {
+ return type;
+ }
+
+ public InetAddress getAddress() {
+ return forAddress;
+ }
+
+ public byte[] getPacket() {
+ return packetData;
+ }
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/proxyarp/BgpProxyArpManager.java b/src/main/java/net/onrc/onos/ofcontroller/proxyarp/BgpProxyArpManager.java
new file mode 100644
index 0000000..801e414
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/proxyarp/BgpProxyArpManager.java
@@ -0,0 +1,637 @@
+package net.onrc.onos.ofcontroller.proxyarp;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.Timer;
+import java.util.TimerTask;
+
+import net.floodlightcontroller.core.FloodlightContext;
+import net.floodlightcontroller.core.IFloodlightProviderService;
+import net.floodlightcontroller.core.IOFMessageListener;
+import net.floodlightcontroller.core.IOFSwitch;
+import net.floodlightcontroller.packet.ARP;
+import net.floodlightcontroller.packet.Ethernet;
+import net.floodlightcontroller.packet.IPv4;
+import net.floodlightcontroller.restserver.IRestApiService;
+import net.floodlightcontroller.topology.ITopologyService;
+import net.floodlightcontroller.util.MACAddress;
+import net.onrc.onos.ofcontroller.bgproute.Interface;
+import net.onrc.onos.ofcontroller.core.IDeviceStorage;
+import net.onrc.onos.ofcontroller.core.config.IConfigInfoService;
+import net.onrc.onos.ofcontroller.core.internal.DeviceStorageImpl;
+
+import org.openflow.protocol.OFMessage;
+import org.openflow.protocol.OFPacketIn;
+import org.openflow.protocol.OFPacketOut;
+import org.openflow.protocol.OFPort;
+import org.openflow.protocol.OFType;
+import org.openflow.protocol.action.OFAction;
+import org.openflow.protocol.action.OFActionOutput;
+import org.openflow.util.HexString;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.Multimaps;
+import com.google.common.collect.SetMultimap;
+
+public class BgpProxyArpManager implements IProxyArpService, IOFMessageListener {
+ private final static Logger log = LoggerFactory.getLogger(BgpProxyArpManager.class);
+
+ private final long ARP_TIMER_PERIOD = 60000; //ms (== 1 min)
+
+ private static final int ARP_REQUEST_TIMEOUT = 2000; //ms
+
+ private IFloodlightProviderService floodlightProvider;
+ private ITopologyService topology;
+ //private IDeviceService deviceService;
+ private IConfigInfoService configService;
+ private IRestApiService restApi;
+
+ private IDeviceStorage deviceStorage;
+
+ private short vlan;
+ private static final short NO_VLAN = 0;
+
+ private ArpCache arpCache;
+
+ private SetMultimap<InetAddress, ArpRequest> arpRequests;
+
+ private static class ArpRequest {
+ private final IArpRequester requester;
+ private final boolean retry;
+ private long requestTime;
+
+ public ArpRequest(IArpRequester requester, boolean retry){
+ this.requester = requester;
+ this.retry = retry;
+ this.requestTime = System.currentTimeMillis();
+ }
+
+ public ArpRequest(ArpRequest old) {
+ this.requester = old.requester;
+ this.retry = old.retry;
+ this.requestTime = System.currentTimeMillis();
+ }
+
+ public boolean isExpired() {
+ return (System.currentTimeMillis() - requestTime) > ARP_REQUEST_TIMEOUT;
+ }
+
+ public boolean shouldRetry() {
+ return retry;
+ }
+
+ public void dispatchReply(InetAddress ipAddress, MACAddress replyMacAddress) {
+ requester.arpResponse(ipAddress, replyMacAddress);
+ }
+ }
+
+ private class HostArpRequester implements IArpRequester {
+ private final ARP arpRequest;
+ private final long dpid;
+ private final short port;
+
+ public HostArpRequester(ARP arpRequest, long dpid, short port) {
+ this.arpRequest = arpRequest;
+ this.dpid = dpid;
+ this.port = port;
+ }
+
+ @Override
+ public void arpResponse(InetAddress ipAddress, MACAddress macAddress) {
+ BgpProxyArpManager.this.sendArpReply(arpRequest, dpid, port, macAddress);
+ }
+ }
+
+ /*
+ public ProxyArpManager(IFloodlightProviderService floodlightProvider,
+ ITopologyService topology, IConfigInfoService configService,
+ IRestApiService restApi){
+
+ }
+ */
+
+ public void init(IFloodlightProviderService floodlightProvider,
+ ITopologyService topology,
+ IConfigInfoService config, IRestApiService restApi){
+ this.floodlightProvider = floodlightProvider;
+ this.topology = topology;
+ //this.deviceService = deviceService;
+ this.configService = config;
+ this.restApi = restApi;
+
+ arpCache = new ArpCache();
+
+ arpRequests = Multimaps.synchronizedSetMultimap(
+ HashMultimap.<InetAddress, ArpRequest>create());
+ }
+
+ public void startUp() {
+ this.vlan = configService.getVlan();
+ log.info("vlan set to {}", this.vlan);
+
+ restApi.addRestletRoutable(new ArpWebRoutable());
+ floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
+
+ deviceStorage = new DeviceStorageImpl();
+ deviceStorage.init("");
+
+ Timer arpTimer = new Timer("arp-processing");
+ arpTimer.scheduleAtFixedRate(new TimerTask() {
+ @Override
+ public void run() {
+ doPeriodicArpProcessing();
+ }
+ }, 0, ARP_TIMER_PERIOD);
+ }
+
+ /*
+ * Function that runs periodically to manage the asynchronous request mechanism.
+ * It basically cleans up old ARP requests if we don't get a response for them.
+ * The caller can designate that a request should be retried indefinitely, and
+ * this task will handle that as well.
+ */
+ private void doPeriodicArpProcessing() {
+ SetMultimap<InetAddress, ArpRequest> retryList
+ = HashMultimap.<InetAddress, ArpRequest>create();
+
+ //Have to synchronize externally on the Multimap while using an iterator,
+ //even though it's a synchronizedMultimap
+ synchronized (arpRequests) {
+ log.debug("Current have {} outstanding requests",
+ arpRequests.size());
+
+ Iterator<Map.Entry<InetAddress, ArpRequest>> it
+ = arpRequests.entries().iterator();
+
+ while (it.hasNext()) {
+ Map.Entry<InetAddress, ArpRequest> entry
+ = it.next();
+ ArpRequest request = entry.getValue();
+ if (request.isExpired()) {
+ log.debug("Cleaning expired ARP request for {}",
+ entry.getKey().getHostAddress());
+
+ it.remove();
+
+ if (request.shouldRetry()) {
+ retryList.put(entry.getKey(), request);
+ }
+ }
+ }
+ }
+
+ for (Map.Entry<InetAddress, Collection<ArpRequest>> entry
+ : retryList.asMap().entrySet()) {
+
+ InetAddress address = entry.getKey();
+
+ log.debug("Resending ARP request for {}", address.getHostAddress());
+
+ sendArpRequestForAddress(address);
+
+ for (ArpRequest request : entry.getValue()) {
+ arpRequests.put(address, new ArpRequest(request));
+ }
+ }
+ }
+
+ @Override
+ public String getName() {
+ return "proxyarpmanager";
+ }
+
+ @Override
+ public boolean isCallbackOrderingPrereq(OFType type, String name) {
+ if (type == OFType.PACKET_IN) {
+ return "devicemanager".equals(name);
+ }
+ else {
+ return false;
+ }
+ }
+
+ @Override
+ public boolean isCallbackOrderingPostreq(OFType type, String name) {
+ return false;
+ }
+
+ @Override
+ public Command receive(
+ IOFSwitch sw, OFMessage msg, FloodlightContext cntx) {
+
+ if (msg.getType() != OFType.PACKET_IN){
+ return Command.CONTINUE;
+ }
+
+ OFPacketIn pi = (OFPacketIn) msg;
+
+ Ethernet eth = IFloodlightProviderService.bcStore.get(cntx,
+ IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
+
+ if (eth.getEtherType() == Ethernet.TYPE_ARP){
+ ARP arp = (ARP) eth.getPayload();
+
+ if (arp.getOpCode() == ARP.OP_REQUEST) {
+ //TODO check what the DeviceManager does about propagating
+ //or swallowing ARPs. We want to go after DeviceManager in the
+ //chain but we really need it to CONTINUE ARP packets so we can
+ //get them.
+ handleArpRequest(sw, pi, arp);
+ }
+ else if (arp.getOpCode() == ARP.OP_REPLY) {
+ handleArpReply(sw, pi, arp);
+ }
+ }
+
+ //TODO should we propagate ARP or swallow it?
+ //Always propagate for now so DeviceManager can learn the host location
+ return Command.CONTINUE;
+ }
+
+ private void handleArpRequest(IOFSwitch sw, OFPacketIn pi, ARP arp) {
+ if (log.isTraceEnabled()) {
+ log.trace("ARP request received for {}",
+ inetAddressToString(arp.getTargetProtocolAddress()));
+ }
+
+ InetAddress target;
+ try {
+ target = InetAddress.getByAddress(arp.getTargetProtocolAddress());
+ } catch (UnknownHostException e) {
+ log.debug("Invalid address in ARP request", e);
+ return;
+ }
+
+ if (configService.fromExternalNetwork(sw.getId(), pi.getInPort())) {
+ //If the request came from outside our network, we only care if
+ //it was a request for one of our interfaces.
+ if (configService.isInterfaceAddress(target)) {
+ log.trace("ARP request for our interface. Sending reply {} => {}",
+ target.getHostAddress(), configService.getRouterMacAddress());
+
+ sendArpReply(arp, sw.getId(), pi.getInPort(),
+ configService.getRouterMacAddress());
+ }
+
+ return;
+ }
+
+ MACAddress macAddress = arpCache.lookup(target);
+
+ //IDevice dstDevice = deviceService.fcStore.get(cntx, IDeviceService.CONTEXT_DST_DEVICE);
+ //Iterator<? extends IDevice> it = deviceService.queryDevices(
+ //null, null, InetAddresses.coerceToInteger(target), null, null);
+
+ //IDevice targetDevice = null;
+ //if (it.hasNext()) {
+ //targetDevice = it.next();
+ //}
+ /*IDeviceObject targetDevice =
+ deviceStorage.getDeviceByIP(InetAddresses.coerceToInteger(target));
+
+ if (targetDevice != null) {
+ //We have the device in our database, so send a reply
+ MACAddress macAddress = MACAddress.valueOf(targetDevice.getMACAddress());
+
+ if (log.isTraceEnabled()) {
+ log.trace("Sending reply: {} => {} to host at {}/{}", new Object [] {
+ inetAddressToString(arp.getTargetProtocolAddress()),
+ macAddress.toString(),
+ HexString.toHexString(sw.getId()), pi.getInPort()});
+ }
+
+ sendArpReply(arp, sw.getId(), pi.getInPort(), macAddress);
+ }*/
+
+ if (macAddress == null){
+ //MAC address is not in our ARP cache.
+
+ //Record where the request came from so we know where to send the reply
+ arpRequests.put(target, new ArpRequest(
+ new HostArpRequester(arp, sw.getId(), pi.getInPort()), false));
+
+ //Flood the request out edge ports
+ sendArpRequestToSwitches(target, pi.getPacketData(), sw.getId(), pi.getInPort());
+ }
+ else {
+ //We know the address, so send a reply
+ if (log.isTraceEnabled()) {
+ log.trace("Sending reply: {} => {} to host at {}/{}", new Object [] {
+ inetAddressToString(arp.getTargetProtocolAddress()),
+ macAddress.toString(),
+ HexString.toHexString(sw.getId()), pi.getInPort()});
+ }
+
+ sendArpReply(arp, sw.getId(), pi.getInPort(), macAddress);
+ }
+ }
+
+ private void handleArpReply(IOFSwitch sw, OFPacketIn pi, ARP arp){
+ if (log.isTraceEnabled()) {
+ log.trace("ARP reply recieved: {} => {}, on {}/{}", new Object[] {
+ inetAddressToString(arp.getSenderProtocolAddress()),
+ HexString.toHexString(arp.getSenderHardwareAddress()),
+ HexString.toHexString(sw.getId()), pi.getInPort()});
+ }
+
+ InetAddress senderIpAddress;
+ try {
+ senderIpAddress = InetAddress.getByAddress(arp.getSenderProtocolAddress());
+ } catch (UnknownHostException e) {
+ log.debug("Invalid address in ARP reply", e);
+ return;
+ }
+
+ MACAddress senderMacAddress = MACAddress.valueOf(arp.getSenderHardwareAddress());
+
+ arpCache.update(senderIpAddress, senderMacAddress);
+
+ //See if anyone's waiting for this ARP reply
+ Set<ArpRequest> requests = arpRequests.get(senderIpAddress);
+
+ //Synchronize on the Multimap while using an iterator for one of the sets
+ List<ArpRequest> requestsToSend = new ArrayList<ArpRequest>(requests.size());
+ synchronized (arpRequests) {
+ Iterator<ArpRequest> it = requests.iterator();
+ while (it.hasNext()) {
+ ArpRequest request = it.next();
+ it.remove();
+ requestsToSend.add(request);
+ }
+ }
+
+ //Don't hold an ARP lock while dispatching requests
+ for (ArpRequest request : requestsToSend) {
+ request.dispatchReply(senderIpAddress, senderMacAddress);
+ }
+ }
+
+ private void sendArpRequestForAddress(InetAddress ipAddress) {
+ //TODO what should the sender IP address and MAC address be if no
+ //IP addresses are configured? Will there ever be a need to send
+ //ARP requests from the controller in that case?
+ //All-zero MAC address doesn't seem to work - hosts don't respond to it
+
+ byte[] zeroIpv4 = {0x0, 0x0, 0x0, 0x0};
+ byte[] zeroMac = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0};
+ byte[] genericNonZeroMac = {0x0, 0x0, 0x0, 0x0, 0x0, 0x01};
+ byte[] broadcastMac = {(byte)0xff, (byte)0xff, (byte)0xff,
+ (byte)0xff, (byte)0xff, (byte)0xff};
+
+ ARP arpRequest = new ARP();
+
+ arpRequest.setHardwareType(ARP.HW_TYPE_ETHERNET)
+ .setProtocolType(ARP.PROTO_TYPE_IP)
+ .setHardwareAddressLength((byte)Ethernet.DATALAYER_ADDRESS_LENGTH)
+ .setProtocolAddressLength((byte)IPv4.ADDRESS_LENGTH)
+ .setOpCode(ARP.OP_REQUEST)
+ .setTargetHardwareAddress(zeroMac)
+ .setTargetProtocolAddress(ipAddress.getAddress());
+
+ MACAddress routerMacAddress = configService.getRouterMacAddress();
+ //TODO hack for now as it's unclear what the MAC address should be
+ byte[] senderMacAddress = genericNonZeroMac;
+ if (routerMacAddress != null) {
+ senderMacAddress = routerMacAddress.toBytes();
+ }
+ arpRequest.setSenderHardwareAddress(senderMacAddress);
+
+ byte[] senderIPAddress = zeroIpv4;
+ Interface intf = configService.getOutgoingInterface(ipAddress);
+ if (intf != null) {
+ senderIPAddress = intf.getIpAddress().getAddress();
+ }
+
+ arpRequest.setSenderProtocolAddress(senderIPAddress);
+
+ Ethernet eth = new Ethernet();
+ eth.setSourceMACAddress(senderMacAddress)
+ .setDestinationMACAddress(broadcastMac)
+ .setEtherType(Ethernet.TYPE_ARP)
+ .setPayload(arpRequest);
+
+ if (vlan != NO_VLAN) {
+ eth.setVlanID(vlan)
+ .setPriorityCode((byte)0);
+ }
+
+ sendArpRequestToSwitches(ipAddress, eth.serialize());
+ }
+
+ private void sendArpRequestToSwitches(InetAddress dstAddress, byte[] arpRequest) {
+ sendArpRequestToSwitches(dstAddress, arpRequest,
+ 0, OFPort.OFPP_NONE.getValue());
+ }
+
+ private void sendArpRequestToSwitches(InetAddress dstAddress, byte[] arpRequest,
+ long inSwitch, short inPort) {
+
+ if (configService.hasLayer3Configuration()) {
+ Interface intf = configService.getOutgoingInterface(dstAddress);
+ if (intf != null) {
+ sendArpRequestOutPort(arpRequest, intf.getDpid(), intf.getPort());
+ }
+ else {
+ //TODO here it should be broadcast out all non-interface edge ports.
+ //I think we can assume that if it's not a request for an external
+ //network, it's an ARP for a host in our own network. So we want to
+ //send it out all edge ports that don't have an interface configured
+ //to ensure it reaches all hosts in our network.
+ log.debug("No interface found to send ARP request for {}",
+ dstAddress.getHostAddress());
+ }
+ }
+ else {
+ broadcastArpRequestOutEdge(arpRequest, inSwitch, inPort);
+ }
+ }
+
+ private void broadcastArpRequestOutEdge(byte[] arpRequest, long inSwitch, short inPort) {
+ for (IOFSwitch sw : floodlightProvider.getSwitches().values()){
+ Collection<Short> enabledPorts = sw.getEnabledPortNumbers();
+ Set<Short> linkPorts = topology.getPortsWithLinks(sw.getId());
+
+ if (linkPorts == null){
+ //I think this means the switch doesn't have any links.
+ //continue;
+ linkPorts = new HashSet<Short>();
+ }
+
+
+ OFPacketOut po = new OFPacketOut();
+ po.setInPort(OFPort.OFPP_NONE)
+ .setBufferId(-1)
+ .setPacketData(arpRequest);
+
+ List<OFAction> actions = new ArrayList<OFAction>();
+
+ for (short portNum : enabledPorts){
+ if (linkPorts.contains(portNum) ||
+ (sw.getId() == inSwitch && portNum == inPort)){
+ //If this port isn't an edge port or is the ingress port
+ //for the ARP, don't broadcast out it
+ continue;
+ }
+
+ actions.add(new OFActionOutput(portNum));
+ }
+
+ po.setActions(actions);
+ short actionsLength = (short) (actions.size() * OFActionOutput.MINIMUM_LENGTH);
+ po.setActionsLength(actionsLength);
+ po.setLengthU(OFPacketOut.MINIMUM_LENGTH + actionsLength
+ + arpRequest.length);
+
+ List<OFMessage> msgList = new ArrayList<OFMessage>();
+ msgList.add(po);
+
+ try {
+ sw.write(msgList, null);
+ sw.flush();
+ } catch (IOException e) {
+ log.error("Failure writing packet out to switch", e);
+ }
+ }
+ }
+
+ private void sendArpRequestOutPort(byte[] arpRequest, long dpid, short port) {
+ if (log.isTraceEnabled()) {
+ log.trace("Sending ARP request out {}/{}",
+ HexString.toHexString(dpid), port);
+ }
+
+ OFPacketOut po = new OFPacketOut();
+ po.setInPort(OFPort.OFPP_NONE)
+ .setBufferId(-1)
+ .setPacketData(arpRequest);
+
+ List<OFAction> actions = new ArrayList<OFAction>();
+ actions.add(new OFActionOutput(port));
+ po.setActions(actions);
+ short actionsLength = (short) (actions.size() * OFActionOutput.MINIMUM_LENGTH);
+ po.setActionsLength(actionsLength);
+ po.setLengthU(OFPacketOut.MINIMUM_LENGTH + actionsLength
+ + arpRequest.length);
+
+ IOFSwitch sw = floodlightProvider.getSwitches().get(dpid);
+
+ if (sw == null) {
+ log.warn("Switch not found when sending ARP request");
+ return;
+ }
+
+ try {
+ sw.write(po, null);
+ sw.flush();
+ } catch (IOException e) {
+ log.error("Failure writing packet out to switch", e);
+ }
+ }
+
+ private void sendArpReply(ARP arpRequest, long dpid, short port, MACAddress targetMac) {
+ if (log.isTraceEnabled()) {
+ log.trace("Sending reply {} => {} to {}", new Object[] {
+ inetAddressToString(arpRequest.getTargetProtocolAddress()),
+ targetMac,
+ inetAddressToString(arpRequest.getSenderProtocolAddress())});
+ }
+
+ ARP arpReply = new ARP();
+ arpReply.setHardwareType(ARP.HW_TYPE_ETHERNET)
+ .setProtocolType(ARP.PROTO_TYPE_IP)
+ .setHardwareAddressLength((byte)Ethernet.DATALAYER_ADDRESS_LENGTH)
+ .setProtocolAddressLength((byte)IPv4.ADDRESS_LENGTH)
+ .setOpCode(ARP.OP_REPLY)
+ .setSenderHardwareAddress(targetMac.toBytes())
+ .setSenderProtocolAddress(arpRequest.getTargetProtocolAddress())
+ .setTargetHardwareAddress(arpRequest.getSenderHardwareAddress())
+ .setTargetProtocolAddress(arpRequest.getSenderProtocolAddress());
+
+
+
+ Ethernet eth = new Ethernet();
+ eth.setDestinationMACAddress(arpRequest.getSenderHardwareAddress())
+ .setSourceMACAddress(targetMac.toBytes())
+ .setEtherType(Ethernet.TYPE_ARP)
+ .setPayload(arpReply);
+
+ if (vlan != NO_VLAN) {
+ eth.setVlanID(vlan)
+ .setPriorityCode((byte)0);
+ }
+
+ List<OFAction> actions = new ArrayList<OFAction>();
+ actions.add(new OFActionOutput(port));
+
+ OFPacketOut po = new OFPacketOut();
+ po.setInPort(OFPort.OFPP_NONE)
+ .setBufferId(-1)
+ .setPacketData(eth.serialize())
+ .setActions(actions)
+ .setActionsLength((short)OFActionOutput.MINIMUM_LENGTH)
+ .setLengthU(OFPacketOut.MINIMUM_LENGTH + OFActionOutput.MINIMUM_LENGTH
+ + po.getPacketData().length);
+
+ List<OFMessage> msgList = new ArrayList<OFMessage>();
+ msgList.add(po);
+
+ IOFSwitch sw = floodlightProvider.getSwitches().get(dpid);
+
+ if (sw == null) {
+ log.warn("Switch {} not found when sending ARP reply",
+ HexString.toHexString(dpid));
+ return;
+ }
+
+ try {
+ sw.write(msgList, null);
+ sw.flush();
+ } catch (IOException e) {
+ log.error("Failure writing packet out to switch", e);
+ }
+ }
+
+ private String inetAddressToString(byte[] bytes) {
+ try {
+ return InetAddress.getByAddress(bytes).getHostAddress();
+ } catch (UnknownHostException e) {
+ log.debug("Invalid IP address", e);
+ return "";
+ }
+ }
+
+ /*
+ * IProxyArpService methods
+ */
+
+ @Override
+ public MACAddress getMacAddress(InetAddress ipAddress) {
+ return arpCache.lookup(ipAddress);
+ }
+
+ @Override
+ public void sendArpRequest(InetAddress ipAddress, IArpRequester requester,
+ boolean retry) {
+ arpRequests.put(ipAddress, new ArpRequest(requester, retry));
+
+ //Sanity check to make sure we don't send a request for our own address
+ if (!configService.isInterfaceAddress(ipAddress)) {
+ sendArpRequestForAddress(ipAddress);
+ }
+ }
+
+ @Override
+ public List<String> getMappings() {
+ return arpCache.getMappings();
+ }
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/proxyarp/IArpEventHandler.java b/src/main/java/net/onrc/onos/ofcontroller/proxyarp/IArpEventHandler.java
new file mode 100644
index 0000000..4ec32ec
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/proxyarp/IArpEventHandler.java
@@ -0,0 +1,11 @@
+package net.onrc.onos.ofcontroller.proxyarp;
+
+public interface IArpEventHandler {
+
+ /**
+ * Notify the ARP event handler that an ARP request has been received.
+ * @param id The string ID of the ARP request
+ * @param arpRequest The ARP request packet
+ */
+ public void arpRequestNotification(ArpMessage arpMessage);
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/proxyarp/IProxyArpService.java b/src/main/java/net/onrc/onos/ofcontroller/proxyarp/IProxyArpService.java
index 97844d3..71546a1 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/proxyarp/IProxyArpService.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/proxyarp/IProxyArpService.java
@@ -3,11 +3,11 @@
import java.net.InetAddress;
import java.util.List;
-import net.floodlightcontroller.core.module.IFloodlightService;
import net.floodlightcontroller.util.MACAddress;
+import net.onrc.onos.ofcontroller.core.module.IOnosService;
//Extends IFloodlightService so we can access it from REST API resources
-public interface IProxyArpService extends IFloodlightService{
+public interface IProxyArpService extends IOnosService{
/**
* Returns the MAC address if there is a valid entry in the cache.
* Otherwise returns null.
diff --git a/src/main/java/net/onrc/onos/ofcontroller/proxyarp/ProxyArpManager.java b/src/main/java/net/onrc/onos/ofcontroller/proxyarp/ProxyArpManager.java
index b6a9591..85fd618 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/proxyarp/ProxyArpManager.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/proxyarp/ProxyArpManager.java
@@ -5,6 +5,7 @@
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -16,14 +17,24 @@
import net.floodlightcontroller.core.IFloodlightProviderService;
import net.floodlightcontroller.core.IOFMessageListener;
import net.floodlightcontroller.core.IOFSwitch;
+import net.floodlightcontroller.devicemanager.IDevice;
import net.floodlightcontroller.packet.ARP;
import net.floodlightcontroller.packet.Ethernet;
import net.floodlightcontroller.packet.IPv4;
import net.floodlightcontroller.restserver.IRestApiService;
import net.floodlightcontroller.topology.ITopologyService;
import net.floodlightcontroller.util.MACAddress;
-import net.onrc.onos.ofcontroller.bgproute.ILayer3InfoService;
+import net.onrc.onos.datagrid.IDatagridService;
import net.onrc.onos.ofcontroller.bgproute.Interface;
+import net.onrc.onos.ofcontroller.core.IDeviceStorage;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IDeviceObject;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IPortObject;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyService.ITopoLinkService;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyService.ITopoSwitchService;
+import net.onrc.onos.ofcontroller.core.config.IConfigInfoService;
+import net.onrc.onos.ofcontroller.core.internal.DeviceStorageImpl;
+import net.onrc.onos.ofcontroller.core.internal.TopoLinkServiceImpl;
+import net.onrc.onos.ofcontroller.core.internal.TopoSwitchServiceImpl;
import org.openflow.protocol.OFMessage;
import org.openflow.protocol.OFPacketIn;
@@ -39,22 +50,32 @@
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.SetMultimap;
+import com.google.common.net.InetAddresses;
-public class ProxyArpManager implements IProxyArpService, IOFMessageListener {
+public class ProxyArpManager implements IProxyArpService, IOFMessageListener,
+ IArpEventHandler {
private final static Logger log = LoggerFactory.getLogger(ProxyArpManager.class);
private final long ARP_TIMER_PERIOD = 60000; //ms (== 1 min)
private static final int ARP_REQUEST_TIMEOUT = 2000; //ms
- private final IFloodlightProviderService floodlightProvider;
- private final ITopologyService topology;
- private final ILayer3InfoService layer3;
- private final IRestApiService restApi;
+ private IFloodlightProviderService floodlightProvider;
+ private ITopologyService topology;
+ private IDatagridService datagrid;
+ private IConfigInfoService configService;
+ private IRestApiService restApi;
- private final ArpCache arpCache;
+ private IDeviceStorage deviceStorage;
+ private volatile ITopoSwitchService topoSwitchService;
+ private ITopoLinkService topoLinkService;
+
+ private short vlan;
+ private static final short NO_VLAN = 0;
+
+ private ArpCache arpCache;
- private final SetMultimap<InetAddress, ArpRequest> arpRequests;
+ private SetMultimap<InetAddress, ArpRequest> arpRequests;
private static class ArpRequest {
private final IArpRequester requester;
@@ -103,22 +124,43 @@
}
}
+ /*
public ProxyArpManager(IFloodlightProviderService floodlightProvider,
- ITopologyService topology, ILayer3InfoService layer3,
+ ITopologyService topology, IConfigInfoService configService,
IRestApiService restApi){
+
+ }
+ */
+
+ public void init(IFloodlightProviderService floodlightProvider,
+ ITopologyService topology, IDatagridService datagrid,
+ IConfigInfoService config, IRestApiService restApi){
this.floodlightProvider = floodlightProvider;
this.topology = topology;
- this.layer3 = layer3;
+ this.datagrid = datagrid;
+ this.configService = config;
this.restApi = restApi;
arpCache = new ArpCache();
arpRequests = Multimaps.synchronizedSetMultimap(
HashMultimap.<InetAddress, ArpRequest>create());
+
+ topoSwitchService = new TopoSwitchServiceImpl();
+ topoLinkService = new TopoLinkServiceImpl();
}
public void startUp() {
+ this.vlan = configService.getVlan();
+ log.info("vlan set to {}", this.vlan);
+
restApi.addRestletRoutable(new ArpWebRoutable());
+ floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
+
+ datagrid.registerArpEventHandler(this);
+
+ deviceStorage = new DeviceStorageImpl();
+ deviceStorage.init("");
Timer arpTimer = new Timer("arp-processing");
arpTimer.scheduleAtFixedRate(new TimerTask() {
@@ -182,12 +224,17 @@
@Override
public String getName() {
- return "ProxyArpManager";
+ return "proxyarpmanager";
}
@Override
public boolean isCallbackOrderingPrereq(OFType type, String name) {
- return false;
+ if (type == OFType.PACKET_IN) {
+ return "devicemanager".equals(name);
+ }
+ else {
+ return false;
+ }
}
@Override
@@ -199,9 +246,10 @@
public Command receive(
IOFSwitch sw, OFMessage msg, FloodlightContext cntx) {
- if (msg.getType() != OFType.PACKET_IN){
- return Command.CONTINUE;
- }
+ //if (msg.getType() != OFType.PACKET_IN){
+ //return Command.CONTINUE;
+ //}
+ log.debug("received packet");
OFPacketIn pi = (OFPacketIn) msg;
@@ -209,13 +257,19 @@
IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
if (eth.getEtherType() == Ethernet.TYPE_ARP){
- ARP arp = (ARP) eth.getPayload();
-
+ log.debug("is arp");
+ ARP arp = (ARP) eth.getPayload();
if (arp.getOpCode() == ARP.OP_REQUEST) {
- handleArpRequest(sw, pi, arp);
+ log.debug("is request");
+ //TODO check what the DeviceManager does about propagating
+ //or swallowing ARPs. We want to go after DeviceManager in the
+ //chain but we really need it to CONTINUE ARP packets so we can
+ //get them.
+ handleArpRequest(sw, pi, arp, eth);
}
else if (arp.getOpCode() == ARP.OP_REPLY) {
- handleArpReply(sw, pi, arp);
+ log.debug("is reply");
+ //handleArpReply(sw, pi, arp);
}
}
@@ -224,7 +278,7 @@
return Command.CONTINUE;
}
- private void handleArpRequest(IOFSwitch sw, OFPacketIn pi, ARP arp) {
+ private void handleArpRequest(IOFSwitch sw, OFPacketIn pi, ARP arp, Ethernet eth) {
if (log.isTraceEnabled()) {
log.trace("ARP request received for {}",
inetAddressToString(arp.getTargetProtocolAddress()));
@@ -238,31 +292,60 @@
return;
}
- if (layer3.fromExternalNetwork(sw.getId(), pi.getInPort())) {
+ if (configService.fromExternalNetwork(sw.getId(), pi.getInPort())) {
//If the request came from outside our network, we only care if
//it was a request for one of our interfaces.
- if (layer3.isInterfaceAddress(target)) {
+ if (configService.isInterfaceAddress(target)) {
log.trace("ARP request for our interface. Sending reply {} => {}",
- target.getHostAddress(), layer3.getRouterMacAddress());
+ target.getHostAddress(), configService.getRouterMacAddress());
sendArpReply(arp, sw.getId(), pi.getInPort(),
- layer3.getRouterMacAddress());
+ configService.getRouterMacAddress());
}
return;
}
- MACAddress macAddress = arpCache.lookup(target);
+ //MACAddress macAddress = arpCache.lookup(target);
- if (macAddress == null){
- //MAC address is not in our ARP cache.
+ IDeviceObject targetDevice =
+ deviceStorage.getDeviceByIP(InetAddresses.coerceToInteger(target));
+
+ log.debug("targetDevice: {}", targetDevice);
+
+ if (targetDevice != null) {
+ // We have the device in our database, so send a reply
+ MACAddress macAddress = MACAddress.valueOf(targetDevice.getMACAddress());
+
+ if (log.isTraceEnabled()) {
+ log.trace("Sending reply: {} => {} to host at {}/{}", new Object [] {
+ inetAddressToString(arp.getTargetProtocolAddress()),
+ macAddress.toString(),
+ HexString.toHexString(sw.getId()), pi.getInPort()});
+ }
+
+ sendArpReply(arp, sw.getId(), pi.getInPort(), macAddress);
+ }
+ else {
+ // We don't know the device so broadcast the request out
+ // the edge of the network
//Record where the request came from so we know where to send the reply
arpRequests.put(target, new ArpRequest(
new HostArpRequester(arp, sw.getId(), pi.getInPort()), false));
+
+ sendToOtherNodes(eth, pi);
+ }
+
+ /*if (macAddress == null){
+ //MAC address is not in our ARP cache.
+
+ //Record where the request came from so we know where to send the reply
+ //arpRequests.put(target, new ArpRequest(
+ //new HostArpRequester(arp, sw.getId(), pi.getInPort()), false));
//Flood the request out edge ports
- sendArpRequestToSwitches(target, pi.getPacketData(), sw.getId(), pi.getInPort());
+ //sendArpRequestToSwitches(target, pi.getPacketData(), sw.getId(), pi.getInPort());
}
else {
//We know the address, so send a reply
@@ -274,7 +357,7 @@
}
sendArpReply(arp, sw.getId(), pi.getInPort(), macAddress);
- }
+ }*/
}
private void handleArpReply(IOFSwitch sw, OFPacketIn pi, ARP arp){
@@ -339,7 +422,7 @@
.setTargetHardwareAddress(zeroMac)
.setTargetProtocolAddress(ipAddress.getAddress());
- MACAddress routerMacAddress = layer3.getRouterMacAddress();
+ MACAddress routerMacAddress = configService.getRouterMacAddress();
//TODO hack for now as it's unclear what the MAC address should be
byte[] senderMacAddress = genericNonZeroMac;
if (routerMacAddress != null) {
@@ -348,7 +431,7 @@
arpRequest.setSenderHardwareAddress(senderMacAddress);
byte[] senderIPAddress = zeroIpv4;
- Interface intf = layer3.getOutgoingInterface(ipAddress);
+ Interface intf = configService.getOutgoingInterface(ipAddress);
if (intf != null) {
senderIPAddress = intf.getIpAddress().getAddress();
}
@@ -361,6 +444,11 @@
.setEtherType(Ethernet.TYPE_ARP)
.setPayload(arpRequest);
+ if (vlan != NO_VLAN) {
+ eth.setVlanID(vlan)
+ .setPriorityCode((byte)0);
+ }
+
sendArpRequestToSwitches(ipAddress, eth.serialize());
}
@@ -372,8 +460,8 @@
private void sendArpRequestToSwitches(InetAddress dstAddress, byte[] arpRequest,
long inSwitch, short inPort) {
- if (layer3.hasLayer3Configuration()) {
- Interface intf = layer3.getOutgoingInterface(dstAddress);
+ if (configService.hasLayer3Configuration()) {
+ Interface intf = configService.getOutgoingInterface(dstAddress);
if (intf != null) {
sendArpRequestOutPort(arpRequest, intf.getDpid(), intf.getPort());
}
@@ -392,17 +480,37 @@
}
}
+ private void sendToOtherNodes(Ethernet eth, OFPacketIn pi) {
+ ARP arp = (ARP) eth.getPayload();
+
+ if (log.isTraceEnabled()) {
+ log.trace("Sending ARP request for {} to other ONOS instances",
+ inetAddressToString(arp.getTargetProtocolAddress()));
+ }
+
+ InetAddress targetAddress;
+ try {
+ targetAddress = InetAddress.getByAddress(arp.getTargetProtocolAddress());
+ } catch (UnknownHostException e) {
+ log.error("Unknown host", e);
+ return;
+ }
+
+ datagrid.sendArpRequest(ArpMessage.newRequest(targetAddress, eth.serialize()));
+ }
+
private void broadcastArpRequestOutEdge(byte[] arpRequest, long inSwitch, short inPort) {
for (IOFSwitch sw : floodlightProvider.getSwitches().values()){
Collection<Short> enabledPorts = sw.getEnabledPortNumbers();
Set<Short> linkPorts = topology.getPortsWithLinks(sw.getId());
if (linkPorts == null){
- //I think this means the switch isn't known to topology yet.
- //Maybe it only just joined.
- continue;
+ //I think this means the switch doesn't have any links.
+ //continue;
+ linkPorts = new HashSet<Short>();
}
+
OFPacketOut po = new OFPacketOut();
po.setInPort(OFPort.OFPP_NONE)
.setBufferId(-1)
@@ -439,6 +547,44 @@
}
}
+ private void broadcastArpRequestOutMyEdge(byte[] arpRequest) {
+ for (IOFSwitch sw : floodlightProvider.getSwitches().values()) {
+
+ OFPacketOut po = new OFPacketOut();
+ po.setInPort(OFPort.OFPP_NONE)
+ .setBufferId(-1)
+ .setPacketData(arpRequest);
+
+ List<OFAction> actions = new ArrayList<OFAction>();
+
+ Iterable<IPortObject> ports
+ = topoSwitchService.getPortsOnSwitch(sw.getStringId());
+ if (ports == null) {
+ continue;
+ }
+
+ for (IPortObject portObject : ports) {
+ if (!portObject.getLinkedPorts().iterator().hasNext()) {
+ actions.add(new OFActionOutput(portObject.getNumber()));
+ }
+ }
+
+ po.setActions(actions);
+ short actionsLength = (short)
+ (actions.size() * OFActionOutput.MINIMUM_LENGTH);
+ po.setActionsLength(actionsLength);
+ po.setLengthU(OFPacketOut.MINIMUM_LENGTH + actionsLength
+ + arpRequest.length);
+
+ try {
+ sw.write(po, null);
+ sw.flush();
+ } catch (IOException e) {
+ log.error("Failure writing packet out to switch", e);
+ }
+ }
+ }
+
private void sendArpRequestOutPort(byte[] arpRequest, long dpid, short port) {
if (log.isTraceEnabled()) {
log.trace("Sending ARP request out {}/{}",
@@ -492,12 +638,19 @@
.setTargetHardwareAddress(arpRequest.getSenderHardwareAddress())
.setTargetProtocolAddress(arpRequest.getSenderProtocolAddress());
+
+
Ethernet eth = new Ethernet();
eth.setDestinationMACAddress(arpRequest.getSenderHardwareAddress())
.setSourceMACAddress(targetMac.toBytes())
.setEtherType(Ethernet.TYPE_ARP)
.setPayload(arpReply);
+ if (vlan != NO_VLAN) {
+ eth.setVlanID(vlan)
+ .setPriorityCode((byte)0);
+ }
+
List<OFAction> actions = new ArrayList<OFAction>();
actions.add(new OFActionOutput(port));
@@ -553,7 +706,7 @@
arpRequests.put(ipAddress, new ArpRequest(requester, retry));
//Sanity check to make sure we don't send a request for our own address
- if (!layer3.isInterfaceAddress(ipAddress)) {
+ if (!configService.isInterfaceAddress(ipAddress)) {
sendArpRequestForAddress(ipAddress);
}
}
@@ -562,4 +715,54 @@
public List<String> getMappings() {
return arpCache.getMappings();
}
+
+ /*
+ * IArpEventHandler methods
+ */
+
+ @Override
+ public void arpRequestNotification(ArpMessage arpMessage) {
+ log.debug("Received ARP notification from other instances");
+
+ switch (arpMessage.getType()){
+ case REQUEST:
+ broadcastArpRequestOutMyEdge(arpMessage.getPacket());
+ break;
+ case REPLY:
+ sendArpReplyToWaitingRequesters(arpMessage.getAddress());
+ break;
+ }
+ }
+
+ private void sendArpReplyToWaitingRequesters(InetAddress address) {
+ log.debug("Sending ARP reply for {} to requesters",
+ address.getHostAddress());
+
+ //See if anyone's waiting for this ARP reply
+ Set<ArpRequest> requests = arpRequests.get(address);
+
+ //Synchronize on the Multimap while using an iterator for one of the sets
+ List<ArpRequest> requestsToSend = new ArrayList<ArpRequest>(requests.size());
+ synchronized (arpRequests) {
+ Iterator<ArpRequest> it = requests.iterator();
+ while (it.hasNext()) {
+ ArpRequest request = it.next();
+ it.remove();
+ requestsToSend.add(request);
+ }
+ }
+
+ IDeviceObject deviceObject = deviceStorage.getDeviceByIP(
+ InetAddresses.coerceToInteger(address));
+
+ MACAddress mac = MACAddress.valueOf(deviceObject.getMACAddress());
+
+ log.debug("Found {} at {} in network map",
+ address.getHostAddress(), mac);
+
+ //Don't hold an ARP lock while dispatching requests
+ for (ArpRequest request : requestsToSend) {
+ request.dispatchReply(address, mac);
+ }
+ }
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/routing/TopoRouteService.java b/src/main/java/net/onrc/onos/ofcontroller/routing/TopoRouteService.java
deleted file mode 100644
index 0aa5f2e..0000000
--- a/src/main/java/net/onrc/onos/ofcontroller/routing/TopoRouteService.java
+++ /dev/null
@@ -1,578 +0,0 @@
-package net.onrc.onos.ofcontroller.routing;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Queue;
-import java.util.Set;
-
-import net.onrc.onos.graph.DBOperation;
-import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.ISwitchObject;
-import net.onrc.onos.ofcontroller.core.INetMapTopologyService.ITopoRouteService;
-import net.onrc.onos.ofcontroller.core.ISwitchStorage.SwitchState;
-import net.onrc.onos.ofcontroller.util.DataPath;
-import net.onrc.onos.ofcontroller.util.Dpid;
-import net.onrc.onos.ofcontroller.util.FlowEntry;
-import net.onrc.onos.ofcontroller.util.Port;
-import net.onrc.onos.ofcontroller.util.SwitchPort;
-
-import org.openflow.util.HexString;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.tinkerpop.blueprints.Direction;
-import com.tinkerpop.blueprints.Vertex;
-import net.onrc.onos.graph.GraphDBManager;
-
-
-/**
- * A class for storing Node and Link information for fast computation
- * of shortest paths.
- */
-class Node {
- /**
- * A class for storing Link information for fast computation of shortest
- * paths.
- */
- class Link {
- public Node me; // The node this link originates from
- public Node neighbor; // The neighbor node on the other side
- public short myPort; // Local port number for the link
- public short neighborPort; // Neighbor port number for the link
-
- /**
- * Link constructor.
- *
- * @param me the node this link originates from.
- * @param the neighbor node on the other side of the link.
- * @param myPort local port number for the link.
- * @param neighborPort neighbor port number for the link.
- */
- public Link(Node me, Node neighbor, short myPort, short neighborPort) {
- this.me = me;
- this.neighbor = neighbor;
- this.myPort = myPort;
- this.neighborPort = neighborPort;
- }
- };
-
- public long nodeId; // The node ID
- public HashMap<Short, Link> links; // The links originating from this node
-
- /**
- * Node constructor.
- *
- * @param nodeId the node ID.
- */
- public Node(long nodeId) {
- this.nodeId = nodeId;
- links = new HashMap<Short, Link>();
- }
-
- /**
- * Add a neighbor.
- *
- * A new link to the neighbor will be created.
- *
- * @param neighbor the neighbor to add.
- * @param myPort the local port number for the link to the neighbor.
- * @param neighborPort the neighbor port number for the link.
- */
- public void addNeighbor(Node neighbor, short myPort, short neighborPort) {
- Link link = new Link(this, neighbor, myPort, neighborPort);
- links.put(myPort, link);
- }
-};
-
-/**
- * A class for implementing Topology Route Service.
- */
-public class TopoRouteService implements ITopoRouteService {
-
- /** The logger. */
- private static Logger log =
- LoggerFactory.getLogger(TopoRouteService.class);
-
- protected DBOperation op;
-
-
- /**
- * Default constructor.
- */
- public TopoRouteService() {
- }
-
- /**
- * Constructor for given database configuration file.
- *
- * @param config the database configuration file to use for
- * the initialization.
- */
- public TopoRouteService(final String dbStore, final String config) {
- this.init(dbStore, config);
- }
-
- /**
- * Init the module.
- *
- * @param config the database configuration file to use for
- * the initialization.
- */
- public void init(final String dbStore, final String config) {
- try {
- op = GraphDBManager.getDBOperation(dbStore, config);
- } catch (Exception e) {
- log.error(e.getMessage());
- }
- }
-
- /**
- * Close the service. It will close the corresponding database connection.
- */
- public void close() {
- op.close();
- }
-
- /**
- * Set the database operation handler.
- *
- * @param init_op the database operation handler to use for the
- * initialization.
- */
- public void setDbOperationHandler(DBOperation init_op) {
- op = init_op;
- }
-
- /**
- * Fetch the Switch and Ports info from the Titan Graph
- * and return it for fast access during the shortest path
- * computation.
- *
- * After fetching the state, method @ref getTopoShortestPath()
- * can be used for fast shortest path computation.
- *
- * Note: There is certain cost to fetch the state, hence it should
- * be used only when there is a large number of shortest path
- * computations that need to be done on the same topology.
- * Typically, a single call to @ref prepareShortestPathTopo()
- * should be followed by a large number of calls to
- * method @ref getTopoShortestPath().
- * After the last @ref getTopoShortestPath() call,
- * method @ref dropShortestPathTopo() should be used to release
- * the internal state that is not needed anymore:
- *
- * Map<Long, ?> shortestPathTopo;
- * shortestPathTopo = prepareShortestPathTopo();
- * for (int i = 0; i < 10000; i++) {
- * dataPath = getTopoShortestPath(shortestPathTopo, ...);
- * ...
- * }
- * dropShortestPathTopo(shortestPathTopo);
- *
- * @return the Shortest Path info handler stored in a map.
- */
- public Map<Long, ?> prepareShortestPathTopo() {
- Map<Long, Node> shortestPathTopo = new HashMap<Long, Node>();
-
- //
- // Fetch the relevant info from the Switch and Port vertices
- // from the Titan Graph.
- //
- Iterable<ISwitchObject> nodes = op.getActiveSwitches();
- for (ISwitchObject switchObj : nodes) {
- Vertex nodeVertex = switchObj.asVertex();
- //
- // The Switch info
- //
- String nodeDpid = nodeVertex.getProperty("dpid").toString();
- long nodeId = HexString.toLong(nodeDpid);
- Node me = shortestPathTopo.get(nodeId);
- if (me == null) {
- me = new Node(nodeId);
- shortestPathTopo.put(nodeId, me);
- }
-
- //
- // The local Port info
- //
- for (Vertex myPortVertex : nodeVertex.getVertices(Direction.OUT, "on")) {
- // Ignore inactive ports
- if (! myPortVertex.getProperty("state").toString().equals("ACTIVE"))
- continue;
-
- short myPort = 0;
- Object obj = myPortVertex.getProperty("number");
- if (obj instanceof Short) {
- myPort = (Short)obj;
- } else if (obj instanceof Integer) {
- Integer int_nodeId = (Integer)obj;
- myPort = int_nodeId.shortValue();
- }
-
- //
- // The neighbor Port info
- //
- for (Vertex neighborPortVertex : myPortVertex.getVertices(Direction.OUT, "link")) {
- // Ignore inactive ports
- if (! neighborPortVertex.getProperty("state").toString().equals("ACTIVE"))
- continue;
-
- short neighborPort = 0;
- obj = neighborPortVertex.getProperty("number");
- if (obj instanceof Short) {
- neighborPort = (Short)obj;
- } else if (obj instanceof Integer) {
- Integer int_nodeId = (Integer)obj;
- neighborPort = int_nodeId.shortValue();
- }
- //
- // The neighbor Switch info
- //
- for (Vertex neighborVertex : neighborPortVertex.getVertices(Direction.IN, "on")) {
- // Ignore inactive switches
- String state = neighborVertex.getProperty("state").toString();
- if (! state.equals(SwitchState.ACTIVE.toString()))
- continue;
-
- String neighborDpid = neighborVertex.getProperty("dpid").toString();
- long neighborId = HexString.toLong(neighborDpid);
- Node neighbor = shortestPathTopo.get(neighborId);
- if (neighbor == null) {
- neighbor = new Node(neighborId);
- shortestPathTopo.put(neighborId, neighbor);
- }
- me.addNeighbor(neighbor, myPort, neighborPort);
- }
- }
- }
- }
- op.commit();
-
- return shortestPathTopo;
- }
-
- /**
- * Release the state that was populated by
- * method @ref prepareShortestPathTopo().
- *
- * See the documentation for method @ref prepareShortestPathTopo()
- * for additional information and usage.
- *
- * @param shortestPathTopo the Shortest Path info handler to release.
- */
- public void dropShortestPathTopo(Map<Long, ?> shortestPathTopo) {
- shortestPathTopo = null;
- }
-
- /**
- * Get the shortest path from a source to a destination by
- * using the pre-populated local topology state prepared
- * by method @ref prepareShortestPathTopo().
- *
- * See the documentation for method @ref prepareShortestPathTopo()
- * for additional information and usage.
- *
- * @param shortestPathTopoHandler the Shortest Path info handler
- * to use.
- * @param src the source in the shortest path computation.
- * @param dest the destination in the shortest path computation.
- * @return the data path with the computed shortest path if
- * found, otherwise null.
- */
- public DataPath getTopoShortestPath(Map<Long, ?> shortestPathTopoHandler,
- SwitchPort src, SwitchPort dest) {
- @SuppressWarnings("unchecked")
- Map<Long, Node> shortestPathTopo = (Map)shortestPathTopoHandler;
- DataPath result_data_path = new DataPath();
-
- // Initialize the source and destination in the data path to return
- result_data_path.setSrcPort(src);
- result_data_path.setDstPort(dest);
-
- String dpid_src = src.dpid().toString();
- String dpid_dest = dest.dpid().toString();
-
- // Get the source vertex
- Node v_src = shortestPathTopo.get(src.dpid().value());
- if (v_src == null) {
- return null; // Source vertex not found
- }
-
- // Get the destination vertex
- Node v_dest = shortestPathTopo.get(dest.dpid().value());
- if (v_dest == null) {
- return null; // Destination vertex not found
- }
-
- //
- // Test whether we are computing a path from/to the same DPID.
- // If "yes", then just add a single flow entry in the return result.
- //
- if (dpid_src.equals(dpid_dest)) {
- FlowEntry flowEntry = new FlowEntry();
- flowEntry.setDpid(src.dpid());
- flowEntry.setInPort(src.port());
- flowEntry.setOutPort(dest.port());
- result_data_path.flowEntries().add(flowEntry);
- return result_data_path;
- }
-
- //
- // Implement the Shortest Path computation by using Breath First Search
- //
- Set<Node> visitedSet = new HashSet<Node>();
- Queue<Node> processingList = new LinkedList<Node>();
- Map<Node, Node.Link> previousVertexMap = new HashMap<Node, Node.Link>();
- processingList.add(v_src);
- visitedSet.add(v_src);
- Boolean path_found = false;
- while (! processingList.isEmpty()) {
- Node nextVertex = processingList.poll();
- if (v_dest == nextVertex) {
- path_found = true;
- break;
- }
- for (Node.Link link : nextVertex.links.values()) {
- Node child = link.neighbor;
- if (! visitedSet.contains(child)) {
- previousVertexMap.put(child, link);
- visitedSet.add(child);
- processingList.add(child);
- }
- }
- }
- if (! path_found)
- return null; // No path found
-
- // Collect the path as a list of links
- List<Node.Link> resultPath = new LinkedList<Node.Link>();
- Node previousVertex = v_dest;
- while (! v_src.equals(previousVertex)) {
- Node.Link currentLink = previousVertexMap.get(previousVertex);
- resultPath.add(currentLink);
- previousVertex = currentLink.me;
- }
- Collections.reverse(resultPath);
-
- //
- // Loop through the result and prepare the return result
- // as a list of Flow Entries.
- //
- Port inPort = new Port(src.port().value());
- Port outPort;
- for (Node.Link link: resultPath) {
- // Setup the outgoing port, and add the Flow Entry
- outPort = new Port(link.myPort);
-
- FlowEntry flowEntry = new FlowEntry();
- flowEntry.setDpid(new Dpid(link.me.nodeId));
- flowEntry.setInPort(inPort);
- flowEntry.setOutPort(outPort);
- result_data_path.flowEntries().add(flowEntry);
-
- // Setup the next incoming port
- inPort = new Port(link.neighborPort);
- }
- if (resultPath.size() > 0) {
- // Add the last Flow Entry
- FlowEntry flowEntry = new FlowEntry();
- flowEntry.setDpid(new Dpid(dest.dpid().value()));
- flowEntry.setInPort(inPort);
- flowEntry.setOutPort(dest.port());
- result_data_path.flowEntries().add(flowEntry);
- }
-
- if (result_data_path.flowEntries().size() > 0)
- return result_data_path;
-
- return null;
- }
-
- /**
- * Get the shortest path from a source to a destination.
- *
- * @param src the source in the shortest path computation.
- * @param dest the destination in the shortest path computation.
- * @return the data path with the computed shortest path if
- * found, otherwise null.
- */
- @Override
- public DataPath getShortestPath(SwitchPort src, SwitchPort dest) {
- DataPath result_data_path = new DataPath();
-
- // Initialize the source and destination in the data path to return
- result_data_path.setSrcPort(src);
- result_data_path.setDstPort(dest);
-
- String dpid_src = src.dpid().toString();
- String dpid_dest = dest.dpid().toString();
-
- // Get the source and destination switches
- ISwitchObject srcSwitch =
- op.searchActiveSwitch(dpid_src);
- ISwitchObject destSwitch =
- op.searchActiveSwitch(dpid_dest);
- if (srcSwitch == null || destSwitch == null) {
- return null;
- }
-
- //
- // Test whether we are computing a path from/to the same DPID.
- // If "yes", then just add a single flow entry in the return result.
- //
- if (dpid_src.equals(dpid_dest)) {
- FlowEntry flowEntry = new FlowEntry();
- flowEntry.setDpid(src.dpid());
- flowEntry.setInPort(src.port());
- flowEntry.setOutPort(dest.port());
- result_data_path.flowEntries().add(flowEntry);
- op.commit();
- return result_data_path;
- }
-
- Vertex v_src = srcSwitch.asVertex();
- Vertex v_dest = destSwitch.asVertex();
-
- //
- // Implement the Shortest Path computation by using Breath First Search
- //
- Set<Vertex> visitedSet = new HashSet<Vertex>();
- Queue<Vertex> processingList = new LinkedList<Vertex>();
- Map<Vertex, Vertex> previousVertexMap = new HashMap<Vertex, Vertex>();
-
- processingList.add(v_src);
- visitedSet.add(v_src);
- Boolean path_found = false;
- while (! processingList.isEmpty()) {
- Vertex nextVertex = processingList.poll();
- if (v_dest.equals(nextVertex)) {
- path_found = true;
- break;
- }
- for (Vertex parentPort : nextVertex.getVertices(Direction.OUT, "on")) {
- // Ignore inactive ports
- if (! parentPort.getProperty("state").toString().equals("ACTIVE"))
- continue;
-
- for (Vertex childPort : parentPort.getVertices(Direction.OUT, "link")) {
- // Ignore inactive ports
- if (! childPort.getProperty("state").toString().equals("ACTIVE"))
- continue;
-
- for (Vertex child : childPort.getVertices(Direction.IN, "on")) {
- // Ignore inactive switches
- String state = child.getProperty("state").toString();
- if (! state.equals(SwitchState.ACTIVE.toString()))
- continue;
-
- if (! visitedSet.contains(child)) {
- previousVertexMap.put(parentPort, nextVertex);
- previousVertexMap.put(childPort, parentPort);
- previousVertexMap.put(child, childPort);
- visitedSet.add(child);
- processingList.add(child);
- }
- }
- }
- }
- }
- if (! path_found)
- return null; // No path found
-
- List<Vertex> resultPath = new LinkedList<Vertex>();
- Vertex previousVertex = v_dest;
- resultPath.add(v_dest);
- while (! v_src.equals(previousVertex)) {
- Vertex currentVertex = previousVertexMap.get(previousVertex);
- resultPath.add(currentVertex);
- previousVertex = currentVertex;
- }
- Collections.reverse(resultPath);
-
-
- //
- // Loop through the result and prepare the return result
- // as a list of Flow Entries.
- //
- long nodeId = 0;
- short portId = 0;
- Port inPort = new Port(src.port().value());
- Port outPort = new Port();
- int idx = 0;
- for (Vertex v: resultPath) {
- String type = v.getProperty("type").toString();
- // System.out.println("type: " + type);
- if (type.equals("port")) {
- String number = v.getProperty("number").toString();
- // System.out.println("number: " + number);
-
- Object obj = v.getProperty("number");
- // String class_str = obj.getClass().toString();
- if (obj instanceof Short) {
- portId = (Short)obj;
- } else if (obj instanceof Integer) {
- Integer int_nodeId = (Integer)obj;
- portId = int_nodeId.shortValue();
- // int int_nodeId = (Integer)obj;
- // portId = (short)int_nodeId.;
- }
- } else if (type.equals("switch")) {
- String dpid = v.getProperty("dpid").toString();
- nodeId = HexString.toLong(dpid);
-
- // System.out.println("dpid: " + dpid);
- }
- idx++;
- if (idx == 1) {
- continue;
- }
- int mod = idx % 3;
- if (mod == 0) {
- // Setup the incoming port
- inPort = new Port(portId);
- continue;
- }
- if (mod == 2) {
- // Setup the outgoing port, and add the Flow Entry
- outPort = new Port(portId);
-
- FlowEntry flowEntry = new FlowEntry();
- flowEntry.setDpid(new Dpid(nodeId));
- flowEntry.setInPort(inPort);
- flowEntry.setOutPort(outPort);
- result_data_path.flowEntries().add(flowEntry);
- continue;
- }
- }
- if (idx > 0) {
- // Add the last Flow Entry
- FlowEntry flowEntry = new FlowEntry();
- flowEntry.setDpid(new Dpid(nodeId));
- flowEntry.setInPort(inPort);
- flowEntry.setOutPort(dest.port());
- result_data_path.flowEntries().add(flowEntry);
- }
-
- op.commit();
- if (result_data_path.flowEntries().size() > 0)
- return result_data_path;
-
- return null;
- }
-
- /**
- * Test whether a route exists from a source to a destination.
- *
- * @param src the source node for the test.
- * @param dest the destination node for the test.
- * @return true if a route exists, otherwise false.
- */
- @Override
- public Boolean routeExists(SwitchPort src, SwitchPort dest) {
- DataPath dataPath = getShortestPath(src, dest);
- return (dataPath != null);
- }
-}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/topology/ITopologyNetService.java b/src/main/java/net/onrc/onos/ofcontroller/topology/ITopologyNetService.java
new file mode 100644
index 0000000..9585366
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/topology/ITopologyNetService.java
@@ -0,0 +1,89 @@
+package net.onrc.onos.ofcontroller.topology;
+
+import java.util.Map;
+
+import net.floodlightcontroller.core.module.IFloodlightService;
+import net.onrc.onos.ofcontroller.util.DataPath;
+import net.onrc.onos.ofcontroller.util.SwitchPort;
+
+/**
+ * Interface for providing Topology Network Service to other modules.
+ */
+public interface ITopologyNetService extends IFloodlightService {
+ /**
+ * Fetch the Switch and Ports info from the Titan Graph
+ * and return it for fast access during the shortest path
+ * computation.
+ *
+ * After fetching the state, method @ref getTopologyShortestPath()
+ * can be used for fast shortest path computation.
+ *
+ * Note: There is certain cost to fetch the state, hence it should
+ * be used only when there is a large number of shortest path
+ * computations that need to be done on the same topology.
+ * Typically, a single call to @ref newDatabaseTopology()
+ * should be followed by a large number of calls to
+ * method @ref getTopologyShortestPath().
+ * After the last @ref getTopologyShortestPath() call,
+ * method @ref dropTopology() should be used to release
+ * the internal state that is not needed anymore:
+ *
+ * Topology topology = topologyManager.newDatabaseTopology();
+ * for (int i = 0; i < 10000; i++) {
+ * dataPath = topologyManager.getTopologyShortestPath(topology, ...);
+ * ...
+ * }
+ * topologyManager.dropTopology(shortestPathTopo);
+ *
+ * @return the allocated topology handler.
+ */
+ Topology newDatabaseTopology();
+
+ /**
+ * Release the topology that was populated by
+ * method @ref newDatabaseTopology().
+ *
+ * See the documentation for method @ref newDatabaseTopology()
+ * for additional information and usage.
+ *
+ * @param topology the topology to release.
+ */
+ void dropTopology(Topology topology);
+
+ /**
+ * Get the shortest path from a source to a destination by
+ * using the pre-populated local topology state prepared
+ * by method @ref newDatabaseTopology().
+ *
+ * See the documentation for method @ref newDatabaseTopology()
+ * for additional information and usage.
+ *
+ * @param topology the topology handler to use.
+ * @param src the source in the shortest path computation.
+ * @param dest the destination in the shortest path computation.
+ * @return the data path with the computed shortest path if
+ * found, otherwise null.
+ */
+ DataPath getTopologyShortestPath(Topology topology,
+ SwitchPort src, SwitchPort dest);
+
+ /**
+ * Get the shortest path from a source to a destination by using
+ * the underlying database.
+ *
+ * @param src the source in the shortest path computation.
+ * @param dest the destination in the shortest path computation.
+ * @return the data path with the computed shortest path if
+ * found, otherwise null.
+ */
+ DataPath getDatabaseShortestPath(SwitchPort src, SwitchPort dest);
+
+ /**
+ * Test whether a route exists from a source to a destination.
+ *
+ * @param src the source node for the test.
+ * @param dest the destination node for the test.
+ * @return true if a route exists, otherwise false.
+ */
+ Boolean routeExists(SwitchPort src, SwitchPort dest);
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/topology/ShortestPath.java b/src/main/java/net/onrc/onos/ofcontroller/topology/ShortestPath.java
new file mode 100644
index 0000000..393e16f
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/topology/ShortestPath.java
@@ -0,0 +1,327 @@
+package net.onrc.onos.ofcontroller.topology;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+
+import net.onrc.onos.graph.DBOperation;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.ISwitchObject;
+import net.onrc.onos.ofcontroller.core.ISwitchStorage.SwitchState;
+import net.onrc.onos.ofcontroller.util.DataPath;
+import net.onrc.onos.ofcontroller.util.Dpid;
+import net.onrc.onos.ofcontroller.util.FlowEntry;
+import net.onrc.onos.ofcontroller.util.Port;
+import net.onrc.onos.ofcontroller.util.SwitchPort;
+
+import org.openflow.util.HexString;
+
+import com.tinkerpop.blueprints.Direction;
+import com.tinkerpop.blueprints.Vertex;
+import net.onrc.onos.graph.GraphDBManager;
+
+/**
+ * Class to calculate a shortest DataPath between 2 SwitchPorts
+ * based on hops in Network Topology.
+ */
+public class ShortestPath {
+ /**
+ * Get the shortest path from a source to a destination by
+ * using the pre-populated local topology state prepared
+ * by method @ref TopologyManager.newDatabaseTopology().
+ *
+ * For additional documentation and usage, see method
+ * @ref TopologyManager.newDatabaseTopology()
+ *
+ * @param topology the topology handler to use.
+ * @param src the source in the shortest path computation.
+ * @param dest the destination in the shortest path computation.
+ * @return the data path with the computed shortest path if
+ * found, otherwise null.
+ */
+ public static DataPath getTopologyShortestPath(
+ Topology topology,
+ SwitchPort src, SwitchPort dest) {
+ DataPath result_data_path = new DataPath();
+
+ // Initialize the source and destination in the data path to return
+ result_data_path.setSrcPort(src);
+ result_data_path.setDstPort(dest);
+
+ String dpid_src = src.dpid().toString();
+ String dpid_dest = dest.dpid().toString();
+
+ // Get the source vertex
+ Node v_src = topology.getNode(src.dpid().value());
+ if (v_src == null) {
+ return null; // Source vertex not found
+ }
+
+ // Get the destination vertex
+ Node v_dest = topology.getNode(dest.dpid().value());
+ if (v_dest == null) {
+ return null; // Destination vertex not found
+ }
+
+ //
+ // Test whether we are computing a path from/to the same DPID.
+ // If "yes", then just add a single flow entry in the return result.
+ //
+ if (dpid_src.equals(dpid_dest)) {
+ FlowEntry flowEntry = new FlowEntry();
+ flowEntry.setDpid(src.dpid());
+ flowEntry.setInPort(src.port());
+ flowEntry.setOutPort(dest.port());
+ result_data_path.flowEntries().add(flowEntry);
+ return result_data_path;
+ }
+
+ //
+ // Implement the Shortest Path computation by using Breath First Search
+ //
+ Set<Node> visitedSet = new HashSet<Node>();
+ Queue<Node> processingList = new LinkedList<Node>();
+ Map<Node, Node.Link> previousVertexMap = new HashMap<Node, Node.Link>();
+ processingList.add(v_src);
+ visitedSet.add(v_src);
+ Boolean path_found = false;
+ while (! processingList.isEmpty()) {
+ Node nextVertex = processingList.poll();
+ if (v_dest == nextVertex) {
+ path_found = true;
+ break;
+ }
+ for (Node.Link link : nextVertex.links.values()) {
+ Node child = link.neighbor;
+ if (! visitedSet.contains(child)) {
+ previousVertexMap.put(child, link);
+ visitedSet.add(child);
+ processingList.add(child);
+ }
+ }
+ }
+ if (! path_found)
+ return null; // No path found
+
+ // Collect the path as a list of links
+ List<Node.Link> resultPath = new LinkedList<Node.Link>();
+ Node previousVertex = v_dest;
+ while (! v_src.equals(previousVertex)) {
+ Node.Link currentLink = previousVertexMap.get(previousVertex);
+ resultPath.add(currentLink);
+ previousVertex = currentLink.me;
+ }
+ Collections.reverse(resultPath);
+
+ //
+ // Loop through the result and prepare the return result
+ // as a list of Flow Entries.
+ //
+ Port inPort = new Port(src.port().value());
+ Port outPort;
+ for (Node.Link link: resultPath) {
+ // Setup the outgoing port, and add the Flow Entry
+ outPort = new Port((short)link.myPort);
+
+ FlowEntry flowEntry = new FlowEntry();
+ flowEntry.setDpid(new Dpid(link.me.nodeId));
+ flowEntry.setInPort(inPort);
+ flowEntry.setOutPort(outPort);
+ result_data_path.flowEntries().add(flowEntry);
+
+ // Setup the next incoming port
+ inPort = new Port((short)link.neighborPort);
+ }
+ if (resultPath.size() > 0) {
+ // Add the last Flow Entry
+ FlowEntry flowEntry = new FlowEntry();
+ flowEntry.setDpid(new Dpid(dest.dpid().value()));
+ flowEntry.setInPort(inPort);
+ flowEntry.setOutPort(dest.port());
+ result_data_path.flowEntries().add(flowEntry);
+ }
+
+ if (result_data_path.flowEntries().size() > 0)
+ return result_data_path;
+
+ return null;
+ }
+
+ /**
+ * Get the shortest path from a source to a destination by using
+ * the underlying Graph Database.
+ *
+ * @param dbHandler the Graph Database handler to use.
+ * @param src the source in the shortest path computation.
+ * @param dest the destination in the shortest path computation.
+ * @return the data path with the computed shortest path if
+ * found, otherwise null.
+ */
+ public static DataPath getDatabaseShortestPath(DBOperation dbHandler,
+ SwitchPort src, SwitchPort dest) {
+ DataPath result_data_path = new DataPath();
+
+ // Initialize the source and destination in the data path to return
+ result_data_path.setSrcPort(src);
+ result_data_path.setDstPort(dest);
+
+ String dpid_src = src.dpid().toString();
+ String dpid_dest = dest.dpid().toString();
+
+ // Get the source and destination switches
+ ISwitchObject srcSwitch =
+ dbHandler.searchActiveSwitch(dpid_src);
+ ISwitchObject destSwitch =
+ dbHandler.searchActiveSwitch(dpid_dest);
+ if (srcSwitch == null || destSwitch == null) {
+ return null;
+ }
+
+ //
+ // Test whether we are computing a path from/to the same DPID.
+ // If "yes", then just add a single flow entry in the return result.
+ //
+ if (dpid_src.equals(dpid_dest)) {
+ FlowEntry flowEntry = new FlowEntry();
+ flowEntry.setDpid(src.dpid());
+ flowEntry.setInPort(src.port());
+ flowEntry.setOutPort(dest.port());
+ result_data_path.flowEntries().add(flowEntry);
+ dbHandler.commit();
+ return result_data_path;
+ }
+
+ Vertex v_src = srcSwitch.asVertex();
+ Vertex v_dest = destSwitch.asVertex();
+
+ //
+ // Implement the Shortest Path computation by using Breath First Search
+ //
+ Set<Vertex> visitedSet = new HashSet<Vertex>();
+ Queue<Vertex> processingList = new LinkedList<Vertex>();
+ Map<Vertex, Vertex> previousVertexMap = new HashMap<Vertex, Vertex>();
+
+ processingList.add(v_src);
+ visitedSet.add(v_src);
+ Boolean path_found = false;
+ while (! processingList.isEmpty()) {
+ Vertex nextVertex = processingList.poll();
+ if (v_dest.equals(nextVertex)) {
+ path_found = true;
+ break;
+ }
+ for (Vertex parentPort : nextVertex.getVertices(Direction.OUT, "on")) {
+ // Ignore inactive ports
+ if (! parentPort.getProperty("state").toString().equals("ACTIVE"))
+ continue;
+
+ for (Vertex childPort : parentPort.getVertices(Direction.OUT, "link")) {
+ // Ignore inactive ports
+ if (! childPort.getProperty("state").toString().equals("ACTIVE"))
+ continue;
+
+ for (Vertex child : childPort.getVertices(Direction.IN, "on")) {
+ // Ignore inactive switches
+ String state = child.getProperty("state").toString();
+ if (! state.equals(SwitchState.ACTIVE.toString()))
+ continue;
+
+ if (! visitedSet.contains(child)) {
+ previousVertexMap.put(parentPort, nextVertex);
+ previousVertexMap.put(childPort, parentPort);
+ previousVertexMap.put(child, childPort);
+ visitedSet.add(child);
+ processingList.add(child);
+ }
+ }
+ }
+ }
+ }
+ if (! path_found)
+ return null; // No path found
+
+ List<Vertex> resultPath = new LinkedList<Vertex>();
+ Vertex previousVertex = v_dest;
+ resultPath.add(v_dest);
+ while (! v_src.equals(previousVertex)) {
+ Vertex currentVertex = previousVertexMap.get(previousVertex);
+ resultPath.add(currentVertex);
+ previousVertex = currentVertex;
+ }
+ Collections.reverse(resultPath);
+
+
+ //
+ // Loop through the result and prepare the return result
+ // as a list of Flow Entries.
+ //
+ long nodeId = 0;
+ short portId = 0;
+ Port inPort = new Port(src.port().value());
+ Port outPort = new Port();
+ int idx = 0;
+ for (Vertex v: resultPath) {
+ String type = v.getProperty("type").toString();
+ // System.out.println("type: " + type);
+ if (type.equals("port")) {
+ //String number = v.getProperty("number").toString();
+ // System.out.println("number: " + number);
+
+ Object obj = v.getProperty("number");
+ // String class_str = obj.getClass().toString();
+ if (obj instanceof Short) {
+ portId = (Short)obj;
+ } else if (obj instanceof Integer) {
+ Integer int_nodeId = (Integer)obj;
+ portId = int_nodeId.shortValue();
+ // int int_nodeId = (Integer)obj;
+ // portId = (short)int_nodeId.;
+ }
+ } else if (type.equals("switch")) {
+ String dpid = v.getProperty("dpid").toString();
+ nodeId = HexString.toLong(dpid);
+
+ // System.out.println("dpid: " + dpid);
+ }
+ idx++;
+ if (idx == 1) {
+ continue;
+ }
+ int mod = idx % 3;
+ if (mod == 0) {
+ // Setup the incoming port
+ inPort = new Port(portId);
+ continue;
+ }
+ if (mod == 2) {
+ // Setup the outgoing port, and add the Flow Entry
+ outPort = new Port(portId);
+
+ FlowEntry flowEntry = new FlowEntry();
+ flowEntry.setDpid(new Dpid(nodeId));
+ flowEntry.setInPort(inPort);
+ flowEntry.setOutPort(outPort);
+ result_data_path.flowEntries().add(flowEntry);
+ continue;
+ }
+ }
+ if (idx > 0) {
+ // Add the last Flow Entry
+ FlowEntry flowEntry = new FlowEntry();
+ flowEntry.setDpid(new Dpid(nodeId));
+ flowEntry.setInPort(inPort);
+ flowEntry.setOutPort(dest.port());
+ result_data_path.flowEntries().add(flowEntry);
+ }
+
+ dbHandler.commit();
+ if (result_data_path.flowEntries().size() > 0)
+ return result_data_path;
+
+ return null;
+ }
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/topology/Topology.java b/src/main/java/net/onrc/onos/ofcontroller/topology/Topology.java
new file mode 100644
index 0000000..dbf9ada
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/topology/Topology.java
@@ -0,0 +1,448 @@
+package net.onrc.onos.ofcontroller.topology;
+
+import java.util.List;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.TreeMap;
+
+import net.onrc.onos.graph.GraphDBOperation;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.ISwitchObject;
+import net.onrc.onos.ofcontroller.core.ISwitchStorage.SwitchState;
+
+import org.openflow.util.HexString;
+
+import com.tinkerpop.blueprints.Direction;
+import com.tinkerpop.blueprints.Vertex;
+
+/**
+ * A class for storing Node and Link information for fast computation
+ * of shortest paths.
+ */
+class Node {
+ /**
+ * A class for storing Link information for fast computation of shortest
+ * paths.
+ */
+ class Link {
+ public Node me; // The node this link originates from
+ public Node neighbor; // The neighbor node on the other side
+ public int myPort; // Local port ID for the link
+ public int neighborPort; // Neighbor port ID for the link
+
+ /**
+ * Link constructor.
+ *
+ * @param me the node this link originates from.
+ * @param the neighbor node on the other side of the link.
+ * @param myPort local port ID for the link.
+ * @param neighborPort neighbor port ID for the link.
+ */
+ public Link(Node me, Node neighbor, int myPort, int neighborPort) {
+ this.me = me;
+ this.neighbor = neighbor;
+ this.myPort = myPort;
+ this.neighborPort = neighborPort;
+ }
+ };
+
+ public long nodeId; // The node ID
+ public TreeMap<Integer, Link> links; // The links from this node:
+ // (src PortID -> Link)
+ private TreeMap<Integer, Link> reverseLinksMap; // The links to this node:
+ // (dst PortID -> Link)
+ private TreeMap<Integer, Integer> portsMap; // The ports on this node:
+ // (PortID -> PortID)
+ // TODO: In the future will be:
+ // (PortID -> Port)
+
+ /**
+ * Node constructor.
+ *
+ * @param nodeId the node ID.
+ */
+ public Node(long nodeId) {
+ this.nodeId = nodeId;
+ links = new TreeMap<Integer, Link>();
+ reverseLinksMap = new TreeMap<Integer, Link>();
+ portsMap = new TreeMap<Integer, Integer>();
+ }
+
+ /**
+ * Get all ports.
+ *
+ * @return all ports.
+ */
+ public Map<Integer, Integer> ports() {
+ return portsMap;
+ }
+
+ /**
+ * Get the port for a given Port ID.
+ *
+ * Note: For now the port itself is just the Port ID. In the future
+ * it might contain more information.
+ *
+ * @return the port if found, otherwise null.
+ */
+ public Integer getPort(int portId) {
+ return portsMap.get(portId);
+ }
+
+ /**
+ * Add a port for a given Port ID.
+ *
+ * Note: For now the port itself is just the Port ID. In the future
+ * it might contain more information.
+ *
+ * @param portId the Port ID of the port to add.
+ * @return the added Port.
+ */
+ Integer addPort(int portId) {
+ Integer port = new Integer(portId);
+ portsMap.put(portId, port);
+ return port;
+ }
+
+ /**
+ * Remove a port for a given Port ID.
+ *
+ * NOTE: The outgoing and incoming links using this port are removed as
+ * well.
+ */
+ void removePort(int portId) {
+ // Remove the outgoing link
+ Link link = getLink(portId);
+ if (link != null) {
+ link.neighbor.removeReverseLink(link);
+ removeLink(portId);
+ }
+
+ // Remove the incoming link
+ Link reverseLink = reverseLinksMap.get(portId);
+ if (reverseLink != null) {
+ // NOTE: reverseLink.myPort is the neighbor's outgoing port
+ reverseLink.me.removeLink(reverseLink.myPort);
+ removeReverseLink(reverseLink);
+ }
+
+ portsMap.remove(portId);
+ }
+
+ /**
+ * Get a link on a port to a neighbor.
+ *
+ * @param myPortId the local port ID for the link to the neighbor.
+ * @return the link if found, otherwise null.
+ */
+ public Link getLink(int myPortId) {
+ return links.get(myPortId);
+ }
+
+ /**
+ * Add a link to a neighbor.
+ *
+ * @param myPortId the local port ID for the link to the neighbor.
+ * @param neighbor the neighbor for the link.
+ * @param neighborPortId the neighbor port ID for the link.
+ * @return the added Link.
+ */
+ public Link addLink(int myPortId, Node neighbor, int neighborPortId) {
+ Link link = new Link(this, neighbor, myPortId, neighborPortId);
+ links.put(myPortId, link);
+ neighbor.addReverseLink(link);
+ return link;
+ }
+
+ /**
+ * Add a reverse link from a neighbor.
+ *
+ * @param link the reverse link from a neighbor to add.
+ */
+ private void addReverseLink(Link link) {
+ // NOTE: link.neghborPort is my port
+ reverseLinksMap.put(link.neighborPort, link);
+ }
+
+ /**
+ * Remove a link to a neighbor.
+ *
+ * @param myPortId the local port ID for the link to the neighbor.
+ */
+ public void removeLink(int myPortId) {
+ links.remove(myPortId);
+ }
+
+ /**
+ * Remove a reverse link from a neighbor.
+ *
+ * @param link the reverse link from a neighbor to remove.
+ */
+ private void removeReverseLink(Link link) {
+ // NOTE: link.neghborPort is my port
+ reverseLinksMap.remove(link.neighborPort);
+ }
+};
+
+/**
+ * A class for storing topology information.
+ */
+public class Topology {
+ private Map<Long, Node> nodesMap; // The dpid->Node mapping
+
+ /**
+ * Default constructor.
+ */
+ public Topology() {
+ nodesMap = new TreeMap<Long, Node>();
+ }
+
+ /**
+ * Add a topology element to the topology.
+ *
+ * @param topologyElement the topology element to add.
+ * @return true if the topology was modified, otherwise false.
+ */
+ public boolean addTopologyElement(TopologyElement topologyElement) {
+ boolean isModified = false;
+
+ switch (topologyElement.getType()) {
+ case ELEMENT_SWITCH: {
+ // Add the switch
+ Node node = getNode(topologyElement.getSwitch());
+ if (node == null) {
+ node = addNode(topologyElement.getSwitch());
+ isModified = true;
+ }
+ break;
+ }
+ case ELEMENT_PORT: {
+ // Add the switch
+ Node node = getNode(topologyElement.getSwitch());
+ if (node == null) {
+ node = addNode(topologyElement.getSwitch());
+ isModified = true;
+ }
+ // Add the port for the switch
+ Integer port = node.getPort(topologyElement.getSwitchPort());
+ if (port == null) {
+ node.addPort(topologyElement.getSwitchPort());
+ isModified = true;
+ }
+ break;
+ }
+ case ELEMENT_LINK: {
+ // Add the "from" switch
+ Node fromNode = getNode(topologyElement.getFromSwitch());
+ if (fromNode == null) {
+ fromNode = addNode(topologyElement.getFromSwitch());
+ isModified = true;
+ }
+ // Add the "to" switch
+ Node toNode = getNode(topologyElement.getToSwitch());
+ if (toNode == null) {
+ toNode = addNode(topologyElement.getToSwitch());
+ isModified = true;
+ }
+ // Add the "from" port
+ Integer fromPort = fromNode.getPort(topologyElement.getFromPort());
+ if (fromPort == null) {
+ fromNode.addPort(topologyElement.getFromPort());
+ isModified = true;
+ }
+ // Add the "to" port
+ Integer toPort = fromNode.getPort(topologyElement.getToPort());
+ if (toPort == null) {
+ toNode.addPort(topologyElement.getToPort());
+ isModified = true;
+ }
+ Node.Link link = fromNode.getLink(topologyElement.getFromPort());
+ if (link == null) {
+ fromNode.addLink(topologyElement.getFromPort(),
+ toNode,
+ topologyElement.getToPort());
+ isModified = true;
+ }
+
+ break;
+ }
+ }
+
+ return isModified;
+ }
+
+ /**
+ * Remove a topology element from the topology.
+ *
+ * @param topologyElement the topology element to remove.
+ * @return true if the topology was modified, otherwise false.
+ */
+ public boolean removeTopologyElement(TopologyElement topologyElement) {
+ boolean isModified = false;
+
+ switch (topologyElement.getType()) {
+ case ELEMENT_SWITCH: {
+ // Remove the switch
+ Node node = getNode(topologyElement.getSwitch());
+ if (node != null) {
+ removeNode(node);
+ isModified = true;
+ }
+ break;
+ }
+ case ELEMENT_PORT: {
+ // Find the switch
+ Node node = getNode(topologyElement.getSwitch());
+ if (node == null)
+ break;
+ // Remove the port for the switch
+ Integer port = node.getPort(topologyElement.getSwitchPort());
+ if (port != null) {
+ node.removePort(topologyElement.getSwitchPort());
+ isModified = true;
+ }
+ break;
+ }
+ case ELEMENT_LINK: {
+ // Find the "from" switch
+ Node fromNode = getNode(topologyElement.getFromSwitch());
+ if (fromNode == null)
+ break;
+ // Remove the link originating from the "from" port
+ Node.Link link = fromNode.getLink(topologyElement.getFromPort());
+ if (link != null) {
+ fromNode.removeLink(topologyElement.getFromPort());
+ isModified = true;
+ }
+ break;
+ }
+ }
+
+ return isModified;
+ }
+
+ /**
+ * Get a node for a given Node ID.
+ *
+ * @param nodeId the Node ID to use.
+ * @return the corresponding Node if found, otherwise null.
+ */
+ Node getNode(long nodeId) {
+ return nodesMap.get(nodeId);
+ }
+
+ /**
+ * Add a node for a given Node ID.
+ *
+ * @param nodeId the Node ID to use.
+ * @return the added Node.
+ */
+ Node addNode(long nodeId) {
+ Node node = new Node(nodeId);
+ nodesMap.put(nodeId, node);
+ return node;
+ }
+
+ /**
+ * Remove an existing node.
+ *
+ * @param node the Node to remove.
+ */
+ void removeNode(Node node) {
+ //
+ // Remove all ports one-by-one. This operation will also remove the
+ // incoming links originating from the neighbors.
+ //
+ // NOTE: We have to extract all Port IDs in advance, otherwise we
+ // cannot loop over the Ports collection and remove entries at the
+ // same time.
+ // TODO: If there is a large number of ports, the implementation
+ // below can be sub-optimal. It should be refactored as follows:
+ // 1. Modify removePort() to perform all the cleanup, except
+ // removing the Port entry from the portsMap
+ // 2. Call portsMap.clear() at the end of this method
+ // 3. In all other methods: if removePort() is called somewhere else,
+ // add an explicit removal of the Port entry from the portsMap.
+ //
+ List<Integer> allPortIdKeys = new LinkedList<Integer>();
+ allPortIdKeys.addAll(node.ports().keySet());
+ for (Integer portId : allPortIdKeys)
+ node.removePort(portId);
+
+ nodesMap.remove(node.nodeId);
+ }
+
+ /**
+ * Read topology state from the database.
+ *
+ * @param dbHandler the Graph Database handler to use.
+ */
+ public void readFromDatabase(GraphDBOperation dbHandler) {
+ //
+ // Fetch the relevant info from the Switch and Port vertices
+ // from the Titan Graph.
+ //
+ Iterable<ISwitchObject> activeSwitches = dbHandler.getActiveSwitches();
+ for (ISwitchObject switchObj : activeSwitches) {
+ Vertex nodeVertex = switchObj.asVertex();
+ //
+ // The Switch info
+ //
+ String nodeDpid = nodeVertex.getProperty("dpid").toString();
+ long nodeId = HexString.toLong(nodeDpid);
+ Node me = nodesMap.get(nodeId);
+ if (me == null)
+ me = addNode(nodeId);
+
+ //
+ // The local Port info
+ //
+ for (Vertex myPortVertex : nodeVertex.getVertices(Direction.OUT, "on")) {
+ // Ignore inactive ports
+ if (! myPortVertex.getProperty("state").toString().equals("ACTIVE"))
+ continue;
+
+ int myPort = 0;
+ Object obj = myPortVertex.getProperty("number");
+ if (obj instanceof Short) {
+ myPort = (Short)obj;
+ } else if (obj instanceof Integer) {
+ myPort = (Integer)obj;
+ }
+
+ //
+ // The neighbor Port info
+ //
+ for (Vertex neighborPortVertex : myPortVertex.getVertices(Direction.OUT, "link")) {
+ // Ignore inactive ports
+ if (! neighborPortVertex.getProperty("state").toString().equals("ACTIVE"))
+ continue;
+
+ int neighborPort = 0;
+ obj = neighborPortVertex.getProperty("number");
+ if (obj instanceof Short) {
+ neighborPort = (Short)obj;
+ } else if (obj instanceof Integer) {
+ neighborPort = (Integer)obj;
+ }
+ //
+ // The neighbor Switch info
+ //
+ for (Vertex neighborVertex : neighborPortVertex.getVertices(Direction.IN, "on")) {
+ // Ignore inactive switches
+ String state = neighborVertex.getProperty("state").toString();
+ if (! state.equals(SwitchState.ACTIVE.toString()))
+ continue;
+
+ String neighborDpid = neighborVertex.getProperty("dpid").toString();
+ long neighborId = HexString.toLong(neighborDpid);
+ Node neighbor = nodesMap.get(neighborId);
+ if (neighbor == null)
+ neighbor = addNode(neighborId);
+ me.addLink(myPort, neighbor, neighborPort);
+ }
+ }
+ }
+ }
+ dbHandler.commit();
+ }
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/topology/TopologyElement.java b/src/main/java/net/onrc/onos/ofcontroller/topology/TopologyElement.java
new file mode 100644
index 0000000..b01c7d3
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/topology/TopologyElement.java
@@ -0,0 +1,184 @@
+package net.onrc.onos.ofcontroller.topology;
+
+import java.util.Map;
+import java.util.TreeMap;
+
+/**
+ * Class for storing information about a Topology Element: Switch, Port or
+ * Link.
+ */
+public class TopologyElement {
+ /**
+ * The Element Type.
+ */
+ public enum Type {
+ ELEMENT_UNKNOWN, // Unknown element
+ ELEMENT_SWITCH, // Network Switch
+ ELEMENT_PORT, // Switch Port
+ ELEMENT_LINK // Unidirectional Link between Switch Ports
+ }
+
+ private Type elementType; // The element type
+ private long fromSwitchDpid = 0; // The Switch DPID
+ private int fromSwitchPort = 0; // The Switch Port
+ private long toSwitchDpid = 0; // The Neighbor Switch DPID
+ private int toSwitchPort = 0; // The Neighbor Switch Port
+
+ /**
+ * Default constructor.
+ */
+ public TopologyElement() {
+ elementType = Type.ELEMENT_UNKNOWN;
+ }
+
+ /**
+ * Constructor to create a Topology Element for a Switch.
+ *
+ * @param switchDpid the Switch DPID.
+ */
+ public TopologyElement(long switchDpid) {
+ this.elementType = Type.ELEMENT_SWITCH;
+ this.fromSwitchDpid = switchDpid;
+ }
+
+ /**
+ * Constructor to create a Topology Element for a Switch Port.
+ *
+ * @param switchDpid the Switch DPID.
+ * @param switchPort the Switch Port.
+ */
+ public TopologyElement(long switchDpid, int switchPort) {
+ this.elementType = Type.ELEMENT_PORT;
+ this.fromSwitchDpid = switchDpid;
+ this.fromSwitchPort = switchPort;
+ }
+
+ /**
+ * Constructor to create a Topology Element for an unidirectional Link
+ * between Switch Ports.
+ *
+ * @param fromSwitchDpid the Switch DPID the Link begins from.
+ * @param fromSwitchPort the Switch Port the Link begins from.
+ * @param toSwitchDpid the Switch DPID the Link ends to.
+ * @param toSwitchPort the Switch Port the Link ends to.
+ */
+ public TopologyElement(long fromSwitchDpid, int fromSwitchPort,
+ long toSwitchDpid, int toSwitchPort) {
+ this.elementType = Type.ELEMENT_LINK;
+ this.fromSwitchDpid = fromSwitchDpid;
+ this.fromSwitchPort = fromSwitchPort;
+ this.toSwitchDpid = toSwitchDpid;
+ this.toSwitchPort = toSwitchPort;
+ }
+
+ /**
+ * Get the Element type.
+ *
+ * @return the Element type.
+ */
+ public TopologyElement.Type getType() {
+ return elementType;
+ }
+
+ /**
+ * Get the Switch DPID.
+ *
+ * NOTE: Applies for Type.ELEMENT_SWITCH and Type.ELEMENT_PORT
+ *
+ * @return the Switch DPID.
+ */
+ public long getSwitch() {
+ return fromSwitchDpid;
+ }
+
+ /**
+ * Get the Switch Port.
+ *
+ * NOTE: Applies for Type.ELEMENT_PORT
+ *
+ * @return the Switch Port.
+ */
+ public int getSwitchPort() {
+ return fromSwitchPort;
+ }
+
+ /**
+ * Get the Switch DPID the Link begins from.
+ *
+ * NOTE: Applies for Type.ELEMENT_LINK
+ */
+ public long getFromSwitch() {
+ return fromSwitchDpid;
+ }
+
+ /**
+ * Get the Switch Port the Link begins from.
+ *
+ * NOTE: Applies for Type.ELEMENT_LINK
+ */
+ public int getFromPort() {
+ return fromSwitchPort;
+ }
+
+ /**
+ * Get the Switch DPID the Link ends to.
+ *
+ * NOTE: Applies for Type.ELEMENT_LINK
+ */
+ public long getToSwitch() {
+ return toSwitchDpid;
+ }
+
+ /**
+ * Get the Switch Port the Link ends to.
+ *
+ * NOTE: Applies for Type.ELEMENT_LINK
+ */
+ public int getToPort() {
+ return toSwitchPort;
+ }
+
+ /**
+ * Get the Topology Element ID.
+ *
+ * The Topology Element ID has the following format:
+ * - Switch: "Switch=<HexLongDpid>"
+ * Example: "Switch=101"
+ * - Switch Port: "Port=<HexLongDpid>/<IntPortId>"
+ * Example: "Port=102/1"
+ * - Link: "Link=<FromHexLongDpid>/<FromIntPortId>/<ToHexLongDpid>/<ToIntPortId>"
+ * Example: "Link=101/2/103/4"
+ *
+ * NOTE: The Topology Element ID has no syntax meaning. It is used only to
+ * uniquely identify a topology element.
+ *
+ * @return the Topology Element ID.
+ */
+ public String elementId() {
+ switch (elementType) {
+ case ELEMENT_SWITCH:
+ return "Switch=" + Long.toHexString(fromSwitchDpid);
+ case ELEMENT_PORT:
+ return "Port=" +
+ Long.toHexString(fromSwitchDpid) + "/" + fromSwitchPort;
+ case ELEMENT_LINK:
+ return "Link=" +
+ Long.toHexString(fromSwitchDpid) + "/" + fromSwitchPort + "/" +
+ Long.toHexString(toSwitchDpid) + "/" + toSwitchPort;
+ }
+
+ assert(false);
+ return null;
+ }
+
+ /**
+ * Convert the Topology Element to a string.
+ *
+ * @return the Topology Element as a string.
+ */
+ @Override
+ public String toString() {
+ // For now, we just return the Element ID.
+ return elementId();
+ }
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/topology/TopologyManager.java b/src/main/java/net/onrc/onos/ofcontroller/topology/TopologyManager.java
new file mode 100644
index 0000000..c0e04f2
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/topology/TopologyManager.java
@@ -0,0 +1,329 @@
+package net.onrc.onos.ofcontroller.topology;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import net.floodlightcontroller.core.IFloodlightProviderService;
+import net.floodlightcontroller.core.module.FloodlightModuleContext;
+import net.floodlightcontroller.core.module.FloodlightModuleException;
+import net.floodlightcontroller.core.module.IFloodlightModule;
+import net.floodlightcontroller.core.module.IFloodlightService;
+
+import net.onrc.onos.datagrid.IDatagridService;
+import net.onrc.onos.graph.GraphDBOperation;
+import net.onrc.onos.ofcontroller.floodlightlistener.INetworkGraphService;
+import net.onrc.onos.ofcontroller.util.DataPath;
+import net.onrc.onos.ofcontroller.util.FlowEntry;
+import net.onrc.onos.ofcontroller.util.FlowPath;
+import net.onrc.onos.ofcontroller.util.Port;
+import net.onrc.onos.ofcontroller.util.SwitchPort;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A class for obtaining Topology Snapshot
+ * and PathComputation.
+ *
+ * TODO: PathComputation part should be refactored out to separate class.
+ */
+public class TopologyManager implements IFloodlightModule,
+ ITopologyNetService {
+ private final static Logger log = LoggerFactory.getLogger(TopologyManager.class);
+ protected IFloodlightProviderService floodlightProvider;
+
+ protected GraphDBOperation dbHandler;
+
+
+ /**
+ * Default constructor.
+ */
+ public TopologyManager() {
+ }
+
+ /**
+ * Constructor for given database configuration file.
+ *
+ * @param config the database configuration file to use for
+ * the initialization.
+ */
+ public TopologyManager(String config) {
+ this.init(config);
+ }
+
+ /**
+ * Constructor for a given database operation handler.
+ *
+ * @param dbHandler the database operation handler to use for the
+ * initialization.
+ */
+ public TopologyManager(GraphDBOperation dbHandler) {
+ this.dbHandler = dbHandler;
+ }
+
+ /**
+ * Init the module.
+ *
+ * @param config the database configuration file to use for
+ * the initialization.
+ */
+ public void init(String config) {
+ try {
+ dbHandler = new GraphDBOperation(config);
+ } catch (Exception e) {
+ log.error(e.getMessage());
+ }
+ }
+
+ /**
+ * Shutdown the Topology Manager operation.
+ */
+ public void finalize() {
+ close();
+ }
+
+ /**
+ * Close the service. It will close the corresponding database connection.
+ */
+ public void close() {
+ dbHandler.close();
+ }
+
+ /**
+ * Get the collection of offered module services.
+ *
+ * @return the collection of offered module services.
+ */
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleServices() {
+ Collection<Class<? extends IFloodlightService>> l =
+ new ArrayList<Class<? extends IFloodlightService>>();
+ l.add(ITopologyNetService.class);
+ return l;
+ }
+
+ /**
+ * Get the collection of implemented services.
+ *
+ * @return the collection of implemented services.
+ */
+ @Override
+ public Map<Class<? extends IFloodlightService>, IFloodlightService>
+ getServiceImpls() {
+ Map<Class<? extends IFloodlightService>,
+ IFloodlightService> m =
+ new HashMap<Class<? extends IFloodlightService>,
+ IFloodlightService>();
+ m.put(ITopologyNetService.class, this);
+ return m;
+ }
+
+ /**
+ * Get the collection of modules this module depends on.
+ *
+ * @return the collection of modules this module depends on.
+ */
+ @Override
+ public Collection<Class<? extends IFloodlightService>>
+ getModuleDependencies() {
+ Collection<Class<? extends IFloodlightService>> l =
+ new ArrayList<Class<? extends IFloodlightService>>();
+ l.add(IFloodlightProviderService.class);
+ l.add(INetworkGraphService.class);
+ l.add(IDatagridService.class);
+ return l;
+ }
+
+ /**
+ * Initialize the module.
+ *
+ * @param context the module context to use for the initialization.
+ */
+ @Override
+ public void init(FloodlightModuleContext context)
+ throws FloodlightModuleException {
+ floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
+
+ String conf = "";
+ this.init(conf);
+ }
+
+ /**
+ * Startup module operation.
+ *
+ * @param context the module context to use for the startup.
+ */
+ @Override
+ public void startUp(FloodlightModuleContext context) {
+
+ }
+
+ /**
+ * Fetch the Switch and Ports info from the Titan Graph
+ * and return it for fast access during the shortest path
+ * computation.
+ *
+ * After fetching the state, method @ref getTopologyShortestPath()
+ * can be used for fast shortest path computation.
+ *
+ * Note: There is certain cost to fetch the state, hence it should
+ * be used only when there is a large number of shortest path
+ * computations that need to be done on the same topology.
+ * Typically, a single call to @ref newDatabaseTopology()
+ * should be followed by a large number of calls to
+ * method @ref getTopologyShortestPath().
+ * After the last @ref getTopologyShortestPath() call,
+ * method @ref dropTopology() should be used to release
+ * the internal state that is not needed anymore:
+ *
+ * Topology topology = topologyManager.newDatabaseTopology();
+ * for (int i = 0; i < 10000; i++) {
+ * dataPath = topologyManager.getTopologyShortestPath(topology, ...);
+ * ...
+ * }
+ * topologyManager.dropTopology(shortestPathTopo);
+ *
+ * @return the allocated topology handler.
+ */
+ public Topology newDatabaseTopology() {
+ Topology topology = new Topology();
+ topology.readFromDatabase(dbHandler);
+
+ return topology;
+ }
+
+ /**
+ * Release the topology that was populated by
+ * method @ref newDatabaseTopology().
+ *
+ * See the documentation for method @ref newDatabaseTopology()
+ * for additional information and usage.
+ *
+ * @param topology the topology to release.
+ */
+ public void dropTopology(Topology topology) {
+ topology = null;
+ }
+
+ /**
+ * Compute the network path for a Flow.
+ *
+ * @param topology the topology handler to use.
+ * @param flowPath the Flow to compute the network path for.
+ * @return the data path with the computed path if found, otherwise null.
+ */
+ public static DataPath computeNetworkPath(Topology topology,
+ FlowPath flowPath) {
+ //
+ // Compute the network path based on the desired Flow Path type
+ //
+ switch (flowPath.flowPathType()) {
+ case FP_TYPE_SHORTEST_PATH: {
+ SwitchPort src = flowPath.dataPath().srcPort();
+ SwitchPort dest = flowPath.dataPath().dstPort();
+ return ShortestPath.getTopologyShortestPath(topology, src, dest);
+ }
+ case FP_TYPE_EXPLICIT_PATH:
+ return flowPath.dataPath();
+ }
+
+ return null;
+ }
+
+ /**
+ * Test whether two Flow Entries represent same points in a data path.
+ *
+ * NOTE: Two Flow Entries represent same points in a data path if
+ * the Switch DPID, incoming port and outgoing port are same.
+ *
+ * NOTE: This method is specialized for shortest-path unicast paths,
+ * and probably should be moved somewhere else.
+ *
+ * @param oldFlowEntry the first Flow Entry to compare.
+ * @param newFlowEntry the second Flow Entry to compare.
+ * @return true if the two Flow Entries represent same points in a
+ * data path, otherwise false.
+ */
+ public static boolean isSameFlowEntryDataPath(FlowEntry oldFlowEntry,
+ FlowEntry newFlowEntry) {
+ // Test the DPID
+ if (oldFlowEntry.dpid().value() != newFlowEntry.dpid().value())
+ return false;
+
+ // Test the inPort
+ do {
+ Port oldPort = oldFlowEntry.inPort();
+ Port newPort = newFlowEntry.inPort();
+ if ((oldPort != null) && (newPort != null) &&
+ (oldPort.value() == newPort.value())) {
+ break;
+ }
+ if ((oldPort == null) && (newPort == null))
+ break;
+ return false; // inPort is different
+ } while (false);
+
+ // Test the outPort
+ do {
+ Port oldPort = oldFlowEntry.outPort();
+ Port newPort = newFlowEntry.outPort();
+ if ((oldPort != null) && (newPort != null) &&
+ (oldPort.value() == newPort.value())) {
+ break;
+ }
+ if ((oldPort == null) && (newPort == null))
+ break;
+ return false; // outPort is different
+ } while (false);
+
+ return true;
+ }
+
+ /**
+ * Get the shortest path from a source to a destination by
+ * using the pre-populated local topology state prepared
+ * by method @ref newDatabaseTopology().
+ *
+ * See the documentation for method @ref newDatabaseTopology()
+ * for additional information and usage.
+ *
+ * @param topology the topology handler to use.
+ * @param src the source in the shortest path computation.
+ * @param dest the destination in the shortest path computation.
+ * @return the data path with the computed shortest path if
+ * found, otherwise null.
+ */
+ public DataPath getTopologyShortestPath(Topology topology,
+ SwitchPort src, SwitchPort dest) {
+ return ShortestPath.getTopologyShortestPath(topology, src, dest);
+ }
+
+ /**
+ * Get the shortest path from a source to a destination by using
+ * the underlying database.
+ *
+ * @param src the source in the shortest path computation.
+ * @param dest the destination in the shortest path computation.
+ * @return the data path with the computed shortest path if
+ * found, otherwise null.
+ */
+ @Override
+ public DataPath getDatabaseShortestPath(SwitchPort src, SwitchPort dest) {
+ return ShortestPath.getDatabaseShortestPath(dbHandler, src, dest);
+ }
+
+ /**
+ * Test whether a route exists from a source to a destination.
+ *
+ * @param src the source node for the test.
+ * @param dest the destination node for the test.
+ * @return true if a route exists, otherwise false.
+ */
+ @Override
+ public Boolean routeExists(SwitchPort src, SwitchPort dest) {
+ DataPath dataPath = getDatabaseShortestPath(src, dest);
+ return (dataPath != null);
+ }
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/topology/web/RouteResource.java b/src/main/java/net/onrc/onos/ofcontroller/topology/web/RouteResource.java
index ee7ffce..839ba28 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/topology/web/RouteResource.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/topology/web/RouteResource.java
@@ -1,7 +1,8 @@
package net.onrc.onos.ofcontroller.topology.web;
-import net.onrc.onos.ofcontroller.core.INetMapTopologyService.ITopoRouteService;
-import net.onrc.onos.ofcontroller.routing.TopoRouteService;
+import net.onrc.onos.ofcontroller.flowmanager.IFlowService;
+import net.onrc.onos.ofcontroller.topology.ITopologyNetService;
+import net.onrc.onos.ofcontroller.topology.TopologyManager;
import net.onrc.onos.ofcontroller.util.DataPath;
import net.onrc.onos.ofcontroller.util.Dpid;
import net.onrc.onos.ofcontroller.util.Port;
@@ -14,13 +15,30 @@
public class RouteResource extends ServerResource {
- protected static Logger log = LoggerFactory.getLogger(RouteResource.class);
+ protected final static Logger log = LoggerFactory.getLogger(RouteResource.class);
@Get("json")
public DataPath retrieve() {
+<<<<<<< HEAD
ITopoRouteService topoRouteService = new TopoRouteService("titan", "");
if (topoRouteService == null) {
log.debug("Topology Route Service not found");
+=======
+ // Get the services that are needed for the computation
+ ITopologyNetService topologyNetService =
+ (ITopologyNetService)getContext().getAttributes().
+ get(ITopologyNetService.class.getCanonicalName());
+ IFlowService flowService =
+ (IFlowService)getContext().getAttributes().
+ get(IFlowService.class.getCanonicalName());
+
+ if (topologyNetService == null) {
+ log.debug("Topology Net Service not found");
+ return null;
+ }
+ if (flowService == null) {
+ log.debug("Flow Service not found");
+>>>>>>> master
return null;
}
@@ -37,8 +55,10 @@
Port dstPort = new Port(Short.parseShort(dstPortStr));
DataPath result =
- topoRouteService.getShortestPath(new SwitchPort(srcDpid, srcPort),
- new SwitchPort(dstDpid, dstPort));
+ topologyNetService.getTopologyShortestPath(
+ flowService.getTopology(),
+ new SwitchPort(srcDpid, srcPort),
+ new SwitchPort(dstDpid, dstPort));
if (result != null) {
return result;
} else {
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/DataPath.java b/src/main/java/net/onrc/onos/ofcontroller/util/DataPath.java
index dec70e3..044cc6d 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/DataPath.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/DataPath.java
@@ -101,12 +101,47 @@
}
/**
+ * Remove Flow Entries that were deleted.
+ */
+ public void removeDeletedFlowEntries() {
+ //
+ // NOTE: We create a new ArrayList, and add only the Flow Entries
+ // that are NOT FE_USER_DELETE.
+ // This is sub-optimal: if it adds notable processing cost,
+ // the Flow Entries container should be changed to LinkedList
+ // or some other container that has O(1) cost of removing an entry.
+ //
+
+ // Test first whether any Flow Entry was deleted
+ boolean foundDeletedFlowEntry = false;
+ for (FlowEntry flowEntry : this.flowEntries) {
+ if (flowEntry.flowEntryUserState() ==
+ FlowEntryUserState.FE_USER_DELETE) {
+ foundDeletedFlowEntry = true;
+ break;
+ }
+ }
+ if (! foundDeletedFlowEntry)
+ return; // Nothing to do
+
+ // Create a new collection and exclude the deleted flow entries
+ ArrayList<FlowEntry> newFlowEntries = new ArrayList<FlowEntry>();
+ for (FlowEntry flowEntry : this.flowEntries()) {
+ if (flowEntry.flowEntryUserState() !=
+ FlowEntryUserState.FE_USER_DELETE) {
+ newFlowEntries.add(flowEntry);
+ }
+ }
+ setFlowEntries(newFlowEntries);
+ }
+
+ /**
* Get a string with the summary of the shortest-path data path
* computation.
*
* NOTE: This method assumes the DataPath was created by
- * using FlowManager::getShortestPath() so the inPort and outPort
- * of the Flow Entries are set.
+ * using the TopologyManager shortest path computation, so the inPort
+ * and outPort of the Flow Entries are set.
* NOTE: This method is a temporary solution and will be removed
* in the future.
*
@@ -116,19 +151,18 @@
* inPort/dpid/outPort;inPort/dpid/outPort;...
*/
public String dataPathSummary() {
- String resultStr = new String();
+ StringBuilder resultStr = new StringBuilder(5+1+20+1+5+1);
if (this.flowEntries != null) {
for (FlowEntry flowEntry : this.flowEntries) {
// The data path summary string
- resultStr = resultStr +
- flowEntry.inPort().toString() + "/"
- + flowEntry.dpid().toString() + "/" +
- flowEntry.outPort().toString() + ";";
+ resultStr.append(flowEntry.inPort().toString()).append('/')
+ .append(flowEntry.dpid().toString()).append('/')
+ .append(flowEntry.outPort().toString()).append(';');
}
}
- if (resultStr.isEmpty())
- resultStr = "X"; // Invalid shortest-path
- return resultStr;
+ if (resultStr.length() == 0)
+ resultStr.append("X"); // Invalid shortest-path
+ return resultStr.toString();
}
/**
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/Dpid.java b/src/main/java/net/onrc/onos/ofcontroller/util/Dpid.java
index c3cf3aa..bd91daa 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/Dpid.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/Dpid.java
@@ -67,4 +67,22 @@
public String toString() {
return HexString.toHexString(this.value);
}
+
+ @Override
+ public boolean equals(Object other) {
+ if (!(other instanceof Dpid)) {
+ return false;
+ }
+
+ Dpid otherDpid = (Dpid) other;
+
+ return value == otherDpid.value;
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 17;
+ hash += 31 * hash + (int)(value ^ value >>> 32);
+ return hash;
+ }
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/EventEntry.java b/src/main/java/net/onrc/onos/ofcontroller/util/EventEntry.java
new file mode 100644
index 0000000..5b296e0
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/EventEntry.java
@@ -0,0 +1,64 @@
+package net.onrc.onos.ofcontroller.util;
+
+/**
+ * Class for encapsulating events with event-related data entry.
+ */
+public class EventEntry<T> {
+ /**
+ * The event types.
+ */
+ public enum Type {
+ ENTRY_ADD, // Add or update an entry
+ ENTRY_REMOVE // Remove an entry
+ }
+
+ private Type eventType; // The event type
+ private T eventData; // The relevant event data entry
+
+ /**
+ * Constructor for a given event type and event-related data entry.
+ *
+ * @param eventType the event type.
+ * @param eventData the event data entry.
+ */
+ public EventEntry(EventEntry.Type eventType, T eventData) {
+ this.eventType = eventType;
+ this.eventData = eventData;
+ }
+
+ /**
+ * Test whether the event type is ENTRY_ADD.
+ *
+ * @return true if the event type is ENTRY_ADD, otherwise false.
+ */
+ public boolean isAdd() {
+ return (this.eventType == Type.ENTRY_ADD);
+ }
+
+ /**
+ * Test whether the event type is ENTRY_REMOVE.
+ *
+ * @return true if the event type is ENTRY_REMOVE, otherwise false.
+ */
+ public boolean isRemove() {
+ return (this.eventType == Type.ENTRY_REMOVE);
+ }
+
+ /**
+ * Get the event type.
+ *
+ * @return the event type.
+ */
+ public EventEntry.Type eventType() {
+ return this.eventType;
+ }
+
+ /**
+ * Get the event-related data entry.
+ *
+ * @return the event-related data entry.
+ */
+ public T eventData() {
+ return this.eventData;
+ }
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntry.java b/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntry.java
index 762d272..15a6233 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntry.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntry.java
@@ -116,10 +116,11 @@
/**
* Get the Flow ID.
+ *
* @return the Flow ID.
*/
@JsonIgnore
- public FlowId getFlowId() { return flowId; }
+ public FlowId flowId() { return flowId; }
/**
* Set the Flow ID.
@@ -131,6 +132,17 @@
}
/**
+ * Test whether the Flow ID is valid.
+ *
+ * @return true if the Flow ID is valid, otherwise false.
+ */
+ public boolean isValidFlowId() {
+ if (this.flowId == null)
+ return false;
+ return (this.flowId.value() != 0);
+ }
+
+ /**
* Get the Flow Entry ID.
*
* @return the Flow Entry ID.
@@ -149,6 +161,17 @@
}
/**
+ * Test whether the Flow Entry ID is valid.
+ *
+ * @return true if the Flow Entry ID is valid, otherwise false.
+ */
+ public boolean isValidFlowEntryId() {
+ if (this.flowEntryId == null)
+ return false;
+ return (this.flowEntryId.value() != 0);
+ }
+
+ /**
* Get the Flow Entry Match.
*
* @return the Flow Entry Match.
@@ -331,6 +354,9 @@
} else {
ret.append("[");
}
+ if ( flowId != null ) {
+ ret.append(" flowId=" + this.flowId.toString());
+ }
if ( flowEntryMatch != null ) {
ret.append(" flowEntryMatch=" + this.flowEntryMatch.toString());
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntryAction.java b/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntryAction.java
index 1f8849a..a1163c8 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntryAction.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntryAction.java
@@ -48,7 +48,7 @@
/**
* Action structure for ACTION_OUTPUT: Output to switch port.
*/
- public class ActionOutput {
+ public static class ActionOutput {
private Port port; // Output port
private short maxLen; // Max. length (in bytes) to send to controller
// if the port is set to PORT_CONTROLLER
@@ -198,7 +198,7 @@
/**
* Action structure for ACTION_SET_VLAN_VID: Set the 802.1q VLAN id
*/
- public class ActionSetVlanId {
+ public static class ActionSetVlanId {
private short vlanId; // The VLAN ID to set
/**
@@ -296,7 +296,7 @@
/**
* Action structure for ACTION_SET_VLAN_PCP: Set the 802.1q priority
*/
- public class ActionSetVlanPriority {
+ public static class ActionSetVlanPriority {
private byte vlanPriority; // The VLAN priority to set
/**
@@ -394,7 +394,7 @@
/**
* Action structure for ACTION_STRIP_VLAN: Strip the 802.1q header
*/
- public class ActionStripVlan {
+ public static class ActionStripVlan {
private boolean stripVlan; // If true, strip the VLAN header
/**
@@ -489,7 +489,7 @@
* Action structure for ACTION_SET_DL_SRC and ACTION_SET_DL_DST:
* Set the Ethernet source/destination address.
*/
- public class ActionSetEthernetAddr {
+ public static class ActionSetEthernetAddr {
private MACAddress addr; // The MAC address to set
/**
@@ -589,7 +589,7 @@
* Action structure for ACTION_SET_NW_SRC and ACTION_SET_NW_DST:
* Set the IPv4 source/destination address.
*/
- public class ActionSetIPv4Addr {
+ public static class ActionSetIPv4Addr {
private IPv4 addr; // The IPv4 address to set
/**
@@ -689,7 +689,7 @@
* Action structure for ACTION_SET_NW_TOS:
* Set the IP ToS (DSCP field, 6 bits).
*/
- public class ActionSetIpToS {
+ public static class ActionSetIpToS {
private byte ipToS; // The IP ToS to set DSCP field, 6 bits)
/**
@@ -788,7 +788,7 @@
* Action structure for ACTION_SET_TP_SRC and ACTION_SET_TP_DST:
* Set the TCP/UDP source/destination port.
*/
- public class ActionSetTcpUdpPort {
+ public static class ActionSetTcpUdpPort {
private short port; // The TCP/UDP port to set
/**
@@ -886,7 +886,7 @@
/**
* Action structure for ACTION_ENQUEUE: Output to queue on port.
*/
- public class ActionEnqueue {
+ public static class ActionEnqueue {
private Port port; // Port that queue belongs. Should
// refer to a valid physical port
// (i.e. < PORT_MAX) or PORT_IN_PORT
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntryId.java b/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntryId.java
index c4e75a5..29efe4c 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntryId.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntryId.java
@@ -66,6 +66,29 @@
public void setValue(long value) {
this.value = value;
}
+
+ /**
+ * Returns true of the object is another Flow Entry ID with
+ * the same value; otherwise, returns false.
+ *
+ * @param Object to compare
+ */
+ @Override
+ public boolean equals(Object obj){
+ if(obj.getClass() == this.getClass()) {
+ FlowEntryId entry = (FlowEntryId) obj;
+ return this.value() == entry.value();
+ }
+ return false;
+ }
+
+ /**
+ * Return the hash code of the Flow Entry ID
+ */
+ @Override
+ public int hashCode() {
+ return Long.valueOf(value).hashCode();
+ }
/**
* Convert the Flow Entry ID value to a hexadecimal string.
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntryMatch.java b/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntryMatch.java
index a721ff2..a2ac748 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntryMatch.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntryMatch.java
@@ -16,7 +16,7 @@
/**
* A class for storing a value to match.
*/
- class Field<T> {
+ public static class Field<T> {
/**
* Default constructor.
*/
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntrySwitchState.java b/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntrySwitchState.java
index a69fdac..44439f2 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntrySwitchState.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntrySwitchState.java
@@ -4,9 +4,9 @@
* The Flow Entry state as set by the controller.
*/
public enum FlowEntrySwitchState {
- FE_SWITCH_UNKNOWN, // Initialization value: state unknown
- FE_SWITCH_NOT_UPDATED, // Switch not updated with this entry
- FE_SWITCH_UPDATE_IN_PROGRESS, // Switch update in progress
- FE_SWITCH_UPDATED, // Switch updated with this entry
- FE_SWITCH_UPDATE_FAILED // Error updating the switch with this entry
+ FE_SWITCH_UNKNOWN, // Initialization value: state unknown
+ FE_SWITCH_NOT_UPDATED, // Switch not updated with this entry
+ FE_SWITCH_UPDATE_IN_PROGRESS, // Switch update in progress
+ FE_SWITCH_UPDATED, // Switch updated with this entry
+ FE_SWITCH_UPDATE_FAILED // Error updating the switch with this entry
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntryUserState.java b/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntryUserState.java
index e3b64f0..5ed8865 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntryUserState.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/FlowEntryUserState.java
@@ -4,8 +4,8 @@
* The Flow Entry state as set by the user (via the ONOS API).
*/
public enum FlowEntryUserState {
- FE_USER_UNKNOWN, // Initialization value: state unknown
- FE_USER_ADD, // Flow entry that is added
- FE_USER_MODIFY, // Flow entry that is modified
- FE_USER_DELETE // Flow entry that is deleted
+ FE_USER_UNKNOWN, // Initialization value: state unknown
+ FE_USER_ADD, // Flow entry that is added
+ FE_USER_MODIFY, // Flow entry that is modified
+ FE_USER_DELETE // Flow entry that is deleted
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/FlowPath.java b/src/main/java/net/onrc/onos/ofcontroller/util/FlowPath.java
index a56dbff..a720fc6 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/FlowPath.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/FlowPath.java
@@ -1,9 +1,10 @@
package net.onrc.onos.ofcontroller.util;
+import java.util.ArrayList;
+
import net.floodlightcontroller.util.MACAddress;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowEntry;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowPath;
-import net.onrc.onos.ofcontroller.util.FlowPathFlags;
import org.codehaus.jackson.annotate.JsonProperty;
@@ -13,6 +14,8 @@
public class FlowPath implements Comparable<FlowPath> {
private FlowId flowId; // The Flow ID
private CallerId installerId; // The Caller ID of the path installer
+ private FlowPathType flowPathType; // The Flow Path type
+ private FlowPathUserState flowPathUserState; // The Flow Path User state
private FlowPathFlags flowPathFlags; // The Flow Path flags
private DataPath dataPath; // The data path
private FlowEntryMatch flowEntryMatch; // Common Flow Entry Match for all
@@ -24,6 +27,8 @@
* Default constructor.
*/
public FlowPath() {
+ flowPathType = FlowPathType.FP_TYPE_UNKNOWN;
+ flowPathUserState = FlowPathUserState.FP_USER_UNKNOWN;
flowPathFlags = new FlowPathFlags();
dataPath = new DataPath();
flowEntryActions = new FlowEntryActions();
@@ -36,6 +41,8 @@
dataPath = new DataPath();
this.setFlowId(new FlowId(flowObj.getFlowId()));
this.setInstallerId(new CallerId(flowObj.getInstallerId()));
+ this.setFlowPathType(FlowPathType.valueOf(flowObj.getFlowPathType()));
+ this.setFlowPathUserState(FlowPathUserState.valueOf(flowObj.getFlowPathUserState()));
this.setFlowPathFlags(new FlowPathFlags(flowObj.getFlowPathFlags()));
this.dataPath().srcPort().setDpid(new Dpid(flowObj.getSrcSwitch()));
this.dataPath().srcPort().setPort(new Port(flowObj.getSrcPort()));
@@ -221,6 +228,42 @@
}
/**
+ * Get the flow path type.
+ *
+ * @return the flow path type.
+ */
+ @JsonProperty("flowPathType")
+ public FlowPathType flowPathType() { return flowPathType; }
+
+ /**
+ * Set the flow path type.
+ *
+ * @param flowPathType the flow path type to set.
+ */
+ @JsonProperty("flowPathType")
+ public void setFlowPathType(FlowPathType flowPathType) {
+ this.flowPathType = flowPathType;
+ }
+
+ /**
+ * Get the flow path user state.
+ *
+ * @return the flow path user state.
+ */
+ @JsonProperty("flowPathUserState")
+ public FlowPathUserState flowPathUserState() { return flowPathUserState; }
+
+ /**
+ * Set the flow path user state.
+ *
+ * @param flowPathUserState the flow path user state to set.
+ */
+ @JsonProperty("flowPathUserState")
+ public void setFlowPathUserState(FlowPathUserState flowPathUserState) {
+ this.flowPathUserState = flowPathUserState;
+ }
+
+ /**
* Get the flow path flags.
*
* @return the flow path flags.
@@ -257,6 +300,15 @@
}
/**
+ * Get the data path flow entries.
+ *
+ * @return the data path flow entries.
+ */
+ public ArrayList<FlowEntry> flowEntries() {
+ return this.dataPath.flowEntries();
+ }
+
+ /**
* Get the flow path's match conditions common for all Flow Entries.
*
* @return the flow path's match conditions common for all Flow Entries.
@@ -300,8 +352,9 @@
* Convert the flow path to a string.
*
* The string has the following form:
- * [flowId=XXX installerId=XXX flowPathFlags=XXX dataPath=XXX
- * flowEntryMatch=XXX flowEntryActions=XXX]
+ * [flowId=XXX installerId=XXX flowPathType = XXX flowPathUserState = XXX
+ * flowPathFlags=XXX dataPath=XXX flowEntryMatch=XXX
+ * flowEntryActions=XXX]
*
* @return the flow path as a string.
*/
@@ -309,6 +362,8 @@
public String toString() {
String ret = "[flowId=" + this.flowId.toString();
ret += " installerId=" + this.installerId.toString();
+ ret += " flowPathType=" + this.flowPathType;
+ ret += " flowPathUserState=" + this.flowPathUserState;
ret += " flowPathFlags=" + this.flowPathFlags.toString();
if (dataPath != null)
ret += " dataPath=" + this.dataPath.toString();
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/FlowPathFlags.java b/src/main/java/net/onrc/onos/ofcontroller/util/FlowPathFlags.java
index 63241f0..4bbd399 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/FlowPathFlags.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/FlowPathFlags.java
@@ -9,10 +9,10 @@
private long flags;
// Discard the first-hop Flow Entry
- private final long DISCARD_FIRST_HOP_ENTRY = (1 << 0);
+ private static final long DISCARD_FIRST_HOP_ENTRY = (1 << 0);
// Keep only the first-hop Flow Entry
- private final long KEEP_ONLY_FIRST_HOP_ENTRY = (1 << 1);
+ private static final long KEEP_ONLY_FIRST_HOP_ENTRY = (1 << 1);
/**
* Default constructor.
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/FlowPathType.java b/src/main/java/net/onrc/onos/ofcontroller/util/FlowPathType.java
new file mode 100644
index 0000000..87f2d98
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/FlowPathType.java
@@ -0,0 +1,10 @@
+package net.onrc.onos.ofcontroller.util;
+
+/**
+ * The Flow Path types.
+ */
+public enum FlowPathType {
+ FP_TYPE_UNKNOWN, // Initialization value: state unknown
+ FP_TYPE_SHORTEST_PATH, // Shortest path flow
+ FP_TYPE_EXPLICIT_PATH // Flow path with explicit flow entries
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/FlowPathUserState.java b/src/main/java/net/onrc/onos/ofcontroller/util/FlowPathUserState.java
new file mode 100644
index 0000000..96b6345
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/FlowPathUserState.java
@@ -0,0 +1,11 @@
+package net.onrc.onos.ofcontroller.util;
+
+/**
+ * The Flow Path state as set by the user (via the ONOS API).
+ */
+public enum FlowPathUserState {
+ FP_USER_UNKNOWN, // Initialization value: state unknown
+ FP_USER_ADD, // Flow path that is added
+ FP_USER_MODIFY, // Flow path that is modified
+ FP_USER_DELETE // Flow path that is deleted
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/Port.java b/src/main/java/net/onrc/onos/ofcontroller/util/Port.java
index bb4851c..fedc8df 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/Port.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/Port.java
@@ -131,4 +131,23 @@
public String toString() {
return Short.toString(this.value);
}
+
+
+ @Override
+ public boolean equals(Object other) {
+ if (!(other instanceof Port)) {
+ return false;
+ }
+
+ Port otherPort = (Port) other;
+
+ return value == otherPort.value;
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 17;
+ hash += 31 * hash + (int)value;
+ return hash;
+ }
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/Switch.java b/src/main/java/net/onrc/onos/ofcontroller/util/Switch.java
new file mode 100644
index 0000000..f7df223
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/Switch.java
@@ -0,0 +1,116 @@
+package net.onrc.onos.ofcontroller.util;
+
+import org.codehaus.jackson.annotate.JsonProperty;
+
+/**
+ * The class representing a Switch.
+ * NOTE: Currently this class is (almost) not used.
+ */
+public class Switch {
+ /**
+ * The Switch state.
+ */
+ public enum SwitchState {
+ INACTIVE,
+ ACTIVE,
+ }
+
+ private Dpid dpid; // The DPID of the switch
+ private SwitchState state; // The state of the switch
+
+ /**
+ * Default constructor.
+ *
+ * NOTE: The default state for the switch is INACTIVE.
+ */
+ public Switch() {
+ this.dpid = new Dpid();
+ this.state = SwitchState.INACTIVE;
+ }
+
+ /**
+ * Constructor for a given DPID.
+ *
+ * NOTE: The state for the switch with a given DPID is ACTIVE.
+ *
+ * @param dpid the DPID to use.
+ */
+ public Switch(Dpid dpid) {
+ this.dpid = dpid;
+ this.state = SwitchState.ACTIVE;
+ }
+
+ /**
+ * Constructor for a given DPID and Switch State.
+ *
+ * @param dpid the DPID to use.
+ * @param state the Switch State to use.
+ */
+ public Switch(Dpid dpid, SwitchState state) {
+ this.dpid = dpid;
+ this.state = state;
+ }
+
+ /**
+ * Get the DPID.
+ *
+ * @return the DPID.
+ */
+ @JsonProperty("dpid")
+ public Dpid dpid() { return dpid; }
+
+ /**
+ * Set the DPID.
+ *
+ * @param dpid the DPID to use.
+ */
+ @JsonProperty("dpid")
+ public void setDpid(Dpid dpid) {
+ this.dpid = dpid;
+ }
+
+ /**
+ * Get the state.
+ *
+ * @return the state.
+ */
+ @JsonProperty("state")
+ public SwitchState state() { return state; }
+
+ /**
+ * Set the state.
+ *
+ * @param state the state to use.
+ */
+ @JsonProperty("state")
+ public void setState(SwitchState state) {
+ this.state = state;
+ }
+
+ /**
+ * Set the Switch State to ACTIVE.
+ */
+ public void setStateActive() {
+ this.state = SwitchState.ACTIVE;
+ }
+
+ /**
+ * Set the Switch State to INACTIVE.
+ */
+ public void setStateInactive() {
+ this.state = SwitchState.INACTIVE;
+ }
+
+ /**
+ * Convert the Switch value to a string.
+ *
+ * The string has the following form:
+ * dpid/state
+ *
+ * @return the Switch value as a string.
+ */
+ @Override
+ public String toString() {
+ return this.dpid.toString() + "/" + this.state.toString();
+ }
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/SwitchPort.java b/src/main/java/net/onrc/onos/ofcontroller/util/SwitchPort.java
index 95a934f..8912803 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/SwitchPort.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/SwitchPort.java
@@ -85,4 +85,25 @@
public String toString() {
return this.dpid.toString() + "/" + this.port;
}
+
+
+ @Override
+ public boolean equals(Object other) {
+ if (!(other instanceof SwitchPort)) {
+ return false;
+ }
+
+ SwitchPort otherSwitchPort = (SwitchPort) other;
+
+ return (dpid.equals(otherSwitchPort.dpid) &&
+ port.equals(otherSwitchPort.port));
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 17;
+ hash += 31 * hash + dpid.hashCode();
+ hash += 31 * hash + port.hashCode();
+ return hash;
+ }
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/DpidDeserializer.java b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/DpidDeserializer.java
index 9075f96..fe93245 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/DpidDeserializer.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/DpidDeserializer.java
@@ -17,7 +17,7 @@
*/
public class DpidDeserializer extends JsonDeserializer<Dpid> {
- protected static Logger log = LoggerFactory.getLogger(DpidDeserializer.class);
+ protected final static Logger log = LoggerFactory.getLogger(DpidDeserializer.class);
@Override
public Dpid deserialize(JsonParser jp,
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/FlowEntryIdDeserializer.java b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/FlowEntryIdDeserializer.java
index 72ddfea..71b02e0 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/FlowEntryIdDeserializer.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/FlowEntryIdDeserializer.java
@@ -17,7 +17,7 @@
*/
public class FlowEntryIdDeserializer extends JsonDeserializer<FlowEntryId> {
- protected static Logger log = LoggerFactory.getLogger(FlowEntryIdDeserializer.class);
+ protected final static Logger log = LoggerFactory.getLogger(FlowEntryIdDeserializer.class);
@Override
public FlowEntryId deserialize(JsonParser jp,
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/FlowIdDeserializer.java b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/FlowIdDeserializer.java
index eb93a23..f341027 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/FlowIdDeserializer.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/FlowIdDeserializer.java
@@ -17,7 +17,7 @@
*/
public class FlowIdDeserializer extends JsonDeserializer<FlowId> {
- protected static Logger log = LoggerFactory.getLogger(FlowIdDeserializer.class);
+ protected final static Logger log = LoggerFactory.getLogger(FlowIdDeserializer.class);
@Override
public FlowId deserialize(JsonParser jp,
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/IPv4Deserializer.java b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/IPv4Deserializer.java
index daf90af..2969e60 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/IPv4Deserializer.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/IPv4Deserializer.java
@@ -17,7 +17,7 @@
*/
public class IPv4Deserializer extends JsonDeserializer<IPv4> {
- protected static Logger log = LoggerFactory.getLogger(IPv4Deserializer.class);
+ protected final static Logger log = LoggerFactory.getLogger(IPv4Deserializer.class);
@Override
public IPv4 deserialize(JsonParser jp,
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/IPv4NetDeserializer.java b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/IPv4NetDeserializer.java
index f67ab38..b2592af 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/IPv4NetDeserializer.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/IPv4NetDeserializer.java
@@ -17,7 +17,7 @@
*/
public class IPv4NetDeserializer extends JsonDeserializer<IPv4Net> {
- protected static Logger log = LoggerFactory.getLogger(IPv4NetDeserializer.class);
+ protected final static Logger log = LoggerFactory.getLogger(IPv4NetDeserializer.class);
@Override
public IPv4Net deserialize(JsonParser jp,
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/IPv6Deserializer.java b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/IPv6Deserializer.java
index 7e3e5f6..c825377 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/IPv6Deserializer.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/IPv6Deserializer.java
@@ -17,7 +17,7 @@
*/
public class IPv6Deserializer extends JsonDeserializer<IPv6> {
- protected static Logger log = LoggerFactory.getLogger(IPv6Deserializer.class);
+ protected final static Logger log = LoggerFactory.getLogger(IPv6Deserializer.class);
@Override
public IPv6 deserialize(JsonParser jp,
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/IPv6NetDeserializer.java b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/IPv6NetDeserializer.java
index d7631b3..7191fa9 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/IPv6NetDeserializer.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/IPv6NetDeserializer.java
@@ -17,7 +17,7 @@
*/
public class IPv6NetDeserializer extends JsonDeserializer<IPv6Net> {
- protected static Logger log = LoggerFactory.getLogger(IPv6NetDeserializer.class);
+ protected final static Logger log = LoggerFactory.getLogger(IPv6NetDeserializer.class);
@Override
public IPv6Net deserialize(JsonParser jp,
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/KryoFactory.java b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/KryoFactory.java
new file mode 100644
index 0000000..1355fe0
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/KryoFactory.java
@@ -0,0 +1,161 @@
+package net.onrc.onos.ofcontroller.util.serializers;
+
+import java.util.ArrayList;
+import java.util.TreeMap;
+
+import net.floodlightcontroller.util.MACAddress;
+import net.onrc.onos.ofcontroller.proxyarp.ArpMessage;
+import net.onrc.onos.ofcontroller.topology.TopologyElement;
+import net.onrc.onos.ofcontroller.util.CallerId;
+import net.onrc.onos.ofcontroller.util.DataPath;
+import net.onrc.onos.ofcontroller.util.DataPathEndpoints;
+import net.onrc.onos.ofcontroller.util.Dpid;
+import net.onrc.onos.ofcontroller.util.FlowEntry;
+import net.onrc.onos.ofcontroller.util.FlowEntryAction;
+import net.onrc.onos.ofcontroller.util.FlowEntryActions;
+import net.onrc.onos.ofcontroller.util.FlowEntryErrorState;
+import net.onrc.onos.ofcontroller.util.FlowEntryId;
+import net.onrc.onos.ofcontroller.util.FlowEntryMatch;
+import net.onrc.onos.ofcontroller.util.FlowEntrySwitchState;
+import net.onrc.onos.ofcontroller.util.FlowEntryUserState;
+import net.onrc.onos.ofcontroller.util.FlowId;
+import net.onrc.onos.ofcontroller.util.FlowPath;
+import net.onrc.onos.ofcontroller.util.FlowPathFlags;
+import net.onrc.onos.ofcontroller.util.FlowPathType;
+import net.onrc.onos.ofcontroller.util.FlowPathUserState;
+import net.onrc.onos.ofcontroller.util.IPv4;
+import net.onrc.onos.ofcontroller.util.IPv4Net;
+import net.onrc.onos.ofcontroller.util.IPv6;
+import net.onrc.onos.ofcontroller.util.IPv6Net;
+import net.onrc.onos.ofcontroller.util.Port;
+import net.onrc.onos.ofcontroller.util.Switch;
+import net.onrc.onos.ofcontroller.util.SwitchPort;
+
+import com.esotericsoftware.kryo2.Kryo;
+
+/**
+ * Class factory for allocating Kryo instances for
+ * serialization/deserialization of classes.
+ */
+public class KryoFactory {
+ private ArrayList<Kryo> kryoList = new ArrayList<Kryo>();
+
+ /**
+ * Default constructor.
+ */
+ public KryoFactory() {
+ Kryo kryo;
+ // Preallocate
+ for (int i = 0; i < 100; i++) {
+ kryo = newKryoImpl();
+ kryoList.add(kryo);
+ }
+ }
+
+ /**
+ * Create and initialize a new Kryo object.
+ *
+ * @return the created Kryo object.
+ */
+ public Kryo newKryo() {
+ return newDeleteKryo(null);
+ }
+
+ /**
+ * Delete an existing Kryo object.
+ *
+ * @param deleteKryo the object to delete.
+ */
+ public void deleteKryo(Kryo deleteKryo) {
+ newDeleteKryo(deleteKryo);
+ }
+
+ /**
+ * Create or delete a Kryo object.
+ *
+ * @param deleteKryo if null, then allocate and return a new object,
+ * otherwise delete the provided object.
+ * @return a new Kryo object if needed, otherwise null.
+ */
+ synchronized private Kryo newDeleteKryo(Kryo deleteKryo) {
+ if (deleteKryo != null) {
+ // Delete an entry by moving it back to the buffer
+ kryoList.add(deleteKryo);
+ return null;
+ } else {
+ Kryo kryo = null;
+ if (kryoList.isEmpty()) {
+ // Preallocate
+ for (int i = 0; i < 100; i++) {
+ kryo = newKryoImpl();
+ kryoList.add(kryo);
+ }
+ }
+
+ kryo = kryoList.remove(kryoList.size() - 1);
+ return kryo;
+ }
+ }
+
+ /**
+ * Create and initialize a new Kryo object.
+ *
+ * @return the created Kryo object.
+ */
+ private Kryo newKryoImpl() {
+ Kryo kryo = new Kryo();
+ kryo.setRegistrationRequired(true);
+ // kryo.setReferences(false);
+ //
+ kryo.register(ArrayList.class);
+
+ // FlowPath and related classes
+ kryo.register(CallerId.class);
+ kryo.register(DataPath.class);
+ kryo.register(DataPathEndpoints.class);
+ kryo.register(Dpid.class);
+ kryo.register(FlowEntryAction.class);
+ kryo.register(FlowEntryAction.ActionEnqueue.class);
+ kryo.register(FlowEntryAction.ActionOutput.class);
+ kryo.register(FlowEntryAction.ActionSetEthernetAddr.class);
+ kryo.register(FlowEntryAction.ActionSetIpToS.class);
+ kryo.register(FlowEntryAction.ActionSetIPv4Addr.class);
+ kryo.register(FlowEntryAction.ActionSetTcpUdpPort.class);
+ kryo.register(FlowEntryAction.ActionSetVlanId.class);
+ kryo.register(FlowEntryAction.ActionSetVlanPriority.class);
+ kryo.register(FlowEntryAction.ActionStripVlan.class);
+ kryo.register(FlowEntryAction.ActionValues.class);
+ kryo.register(FlowEntryActions.class);
+ kryo.register(FlowEntryErrorState.class);
+ kryo.register(FlowEntryId.class);
+ kryo.register(FlowEntry.class);
+ kryo.register(FlowEntryMatch.class);
+ kryo.register(FlowEntryMatch.Field.class);
+ kryo.register(FlowEntrySwitchState.class);
+ kryo.register(FlowEntryUserState.class);
+ kryo.register(FlowId.class);
+ kryo.register(FlowPath.class);
+ kryo.register(FlowPathFlags.class);
+ kryo.register(FlowPathType.class);
+ kryo.register(FlowPathUserState.class);
+ kryo.register(IPv4.class);
+ kryo.register(IPv4Net.class);
+ kryo.register(IPv6.class);
+ kryo.register(IPv6Net.class);
+ kryo.register(byte[].class);
+ kryo.register(MACAddress.class);
+ kryo.register(Port.class);
+ kryo.register(Switch.class);
+ kryo.register(SwitchPort.class);
+
+ // Topology-related classes
+ kryo.register(TopologyElement.class);
+ kryo.register(TopologyElement.Type.class);
+ kryo.register(TreeMap.class);
+
+ //ARP message
+ kryo.register(ArpMessage.class);
+
+ return kryo;
+ }
+}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/MACAddressDeserializer.java b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/MACAddressDeserializer.java
index dc4a0e2..5253dce 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/util/serializers/MACAddressDeserializer.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/util/serializers/MACAddressDeserializer.java
@@ -17,7 +17,7 @@
*/
public class MACAddressDeserializer extends JsonDeserializer<MACAddress> {
- protected static Logger log = LoggerFactory.getLogger(MACAddressDeserializer.class);
+ protected final static Logger log = LoggerFactory.getLogger(MACAddressDeserializer.class);
@Override
public MACAddress deserialize(JsonParser jp,