Merge branch 'devchanges'
diff --git a/src/main/java/net/onrc/onos/datagrid/HazelcastDatagrid.java b/src/main/java/net/onrc/onos/datagrid/HazelcastDatagrid.java
index 41b4957..d04e50a 100644
--- a/src/main/java/net/onrc/onos/datagrid/HazelcastDatagrid.java
+++ b/src/main/java/net/onrc/onos/datagrid/HazelcastDatagrid.java
@@ -17,7 +17,9 @@
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.onrc.onos.datagrid.web.DatagridWebRoutable;
import net.onrc.onos.ofcontroller.flowmanager.IFlowEventHandlerService;
import net.onrc.onos.ofcontroller.topology.TopologyElement;
import net.onrc.onos.ofcontroller.util.FlowEntry;
@@ -48,6 +50,7 @@
protected final static Logger log = LoggerFactory.getLogger(HazelcastDatagrid.class);
protected IFloodlightProviderService floodlightProvider;
+ protected IRestApiService restApi;
protected static final String HazelcastConfigFile = "datagridConfig";
private HazelcastInstance hazelcastInstance = null;
@@ -163,6 +166,12 @@
* @param event the notification event for the entry.
*/
public void entryAdded(EntryEvent event) {
+ //
+ // NOTE: Ignore Flow Entries Events originated by this instance
+ //
+ if (event.getMember().localMember())
+ return;
+
Long keyLong = (Long)event.getKey();
byte[] valueBytes = (byte[])event.getValue();
@@ -182,6 +191,12 @@
* @param event the notification event for the entry.
*/
public void entryRemoved(EntryEvent event) {
+ //
+ // NOTE: Ignore Flow Entries Events originated by this instance
+ //
+ if (event.getMember().localMember())
+ return;
+
Long keyLong = (Long)event.getKey();
byte[] valueBytes = (byte[])event.getValue();
@@ -201,6 +216,12 @@
* @param event the notification event for the entry.
*/
public void entryUpdated(EntryEvent event) {
+ //
+ // NOTE: Ignore Flow Entries Events originated by this instance
+ //
+ if (event.getMember().localMember())
+ return;
+
Long keyLong = (Long)event.getKey();
byte[] valueBytes = (byte[])event.getValue();
@@ -385,6 +406,7 @@
Collection<Class<? extends IFloodlightService>> l =
new ArrayList<Class<? extends IFloodlightService>>();
l.add(IFloodlightProviderService.class);
+ l.add(IRestApiService.class);
return l;
}
@@ -397,6 +419,7 @@
public void init(FloodlightModuleContext context)
throws FloodlightModuleException {
floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
+ restApi = context.getServiceImpl(IRestApiService.class);
// Get the configuration file name and configure the Datagrid
Map<String, String> configMap = context.getConfigParams(this);
@@ -412,6 +435,8 @@
@Override
public void startUp(FloodlightModuleContext context) {
hazelcastInstance = Hazelcast.newHazelcastInstance(hazelcastConfig);
+
+ restApi.addRestletRoutable(new DatagridWebRoutable());
}
/**
diff --git a/src/main/java/net/onrc/onos/datagrid/web/DatagridWebRoutable.java b/src/main/java/net/onrc/onos/datagrid/web/DatagridWebRoutable.java
new file mode 100644
index 0000000..2c99ece
--- /dev/null
+++ b/src/main/java/net/onrc/onos/datagrid/web/DatagridWebRoutable.java
@@ -0,0 +1,30 @@
+package net.onrc.onos.datagrid.web;
+
+import net.floodlightcontroller.restserver.RestletRoutable;
+
+import org.restlet.Context;
+import org.restlet.Restlet;
+import org.restlet.routing.Router;
+
+/**
+ * REST API implementation for the Datagrid.
+ */
+public class DatagridWebRoutable implements RestletRoutable {
+ /**
+ * Create the Restlet router and bind to the proper resources.
+ */
+ @Override
+ public Restlet getRestlet(Context context) {
+ Router router = new Router(context);
+ router.attach("/get/map/{map-name}/json", GetMapResource.class);
+ return router;
+ }
+
+ /**
+ * Set the base path for the Topology
+ */
+ @Override
+ public String basePath() {
+ return "/wm/datagrid";
+ }
+}
diff --git a/src/main/java/net/onrc/onos/datagrid/web/GetMapResource.java b/src/main/java/net/onrc/onos/datagrid/web/GetMapResource.java
new file mode 100644
index 0000000..124ac28
--- /dev/null
+++ b/src/main/java/net/onrc/onos/datagrid/web/GetMapResource.java
@@ -0,0 +1,84 @@
+package net.onrc.onos.datagrid.web;
+
+import java.util.Collection;
+
+import net.onrc.onos.datagrid.IDatagridService;
+import net.onrc.onos.ofcontroller.topology.TopologyElement;
+import net.onrc.onos.ofcontroller.util.FlowEntry;
+import net.onrc.onos.ofcontroller.util.FlowPath;
+
+import org.restlet.resource.Get;
+import org.restlet.resource.ServerResource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Datagrid REST API implementation: Get the state of a map.
+ *
+ * Valid map names:
+ * - "all" : Get all maps
+ * - "flow" : Get the Flows
+ * - "flow-entry" : Get the Flow Entries
+ * - "topology" : Get the Topology
+ *
+ * GET /wm/datagrid/get/map/{map-name}/json
+ */
+public class GetMapResource extends ServerResource {
+ protected final static Logger log = LoggerFactory.getLogger(GetMapResource.class);
+
+ /**
+ * Implement the API.
+ *
+ * @return a string with the state of the map(s).
+ */
+ @Get("json")
+ public String retrieve() {
+ String result = "";
+
+ IDatagridService datagridService =
+ (IDatagridService)getContext().getAttributes().
+ get(IDatagridService.class.getCanonicalName());
+
+ if (datagridService == null) {
+ log.debug("ONOS Datagrid Service not found");
+ return result;
+ }
+
+ // Extract the arguments
+ String mapNameStr = (String)getRequestAttributes().get("map-name");
+
+ log.debug("Get Datagrid Map: " + mapNameStr);
+
+ //
+ // Get the Flows
+ //
+ if (mapNameStr.equals("flow") || mapNameStr.equals("all")) {
+ Collection<FlowPath> flowPaths = datagridService.getAllFlows();
+ result += "Flows:\n";
+ for (FlowPath flowPath : flowPaths) {
+ result += flowPath.toString() + "\n";
+ }
+ }
+
+ //
+ // Get the Flow Entries
+ //
+ if (mapNameStr.equals("flow-entry") || mapNameStr.equals("all")) {
+ Collection<FlowEntry> flowEntries = datagridService.getAllFlowEntries();
+ result += "Flow Entries:\n";
+ for (FlowEntry flowEntry : flowEntries) {
+ result += flowEntry.toString() + "\n";
+ }
+ }
+
+ if (mapNameStr.equals("topology") || mapNameStr.equals("all")) {
+ Collection<TopologyElement> topologyElements = datagridService.getAllTopologyElements();
+ result += "Topology:\n";
+ for (TopologyElement topologyElement : topologyElements) {
+ result += topologyElement.toString() + "\n";
+ }
+ }
+
+ return result;
+ }
+}
diff --git a/src/main/java/net/onrc/onos/graph/GraphDBConnection.java b/src/main/java/net/onrc/onos/graph/GraphDBConnection.java
index 232deed..bf30297 100644
--- a/src/main/java/net/onrc/onos/graph/GraphDBConnection.java
+++ b/src/main/java/net/onrc/onos/graph/GraphDBConnection.java
@@ -7,7 +7,6 @@
import com.thinkaurelius.titan.core.TitanFactory;
import com.thinkaurelius.titan.core.TitanGraph;
-import com.thinkaurelius.titan.diskstorage.StorageException;
import com.tinkerpop.blueprints.TransactionalGraph;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.util.wrappers.event.EventTransactionalGraph;
@@ -82,6 +81,9 @@
if (!s.contains("switch_state")) {
graph.createKeyIndex("switch_state", Vertex.class);
}
+ if (!s.contains("ipv4_address")) {
+ graph.createKeyIndex("ipv4_address", Vertex.class);
+ }
graph.commit();
eg = new EventTransactionalGraph<TitanGraph>(graph);
}
diff --git a/src/main/java/net/onrc/onos/graph/GraphDBOperation.java b/src/main/java/net/onrc/onos/graph/GraphDBOperation.java
index f1e9b46..bfd9046 100644
--- a/src/main/java/net/onrc/onos/graph/GraphDBOperation.java
+++ b/src/main/java/net/onrc/onos/graph/GraphDBOperation.java
@@ -1,11 +1,14 @@
package net.onrc.onos.graph;
import java.util.ArrayList;
+import java.util.Iterator;
import java.util.List;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IBaseObject;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IDeviceObject;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowEntry;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowPath;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IIpv4Address;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IPortObject;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.ISwitchObject;
import net.onrc.onos.ofcontroller.core.ISwitchStorage.SwitchState;
@@ -225,6 +228,49 @@
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
if (fg != null) fg.removeVertex(dev.asVertex());
}
+
+ public IIpv4Address newIpv4Address() {
+ return newVertex("ipv4Address", IIpv4Address.class);
+ }
+
+ private <T extends IBaseObject> T newVertex(String type, Class<T> vertexType) {
+ FramedGraph<TitanGraph> fg = conn.getFramedGraph();
+ T newVertex = fg.addVertex(null, vertexType);
+ if (newVertex != null) {
+ newVertex.setType(type);
+ }
+ return newVertex;
+ }
+
+ public IIpv4Address searchIpv4Address(int intIpv4Address) {
+ return searchForVertex("ipv4_address", intIpv4Address, IIpv4Address.class);
+ }
+
+ private <T> T searchForVertex(String propertyName, Object propertyValue, Class<T> vertexType) {
+ FramedGraph<TitanGraph> fg = conn.getFramedGraph();
+ if (fg != null) {
+ Iterator<T> it =
+ fg.getVertices(propertyName, propertyValue, vertexType).iterator();
+ if (it.hasNext()) {
+ return it.next();
+ }
+ }
+ return null;
+ }
+
+ public IIpv4Address ensureIpv4Address(int intIpv4Address) {
+ IIpv4Address ipv4Vertex = searchIpv4Address(intIpv4Address);
+ if (ipv4Vertex == null) {
+ ipv4Vertex = newIpv4Address();
+ ipv4Vertex.setIpv4Address(intIpv4Address);
+ }
+ return ipv4Vertex;
+ }
+
+ public void removeIpv4Address(IIpv4Address ipv4Address) {
+ FramedGraph<TitanGraph> fg = conn.getFramedGraph();
+ fg.removeVertex(ipv4Address.asVertex());
+ }
/**
* Create and return a flow path object.
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 d84d30d..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,13 +34,14 @@
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.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.topology.ITopologyNetService;
import net.onrc.onos.ofcontroller.topology.Topology;
import net.onrc.onos.ofcontroller.topology.TopologyManager;
@@ -77,7 +78,7 @@
public class BgpRoute implements IFloodlightModule, IBgpRouteService,
ITopologyListener, IArpRequester,
- IOFSwitchListener, ILayer3InfoService,
+ IOFSwitchListener, IConfigInfoService,
IProxyArpService {
private final static Logger log = LoggerFactory.getLogger(BgpRoute.class);
@@ -88,7 +89,7 @@
private ILinkDiscoveryService linkDiscoveryService;
private IRestApiService restApi;
- private ProxyArpManager proxyArp;
+ private BgpProxyArpManager proxyArp;
private IPatriciaTrie<RibEntry> ptree;
private IPatriciaTrie<Interface> interfacePtrie;
@@ -230,6 +231,7 @@
Collection<Class<? extends IFloodlightService>> l
= new ArrayList<Class<? extends IFloodlightService>>();
l.add(IBgpRouteService.class);
+ l.add(IConfigInfoService.class);
return l;
}
@@ -238,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;
}
@@ -269,7 +271,10 @@
//TODO We'll initialise this here for now, but it should really be done as
//part of the controller core
- proxyArp = new ProxyArpManager(floodlightProvider, topologyService, 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);
@@ -324,9 +329,9 @@
topologyService.addListener(this);
floodlightProvider.addOFSwitchListener(this);
- proxyArp.startUp(vlan);
+ proxyArp.startUp();
- floodlightProvider.addOFMessageListener(OFType.PACKET_IN, proxyArp);
+ //floodlightProvider.addOFMessageListener(OFType.PACKET_IN, proxyArp);
//Retrieve the RIB from BGPd during startup
retrieveRib();
@@ -1238,7 +1243,7 @@
}
/*
- * ILayer3InfoService methods
+ * IConfigInfoService methods
*/
@Override
@@ -1277,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/Configuration.java b/src/main/java/net/onrc/onos/ofcontroller/bgproute/Configuration.java
index 7fabc72..4c81d1b 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/bgproute/Configuration.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/bgproute/Configuration.java
@@ -47,7 +47,7 @@
public void setBgpdMacAddress(String strMacAddress) {
this.bgpdMacAddress = MACAddress.valueOf(strMacAddress);
}
-
+
public List<String> getSwitches() {
return Collections.unmodifiableList(switches);
}
@@ -65,7 +65,7 @@
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/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 483fbda..c8312d4 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/core/ILinkStorage.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/ILinkStorage.java
@@ -43,7 +43,17 @@
* 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);
+
+ /**
+ * 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 6f13080..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();
@@ -367,7 +396,7 @@
public String getState();
}
-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/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 63eaacb..6438ffd 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,30 +1,31 @@
package net.onrc.onos.ofcontroller.core.internal;
-import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
+
+import net.floodlightcontroller.devicemanager.IDevice;
+import net.floodlightcontroller.devicemanager.SwitchPort;
+import net.onrc.onos.graph.GraphDBOperation;
+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.thinkaurelius.titan.core.TitanException;
-import net.floodlightcontroller.devicemanager.IDevice;
-import net.floodlightcontroller.devicemanager.SwitchPort;
-import net.floodlightcontroller.packet.IPv4;
-import net.onrc.onos.graph.GraphDBOperation;
-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.internal.SwitchStorageImpl;
/**
* This is the class for storing the information of devices into CassandraDB
* @author Pankaj
*/
public class DeviceStorageImpl implements IDeviceStorage {
+ protected final static Logger log = LoggerFactory.getLogger(SwitchStorageImpl.class);
private GraphDBOperation ope;
- protected final static Logger log = LoggerFactory.getLogger(SwitchStorageImpl.class);
/***
* Initialize function. Before you use this class, please call this method
@@ -32,10 +33,10 @@
*/
@Override
public void init(String conf) {
- try{
+ try {
ope = new GraphDBOperation(conf);
- } catch(Exception e) {
- log.error(e.getMessage());
+ } catch (TitanException e) {
+ log.error("Couldn't open graph operation", e);
}
}
@@ -67,39 +68,32 @@
IDeviceObject obj = null;
try {
if ((obj = ope.searchDevice(device.getMACAddressString())) != null) {
- log.debug("Adding device {}: found existing device",device.getMACAddressString());
+ log.debug("Adding device {}: found existing device", device.getMACAddressString());
} else {
obj = ope.newDevice();
- log.debug("Adding device {}: creating new device",device.getMACAddressString());
+ log.debug("Adding device {}: creating new device", device.getMACAddressString());
}
- changeDeviceAttachments(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);
- }
- }
-
- if(multiIntString.toString() != null && !multiIntString.toString().isEmpty()){
- obj.setIPAddress(multiIntString + "]");
- }
-
- obj.setMACAddress(device.getMACAddressString());
- obj.setType("device");
- obj.setState("ACTIVE");
- ope.commit();
- log.debug("Adding device {}",device.getMACAddressString());
- } catch (Exception e) {
+ changeDeviceAttachments(device, obj);
+
+ changeDeviceIpv4Addresses(device, obj);
+ /*for (Integer intIpv4Address : device.getIPv4Addresses()) {
+ obj.addIpv4Address(ope.ensureIpv4Address(intIpv4Address));
+ }*/
+
+ 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(":addDevice mac:{} failed", device.getMACAddressString());
obj = null;
- }
- return obj;
+ }
+
+ return obj;
}
/***
@@ -121,11 +115,15 @@
IDeviceObject dev;
try {
if ((dev = ope.searchDevice(device.getMACAddressString())) != null) {
+ for (IIpv4Address ipv4AddressVertex : dev.getIpv4Addresses()) {
+ ope.removeIpv4Address(ipv4AddressVertex);
+ }
+
ope.removeDevice(dev);
ope.commit();
log.error("DeviceStorage:removeDevice mac:{} done", device.getMACAddressString());
}
- } catch (Exception e) {
+ } catch (TitanException e) {
ope.rollback();
log.error("DeviceStorage:removeDevice mac:{} failed", device.getMACAddressString());
}
@@ -147,23 +145,15 @@
* @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;
- }
- }
+ public IDeviceObject getDeviceByIP(int ipv4Address) {
+ try {
+ IIpv4Address ipv4AddressVertex = ope.searchIpv4Address(ipv4Address);
+ if (ipv4AddressVertex != null) {
+ return ipv4AddressVertex.getDevice();
}
return null;
}
- catch (Exception e)
- {
+ catch (TitanException e) {
log.error("DeviceStorage:getDeviceByIP:{} failed");
return null;
}
@@ -178,14 +168,14 @@
IDeviceObject obj = null;
try {
if ((obj = ope.searchDevice(device.getMACAddressString())) != null) {
- log.debug("Changing device ports {}: found existing device",device.getMACAddressString());
+ 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());
+ log.debug("failed to search device...now adding {}", device.getMACAddressString());
addDevice(device);
- }
- } catch (Exception e) {
+ }
+ } catch (TitanException e) {
ope.rollback();
log.error(":addDevice mac:{} failed", device.getMACAddressString());
}
@@ -199,33 +189,33 @@
public void changeDeviceAttachments(IDevice device, IDeviceObject obj) {
SwitchPort[] attachmentPoints = device.getAttachmentPoints();
List<IPortObject> attachedPorts = Lists.newArrayList(obj.getAttachedPorts());
-
- 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);
- }
-
- log.debug("port number is {}", port.getNumber().toString());
- log.debug("port desc is {}", port.getDesc());
- }
- }
-
- for (IPortObject port: attachedPorts) {
- log.debug("Detouching the device {}: detouching from port",device.getMACAddressString());
- port.removeDevice(obj);
- }
+
+ 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());
+
+ 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());
+ }
+ }
+
+ for (IPortObject port: attachedPorts) {
+ log.debug("Detaching the device {}: detaching from port", device.getMACAddressString());
+ port.removeDevice(obj);
+ }
}
/***
@@ -234,22 +224,12 @@
*/
@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) {
-
- 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 + "]");
- }
+ changeDeviceIpv4Addresses(device, obj);
ope.commit();
} else {
@@ -257,7 +237,23 @@
}
} catch (TitanException e) {
ope.rollback();
- log.error(":changeDeviceIPv4Address mac:{} failed due to exception {}", device.getMACAddressString(),e);
+ log.error(":changeDeviceIPv4Address mac:{} failed due to exception {}", device.getMACAddressString(), e);
+ }
+ }
+
+ private void changeDeviceIpv4Addresses(IDevice device, IDeviceObject deviceObject) {
+ for (int ipv4Address : device.getIPv4Addresses()) {
+ if (deviceObject.getIpv4Address(ipv4Address) == null) {
+ IIpv4Address dbIpv4Address = ope.ensureIpv4Address(ipv4Address);
+ deviceObject.addIpv4Address(dbIpv4Address);
+ }
+ }
+
+ List<Integer> deviceIpv4Addresses = Arrays.asList(device.getIPv4Addresses());
+ for (IIpv4Address dbIpv4Address : deviceObject.getIpv4Addresses()) {
+ if (!deviceIpv4Addresses.contains(dbIpv4Address.getIpv4Address())) {
+ 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 68e2c6f..09e87ca 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
@@ -306,6 +306,38 @@
}
/**
+ * 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>();
+
+ ISwitchObject srcSw = op.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(srcSw.getDPID()),
+ srcPort.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.
*/
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 ac61b51..c01a3cb 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
@@ -306,6 +306,7 @@
op.commit();
}
}
+ success = true;
} catch (Exception e) {
op.rollback();
e.printStackTrace();
@@ -342,6 +343,11 @@
}
}
+ // 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");
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..f3d0da5
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/core/module/OnosModuleLoader.java
@@ -0,0 +1,95 @@
+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.devicemanager.IDeviceService;
+import net.floodlightcontroller.restserver.IRestApiService;
+import net.floodlightcontroller.topology.ITopologyService;
+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 IDeviceService deviceService;
+ private IConfigInfoService config;
+ private IRestApiService restApi;
+ private IFlowService flowService;
+
+ 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(IDeviceService.class);
+ //dependencies.add(IConfigInfoService.class);
+ dependencies.add(IRestApiService.class);
+ dependencies.add(IFlowService.class);
+ return dependencies;
+ }
+
+ @Override
+ public void init(FloodlightModuleContext context)
+ throws FloodlightModuleException {
+ floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
+ topology = context.getServiceImpl(ITopologyService.class);
+ deviceService = context.getServiceImpl(IDeviceService.class);
+ restApi = context.getServiceImpl(IRestApiService.class);
+ flowService = context.getServiceImpl(IFlowService.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, deviceService, config, restApi);
+ forwarding.init(floodlightProvider, flowService);
+ }
+
+ @Override
+ public void startUp(FloodlightModuleContext context) {
+ arpManager.startUp();
+ forwarding.startUp();
+ }
+
+}
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 14cffd8..26292d9 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/floodlightlistener/NetworkGraphPublisher.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/floodlightlistener/NetworkGraphPublisher.java
@@ -3,6 +3,7 @@
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;
@@ -212,11 +213,29 @@
// TODO publish ADD_SWITCH event here
TopologyElement topologyElement =
new TopologyElement(sw.getId());
+ datagridService.notificationSendTopologyElementAdded(topologyElement);
+ // Add the ports
// TODO: Add only ports that are UP?
for (OFPhysicalPort port : sw.getPorts()) {
- topologyElement.addSwitchPort(port.getPortNumber());
+ TopologyElement topologyElementPort =
+ new TopologyElement(sw.getId(),
+ port.getPortNumber());
+ datagridService.notificationSendTopologyElementAdded(topologyElementPort);
}
- datagridService.notificationSendTopologyElementAdded(topologyElement);
+
+ // 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);
+ for (Link link : links) {
+ TopologyElement topologyElementLink =
+ new TopologyElement(link.getSrc(),
+ link.getSrcPort(),
+ link.getDst(),
+ link.getDstPort());
+ datagridService.notificationSendTopologyElementAdded(topologyElementLink);
+ }
}
}
}
@@ -273,6 +292,7 @@
@Override
public void deviceRemoved(IDevice device) {
// TODO Auto-generated method stub
+ devStore.removeDevice(device);
}
@Override
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowDatabaseOperation.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowDatabaseOperation.java
index d06c62c..926788f 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowDatabaseOperation.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowDatabaseOperation.java
@@ -326,6 +326,44 @@
}
/**
+ * 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.
diff --git a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowEventHandler.java b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowEventHandler.java
index 29deb94..cb1e678 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowEventHandler.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowEventHandler.java
@@ -7,12 +7,10 @@
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
-
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import net.onrc.onos.datagrid.IDatagridService;
-import net.onrc.onos.ofcontroller.topology.ShortestPath;
import net.onrc.onos.ofcontroller.topology.Topology;
import net.onrc.onos.ofcontroller.topology.TopologyElement;
import net.onrc.onos.ofcontroller.topology.TopologyManager;
@@ -33,7 +31,11 @@
import org.slf4j.LoggerFactory;
/**
- * Class for implementing the Path Computation and Path Maintenance.
+ * 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. */
@@ -72,6 +74,13 @@
}
/**
+ * Get the network topology.
+ *
+ * @return the network topology.
+ */
+ protected Topology getTopology() { return this.topology; }
+
+ /**
* Run the thread.
*/
@Override
@@ -105,7 +114,7 @@
flowEntryEvents.add(eventEntry);
}
- // Process the events (if any)
+ // Process the initial events (if any)
processEvents();
//
@@ -168,6 +177,9 @@
for (EventEntry<FlowPath> eventEntry : flowPathEvents) {
FlowPath flowPath = eventEntry.eventData();
+ log.debug("Flow Event: {} {}", eventEntry.eventType(),
+ flowPath.toString());
+
switch (eventEntry.eventType()) {
case ENTRY_ADD: {
//
@@ -224,7 +236,7 @@
flowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.FE_SWITCH_NOT_UPDATED);
}
- allFlowPaths.remove(existingFlowPath.flowId());
+ allFlowPaths.remove(existingFlowPath.flowId().value());
modifiedFlowPaths.add(existingFlowPath);
break;
@@ -238,12 +250,16 @@
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);
+ isTopologyModified |= topology.addTopologyElement(topologyElement);
break;
case ENTRY_REMOVE:
- isTopologyModified = topology.removeTopologyElement(topologyElement);
+ isTopologyModified |= topology.removeTopologyElement(topologyElement);
break;
}
}
@@ -386,6 +402,8 @@
// 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:
@@ -458,7 +476,7 @@
FlowEntry newFlowEntry =
newFlowEntriesMap.get(oldFlowEntry.dpid().value());
if (newFlowEntry == null) {
- // The old Flow Entry should be deleted
+ // 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);
@@ -486,7 +504,7 @@
if (oldFlowEntry != null) {
//
- // The old Flow Entry should be deleted
+ // The old Flow Entry should be deleted: path diverges
//
oldFlowEntry.setFlowEntryUserState(FlowEntryUserState.FE_USER_DELETE);
oldFlowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.FE_SWITCH_NOT_UPDATED);
@@ -541,8 +559,7 @@
// Note that the Flow Entries that will be deleted are added at
// the end.
//
- for (FlowEntry flowEntry : deletedFlowEntries)
- finalFlowEntries.add(flowEntry);
+ finalFlowEntries.addAll(deletedFlowEntries);
flowPath.dataPath().setFlowEntries(finalFlowEntries);
return hasChanged;
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 4465835..c22b916 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowManager.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowManager.java
@@ -551,6 +551,18 @@
}
/**
+ * 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(dbHandler, flowObj,
+ flowEntry);
+ }
+
+ /**
* Delete all previously added flows.
*
* @return true on success, otherwise false.
@@ -702,6 +714,15 @@
}
/**
+ * Get the network topology.
+ *
+ * @return the network topology.
+ */
+ public Topology getTopology() {
+ return flowEventHandler.getTopology();
+ }
+
+ /**
* Reconcile a flow.
*
* @param flowObj the flow that needs to be reconciliated.
@@ -840,7 +861,6 @@
* Flow Entries.
*/
public void pushModifiedFlowEntries(Collection<FlowPath> modifiedFlowPaths) {
-
// TODO: For now, the pushing of Flow Entries is disabled
if (true)
return;
@@ -848,57 +868,83 @@
Map<Long, IOFSwitch> mySwitches = floodlightProvider.getSwitches();
for (FlowPath flowPath : modifiedFlowPaths) {
+ //
+ // 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 = dbHandler.searchFlowPath(flowPath.flowId());
- if (flowObj == null) {
- String logMsg = "Cannot find Network MAP entry for Flow Path " +
- flowPath.flowId();
- log.error(logMsg);
- continue;
- }
+ boolean isFlowEntryDeleted = false;
for (FlowEntry flowEntry : flowPath.flowEntries()) {
+ log.debug("Updating Flow Entry: {}", flowEntry.toString());
+
if (flowEntry.flowEntrySwitchState() !=
FlowEntrySwitchState.FE_SWITCH_NOT_UPDATED) {
continue; // No need to update the entry
}
+ if (flowEntry.flowEntryUserState() ==
+ FlowEntryUserState.FE_USER_DELETE) {
+ isFlowEntryDeleted = true;
+ }
+ //
+ // Install the Flow Entries into my switches
+ //
IOFSwitch mySwitch = mySwitches.get(flowEntry.dpid().value());
- if (mySwitch == null)
- continue; // Ignore the entry: not my switch
+ if (mySwitch != null) {
+ //
+ // Assign the FlowEntry ID if needed
+ //
+ if (! flowEntry.isValidFlowEntryId()) {
+ long id = getNextFlowEntryId();
+ flowEntry.setFlowEntryId(new FlowEntryId(id));
+ }
- //
- // Assign the FlowEntry ID if needed
- //
- if (! flowEntry.isValidFlowEntryId()) {
- long id = getNextFlowEntryId();
- flowEntry.setFlowEntryId(new FlowEntryId(id));
+ //
+ // 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);
}
//
- // Install the Flow Entry into the switch
+ // TODO: For now Flow Entries are removed from the Datagrid
+ // and from the Network Map by all instances, even if this
+ // Flow Entry is not for our switches.
//
- 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;
- }
+ // 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.
+ //
//
- // NOTE: Here we assume that the switch has been successfully
- // updated.
- //
- flowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.FE_SWITCH_UPDATED);
- //
// 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:
@@ -909,15 +955,41 @@
//
// Write the Flow Entry to the Network Map
//
- try {
- if (addFlowEntry(flowObj, flowEntry) == null) {
- String logMsg = "Cannot write to Network MAP Flow Entry " +
- flowEntry.flowEntryId() +
- " from Flow Path " + flowPath.flowId() +
- " on switch " + flowEntry.dpid();
- log.error(logMsg);
+ if (mySwitch == null) {
+ if (flowEntry.flowEntryUserState() !=
+ FlowEntryUserState.FE_USER_DELETE) {
continue;
}
+ if (! flowEntry.isValidFlowEntryId())
+ continue;
+ }
+ if (flowObj == null) {
+ String logMsg = "Cannot find Network MAP entry for Flow Path " + flowPath.flowId();
+ continue;
+ }
+ try {
+ 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 " + flowPath.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 " + flowPath.flowId() +
+ " on switch " + flowEntry.dpid();
+ log.error(logMsg);
+ }
+ break;
+ }
} catch (Exception e) {
String logMsg = "Exception writing Flow Entry to Network MAP";
log.debug(logMsg);
@@ -925,6 +997,26 @@
continue;
}
}
+
+ //
+ // Remove Flow Entries that were deleted
+ //
+ // 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.
+ //
+ if (isFlowEntryDeleted) {
+ ArrayList<FlowEntry> newFlowEntries = new ArrayList<FlowEntry>();
+ for (FlowEntry flowEntry : flowPath.flowEntries()) {
+ if (flowEntry.flowEntryUserState() !=
+ FlowEntryUserState.FE_USER_DELETE) {
+ newFlowEntries.add(flowEntry);
+ }
+ }
+ flowPath.dataPath().setFlowEntries(newFlowEntries);
+ }
}
dbHandler.commit();
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 1f8cd5b..8d362d1 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;
@@ -112,4 +113,11 @@
* @return the added shortest-path flow on success, otherwise null.
*/
FlowPath addAndMaintainShortestPathFlow(FlowPath flowPath);
+
+ /**
+ * Get the network topology.
+ *
+ * @return the network topology.
+ */
+ Topology getTopology();
}
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..d6bac5c
--- /dev/null
+++ b/src/main/java/net/onrc/onos/ofcontroller/forwarding/Forwarding.java
@@ -0,0 +1,157 @@
+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.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.FlowManager;
+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.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 IDeviceStorage deviceStorage;
+ private TopologyManager topologyService;
+
+ public Forwarding() {
+
+ }
+
+ public void init(IFloodlightProviderService floodlightProvider,
+ IFlowService flowService) {
+ this.floodlightProvider = floodlightProvider;
+ this.flowService = flowService;
+
+ 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 don't want to handle broadcast traffic
+ if (eth.isBroadcast()) {
+ 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));
+ DataPath shortestPath =
+ topologyService.getDatabaseShortestPath(srcSwitchPort, dstSwitchPort);
+
+ if (shortestPath == null) {
+ log.debug("Shortest path not found between {} and {}",
+ srcSwitchPort, dstSwitchPort);
+ return;
+ }
+
+ MACAddress srcMacAddress = MACAddress.valueOf(eth.getSourceMACAddress());
+ MACAddress dstMacAddress = MACAddress.valueOf(eth.getDestinationMACAddress());
+
+ FlowId flowId = new FlowId(1L); //dummy flow ID
+ 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.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);
+ flowService.addFlow(flowPath, flowId);
+ //flowService.addAndMaintainShortestPathFlow(shortestPath.)
+ }
+
+}
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/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 0151212..a5dabc9 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,18 @@
import net.floodlightcontroller.core.IFloodlightProviderService;
import net.floodlightcontroller.core.IOFMessageListener;
import net.floodlightcontroller.core.IOFSwitch;
+import net.floodlightcontroller.devicemanager.IDeviceService;
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.ofcontroller.bgproute.Interface;
+import net.onrc.onos.ofcontroller.core.IDeviceStorage;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IDeviceObject;
+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;
@@ -39,6 +44,7 @@
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 {
private final static Logger log = LoggerFactory.getLogger(ProxyArpManager.class);
@@ -47,17 +53,20 @@
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 IDeviceService deviceService;
+ private IConfigInfoService configService;
+ private IRestApiService restApi;
+
+ private IDeviceStorage deviceStorage;
private short vlan;
private static final short NO_VLAN = 0;
- private final ArpCache arpCache;
+ private ArpCache arpCache;
- private final SetMultimap<InetAddress, ArpRequest> arpRequests;
+ private SetMultimap<InetAddress, ArpRequest> arpRequests;
private static class ArpRequest {
private final IArpRequester requester;
@@ -106,12 +115,21 @@
}
}
+ /*
public ProxyArpManager(IFloodlightProviderService floodlightProvider,
- ITopologyService topology, ILayer3InfoService layer3,
+ ITopologyService topology, IConfigInfoService configService,
IRestApiService restApi){
+
+ }
+ */
+
+ public void init(IFloodlightProviderService floodlightProvider,
+ ITopologyService topology, IDeviceService deviceService,
+ IConfigInfoService config, IRestApiService restApi){
this.floodlightProvider = floodlightProvider;
this.topology = topology;
- this.layer3 = layer3;
+ this.deviceService = deviceService;
+ this.configService = config;
this.restApi = restApi;
arpCache = new ArpCache();
@@ -120,11 +138,15 @@
HashMultimap.<InetAddress, ArpRequest>create());
}
- public void startUp(short vlan) {
- this.vlan = vlan;
+ 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() {
@@ -188,12 +210,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
@@ -218,10 +245,14 @@
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);
+ //handleArpReply(sw, pi, arp);
}
}
@@ -244,31 +275,56 @@
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){
+ //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));
+ //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
@@ -280,7 +336,7 @@
}
sendArpReply(arp, sw.getId(), pi.getInPort(), macAddress);
- }
+ }*/
}
private void handleArpReply(IOFSwitch sw, OFPacketIn pi, ARP arp){
@@ -345,7 +401,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) {
@@ -354,7 +410,7 @@
arpRequest.setSenderHardwareAddress(senderMacAddress);
byte[] senderIPAddress = zeroIpv4;
- Interface intf = layer3.getOutgoingInterface(ipAddress);
+ Interface intf = configService.getOutgoingInterface(ipAddress);
if (intf != null) {
senderIPAddress = intf.getIpAddress().getAddress();
}
@@ -383,8 +439,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());
}
@@ -409,11 +465,12 @@
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)
@@ -571,7 +628,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);
}
}
diff --git a/src/main/java/net/onrc/onos/ofcontroller/topology/ShortestPath.java b/src/main/java/net/onrc/onos/ofcontroller/topology/ShortestPath.java
index dabe916..f187c27 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/topology/ShortestPath.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/topology/ShortestPath.java
@@ -24,7 +24,8 @@
import com.tinkerpop.blueprints.Vertex;
/**
- * A class for implementing the Shortest Path in a topology.
+ * Class to calculate a shortest DataPath between 2 SwitchPorts
+ * based on hops in Network Topology.
*/
public class ShortestPath {
/**
diff --git a/src/main/java/net/onrc/onos/ofcontroller/topology/Topology.java b/src/main/java/net/onrc/onos/ofcontroller/topology/Topology.java
index 612b72a..7d7d739 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/topology/Topology.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/topology/Topology.java
@@ -1,7 +1,9 @@
package net.onrc.onos.ofcontroller.topology;
-import java.util.HashMap;
+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;
@@ -44,9 +46,14 @@
};
public long nodeId; // The node ID
- public HashMap<Integer, Link> links; // The links from this node
- private HashMap<Integer, Link> reverseLinksMap; // The links to this node
- private HashMap<Integer, Integer> portsMap; // The ports for this node
+ 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.
@@ -55,9 +62,9 @@
*/
public Node(long nodeId) {
this.nodeId = nodeId;
- links = new HashMap<Integer, Link>();
- reverseLinksMap = new HashMap<Integer, Link>();
- portsMap = new HashMap<Integer, Integer>();
+ links = new TreeMap<Integer, Link>();
+ reverseLinksMap = new TreeMap<Integer, Link>();
+ portsMap = new TreeMap<Integer, Integer>();
}
/**
@@ -78,7 +85,7 @@
* @return the port if found, otherwise null.
*/
public Integer getPort(int portId) {
- return portsMap.get(nodeId);
+ return portsMap.get(portId);
}
/**
@@ -120,7 +127,7 @@
portsMap.remove(portId);
}
-
+
/**
* Get a link on a port to a neighbor.
*
@@ -186,7 +193,7 @@
* Default constructor.
*/
public Topology() {
- nodesMap = new HashMap<Long, Node>();
+ nodesMap = new TreeMap<Long, Node>();
}
/**
@@ -206,14 +213,6 @@
node = addNode(topologyElement.getSwitch());
isModified = true;
}
- // Add the ports for the switch
- for (Integer portId : topologyElement.getSwitchPorts().values()) {
- Integer port = node.getPort(portId);
- if (port == null) {
- node.addPort(portId);
- isModified = true;
- }
- }
break;
}
case ELEMENT_PORT: {
@@ -353,7 +352,20 @@
// Remove all ports one-by-one. This operation will also remove the
// incoming links originating from the neighbors.
//
- for (Integer portId : node.ports().keySet())
+ // 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);
diff --git a/src/main/java/net/onrc/onos/ofcontroller/topology/TopologyElement.java b/src/main/java/net/onrc/onos/ofcontroller/topology/TopologyElement.java
index fe84654..b01c7d3 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/topology/TopologyElement.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/topology/TopologyElement.java
@@ -24,9 +24,6 @@
private long toSwitchDpid = 0; // The Neighbor Switch DPID
private int toSwitchPort = 0; // The Neighbor Switch Port
- // All (known) ports for a Switch
- private Map<Integer, Integer> switchPorts = new TreeMap<Integer, Integer>();
-
/**
* Default constructor.
*/
@@ -95,28 +92,6 @@
}
/**
- * Get the Switch Ports.
- *
- * NOTE: Applies for Type.ELEMENT_SWITCH
- *
- * @return the collection of Switch Ports.
- */
- public Map<Integer, Integer> getSwitchPorts() {
- return switchPorts;
- }
-
- /**
- * Add a Switch Port.
- *
- * NOTE: Applies for Type.ELEMENT_SWITCH
- *
- * @param switchPort the Switch Port to add.
- */
- public void addSwitchPort(int switchPort) {
- switchPorts.put(switchPort, switchPort);
- }
-
- /**
* Get the Switch Port.
*
* NOTE: Applies for Type.ELEMENT_PORT
@@ -195,4 +170,15 @@
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
index ffe806a..c0e04f2 100644
--- a/src/main/java/net/onrc/onos/ofcontroller/topology/TopologyManager.java
+++ b/src/main/java/net/onrc/onos/ofcontroller/topology/TopologyManager.java
@@ -24,7 +24,10 @@
import org.slf4j.LoggerFactory;
/**
- * A class for implementing Topology Network Service.
+ * A class for obtaining Topology Snapshot
+ * and PathComputation.
+ *
+ * TODO: PathComputation part should be refactored out to separate class.
*/
public class TopologyManager implements IFloodlightModule,
ITopologyNetService {
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 b340996..0d33b27 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,5 +1,6 @@
package net.onrc.onos.ofcontroller.topology.web;
+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;
@@ -18,11 +19,22 @@
@Get("json")
public DataPath retrieve() {
- ITopologyNetService topologyNetService = new TopologyManager("");
+ // 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");
+ return null;
+ }
String srcDpidStr = (String) getRequestAttributes().get("src-dpid");
String srcPortStr = (String) getRequestAttributes().get("src-port");
@@ -37,7 +49,8 @@
Port dstPort = new Port(Short.parseShort(dstPortStr));
DataPath result =
- topologyNetService.getDatabaseShortestPath(
+ topologyNetService.getTopologyShortestPath(
+ flowService.getTopology(),
new SwitchPort(srcDpid, srcPort),
new SwitchPort(dstDpid, dstPort));
if (result != null) {
diff --git a/src/main/resources/META-INF/services/net.floodlightcontroller.core.module.IFloodlightModule b/src/main/resources/META-INF/services/net.floodlightcontroller.core.module.IFloodlightModule
index 99ded31..7c4bc1a 100644
--- a/src/main/resources/META-INF/services/net.floodlightcontroller.core.module.IFloodlightModule
+++ b/src/main/resources/META-INF/services/net.floodlightcontroller.core.module.IFloodlightModule
@@ -24,3 +24,4 @@
net.onrc.onos.ofcontroller.bgproute.BgpRoute
net.onrc.onos.registry.controller.ZookeeperRegistry
net.onrc.onos.registry.controller.StandaloneRegistry
+net.onrc.onos.ofcontroller.core.module.OnosModuleLoader
\ No newline at end of file
diff --git a/src/test/java/net/onrc/onos/graph/GraphDBConnectionTest.java b/src/test/java/net/onrc/onos/graph/GraphDBConnectionTest.java
index 397ed88..b50f889 100644
--- a/src/test/java/net/onrc/onos/graph/GraphDBConnectionTest.java
+++ b/src/test/java/net/onrc/onos/graph/GraphDBConnectionTest.java
@@ -87,6 +87,7 @@
graph.createKeyIndex("flow_id", Vertex.class);
graph.createKeyIndex("flow_entry_id", Vertex.class);
graph.createKeyIndex("switch_state", Vertex.class);
+ graph.createKeyIndex("ipv4_address", Vertex.class);
graph.commit();
expectNew(EventTransactionalGraph.class, graph).andReturn(eg);
}
diff --git a/src/test/java/net/onrc/onos/graph/GraphDBOperationTest.java b/src/test/java/net/onrc/onos/graph/GraphDBOperationTest.java
index e99ca81..b40d2af 100644
--- a/src/test/java/net/onrc/onos/graph/GraphDBOperationTest.java
+++ b/src/test/java/net/onrc/onos/graph/GraphDBOperationTest.java
@@ -3,16 +3,19 @@
*/
package net.onrc.onos.graph;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertArrayEquals;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
import junit.framework.TestCase;
-
-import net.onrc.onos.graph.GraphDBOperation;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IDeviceObject;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowEntry;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowPath;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IIpv4Address;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IPortObject;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.ISwitchObject;
import net.onrc.onos.ofcontroller.core.ISwitchStorage.SwitchState;
@@ -25,12 +28,14 @@
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
+import com.google.common.net.InetAddresses;
import com.thinkaurelius.titan.core.TitanFactory;
import com.thinkaurelius.titan.core.TitanGraph;
import com.tinkerpop.blueprints.Vertex;
@@ -334,14 +339,14 @@
IDeviceObject device = op.newDevice();
device.setMACAddress("11:22:33:44:55:66");
- device.setIPAddress("192.168.1.1");
+ //device.setIPAddress("192.168.1.1");
op.commit();
Iterator<Vertex> vertices = testdb.getVertices("type", "device").iterator();
assertTrue(vertices.hasNext());
Vertex v = vertices.next();
assertEquals("11:22:33:44:55:66", v.getProperty("dl_addr").toString());
- assertEquals("192.168.1.1", v.getProperty("nw_addr").toString());
+ //assertEquals("192.168.1.1", v.getProperty("nw_addr").toString());
}
/**
@@ -395,6 +400,53 @@
op.commit();
assertNull(op.searchDevice("11:22:33:44:55:66"));
}
+
+ /**
+ * Test method for {@link net.onrc.onos.graph.GraphDBOperation#newIpv4Address(net.onrc.onos.graph.GraphDBConnection, net.floodlightcontroller.core.INetMapTopologyObjects.IIpv4Address)}.
+ */
+ @Test
+ public final void testNewIpv4Address() {
+ int intIpv4Address = InetAddresses.coerceToInteger(InetAddresses.forString("192.168.10.1"));
+
+ assertFalse(testdb.getVertices("type", "ipv4Address").iterator().hasNext());
+
+ IIpv4Address ipv4Address = op.newIpv4Address();
+ ipv4Address.setIpv4Address(intIpv4Address);
+ //device.setIPAddress("192.168.1.1");
+ op.commit();
+
+ Iterator<Vertex> vertices = testdb.getVertices("type", "ipv4Address").iterator();
+ assertTrue(vertices.hasNext());
+ Vertex v = vertices.next();
+ assertEquals(intIpv4Address, ((Integer) v.getProperty("ipv4_address")).intValue());
+ }
+
+ /**
+ * Test method for {@link net.onrc.onos.graph.GraphDBOperation#searchIpv4Address(net.onrc.onos.graph.GraphDBConnection, net.floodlightcontroller.core.INetMapTopologyObjects.IIpv4Address)}.
+ */
+ @Test
+ public final void testSearchIpv4Address() {
+ int addr1 = InetAddresses.coerceToInteger(InetAddresses.forString("192.168.20.1"));
+ int addr2 = InetAddresses.coerceToInteger(InetAddresses.forString("59.203.2.15"));
+
+ assertNull(op.searchIpv4Address(addr1));
+ assertNull(op.searchIpv4Address(addr2));
+
+ op.newIpv4Address().setIpv4Address(addr1);
+ op.commit();
+
+ IIpv4Address ipv4Address = op.searchIpv4Address(addr1);
+ assertNotNull(ipv4Address);
+ assertEquals(addr1, ipv4Address.getIpv4Address());
+
+ assertNull(op.searchIpv4Address(addr2));
+ }
+
+ @Ignore
+ @Test
+ public final void testEnsureIpv4Address() {
+ // TODO not yet implemented
+ }
/**
* Test method for {@link net.onrc.onos.graph.GraphDBOperation#newFlowPath(net.onrc.onos.graph.GraphDBConnection)}.
diff --git a/src/test/java/net/onrc/onos/ofcontroller/core/INetMapTopologyObjectsIDeviceObjectTest.java b/src/test/java/net/onrc/onos/ofcontroller/core/INetMapTopologyObjectsIDeviceObjectTest.java
index 880335b..7bd75d2 100644
--- a/src/test/java/net/onrc/onos/ofcontroller/core/INetMapTopologyObjectsIDeviceObjectTest.java
+++ b/src/test/java/net/onrc/onos/ofcontroller/core/INetMapTopologyObjectsIDeviceObjectTest.java
@@ -1,16 +1,19 @@
package net.onrc.onos.ofcontroller.core;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import net.onrc.onos.graph.GraphDBConnection;
import net.onrc.onos.graph.GraphDBOperation;
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 net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.ISwitchObject;
import net.onrc.onos.ofcontroller.core.internal.SwitchStorageImpl;
import net.onrc.onos.ofcontroller.core.internal.TestDatabaseManager;
+
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
@@ -18,9 +21,10 @@
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.slf4j.LoggerFactory;
import org.powermock.modules.junit4.PowerMockRunner;
+import org.slf4j.LoggerFactory;
+import com.google.common.net.InetAddresses;
import com.thinkaurelius.titan.core.TitanFactory;
import com.thinkaurelius.titan.core.TitanGraph;
@@ -89,10 +93,12 @@
*/
@Test
public void testSetGetIPAddress() {
- String ipaddr = "192.168.0.1";
+ int ipaddr = InetAddresses.coerceToInteger(InetAddresses.forString("192.168.0.1"));
IDeviceObject devObj = ope.newDevice();
- devObj.setIPAddress(ipaddr);
- assertEquals(devObj.getIPAddress(), ipaddr);
+ IIpv4Address ipv4Address = ope.newIpv4Address();
+ ipv4Address.setIpv4Address(ipaddr);
+ devObj.addIpv4Address(ipv4Address);
+ assertEquals(devObj.getIpv4Address(ipaddr), ipv4Address);
}
/**
diff --git a/src/test/java/net/onrc/onos/ofcontroller/core/internal/LinkStorageImplTest.java b/src/test/java/net/onrc/onos/ofcontroller/core/internal/LinkStorageImplTest.java
index abb8809..4aea22a 100644
--- a/src/test/java/net/onrc/onos/ofcontroller/core/internal/LinkStorageImplTest.java
+++ b/src/test/java/net/onrc/onos/ofcontroller/core/internal/LinkStorageImplTest.java
@@ -256,6 +256,21 @@
Link linkToVerifyNot = createFeasibleLink();
assertFalse(links.contains(linkToVerifyNot));
}
+
+ /**
+ * Test if {@link LinkStorageImpl#getReverseLinks(String)} can correctly return Links connected to specific MAC address.
+ */
+ @Test
+ public void testGetReverseLinks_ByString() {
+ Link linkToVeryfy = createExistingLink();
+ String dpid = HexString.toHexString(linkToVeryfy.getDst());
+
+ List<Link> links = linkStorage.getReverseLinks(dpid);
+ assertTrue(links.contains(linkToVeryfy));
+
+ Link linkToVerifyNot = createFeasibleLink();
+ assertFalse(links.contains(linkToVerifyNot));
+ }
/**
* Test if {@link LinkStorageImpl#deleteLink(Link)} can correctly delete a Link.
@@ -447,6 +462,35 @@
}
/**
+ * Class defines a function called back when {@link IPortObject#getReverseLinkedPorts()} is called.
+ * @author Naoki Shiota
+ *
+ */
+ private class GetReverseLinkedPortsCallback implements IAnswer< Iterable<IPortObject> > {
+ private long dpid;
+ private short port;
+
+ public GetReverseLinkedPortsCallback(long dpid, short port) {
+ this.dpid = dpid;
+ this.port = port;
+ }
+
+ @Override
+ public Iterable<IPortObject> answer() throws Throwable {
+ List<IPortObject> ports = new ArrayList<IPortObject>();
+
+ for(Link lk : links) {
+ if(lk.getDst() == dpid && lk.getDstPort() == port) {
+ ports.add(createMockPort(lk.getSrc(), lk.getSrcPort()));
+ }
+ }
+
+ return ports;
+ }
+
+ }
+
+ /**
* Class defines a function called back when {@link LinkStorageImplTest} is called.
* @author Naoki Shiota
*
@@ -567,6 +611,9 @@
// Mock getLinkPorts() method
EasyMock.expect(mockPort.getLinkedPorts()).andAnswer(new GetLinkedPortsCallback(dpid, number)).anyTimes();
+
+ // Mock getReverseLinkPorts() method
+ EasyMock.expect(mockPort.getReverseLinkedPorts()).andAnswer(new GetReverseLinkedPortsCallback(dpid, number)).anyTimes();
// Mock getSwitch() method
EasyMock.expect(mockPort.getSwitch()).andAnswer(new GetSwitchCallback(dpid)).anyTimes();
diff --git a/src/test/java/net/onrc/onos/ofcontroller/core/internal/SwitchStorageImplTestBB.java b/src/test/java/net/onrc/onos/ofcontroller/core/internal/SwitchStorageImplTestBB.java
index 585a8fd..7edc1c5 100644
--- a/src/test/java/net/onrc/onos/ofcontroller/core/internal/SwitchStorageImplTestBB.java
+++ b/src/test/java/net/onrc/onos/ofcontroller/core/internal/SwitchStorageImplTestBB.java
@@ -1,20 +1,21 @@
package net.onrc.onos.ofcontroller.core.internal;
-import static org.junit.Assert.*;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import net.floodlightcontroller.core.internal.TestDatabaseManager;
import net.onrc.onos.graph.GraphDBConnection;
import net.onrc.onos.graph.GraphDBOperation;
-import net.onrc.onos.ofcontroller.core.ISwitchStorage;
-import net.onrc.onos.ofcontroller.core.ISwitchStorage.SwitchState;
-import net.onrc.onos.ofcontroller.core.internal.SwitchStorageImpl;
import net.onrc.onos.ofcontroller.core.INetMapStorage;
import net.onrc.onos.ofcontroller.core.INetMapStorage.DM_OPERATION;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IPortObject;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.ISwitchObject;
+import net.onrc.onos.ofcontroller.core.ISwitchStorage;
+import net.onrc.onos.ofcontroller.core.ISwitchStorage.SwitchState;
+
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openflow.protocol.OFPhysicalPort;
@@ -27,6 +28,19 @@
import com.thinkaurelius.titan.core.TitanFactory;
import com.thinkaurelius.titan.core.TitanGraph;
+/*
+ * Jono, 11/4/2013
+ * These tests are being ignored because they don't work because they
+ * rely on test functionality that was written ages ago and hasn't been
+ * updated as the database schema has evolved.
+ * These tests work by getting an in-memory Titan database and testing
+ * the SwitchStorageImpl on top of that. In this regard they're not really
+ * unit tests as they test the entire DB stack (i.e. GraphDBOperation and
+ * GraphDBConnection), not just SwitchStorageImpl.
+ * I've left them here as we may wish to resurrect this kind of
+ * integration testing of the DB layers in the future.
+ */
+@Ignore
//Add Powermock preparation
@RunWith(PowerMockRunner.class)
@PrepareForTest({TitanFactory.class, GraphDBConnection.class, GraphDBOperation.class, SwitchStorageImpl.class})
diff --git a/src/test/java/net/onrc/onos/ofcontroller/core/internal/TestableGraphDBOperation.java b/src/test/java/net/onrc/onos/ofcontroller/core/internal/TestableGraphDBOperation.java
index dfe6ccf..d7724ae 100644
--- a/src/test/java/net/onrc/onos/ofcontroller/core/internal/TestableGraphDBOperation.java
+++ b/src/test/java/net/onrc/onos/ofcontroller/core/internal/TestableGraphDBOperation.java
@@ -19,6 +19,7 @@
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IDeviceObject;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowEntry;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowPath;
+import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IIpv4Address;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IPortObject;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.ISwitchObject;
import net.onrc.onos.ofcontroller.util.FlowEntryId;
@@ -162,6 +163,7 @@
private ISwitchObject sw;
private List<IPortObject> linkedPorts;
+ private List<IPortObject> reverseLinkedPorts;
private List<IDeviceObject> devices;
private List<IFlowEntry> inflows,outflows;
@@ -179,6 +181,7 @@
type = "port";
linkedPorts = new ArrayList<IPortObject>();
+ reverseLinkedPorts = new ArrayList<IPortObject>();
linkedPortsToAdd = new ArrayList<IPortObject>();
linkedPortsToRemove = new ArrayList<IPortObject>();
devices = new ArrayList<IDeviceObject>();
@@ -289,6 +292,9 @@
public Iterable<IPortObject> getLinkedPorts() { return linkedPorts; }
@Override
+ public Iterable<IPortObject> getReverseLinkedPorts() { return reverseLinkedPorts; }
+
+ @Override
public void removeLink(IPortObject dest_port) { linkedPortsToRemove.add(dest_port); }
@Override
@@ -311,6 +317,14 @@
}
}
+ /*
+ * Note by Jono, 11/4/2013
+ * I changed the interface of IDeviceObject but I didn't spend the
+ * time to update this class, because I can't see where this is used.
+ * I think this whole file is a candidate for deletion if it is not
+ * used anywhere - the graphDB objects are tested elsewhere by the
+ * tests in net.onrc.onos.ofcontroller.core.*
+ */
public static class TestDeviceObject implements IDeviceObject {
private String state,type,mac,ipaddr;
private List<IPortObject> ports;
@@ -393,11 +407,11 @@
@Override
public void setMACAddress(String macaddr) { macToUpdate = macaddr; }
- @Override
- public String getIPAddress() { return ipaddr; }
+ //@Override
+ //public String getIPAddress() { return ipaddr; }
- @Override
- public void setIPAddress(String ipaddr) { ipaddrToUpdate = ipaddr; }
+ //@Override
+ //public void setIPAddress(String ipaddr) { ipaddrToUpdate = ipaddr; }
@Override
public Iterable<IPortObject> getAttachedPorts() {
@@ -411,6 +425,30 @@
@Override
public Iterable<ISwitchObject> getSwitch() { return switches; }
+
+ @Override
+ public Iterable<IIpv4Address> getIpv4Addresses() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IIpv4Address getIpv4Address(int ipv4Address) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public void addIpv4Address(IIpv4Address ipv4Address) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void removeIpv4Address(IIpv4Address ipv4Address) {
+ // TODO Auto-generated method stub
+
+ }
}
public static class TestFlowPath implements IFlowPath {
diff --git a/src/test/java/net/onrc/onos/ofcontroller/devicemanager/internal/DeviceStorageImplTest.java b/src/test/java/net/onrc/onos/ofcontroller/devicemanager/internal/DeviceStorageImplTest.java
index 89d4b92..b81370a 100644
--- a/src/test/java/net/onrc/onos/ofcontroller/devicemanager/internal/DeviceStorageImplTest.java
+++ b/src/test/java/net/onrc/onos/ofcontroller/devicemanager/internal/DeviceStorageImplTest.java
@@ -6,21 +6,21 @@
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
import net.floodlightcontroller.devicemanager.IDevice;
import net.floodlightcontroller.devicemanager.SwitchPort;
-import net.floodlightcontroller.packet.IPv4;
import net.onrc.onos.graph.GraphDBConnection;
import net.onrc.onos.graph.GraphDBOperation;
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 net.onrc.onos.ofcontroller.core.internal.DeviceStorageImpl;
import net.onrc.onos.ofcontroller.core.internal.SwitchStorageImpl;
-import net.floodlightcontroller.devicemanager.internal.Device;
+
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
@@ -33,12 +33,14 @@
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
+import com.google.common.net.InetAddresses;
import com.thinkaurelius.titan.core.TitanFactory;
//Add Powermock preparation
@RunWith(PowerMockRunner.class)
@PrepareForTest({TitanFactory.class, GraphDBConnection.class, GraphDBOperation.class, DeviceStorageImpl.class})
-public class DeviceStorageImplTest{ //extends FloodlightTestCase{
+public class DeviceStorageImplTest{
protected final static Logger log = LoggerFactory.getLogger(SwitchStorageImpl.class);
@@ -61,288 +63,187 @@
//PowerMock.mockStatic(GraphDBOperation.class);
mockOpe = PowerMock.createMock(GraphDBOperation.class);
PowerMock.expectNew(GraphDBOperation.class, new Class<?>[]{String.class}, conf).andReturn(mockOpe);
- mockOpe.close();
+ //mockOpe.close();
PowerMock.replay(GraphDBOperation.class);
// Replace the conf to dummy conf
// String conf = "/tmp/cassandra.titan";
-
+ deviceImpl.init(conf);
}
@After
public void tearDown() throws Exception {
- deviceImpl.close();
- deviceImpl = null;
-
verify(mockOpe);
}
- private String makeIPStringFromArray(Integer[] ipaddresses){
- String multiIntString = "";
- for(Integer intValue : ipaddresses)
- {
- if (multiIntString == null || multiIntString.isEmpty()){
- multiIntString = "[" + IPv4.fromIPv4Address(intValue);
- }
- else{
- multiIntString += "," + IPv4.fromIPv4Address(intValue);
- }
- }
- return multiIntString + "]";
+ private IPortObject getMockPort(long dpid, short port) {
+ IPortObject mockPortObject = createMock(IPortObject.class);
+ expect(mockPortObject.getNumber()).andReturn(port).anyTimes();
+ expect(mockPortObject.getDesc()).andReturn("test port").anyTimes();
+ return mockPortObject;
}
-
+ private IDevice getMockDevice(String strMacAddress, long attachmentDpid,
+ short attachmentPort, int ipv4Address) {
+ IDevice mockIDevice = createMock(IDevice.class);
+
+
+ long longMacAddress = HexString.toLong(strMacAddress);
+
+ SwitchPort[] attachmentSwitchPorts = {new SwitchPort(attachmentDpid, attachmentPort)};
+
+ expect(mockIDevice.getMACAddress()).andReturn(longMacAddress).anyTimes();
+ expect(mockIDevice.getMACAddressString()).andReturn(strMacAddress).anyTimes();
+ expect(mockIDevice.getAttachmentPoints()).andReturn(attachmentSwitchPorts).anyTimes();
+ expect(mockIDevice.getIPv4Addresses()).andReturn(new Integer[] {ipv4Address}).anyTimes();
+
+ replay(mockIDevice);
+
+ return mockIDevice;
+ }
+
/**
- * Desc:
+ * Description:
* Test method for addDevice method.
- * Codition:
- * N/A
+ * Condition:
+ * The device does not already exist in the database
* Expect:
* Get proper IDeviceObject
*/
- //@Ignore
@Test
public void testAddNewDevice() {
- try
- {
- //Make mockDevice
- IDevice mockDev = createMock(Device.class);
- // Mac addr for test device.
- String macAddr = "99:99:99:99:99:99";
- // IP addr for test device
- String ip = "192.168.100.1";
- Integer[] ipaddrs = {IPv4.toIPv4Address(ip)};
- // Mac addr for attached switch
- String switchMacAddr = "00:00:00:00:00:00:0a:01";
- long switchMacAddrL = HexString.toLong(switchMacAddr);
- // Port number for attached switch
- short portNum = 2;
- SwitchPort sp1 = new SwitchPort(switchMacAddrL, portNum);
- SwitchPort[] sps = {sp1};
+ String strMacAddress = "99:99:99:99:99:99";
+ long attachmentDpid = HexString.toLong("00:00:00:00:00:00:0a:01");
+ short attachmentPort = 2;
+ int intIpv4Address = InetAddresses.coerceToInteger(InetAddresses.forString("192.168.100.1"));
- expect(mockDev.getMACAddressString()).andReturn(macAddr).anyTimes();
- expect(mockDev.getIPv4Addresses()).andReturn(ipaddrs).anyTimes();
- expect(mockDev.getAttachmentPoints()).andReturn(sps).anyTimes();
- replay(mockDev);
-
- //Mock IPortObject 1 with dpid "00:00:00:00:00:00:0a:01" and port "1"
- IPortObject mockIPort = createMock(IPortObject.class);
- mockIPort.setNumber(portNum);
- mockIPort.setType("port");
- String iPortDesc = "port 1 at SEA Switch";
- expect(mockIPort.getNumber()).andReturn(portNum).anyTimes();
- expect(mockIPort.getDesc()).andReturn(iPortDesc).anyTimes();
- replay(mockIPort);
-
- //Make Iterator for mockIport
- List<IPortObject> portList = new ArrayList<IPortObject>();
- portList.add(mockIPort);
-
- //Expectation for mockIDeviceObject
- IDeviceObject mockIDev = createMock(IDeviceObject.class);
- expect(mockIDev.getAttachedPorts()).andReturn(portList);
- mockIDev.setIPAddress(makeIPStringFromArray(ipaddrs));
- mockIDev.setMACAddress(macAddr);
- mockIDev.setType("device");
- mockIDev.setState("ACTIVE");
- replay(mockIDev);
-
- //Expectation for mockOpe
- expect(mockOpe.searchDevice(macAddr)).andReturn(null);
- expect(mockOpe.newDevice()).andReturn(mockIDev);
- expect(mockOpe.searchPort(switchMacAddr, portNum)).andReturn(mockIPort);
- mockOpe.commit();
- replay(mockOpe);
-
- deviceImpl.init(conf);
-
- //Add the device
- IDeviceObject obj = deviceImpl.addDevice(mockDev);
- assertNotNull(obj);
-
- verify(mockIDev);
-
- } catch(Exception e) {
- fail(e.getMessage());
- }
+ IDevice device = getMockDevice(strMacAddress, attachmentDpid, attachmentPort, intIpv4Address);
+
+ IDeviceObject mockDeviceObject = createMock(IDeviceObject.class);
+ IPortObject mockPortObject = getMockPort(attachmentDpid, attachmentPort);
+ IIpv4Address mockIpv4Address = createMock(IIpv4Address.class);
+
+ expect(mockOpe.searchDevice(strMacAddress)).andReturn(null);
+ expect(mockOpe.newDevice()).andReturn(mockDeviceObject);
+ expect(mockDeviceObject.getAttachedPorts()).andReturn(Collections.<IPortObject>emptyList());
+ expect(mockOpe.searchPort(HexString.toHexString(attachmentDpid), attachmentPort)).andReturn(mockPortObject);
+ mockPortObject.setDevice(mockDeviceObject);
+ expect(mockDeviceObject.getIpv4Address(intIpv4Address)).andReturn(null);
+ expect(mockOpe.ensureIpv4Address(intIpv4Address)).andReturn(mockIpv4Address);
+ mockDeviceObject.addIpv4Address(mockIpv4Address);
+ expect(mockDeviceObject.getIpv4Addresses()).andReturn(Collections.singleton(mockIpv4Address));
+ expect(mockIpv4Address.getIpv4Address()).andReturn(intIpv4Address);
+
+ mockDeviceObject.setMACAddress(strMacAddress);
+ mockDeviceObject.setType("device");
+ mockDeviceObject.setState("ACTIVE");
+ mockOpe.commit();
+
+ replay(mockDeviceObject);
+ replay(mockPortObject);
+ replay(mockIpv4Address);
+ replay(mockOpe);
+
+ IDeviceObject addedObject = deviceImpl.addDevice(device);
+ assertNotNull(addedObject);
+
+ verify(mockDeviceObject);
}
/**
- * Desc:
+ * Description:
* Test method for addDevice method.
* Condition:
- * Already added device is existed.
+ * The device already exists in the database.
* Expect:
* Get proper IDeviceObject still.
* Check the IDeviceObject properties set expectedly.
*/
- //@Ignore
@Test
- public void testAddDeviceExisting() {
- try
- {
- IDevice mockDev = createMock(Device.class);
- String macAddr = "99:99:99:99:99:99";
- String ip = "192.168.100.1";
- Integer[] ipaddrs = {IPv4.toIPv4Address(ip)};
- String switchMacAddr = "00:00:00:00:00:00:0a:01";
- long switchMacAddrL = HexString.toLong(switchMacAddr);
- short portNum = 2;
- SwitchPort sp1 = new SwitchPort(switchMacAddrL, portNum);
- SwitchPort[] sps = {sp1};
+ public void testAddExistingDevice() {
+ String strMacAddress = "99:99:99:99:99:99";
+ long attachmentDpid = HexString.toLong("00:00:00:00:00:00:0a:01");
+ short attachmentPort = 2;
+ int intIpv4Address = InetAddresses.coerceToInteger(InetAddresses.forString("192.168.100.1"));
- expect(mockDev.getMACAddressString()).andReturn(macAddr).anyTimes();
- expect(mockDev.getIPv4Addresses()).andReturn(ipaddrs).times(2);
- expect(mockDev.getAttachmentPoints()).andReturn(sps).times(2);
- replay(mockDev);
-
- //Mock IPortObject 1 with dpid "00:00:00:00:00:00:0a:01" and port "1"
- IPortObject mockIPort = createMock(IPortObject.class);
- mockIPort.setNumber(portNum);
- mockIPort.setType("port");
- String iPortDesc = "port 1 at SEA Switch";
- expect(mockIPort.getNumber()).andReturn(portNum).anyTimes();
- expect(mockIPort.getDesc()).andReturn(iPortDesc).anyTimes();
- replay(mockIPort);
-
- //Make Iterator for mockIport
- List<IPortObject> portList = new ArrayList<IPortObject>();
- portList.add(mockIPort);
-
- //Expectation for mockIDeviceObject
- IDeviceObject mockIDev = createMock(IDeviceObject.class);
- expect(mockIDev.getAttachedPorts()).andReturn(portList).anyTimes();
- mockIDev.setIPAddress(makeIPStringFromArray(ipaddrs));
- mockIDev.setMACAddress(macAddr);
- mockIDev.setType("device");
- mockIDev.setState("ACTIVE");
- mockIDev.setIPAddress(makeIPStringFromArray(ipaddrs));
- mockIDev.setMACAddress(macAddr);
- mockIDev.setType("device");
- mockIDev.setState("ACTIVE");
- replay(mockIDev);
-
- //Expectation for mockOpe
- expect(mockOpe.searchDevice(macAddr)).andReturn(null);
- expect(mockOpe.newDevice()).andReturn(mockIDev);
- expect(mockOpe.searchPort(switchMacAddr, portNum)).andReturn(mockIPort);
- mockOpe.commit();
- expect(mockOpe.searchDevice(macAddr)).andReturn(mockIDev);
- expect(mockOpe.searchPort(switchMacAddr, portNum)).andReturn(mockIPort);
- mockOpe.commit();
- replay(mockOpe);
-
- deviceImpl.init(conf);
-
- //Add the device
- IDeviceObject obj = deviceImpl.addDevice(mockDev);
- assertNotNull(obj);
-
- //Add the same device
- IDeviceObject obj2 = deviceImpl.addDevice(mockDev);
- assertNotNull(obj2);
-
- } catch(Exception e) {
- fail(e.getMessage());
- }
+ IDevice device = getMockDevice(strMacAddress, attachmentDpid, attachmentPort, intIpv4Address);
+
+ IDeviceObject mockDeviceObject = createMock(IDeviceObject.class);
+ IPortObject mockPortObject = getMockPort(attachmentDpid, attachmentPort);
+ IIpv4Address mockIpv4Address = createMock(IIpv4Address.class);
+
+ expect(mockOpe.searchDevice(strMacAddress)).andReturn(mockDeviceObject);
+ expect(mockDeviceObject.getAttachedPorts()).andReturn(Collections.singleton(mockPortObject));
+ expect(mockOpe.searchPort(HexString.toHexString(attachmentDpid), attachmentPort)).andReturn(mockPortObject);
+ expect(mockDeviceObject.getIpv4Address(intIpv4Address)).andReturn(mockIpv4Address);
+ expect(mockDeviceObject.getIpv4Addresses()).andReturn(Collections.singleton(mockIpv4Address));
+ expect(mockIpv4Address.getIpv4Address()).andReturn(intIpv4Address);
+
+ mockDeviceObject.setMACAddress(strMacAddress);
+ mockDeviceObject.setType("device");
+ mockDeviceObject.setState("ACTIVE");
+ mockOpe.commit();
+
+ replay(mockDeviceObject);
+ replay(mockPortObject);
+ replay(mockIpv4Address);
+ replay(mockOpe);
+
+ IDeviceObject addedObject = deviceImpl.addDevice(device);
+ assertNotNull(addedObject);
+
+ verify(mockDeviceObject);
}
/**
- * Desc:
+ * Description:
* Test method for updateDevice method.
+ * NB. this is the same test as testAddExistingDevice
* Condition:
- * The mac address and attachment point are the same.
+ * The MAC address and attachment point are the same.
* All of the other parameter are different.
* Expect:
* Changed parameters are set expectedly.
*/
- //@Ignore
@Test
- public void testUpdateDevice() {
- try
- {
- IDevice mockDev = createMock(Device.class);
- String macAddr = "99:99:99:99:99:99";
- String ip = "192.168.100.1";
- Integer ipInt = IPv4.toIPv4Address(ip);
- Integer[] ipaddrs = {ipInt};
- String switchMacAddr = "00:00:00:00:00:00:0a:01";
- long switchMacAddrL = HexString.toLong(switchMacAddr);
- short portNum = 2;
- SwitchPort sp1 = new SwitchPort(switchMacAddrL, portNum);
- SwitchPort[] sps = {sp1};
-
- expect(mockDev.getMACAddressString()).andReturn(macAddr).anyTimes();
- expect(mockDev.getIPv4Addresses()).andReturn(ipaddrs);
- expect(mockDev.getAttachmentPoints()).andReturn(sps);
- replay(mockDev);
-
- //Dev2 (attached port is the same)
- IDevice mockDev2 = createMock(Device.class);
- String ip2 = "192.168.100.2";
- Integer ipInt2 = IPv4.toIPv4Address(ip2);
- Integer[] ipaddrs2 = {ipInt2};
-
- expect(mockDev2.getMACAddressString()).andReturn(macAddr).anyTimes();
- expect(mockDev2.getIPv4Addresses()).andReturn(ipaddrs2);
- expect(mockDev2.getAttachmentPoints()).andReturn(sps);
- replay(mockDev2);
-
- //Mock IPortObject 1 with dpid "00:00:00:00:00:00:0a:01" and port "1"
- IPortObject mockIPort = createMock(IPortObject.class);
- mockIPort.setNumber(portNum);
- mockIPort.setType("port");
- String iPortDesc = "port 1 at SEA Switch";
- expect(mockIPort.getNumber()).andReturn(portNum).anyTimes();
- expect(mockIPort.getDesc()).andReturn(iPortDesc).anyTimes();
- replay(mockIPort);
-
- //Make Iterator for mockIport
- List<IPortObject> portList = new ArrayList<IPortObject>();
- portList.add(mockIPort);
-
- //Expectation for mockIDeviceObject
- IDeviceObject mockIDev = createMock(IDeviceObject.class);
- expect(mockIDev.getAttachedPorts()).andReturn(portList).anyTimes();
- mockIDev.setIPAddress(makeIPStringFromArray(ipaddrs));
- mockIDev.setMACAddress(macAddr);
- mockIDev.setType("device");
- mockIDev.setState("ACTIVE");
- mockIDev.setIPAddress(makeIPStringFromArray(ipaddrs2));
- mockIDev.setMACAddress(macAddr);
- mockIDev.setType("device");
- mockIDev.setState("ACTIVE");
- replay(mockIDev);
-
- //Expectation for mockOpe
- expect(mockOpe.searchDevice(macAddr)).andReturn(null);
- expect(mockOpe.newDevice()).andReturn(mockIDev);
- expect(mockOpe.searchPort(switchMacAddr, portNum)).andReturn(mockIPort);
- mockOpe.commit();
- expect(mockOpe.searchDevice(macAddr)).andReturn(mockIDev);
- expect(mockOpe.searchPort(switchMacAddr, portNum)).andReturn(mockIPort);
- mockOpe.commit();
- replay(mockOpe);
-
- deviceImpl.init(conf);
-
- IDeviceObject obj = deviceImpl.addDevice(mockDev);
- assertNotNull(obj);
-
- //update theDevice
- IDeviceObject obj2 = deviceImpl.updateDevice(mockDev2);
- assertNotNull(obj2);
-
- verify(mockIDev);
-
- } catch(Exception e) {
- fail(e.getMessage());
- }
+ public void testAddUpdateDevice() {
+ String strMacAddress = "99:99:99:99:99:99";
+ long attachmentDpid = HexString.toLong("00:00:00:00:00:00:0a:01");
+ short attachmentPort = 2;
+ int intIpv4Address = InetAddresses.coerceToInteger(InetAddresses.forString("192.168.100.1"));
+
+ IDevice device = getMockDevice(strMacAddress, attachmentDpid, attachmentPort, intIpv4Address);
+
+ IDeviceObject mockDeviceObject = createMock(IDeviceObject.class);
+ IPortObject mockPortObject = getMockPort(attachmentDpid, attachmentPort);
+ IIpv4Address mockIpv4Address = createMock(IIpv4Address.class);
+
+ expect(mockOpe.searchDevice(strMacAddress)).andReturn(mockDeviceObject);
+ expect(mockDeviceObject.getAttachedPorts()).andReturn(Collections.singleton(mockPortObject));
+ expect(mockOpe.searchPort(HexString.toHexString(attachmentDpid), attachmentPort)).andReturn(mockPortObject);
+ expect(mockDeviceObject.getIpv4Address(intIpv4Address)).andReturn(mockIpv4Address);
+ expect(mockDeviceObject.getIpv4Addresses()).andReturn(Collections.singleton(mockIpv4Address));
+ expect(mockIpv4Address.getIpv4Address()).andReturn(intIpv4Address);
+
+ mockDeviceObject.setMACAddress(strMacAddress);
+ mockDeviceObject.setType("device");
+ mockDeviceObject.setState("ACTIVE");
+ mockOpe.commit();
+
+ replay(mockDeviceObject);
+ replay(mockPortObject);
+ replay(mockIpv4Address);
+ replay(mockOpe);
+
+ IDeviceObject addedObject = deviceImpl.updateDevice(device);
+ assertNotNull(addedObject);
+
+ verify(mockDeviceObject);
}
/**
- * Desc:
+ * Description:
* Test method for testRemoveDevice method.
* Condition:
* 1. Unregistered IDeviceObject argument is put.
@@ -350,395 +251,174 @@
* 1. Nothing happen when unregistered IDeviceObject is put
* 2. IDeviceObject will be removed.
*/
- //@Ignore
@Test
public void testRemoveDevice() {
- try
- {
- IDevice mockDev = createMock(Device.class);
- String macAddr = "99:99:99:99:99:99";
- String ip = "192.168.100.1";
- Integer ipInt = IPv4.toIPv4Address(ip);
- Integer[] ipaddrs = {ipInt};
- String switchMacAddr = "00:00:00:00:00:00:0a:01";
- long switchMacAddrL = HexString.toLong(switchMacAddr);
- short portNum = 2;
- SwitchPort sp1 = new SwitchPort(switchMacAddrL, portNum);
- SwitchPort[] sps = {sp1};
-
- expect(mockDev.getMACAddressString()).andReturn(macAddr).anyTimes();
- expect(mockDev.getAttachmentPoints()).andReturn(sps);
- expect(mockDev.getIPv4Addresses()).andReturn(ipaddrs);
- replay(mockDev);
-
- //Dev2 (attached port is the same)
- IDevice mockDev2 = createMock(Device.class);
- String macAddr2 = "33:33:33:33:33:33";
- expect(mockDev2.getMACAddressString()).andReturn(macAddr2).anyTimes();
- expect(mockDev2.getIPv4Addresses()).andReturn(ipaddrs);
- expect(mockDev2.getAttachmentPoints()).andReturn(sps);
- replay(mockDev2);
-
- //Mock IPortObject 1 with dpid "00:00:00:00:00:00:0a:01" and port "1"
- IPortObject mockIPort = createMock(IPortObject.class);
- mockIPort.setNumber(portNum);
- mockIPort.setType("port");
- String iPortDesc = "port 1 at SEA Switch";
- expect(mockIPort.getNumber()).andReturn(portNum).anyTimes();
- expect(mockIPort.getDesc()).andReturn(iPortDesc).anyTimes();
- replay(mockIPort);
-
- //Make Iterator for mockIport
- List<IPortObject> portList = new ArrayList<IPortObject>();
- portList.add(mockIPort);
-
- //Expectation for mockIDeviceObject
- IDeviceObject mockIDev = createMock(IDeviceObject.class);
- expect(mockIDev.getAttachedPorts()).andReturn(portList);
- mockIDev.setIPAddress(makeIPStringFromArray(ipaddrs));
- mockIDev.setMACAddress(macAddr);
- mockIDev.setType("device");
- mockIDev.setState("ACTIVE");
- replay(mockIDev);
-
- //Expectation for mockOpe
- expect(mockOpe.searchDevice(macAddr)).andReturn(null);
- expect(mockOpe.newDevice()).andReturn(mockIDev);
- expect(mockOpe.searchPort(switchMacAddr, portNum)).andReturn(mockIPort);
- mockOpe.commit();
- expect(mockOpe.searchDevice(macAddr2)).andReturn(null);
- expect(mockOpe.searchDevice(macAddr)).andReturn(mockIDev);
- expect(mockOpe.searchDevice(macAddr)).andReturn(mockIDev);
- mockOpe.removeDevice(mockIDev);
- mockOpe.commit();
- expect(mockOpe.searchDevice(macAddr)).andReturn(null);
- replay(mockOpe);
-
- deviceImpl.init(conf);
-
- IDeviceObject obj = deviceImpl.addDevice(mockDev);
- assertNotNull(obj);
+ String strMacAddress = "99:99:99:99:99:99";
+ long attachmentDpid = HexString.toLong("00:00:00:00:00:00:0a:01");
+ short attachmentPort = 2;
+ int intIpv4Address = InetAddresses.coerceToInteger(InetAddresses.forString("192.168.100.1"));
+
+ IIpv4Address ipv4AddressObject = createMock(IIpv4Address.class);
+ IDeviceObject deviceObject = createMock(IDeviceObject.class);
+ expect(deviceObject.getIpv4Addresses()).andReturn(Collections.singleton(ipv4AddressObject));
+ replay(deviceObject);
+
+ expect(mockOpe.searchDevice(strMacAddress)).andReturn(deviceObject);
+ mockOpe.removeIpv4Address(ipv4AddressObject);
+ mockOpe.removeDevice(deviceObject);
+ mockOpe.commit();
+ replay(mockOpe);
+
+ IDevice device = getMockDevice(strMacAddress, attachmentDpid, attachmentPort, intIpv4Address);
- deviceImpl.removeDevice(mockDev2);
- IDeviceObject dev = deviceImpl.getDeviceByMac(macAddr);
- assertNotNull(dev);
-
- deviceImpl.removeDevice(mockDev);
- IDeviceObject dev2 = deviceImpl.getDeviceByMac(macAddr);
- assertNull(dev2);
-
- verify(mockIDev);
-
- } catch(Exception e) {
- fail(e.getMessage());
- }
+ deviceImpl.removeDevice(device);
+
+ verify(mockOpe);
}
/**
- * Desc:
+ * Description:
* Test method for getDeviceByMac
* Condition:
- * 1. Unregistered mac address argument is set
+ * 1. Unregistered MAC address argument is set
* Expect:
- * 1.Nothing happen when you put unregistered mac address
+ * 1.Nothing happen when you put unregistered MAC address
* 2.Get the proper IDeviceObject.
* 3.Check the IDeviceObject properties set expectedly.
*/
- //@Ignore
@Test
public void testGetDeviceByMac() {
- try
- {
- IDevice mockDev = createMock(Device.class);
- String macAddr = "99:99:99:99:99:99";
- String ip = "192.168.100.1";
- Integer ipInt = IPv4.toIPv4Address(ip);
- Integer[] ipaddrs = {ipInt};
- String switchMacAddr = "00:00:00:00:00:00:0a:01";
- long switchMacAddrL = HexString.toLong(switchMacAddr);
- short portNum = 2;
- SwitchPort sp1 = new SwitchPort(switchMacAddrL, portNum);
- SwitchPort[] sps = {sp1};
-
- String dummyMac = "33:33:33:33:33:33";
-
- expect(mockDev.getMACAddressString()).andReturn(macAddr).anyTimes();
- expect(mockDev.getIPv4Addresses()).andReturn(ipaddrs);
- expect(mockDev.getAttachmentPoints()).andReturn(sps);
- replay(mockDev);
-
- //Mock IPortObject 1 with dpid "00:00:00:00:00:00:0a:01" and port "1"
- IPortObject mockIPort = createMock(IPortObject.class);
- mockIPort.setNumber(portNum);
- mockIPort.setType("port");
- String iPortDesc = "port 1 at SEA Switch";
- expect(mockIPort.getNumber()).andReturn(portNum).anyTimes();
- expect(mockIPort.getDesc()).andReturn(iPortDesc).anyTimes();
- replay(mockIPort);
-
- //Make Iterator for mockIport
- List<IPortObject> portList = new ArrayList<IPortObject>();
- portList.add(mockIPort);
-
- //Expectation for mockIDeviceObject
- IDeviceObject mockIDev = createMock(IDeviceObject.class);
- expect(mockIDev.getAttachedPorts()).andReturn(portList);
- mockIDev.setIPAddress(makeIPStringFromArray(ipaddrs));
- mockIDev.setMACAddress(macAddr);
- mockIDev.setType("device");
- mockIDev.setState("ACTIVE");
- replay(mockIDev);
-
- //Expectation for mockOpe
- expect(mockOpe.searchDevice(macAddr)).andReturn(null);
- expect(mockOpe.newDevice()).andReturn(mockIDev);
- expect(mockOpe.searchPort(switchMacAddr, portNum)).andReturn(mockIPort);
- mockOpe.commit();
- expect(mockOpe.searchDevice(dummyMac)).andReturn(null);
- expect(mockOpe.searchDevice(macAddr)).andReturn(mockIDev);
- replay(mockOpe);
-
- deviceImpl.init(conf);
-
- IDeviceObject obj = deviceImpl.addDevice(mockDev);
- assertNotNull(obj);
-
- IDeviceObject dummyDev = deviceImpl.getDeviceByMac(dummyMac);
- assertNull(dummyDev);
-
- IDeviceObject dev = deviceImpl.getDeviceByMac(macAddr);
- assertNotNull(dev);
-
- verify(mockIDev);
-
- } catch(Exception e) {
- fail(e.getMessage());
- }
+ String mac = "99:99:99:99:99:99";
+
+ IDeviceObject mockDevice = createMock(IDeviceObject.class);
+
+ expect(mockOpe.searchDevice(mac)).andReturn(mockDevice);
+
+ replay(mockOpe);
+
+ IDeviceObject result = deviceImpl.getDeviceByMac(mac);
+ assertNotNull(result);
+
+ verify(mockOpe);
}
-
+
/**
- * Desc:
+ * Description:
* Test method for getDeviceByIP method.
* Condition:
- * 1. Unregistered ip address argument is set
+ * 1. Unregistered IP address argument is set
* Expect:
- * 1. Nothing happen when you put unregistered mac address
+ * 1. Nothing happen when you put unregistered IP address
* 2. Get the proper IDeviceObject.
* 3. Check the IDeviceObject properties set expectedly.
*/
- //@Ignore
@Test
public void testGetDeviceByIP() {
- try
- {
- IDevice mockDev = createMock(Device.class);
- String macAddr = "99:99:99:99:99:99";
- String ip = "192.168.100.1";
- String ip2 = "192.168.100.2";
- Integer ipInt = IPv4.toIPv4Address(ip);
- Integer ipInt2 = IPv4.toIPv4Address(ip2);
- Integer[] ipaddrs = {ipInt, ipInt2};
- String switchMacAddr = "00:00:00:00:00:00:0a:01";
- long switchMacAddrL = HexString.toLong(switchMacAddr);
- short portNum = 2;
- SwitchPort sp1 = new SwitchPort(switchMacAddrL, portNum);
- SwitchPort[] sps = {sp1};
-
- String dummyIP = "222.222.222.222";
-
- expect(mockDev.getMACAddressString()).andReturn(macAddr).anyTimes();
- expect(mockDev.getIPv4Addresses()).andReturn(ipaddrs);
- expect(mockDev.getAttachmentPoints()).andReturn(sps);
- replay(mockDev);
-
- //Mock IPortObject 1 with dpid "00:00:00:00:00:00:0a:01" and port "1"
- IPortObject mockIPort = createMock(IPortObject.class);
- mockIPort.setNumber(portNum);
- mockIPort.setType("port");
- String iPortDesc = "port 1 at SEA Switch";
- expect(mockIPort.getNumber()).andReturn(portNum).anyTimes();
- expect(mockIPort.getDesc()).andReturn(iPortDesc).anyTimes();
- replay(mockIPort);
-
- //Make Iterator for mockIport
- List<IPortObject> portList = new ArrayList<IPortObject>();
- portList.add(mockIPort);
-
- //Expectation for mockIDeviceObject
- IDeviceObject mockIDev = createMock(IDeviceObject.class);
- expect(mockIDev.getAttachedPorts()).andReturn(portList);
- expect(mockIDev.getIPAddress()).andReturn(makeIPStringFromArray(ipaddrs)).times(2);
- mockIDev.setIPAddress(makeIPStringFromArray(ipaddrs));
- mockIDev.setMACAddress(macAddr);
- mockIDev.setType("device");
- mockIDev.setState("ACTIVE");
- replay(mockIDev);
-
-
- //Make mock Iterator for IDeviceObject
- List<IDeviceObject> deviceList = new ArrayList<IDeviceObject>();
- deviceList.add(mockIDev);
-
- //Expectation for mockOpe
- expect(mockOpe.searchDevice(macAddr)).andReturn(null);
- expect(mockOpe.newDevice()).andReturn(mockIDev);
- expect(mockOpe.searchPort(switchMacAddr, portNum)).andReturn(mockIPort);
- mockOpe.commit();
- expect(mockOpe.getDevices()).andReturn(deviceList).times(2);
- replay(mockOpe);
-
- deviceImpl.init(conf);
-
- IDeviceObject obj = deviceImpl.addDevice(mockDev);
- assertNotNull(obj);
-
- IDeviceObject dummyDev = deviceImpl.getDeviceByIP(dummyIP);
- assertNull(dummyDev);
-
- IDeviceObject dev = deviceImpl.getDeviceByIP(ip);
- assertNotNull(dev);
-
- verify(mockIDev);
-
-
- } catch(Exception e) {
- fail(e.getMessage());
- }
+ int nonExistingIp = InetAddresses.coerceToInteger(InetAddresses.forString("192.168.10.50"));
+ int existingIp = InetAddresses.coerceToInteger(InetAddresses.forString("10.5.12.128"));
+
+ IDeviceObject mockDevice = createMock(IDeviceObject.class);
+ IIpv4Address mockExistingIp = createMock(IIpv4Address.class);
+ expect(mockExistingIp.getDevice()).andReturn(mockDevice);
+
+ expect(mockOpe.searchIpv4Address(nonExistingIp)).andReturn(null);
+ expect(mockOpe.searchIpv4Address(existingIp)).andReturn(mockExistingIp);
+
+ replay(mockExistingIp);
+ replay(mockOpe);
+
+ IDeviceObject result = deviceImpl.getDeviceByIP(nonExistingIp);
+ assertNull(result);
+
+ result = deviceImpl.getDeviceByIP(existingIp);
+ assertNotNull(result);
+
+ verify(mockOpe);
}
/**
- * Desc:
+ * Description:
* Test method for testChangeDeviceAttachmentsIDevice
* Condition:
- * 1. Unexisting attachment point argument is set
+ * 1. The device is not currently attached to any point.
* Expect:
- * 1. Nothing happen when you put unexisting attachment point.
+ * 1. Nothing happen when you put nonexistent attachment point.
* 2. Set the attachment point expectedly;
*/
- //@Ignore
@Test
- public void testChangeDeviceAttachmentsIDevice() {
- try
- {
- IDevice mockDev = createMock(Device.class);
- String macAddr = "99:99:99:99:99:99";
- String ip = "192.168.100.1";
- Integer ipInt = IPv4.toIPv4Address(ip);
- Integer[] ipaddrs = {ipInt};
- String switchMacAddr = "00:00:00:00:00:00:0a:01";
- long switchMacAddrL = HexString.toLong(switchMacAddr);
- short portNum = 2;
- SwitchPort sp1 = new SwitchPort(switchMacAddrL, portNum);
- SwitchPort[] sps = {sp1};
-
- expect(mockDev.getMACAddressString()).andReturn(macAddr).anyTimes();
- expect(mockDev.getIPv4Addresses()).andReturn(ipaddrs);
- expect(mockDev.getAttachmentPoints()).andReturn(sps);
- replay(mockDev);
-
- //Dev2
- IDevice mockDev2 = createMock(Device.class);
- String switchMacAddr2 = "00:00:00:00:00:00:0a:02";
- long lSwitchMacAddr2 = HexString.toLong(switchMacAddr2);
- short portNum2 = 2;
- SwitchPort sp2 = new SwitchPort(lSwitchMacAddr2, portNum2);
- SwitchPort sps2[] = {sp2};
-
- expect(mockDev2.getMACAddressString()).andReturn(macAddr).anyTimes();
- expect(mockDev2.getIPv4Addresses()).andReturn(ipaddrs);
- expect(mockDev2.getAttachmentPoints()).andReturn(sps2);
- replay(mockDev2);
-
- //Dev3
- IDevice mockDev3 = createMock(Device.class);
- String switchMacAddr3 = "00:00:00:00:00:00:00:00";
- long lSwitchMacAddr3 = HexString.toLong(switchMacAddr3);
- short portNum3 = 1;
- SwitchPort sp3 = new SwitchPort(lSwitchMacAddr3, portNum3);
- SwitchPort sps3[] = {sp3};
-
- expect(mockDev3.getMACAddressString()).andReturn(macAddr).anyTimes();
- expect(mockDev3.getIPv4Addresses()).andReturn(ipaddrs);
- expect(mockDev3.getAttachmentPoints()).andReturn(sps3);
- replay(mockDev3);
-
- IDeviceObject mockIDev = createMock(IDeviceObject.class);
-
- //Mock IPortObject 1 with dpid "00:00:00:00:00:00:0a:01" and port "1"
- IPortObject mockIPort = createMock(IPortObject.class);
- mockIPort.setNumber(portNum);
- mockIPort.setType("port");
- String iPortDesc = "port 1 at SEA Switch";
- expect(mockIPort.getNumber()).andReturn(portNum).anyTimes();
- expect(mockIPort.getDesc()).andReturn(iPortDesc).anyTimes();
- mockIPort.removeDevice(mockIDev);
- mockIPort.removeDevice(mockIDev);
- replay(mockIPort);
-
- //Make Iterator for mockIport
- List<IPortObject> portList = new ArrayList<IPortObject>();
- portList.add(mockIPort);
-
- //Expectation for mockIDeviceObject
- expect(mockIDev.getAttachedPorts()).andReturn(portList).anyTimes();
- mockIDev.setIPAddress(makeIPStringFromArray(ipaddrs));
- mockIDev.setMACAddress(macAddr);
- mockIDev.setType("device");
- mockIDev.setState("ACTIVE");
- replay(mockIDev);
-
- //Mock IPortObject 2 with dpid "00:00:00:00:00:00:0a:02" and port "2"
- IPortObject mockIPort2 = createMock(IPortObject.class);
- mockIPort2.setNumber(portNum2);
- mockIPort2.setType("port");
- String iPortDesc2 = "port 2 at LAX Switch";
- expect(mockIPort2.getNumber()).andReturn(portNum2).anyTimes();
- expect(mockIPort2.getDesc()).andReturn(iPortDesc2).anyTimes();
- mockIPort2.setDevice(mockIDev);
- replay(mockIPort2);
-
- //Make Iterator for mockIport
- List<IPortObject> portList2 = new ArrayList<IPortObject>();
- portList2.add(mockIPort2);
-
- //Mock IPortObject 3 with dpid "00:00:00:00:00:00:00:00" and port "1"
- IPortObject mockIPort3 = createMock(IPortObject.class);
- mockIPort3.setNumber(portNum3);
- mockIPort3.setType("port");
- String iPortDesc3 = "n/a";
- expect(mockIPort3.getNumber()).andReturn(portNum3).anyTimes();
- expect(mockIPort3.getDesc()).andReturn(iPortDesc3).anyTimes();
- mockIPort3.setDevice(mockIDev);
- replay(mockIPort3);
-
- //Expectation for mockOpe
- expect(mockOpe.searchDevice(macAddr)).andReturn(null);
- expect(mockOpe.newDevice()).andReturn(mockIDev);
- expect(mockOpe.searchPort(switchMacAddr, portNum)).andReturn(mockIPort);
- mockOpe.commit();
- expect(mockOpe.searchDevice(macAddr)).andReturn(mockIDev);
- expect(mockOpe.searchPort(switchMacAddr2, portNum2)).andReturn(mockIPort2);
- mockOpe.commit();
- expect(mockOpe.searchDevice(macAddr)).andReturn(mockIDev);
- expect(mockOpe.searchPort(switchMacAddr3, portNum3)).andReturn(null);
- mockOpe.commit();
- replay(mockOpe);
-
- deviceImpl.init(conf);
+ public void testChangeDeviceAttachementsWhenUnattached() {
+ String strMacAddress = "99:99:99:99:99:99";
+ long attachmentDpid = HexString.toLong("00:00:00:00:00:00:0a:01");
+ short attachmentPort = 2;
+ int intIpv4Address = InetAddresses.coerceToInteger(InetAddresses.forString("192.168.100.1"));
+
+ IDevice device = getMockDevice(strMacAddress, attachmentDpid, attachmentPort, intIpv4Address);
+
+ IDeviceObject mockDeviceObject = createMock(IDeviceObject.class);
+ IPortObject mockPortObject = getMockPort(attachmentDpid, attachmentPort);
+
+ expect(mockOpe.searchDevice(strMacAddress)).andReturn(mockDeviceObject);
+ expect(mockDeviceObject.getAttachedPorts()).andReturn(Collections.<IPortObject>emptyList());
+ expect(mockOpe.searchPort(HexString.toHexString(attachmentDpid), attachmentPort)).andReturn(mockPortObject);
+ mockPortObject.setDevice(mockDeviceObject);
+ mockOpe.commit();
+
+ replay(mockDeviceObject);
+ replay(mockPortObject);
+ replay(mockOpe);
+
+ deviceImpl.changeDeviceAttachments(device);
+
+ verify(mockDeviceObject);
+ verify(mockPortObject);
+ verify(mockOpe);
+ }
- IDeviceObject obj = deviceImpl.addDevice(mockDev);
- assertNotNull(obj);
-
- deviceImpl.changeDeviceAttachments(mockDev2);
-
- deviceImpl.changeDeviceAttachments(mockDev3);
-
- verify(mockIDev);
-
-
- } catch(Exception e) {
- fail(e.getMessage());
- }
+ /**
+ * Description:
+ * Test method for testChangeDeviceAttachmentsIDevice
+ * Condition:
+ * 1. The device is currently attached to a switch, but this attachment point
+ * has now changed.
+ * Expect:
+ * 1. The device should be removed from the old attachment point.
+ * 2. Set the attachment point expectedly;
+ */
+ @Test
+ public void testChangeDeviceAttachementsWhenAttached() {
+ String strMacAddress = "99:99:99:99:99:99";
+ long attachmentDpid = HexString.toLong("00:00:00:00:00:00:0a:01");
+ short attachmentPort = 2;
+ int intIpv4Address = InetAddresses.coerceToInteger(InetAddresses.forString("192.168.100.1"));
+
+ //Details for the port the device will be moved from
+ long alreadyAttachedDpid = HexString.toLong("00:00:00:00:00:00:0b:01");
+ short alreadyAttachedPort = 5;
+
+ IDevice device = getMockDevice(strMacAddress, attachmentDpid, attachmentPort, intIpv4Address);
+
+ IDeviceObject mockDeviceObject = createMock(IDeviceObject.class);
+ IPortObject mockPortObject = getMockPort(attachmentDpid, attachmentPort);
+ IPortObject alreadyAttachedPortObject = getMockPort(alreadyAttachedDpid, alreadyAttachedPort);
+
+ expect(mockOpe.searchDevice(strMacAddress)).andReturn(mockDeviceObject);
+ expect(mockDeviceObject.getAttachedPorts()).andReturn(Collections.singletonList(alreadyAttachedPortObject));
+ expect(mockOpe.searchPort(HexString.toHexString(attachmentDpid), attachmentPort)).andReturn(mockPortObject);
+ mockPortObject.setDevice(mockDeviceObject);
+ alreadyAttachedPortObject.removeDevice(mockDeviceObject);
+ mockOpe.commit();
+
+ replay(mockDeviceObject);
+ replay(alreadyAttachedPortObject);
+ replay(mockPortObject);
+ replay(mockOpe);
+
+ deviceImpl.changeDeviceAttachments(device);
+
+ verify(mockDeviceObject);
+ verify(alreadyAttachedPortObject);
+ verify(mockPortObject);
+ verify(mockOpe);
}
@Ignore
@@ -748,90 +428,89 @@
}
/**
- * Desc:
+ * Description:
* Test method for testChangeDeviceIPv4Address
* Condition:
* N/A
* Expect:
- * 1. Set the ipadress expectedly.
+ * 1. Set the IP address expectedly.
*/
- //@Ignore
@Test
- public void testChangeDeviceIPv4Address() {
- try
- {
- //Dev1
- IDevice mockDev = createMock(Device.class);
- String macAddr = "99:99:99:99:99:99";
- String ip = "192.168.100.1";
- Integer ipInt = IPv4.toIPv4Address(ip);
- Integer[] ipaddrs = {ipInt};
- String switchMacAddr = "00:00:00:00:00:00:0a:01";
- long switchMacAddrL = HexString.toLong(switchMacAddr);
- short portNum = 2;
- SwitchPort sp1 = new SwitchPort(switchMacAddrL, portNum);
- SwitchPort[] sps = {sp1};
-
- expect(mockDev.getMACAddressString()).andReturn(macAddr).anyTimes();
- expect(mockDev.getIPv4Addresses()).andReturn(ipaddrs);
- expect(mockDev.getAttachmentPoints()).andReturn(sps);
- replay(mockDev);
-
- //Dev2
- IDevice mockDev2 = createMock(Device.class);
- String ip2 = "192.168.100.2";
- Integer ipInt2 = IPv4.toIPv4Address(ip2);
- Integer[] ipaddrs2 = {ipInt2};
- expect(mockDev2.getMACAddressString()).andReturn(macAddr);
- expect(mockDev2.getIPv4Addresses()).andReturn(ipaddrs2);
- replay(mockDev2);
-
- //Mock IPortObject 1 with dpid "00:00:00:00:00:00:0a:01" and port "1"
- IPortObject mockIPort = createMock(IPortObject.class);
- mockIPort.setNumber(portNum);
- mockIPort.setType("port");
- String iPortDesc = "port 1 at SEA Switch";
- expect(mockIPort.getNumber()).andReturn(portNum).anyTimes();
- expect(mockIPort.getDesc()).andReturn(iPortDesc).anyTimes();
- replay(mockIPort);
-
- //Make Iterator for mockIport
- List<IPortObject> portList = new ArrayList<IPortObject>();
- portList.add(mockIPort);
-
- //Expectation for mockIDeviceObject
- IDeviceObject mockIDev = createMock(IDeviceObject.class);
- expect(mockIDev.getAttachedPorts()).andReturn(portList);
- mockIDev.setIPAddress(makeIPStringFromArray(ipaddrs));
- mockIDev.setMACAddress(macAddr);
- mockIDev.setType("device");
- mockIDev.setState("ACTIVE");
- mockIDev.setIPAddress(makeIPStringFromArray(ipaddrs2));
- replay(mockIDev);
-
- //Expectation for mockOpe
- expect(mockOpe.searchDevice(macAddr)).andReturn(null);
- expect(mockOpe.newDevice()).andReturn(mockIDev);
- expect(mockOpe.searchPort(switchMacAddr, portNum)).andReturn(mockIPort);
- mockOpe.commit();
- expect(mockOpe.searchDevice(macAddr)).andReturn(mockIDev);
- mockOpe.commit();
- replay(mockOpe);
-
- deviceImpl.init(conf);
-
- IDeviceObject obj = deviceImpl.addDevice(mockDev);
- assertNotNull(obj);
-
- deviceImpl.changeDeviceIPv4Address(mockDev2);
-
- verify(mockIDev);
-
-
- }
- catch(Exception e) {
- fail(e.getMessage());
- }
+ public void testChangeDeviceIpv4Address() {
+ String strMacAddress = "99:99:99:99:99:99";
+ long attachmentDpid = HexString.toLong("00:00:00:00:00:00:0a:01");
+ short attachmentPort = 2;
+ int intIpv4Address = InetAddresses.coerceToInteger(InetAddresses.forString("192.168.100.1"));
+
+ IDevice device = getMockDevice(strMacAddress, attachmentDpid, attachmentPort, intIpv4Address);
+
+ IDeviceObject mockDeviceObject = createMock(IDeviceObject.class);
+ IIpv4Address mockIpv4Address = createMock(IIpv4Address.class);
+
+ expect(mockOpe.searchDevice(strMacAddress)).andReturn(mockDeviceObject);
+ expect(mockDeviceObject.getIpv4Address(intIpv4Address)).andReturn(null);
+ expect(mockOpe.ensureIpv4Address(intIpv4Address)).andReturn(mockIpv4Address);
+ mockDeviceObject.addIpv4Address(mockIpv4Address);
+ expect(mockDeviceObject.getIpv4Addresses()).andReturn(Collections.singletonList(mockIpv4Address));
+ expect(mockIpv4Address.getIpv4Address()).andReturn(intIpv4Address);
+ mockOpe.commit();
+
+ replay(mockDeviceObject);
+ replay(mockIpv4Address);
+ replay(mockOpe);
+
+ deviceImpl.changeDeviceIPv4Address(device);
+
+ verify(mockDeviceObject);
+ verify(mockIpv4Address);
+ verify(mockOpe);
+ }
+
+ /**
+ * Description:
+ * Test method for testChangeDeviceIPv4Address
+ * Condition:
+ * 1. The device had an old IP address which has now changed.
+ * Expect:
+ * 1. The old IP address should be removed from the device.
+ * 2. Set the IP address expectedly.
+ */
+ @Test
+ public void testChangeDeviceIpv4AddressAndRemoveExisting() {
+ String strMacAddress = "99:99:99:99:99:99";
+ long attachmentDpid = HexString.toLong("00:00:00:00:00:00:0a:01");
+ short attachmentPort = 2;
+ int intIpv4Address = InetAddresses.coerceToInteger(InetAddresses.forString("192.168.100.1"));
+
+ IDevice device = getMockDevice(strMacAddress, attachmentDpid, attachmentPort, intIpv4Address);
+
+ IDeviceObject mockDeviceObject = createMock(IDeviceObject.class);
+
+ IIpv4Address mockIpv4Address = createMock(IIpv4Address.class);
+ IIpv4Address mockDeletingIpv4Address = createMock(IIpv4Address.class);
+ List<IIpv4Address> ipv4Vertices = new ArrayList<IIpv4Address>(2);
+ ipv4Vertices.add(mockIpv4Address);
+ ipv4Vertices.add(mockDeletingIpv4Address);
+
+ expect(mockOpe.searchDevice(strMacAddress)).andReturn(mockDeviceObject);
+ expect(mockDeviceObject.getIpv4Address(intIpv4Address)).andReturn(null);
+ expect(mockOpe.ensureIpv4Address(intIpv4Address)).andReturn(mockIpv4Address);
+ mockDeviceObject.addIpv4Address(mockIpv4Address);
+ expect(mockDeviceObject.getIpv4Addresses()).andReturn(ipv4Vertices);
+ expect(mockIpv4Address.getIpv4Address()).andReturn(intIpv4Address);
+ expect(mockDeletingIpv4Address.getIpv4Address()).andReturn(1);
+ mockDeviceObject.removeIpv4Address(mockDeletingIpv4Address);
+ mockOpe.commit();
+
+ replay(mockDeviceObject);
+ replay(mockIpv4Address);
+ replay(mockOpe);
+
+ deviceImpl.changeDeviceIPv4Address(device);
+
+ verify(mockDeviceObject);
+ verify(mockIpv4Address);
+ verify(mockOpe);
}
}
diff --git a/src/test/java/net/onrc/onos/ofcontroller/devicemanager/internal/DeviceStorageImplTestBB.java b/src/test/java/net/onrc/onos/ofcontroller/devicemanager/internal/DeviceStorageImplTestBB.java
index 552cb9c..c7c74a5 100644
--- a/src/test/java/net/onrc/onos/ofcontroller/devicemanager/internal/DeviceStorageImplTestBB.java
+++ b/src/test/java/net/onrc/onos/ofcontroller/devicemanager/internal/DeviceStorageImplTestBB.java
@@ -22,6 +22,7 @@
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openflow.util.HexString;
@@ -33,6 +34,19 @@
import com.thinkaurelius.titan.core.TitanFactory;
import com.thinkaurelius.titan.core.TitanGraph;
+/*
+ * Jono, 11/4/2013
+ * These tests are being ignored because they don't work because they
+ * rely on test functionality that was written ages ago and hasn't been
+ * updated as the database schema has evolved.
+ * These tests work by getting an in-memory Titan database and testing
+ * the DeviceStorageImpl on top of that. In this regard they're not really
+ * unit tests as they test the entire DB stack (i.e. GraphDBOperation and
+ * GraphDBConnection), not just DeviceStorageImpl.
+ * I've left them here as we may wish to resurrect this kind of
+ * integration testing of the DB layers in the future.
+ */
+@Ignore
//Add Powermock preparation
@RunWith(PowerMockRunner.class)
@PrepareForTest({TitanFactory.class, GraphDBConnection.class, GraphDBOperation.class, SwitchStorageImpl.class})
@@ -130,7 +144,11 @@
//Test to take a IP addr from DB
//TodoForGettingIPaddr. There may be bug in the test class.
- String ipFromDB = devObj1.getIPAddress();
+
+ //XXX not updated to new interface
+ //String ipFromDB = devObj1.getIPAddress();
+ String ipFromDB = "foo";
+
String[] ipsFromDB = ipFromDB.replace("[", "").replace("]", "").split(",");
List<String> ipsList = Arrays.asList(ipsFromDB);
assertTrue(ipsList.contains(ip));
@@ -219,7 +237,10 @@
}
}
- String ipFromDB = devObj2.getIPAddress();
+ //XXX not updated to new interface
+ //String ipFromDB = devObj2.getIPAddress();
+ String ipFromDB = "foo";
+
String[] ipsFromDB = ipFromDB.replace("[", "").replace("]", "").split(",");
List<String> ipsList = Arrays.asList(ipsFromDB);
assertTrue(ipsList.contains(ip));
@@ -464,9 +485,16 @@
IDeviceObject dev1 = ope.searchDevice(macAddr);
assertEquals(macAddr, dev1.getMACAddress());
- IDeviceObject dev = deviceImpl.getDeviceByIP(ip);
+ //XXX not updated to new interface
+ //IDeviceObject dev = deviceImpl.getDeviceByIP(ip);
+ IDeviceObject dev = null;
+
assertNotNull(dev);
- String ipFromDB = dev.getIPAddress();
+
+ //XXX not updated to new interface
+ //String ipFromDB = dev.getIPAddress();
+ String ipFromDB = "foo";
+
String[] ipsFromDB = ipFromDB.replace("[", "").replace("]", "").split(",");
List<String> ipsList = Arrays.asList(ipsFromDB);
assertTrue(ipsList.contains(ip));
@@ -601,7 +629,11 @@
IDeviceObject dev1 = ope.searchDevice(macAddr);
assertEquals(macAddr, dev1.getMACAddress());
- String ipFromDB = dev1.getIPAddress();
+
+ //XXX not updated to new interface
+ //String ipFromDB = dev1.getIPAddress();
+ String ipFromDB = "foo";
+
String[] ipsFromDB = ipFromDB.replace("[", "").replace("]", "").split(",");
List<String> ipsList = Arrays.asList(ipsFromDB);
assertTrue(ipsList.contains(ip));
@@ -610,7 +642,11 @@
IDeviceObject dev2 = ope.searchDevice(macAddr);
assertEquals(macAddr, dev2.getMACAddress());
- String ipFromDB2 = dev2.getIPAddress();
+
+ //XXX not updated to new interface
+ //String ipFromDB2 = dev2.getIPAddress();
+ String ipFromDB2 = "foo";
+
String[] ipsFromDB2 = ipFromDB2.replace("[", "").replace("]", "").split(",");
List<String> ipsList2 = Arrays.asList(ipsFromDB2);
assertTrue(ipsList2.contains(ip2));
diff --git a/web/get_datagrid.py b/web/get_datagrid.py
new file mode 100755
index 0000000..2d26846
--- /dev/null
+++ b/web/get_datagrid.py
@@ -0,0 +1,84 @@
+#! /usr/bin/env python
+# -*- Mode: python; py-indent-offset: 4; tab-width: 8; indent-tabs-mode: t; -*-
+
+import pprint
+import os
+import sys
+import subprocess
+import json
+import argparse
+import io
+import time
+
+from flask import Flask, json, Response, render_template, make_response, request
+
+## Global Var ##
+ControllerIP="127.0.0.1"
+ControllerPort=8080
+
+DEBUG=0
+pp = pprint.PrettyPrinter(indent=4)
+
+app = Flask(__name__)
+
+## Worker Functions ##
+def log_error(txt):
+ print '%s' % (txt)
+
+def debug(txt):
+ if DEBUG:
+ print '%s' % (txt)
+
+# @app.route("/wm/datagrid/get/map/<map-name>/json ")
+# Sample output:
+
+def print_datagrid_map(parsedResult):
+ print '%s' % (parsedResult)
+
+def get_datagrid_map(map_name):
+ try:
+ command = "curl -s \"http://%s:%s/wm/datagrid/get/map/%s/json\"" % (ControllerIP, ControllerPort, map_name)
+ debug("get_datagrid_map %s" % command)
+
+ result = os.popen(command).read()
+ debug("result %s" % result)
+ if len(result) == 0:
+ print "No Map found"
+ return;
+
+ # TODO: For now, the string is not JSON-formatted
+ # parsedResult = json.loads(result)
+ parsedResult = result
+ debug("parsed %s" % parsedResult)
+ except:
+ log_error("Controller IF has issue")
+ exit(1)
+
+ print_datagrid_map(parsedResult)
+
+
+if __name__ == "__main__":
+ usage_msg1 = "Usage:\n"
+ usage_msg2 = "%s <map_name> : Print datagrid map with name of <map_name>\n" % (sys.argv[0])
+ usage_msg3 = " Valid map names:\n"
+ usage_msg4 = " all : Print all maps\n"
+ usage_msg5 = " flow : Print all flows\n"
+ usage_msg6 = " flow-entry : Print all flow entries\n"
+ usage_msg7 = " topology : Print the topology\n"
+ usage_msg = usage_msg1 + usage_msg2 + usage_msg3 + usage_msg4 + usage_msg5
+ usage_msg = usage_msg + usage_msg6 + usage_msg7
+
+ # app.debug = False;
+
+ # Usage info
+ if len(sys.argv) > 1 and (sys.argv[1] == "-h" or sys.argv[1] == "--help"):
+ print(usage_msg)
+ exit(0)
+
+ # Check arguments
+ if len(sys.argv) < 2:
+ log_error(usage_msg)
+ exit(1)
+
+ # Do the work
+ get_datagrid_map(sys.argv[1])