Fix checkstyle whitespace issues - WHITESPACE ONLY
Change-Id: Ic205c1afd639c6008d61d9de95cb764eeb6238ca
diff --git a/src/main/java/net/floodlightcontroller/core/FloodlightContext.java b/src/main/java/net/floodlightcontroller/core/FloodlightContext.java
index aa4fe6b..2b915f0 100644
--- a/src/main/java/net/floodlightcontroller/core/FloodlightContext.java
+++ b/src/main/java/net/floodlightcontroller/core/FloodlightContext.java
@@ -1,28 +1,29 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core;
import java.util.concurrent.ConcurrentHashMap;
/**
- * This is a context object where floodlight listeners can register
+ * This is a context object where floodlight listeners can register
* and later retrieve context information associated with an
* event
+ *
* @author readams
*/
public class FloodlightContext {
diff --git a/src/main/java/net/floodlightcontroller/core/FloodlightContextStore.java b/src/main/java/net/floodlightcontroller/core/FloodlightContextStore.java
index 5455284..684cdd7 100644
--- a/src/main/java/net/floodlightcontroller/core/FloodlightContextStore.java
+++ b/src/main/java/net/floodlightcontroller/core/FloodlightContextStore.java
@@ -1,33 +1,33 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core;
public class FloodlightContextStore<V> {
-
+
@SuppressWarnings("unchecked")
public V get(FloodlightContext bc, String key) {
- return (V)bc.storage.get(key);
+ return (V) bc.storage.get(key);
}
-
+
public void put(FloodlightContext bc, String key, V value) {
bc.storage.put(key, value);
}
-
+
public void remove(FloodlightContext bc, String key) {
bc.storage.remove(key);
}
diff --git a/src/main/java/net/floodlightcontroller/core/FloodlightProvider.java b/src/main/java/net/floodlightcontroller/core/FloodlightProvider.java
index 0790c17..4183877 100644
--- a/src/main/java/net/floodlightcontroller/core/FloodlightProvider.java
+++ b/src/main/java/net/floodlightcontroller/core/FloodlightProvider.java
@@ -17,7 +17,7 @@
public class FloodlightProvider implements IFloodlightModule {
Controller controller;
-
+
@Override
public Collection<Class<? extends IFloodlightService>> getModuleServices() {
Collection<Class<? extends IFloodlightService>> services =
@@ -28,13 +28,13 @@
@Override
public Map<Class<? extends IFloodlightService>,
- IFloodlightService> getServiceImpls() {
+ IFloodlightService> getServiceImpls() {
controller = new Controller();
-
+
Map<Class<? extends IFloodlightService>,
- IFloodlightService> m =
+ IFloodlightService> m =
new HashMap<Class<? extends IFloodlightService>,
- IFloodlightService>();
+ IFloodlightService>();
m.put(IFloodlightProviderService.class, controller);
return m;
}
@@ -42,7 +42,7 @@
@Override
public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
Collection<Class<? extends IFloodlightService>> dependencies =
- new ArrayList<Class<? extends IFloodlightService>>(4);
+ new ArrayList<Class<? extends IFloodlightService>>(4);
dependencies.add(IRestApiService.class);
dependencies.add(IThreadPoolService.class);
// Following added by ONOS
@@ -54,17 +54,17 @@
@Override
public void init(FloodlightModuleContext context) throws FloodlightModuleException {
- controller.setRestApiService(
- context.getServiceImpl(IRestApiService.class));
- controller.setThreadPoolService(
- context.getServiceImpl(IThreadPoolService.class));
- // Following added by ONOS
- controller.setMastershipService(
- context.getServiceImpl(IControllerRegistryService.class));
- controller.setLinkDiscoveryService(
- context.getServiceImpl(ILinkDiscoveryService.class));
+ controller.setRestApiService(
+ context.getServiceImpl(IRestApiService.class));
+ controller.setThreadPoolService(
+ context.getServiceImpl(IThreadPoolService.class));
+ // Following added by ONOS
+ controller.setMastershipService(
+ context.getServiceImpl(IControllerRegistryService.class));
+ controller.setLinkDiscoveryService(
+ context.getServiceImpl(ILinkDiscoveryService.class));
- controller.init(context.getConfigParams(this));
+ controller.init(context.getConfigParams(this));
}
@Override
diff --git a/src/main/java/net/floodlightcontroller/core/IFloodlightProviderService.java b/src/main/java/net/floodlightcontroller/core/IFloodlightProviderService.java
index 08e06d9..1066c8b 100644
--- a/src/main/java/net/floodlightcontroller/core/IFloodlightProviderService.java
+++ b/src/main/java/net/floodlightcontroller/core/IFloodlightProviderService.java
@@ -1,7 +1,7 @@
/**
* Copyright 2011, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
@@ -37,40 +37,45 @@
/**
* A value stored in the floodlight context containing a parsed packet
- * representation of the payload of a packet-in message.
+ * representation of the payload of a packet-in message.
*/
- public static final String CONTEXT_PI_PAYLOAD =
+ public static final String CONTEXT_PI_PAYLOAD =
"net.floodlightcontroller.core.IFloodlightProvider.piPayload";
/**
* The role of the controller as used by the OF 1.2 and OVS failover and
* load-balancing mechanism.
*/
- public static enum Role { EQUAL, MASTER, SLAVE };
-
+ public static enum Role {
+ EQUAL, MASTER, SLAVE
+ }
+
/**
- * A FloodlightContextStore object that can be used to retrieve the
+ * A FloodlightContextStore object that can be used to retrieve the
* packet-in payload
*/
- public static final FloodlightContextStore<Ethernet> bcStore =
+ public static final FloodlightContextStore<Ethernet> bcStore =
new FloodlightContextStore<Ethernet>();
/**
* Adds an OpenFlow message listener
- * @param type The OFType the component wants to listen for
+ *
+ * @param type The OFType the component wants to listen for
* @param listener The component that wants to listen for the message
*/
public void addOFMessageListener(OFType type, IOFMessageListener listener);
/**
* Removes an OpenFlow message listener
- * @param type The OFType the component no long wants to listen for
+ *
+ * @param type The OFType the component no long wants to listen for
* @param listener The component that no longer wants to receive the message
*/
public void removeOFMessageListener(OFType type, IOFMessageListener listener);
-
+
/**
* Return a non-modifiable list of all current listeners
+ *
* @return listeners
*/
public Map<OFType, List<IOFMessageListener>> getListeners();
@@ -78,34 +83,38 @@
/**
* Returns an unmodifiable map of all actively connected OpenFlow switches. This doesn't
* contain switches that are connected but the controller's in the slave role.
+ *
* @return the set of actively connected switches
*/
public Map<Long, IOFSwitch> getSwitches();
-
+
/**
* Get the current mapping of controller IDs to their IP addresses
- * Returns a copy of the current mapping.
+ * Returns a copy of the current mapping.
+ *
* @see IHAListener
*/
- public Map<String,String> getControllerNodeIPs();
-
+ public Map<String, String> getControllerNodeIPs();
+
/**
* Gets the ID of the controller
*/
public String getControllerId();
-
+
/**
* Add a switch listener
+ *
* @param listener The module that wants to listen for events
*/
public void addOFSwitchListener(IOFSwitchListener listener);
/**
* Remove a switch listener
+ *
* @param listener The The module that no longer wants to listen for events
*/
public void removeOFSwitchListener(IOFSwitchListener listener);
-
+
/**
* Terminate the process
*/
@@ -113,7 +122,8 @@
/**
* Re-injects an OFMessage back into the packet processing chain
- * @param sw The switch to use for the message
+ *
+ * @param sw The switch to use for the message
* @param msg the message to inject
* @return True if successfully re-injected, false otherwise
*/
@@ -121,25 +131,28 @@
/**
* Re-injects an OFMessage back into the packet processing chain
- * @param sw The switch to use for the message
- * @param msg the message to inject
+ *
+ * @param sw The switch to use for the message
+ * @param msg the message to inject
* @param bContext a floodlight context to use if required
* @return True if successfully re-injected, false otherwise
*/
- public boolean injectOfMessage(IOFSwitch sw, OFMessage msg,
- FloodlightContext bContext);
+ public boolean injectOfMessage(IOFSwitch sw, OFMessage msg,
+ FloodlightContext bContext);
/**
* Process written messages through the message listeners for the controller
+ *
* @param sw The switch being written to
- * @param m the message
+ * @param m the message
* @param bc any accompanying context object
*/
- public void handleOutgoingMessage(IOFSwitch sw, OFMessage m,
- FloodlightContext bc);
+ public void handleOutgoingMessage(IOFSwitch sw, OFMessage m,
+ FloodlightContext bc);
/**
* Gets the BasicFactory
+ *
* @return an OpenFlow message factory
*/
public BasicFactory getOFMessageFactory();
@@ -148,25 +161,27 @@
* Run the main I/O loop of the Controller.
*/
public void run();
-
- /**
- * Return the controller start time in milliseconds
- * @return
- */
- public long getSystemStartTime();
-
- /**
- * Configure controller to always clear the flow table on the switch,
- * when it connects to controller. This will be true for first time switch
- * reconnect, as well as a switch re-attaching to Controller after HA
- * switch over to ACTIVE role
- */
- public void setAlwaysClearFlowsOnSwAdd(boolean value);
-
- /**
- * Publish updates to Controller updates queue
- * @param IUpdate
- */
- public void publishUpdate(IUpdate update);
+
+ /**
+ * Return the controller start time in milliseconds
+ *
+ * @return
+ */
+ public long getSystemStartTime();
+
+ /**
+ * Configure controller to always clear the flow table on the switch,
+ * when it connects to controller. This will be true for first time switch
+ * reconnect, as well as a switch re-attaching to Controller after HA
+ * switch over to ACTIVE role
+ */
+ public void setAlwaysClearFlowsOnSwAdd(boolean value);
+
+ /**
+ * Publish updates to Controller updates queue
+ *
+ * @param IUpdate
+ */
+ public void publishUpdate(IUpdate update);
}
diff --git a/src/main/java/net/floodlightcontroller/core/IListener.java b/src/main/java/net/floodlightcontroller/core/IListener.java
index 1bd6560..74ff1f3 100644
--- a/src/main/java/net/floodlightcontroller/core/IListener.java
+++ b/src/main/java/net/floodlightcontroller/core/IListener.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core;
@@ -21,18 +21,20 @@
public enum Command {
CONTINUE, STOP
}
-
+
/**
* The name assigned to this listener
+ *
* @return
*/
public String getName();
/**
* Check if the module called name is a callback ordering prerequisite
- * for this module. In other words, if this function returns true for
+ * for this module. In other words, if this function returns true for
* the given name, then this message listener will be called after that
* message listener.
+ *
* @param type the message type to which this applies
* @param name the name of the module
* @return whether name is a prerequisite.
@@ -41,9 +43,10 @@
/**
* Check if the module called name is a callback ordering post-requisite
- * for this module. In other words, if this function returns true for
+ * for this module. In other words, if this function returns true for
* the given name, then this message listener will be called before that
* message listener.
+ *
* @param type the message type to which this applies
* @param name the name of the module
* @return whether name is a post-requisite.
diff --git a/src/main/java/net/floodlightcontroller/core/IOFMessageListener.java b/src/main/java/net/floodlightcontroller/core/IOFMessageListener.java
index 00fdac1..b14af57 100644
--- a/src/main/java/net/floodlightcontroller/core/IOFMessageListener.java
+++ b/src/main/java/net/floodlightcontroller/core/IOFMessageListener.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core;
@@ -21,18 +21,17 @@
import org.openflow.protocol.OFType;
/**
- *
- *
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public interface IOFMessageListener extends IListener<OFType> {
- /**
- * This is the method Floodlight uses to call listeners with OpenFlow messages
- * @param sw the OpenFlow switch that sent this message
- * @param msg the message
- * @param cntx a Floodlight message context object you can use to pass
- * information between listeners
- * @return the command to continue or stop the execution
- */
- public Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx);
+ /**
+ * This is the method Floodlight uses to call listeners with OpenFlow messages
+ *
+ * @param sw the OpenFlow switch that sent this message
+ * @param msg the message
+ * @param cntx a Floodlight message context object you can use to pass
+ * information between listeners
+ * @return the command to continue or stop the execution
+ */
+ public Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx);
}
diff --git a/src/main/java/net/floodlightcontroller/core/IOFSwitch.java b/src/main/java/net/floodlightcontroller/core/IOFSwitch.java
index 5359812..90a7e12 100644
--- a/src/main/java/net/floodlightcontroller/core/IOFSwitch.java
+++ b/src/main/java/net/floodlightcontroller/core/IOFSwitch.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core;
@@ -35,8 +35,6 @@
import org.openflow.protocol.statistics.OFStatistics;
/**
- *
- *
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public interface IOFSwitch {
@@ -50,64 +48,69 @@
public static final String PROP_SUPPORTS_OFPP_TABLE = "supportsOfppTable";
public static final String PROP_SUPPORTS_OFPP_FLOOD = "supportsOfppFlood";
public static final String PROP_SUPPORTS_NETMASK_TBL = "supportsNetmaskTbl";
-
+
/**
* Writes to the OFMessage to the output stream.
* The message will be handed to the floodlightProvider for possible filtering
* and processing by message listeners
- * @param m
- * @param bc
- * @throws IOException
+ *
+ * @param m
+ * @param bc
+ * @throws IOException
*/
- public void write(OFMessage m, FloodlightContext bc) throws IOException;
-
+ public void write(OFMessage m, FloodlightContext bc) throws IOException;
+
/**
* Writes the list of messages to the output stream
* The message will be handed to the floodlightProvider for possible filtering
* and processing by message listeners.
+ *
* @param msglist
* @param bc
* @throws IOException
*/
public void write(List<OFMessage> msglist, FloodlightContext bc) throws IOException;
-
+
/**
- *
* @throws IOException
*/
public void disconnectOutputStream();
/**
* FIXME: remove getChannel(). All access to the channel should be through
- * wrapper functions in IOFSwitch
+ * wrapper functions in IOFSwitch
+ *
* @return
*/
public Channel getChannel();
/**
* Returns switch features from features Reply
+ *
* @return
*/
public int getBuffers();
-
+
public int getActions();
-
+
public int getCapabilities();
-
+
public byte getTables();
/**
* Set the OFFeaturesReply message returned by the switch during initial
* handshake.
+ *
* @param featuresReply
*/
public void setFeaturesReply(OFFeaturesReply featuresReply);
-
+
/**
* Set the SwitchProperties based on it's description
+ *
* @param description
*/
- public void setSwitchProperties(OFDescriptionStatistics description);
+ public void setSwitchProperties(OFDescriptionStatistics description);
/**
* Get list of all enabled ports. This will typically be different from
@@ -115,16 +118,18 @@
* snapshot of the ports at the time the switch connected to the controller
* whereas this port list also reflects the port status messages that have
* been received.
+ *
* @return Unmodifiable list of ports not backed by the underlying collection
*/
public Collection<OFPhysicalPort> getEnabledPorts();
-
+
/**
* Get list of the port numbers of all enabled ports. This will typically
* be different from the list of ports in the OFFeaturesReply, since that
- * one is a static snapshot of the ports at the time the switch connected
+ * one is a static snapshot of the ports at the time the switch connected
* to the controller whereas this port list also reflects the port status
* messages that have been received.
+ *
* @return Unmodifiable list of ports not backed by the underlying collection
*/
public Collection<Short> getEnabledPortNumbers();
@@ -133,24 +138,27 @@
* Retrieve the port object by the port number. The port object
* is the one that reflects the port status updates that have been
* received, not the one from the features reply.
+ *
* @param portNumber
* @return port object
*/
public OFPhysicalPort getPort(short portNumber);
-
+
/**
* Retrieve the port object by the port name. The port object
* is the one that reflects the port status updates that have been
* received, not the one from the features reply.
+ *
* @param portName
* @return port object
*/
public OFPhysicalPort getPort(String portName);
-
+
/**
* Add or modify a switch port. This is called by the core controller
* code in response to a OFPortStatus message. It should not typically be
* called by other floodlight applications.
+ *
* @param port
*/
public void setPort(OFPhysicalPort port);
@@ -159,25 +167,28 @@
* Delete a port for the switch. This is called by the core controller
* code in response to a OFPortStatus message. It should not typically be
* called by other floodlight applications.
+ *
* @param portNumber
*/
public void deletePort(short portNumber);
-
+
/**
* Delete a port for the switch. This is called by the core controller
* code in response to a OFPortStatus message. It should not typically be
* called by other floodlight applications.
+ *
* @param portName
*/
public void deletePort(String portName);
-
+
/**
* Get list of all ports. This will typically be different from
* the list of ports in the OFFeaturesReply, since that one is a static
* snapshot of the ports at the time the switch connected to the controller
* whereas this port list also reflects the port status messages that have
* been received.
- * @return Unmodifiable list of ports
+ *
+ * @return Unmodifiable list of ports
*/
public Collection<OFPhysicalPort> getPorts();
@@ -187,7 +198,7 @@
* (not configured down nor link down nor in spanning tree blocking state)
*/
public boolean portEnabled(short portName);
-
+
/**
* @param portNumber
* @return Whether a port is enabled per latest port status message
@@ -204,30 +215,35 @@
/**
* Get the datapathId of the switch
+ *
* @return
*/
public long getId();
/**
* Get a string version of the ID for this switch
+ *
* @return
*/
public String getStringId();
-
+
/**
* Retrieves attributes of this switch
+ *
* @return
*/
public Map<Object, Object> getAttributes();
/**
* Retrieves the date the switch connected to this controller
+ *
* @return the date
*/
public Date getConnectedSince();
/**
* Returns the next available transaction id
+ *
* @return
*/
public int getNextTransactionId();
@@ -238,24 +254,25 @@
*
* @param request statistics request
* @return Future object wrapping OFStatisticsReply
- * @throws IOException
+ * @throws IOException
*/
public Future<List<OFStatistics>> getStatistics(OFStatisticsRequest request)
throws IOException;
-
+
/**
* Returns a Future object that can be used to retrieve the asynchronous
* OFStatisticsReply when it is available.
*
* @param request statistics request
* @return Future object wrapping OFStatisticsReply
- * @throws IOException
+ * @throws IOException
*/
public Future<OFFeaturesReply> getFeaturesReplyFromSwitch()
throws IOException;
/**
* Deliver the featuresReply future reply
+ *
* @param reply the reply to deliver
*/
void deliverOFFeaturesReply(OFMessage reply);
@@ -269,42 +286,48 @@
/**
* Check if the switch is still connected;
* Only call while holding processMessageLock
+ *
* @return whether the switch is still disconnected
*/
public boolean isConnected();
-
+
/**
* Set whether the switch is connected
* Only call while holding modifySwitchLock
+ *
* @param connected whether the switch is connected
*/
public void setConnected(boolean connected);
-
+
/**
* Get the current role of the controller for the switch
+ *
* @return the role of the controller
*/
public Role getRole();
-
+
/**
* Check if the controller is an active controller for the switch.
* The controller is active if its role is MASTER or EQUAL.
+ *
* @return whether the controller is active
*/
public boolean isActive();
-
+
/**
* Deliver the statistics future reply
+ *
* @param reply the reply to deliver
*/
public void deliverStatisticsReply(OFMessage reply);
-
+
/**
* Cancel the statistics reply with the given transaction ID
+ *
* @param transactionId the transaction ID
*/
public void cancelStatisticsReply(int transactionId);
-
+
/**
* Cancel all statistics replies
*/
@@ -312,6 +335,7 @@
/**
* Checks if a specific switch property exists for this switch
+ *
* @param name name of property
* @return value for name
*/
@@ -319,6 +343,7 @@
/**
* Set properties for switch specific behavior
+ *
* @param name name of property
* @return value for name
*/
@@ -326,13 +351,15 @@
/**
* Set properties for switch specific behavior
- * @param name name of property
+ *
+ * @param name name of property
* @param value value for name
*/
void setAttribute(String name, Object value);
/**
* Set properties for switch specific behavior
+ *
* @param name name of property
* @return current value for name or null (if not present)
*/
@@ -345,14 +372,16 @@
/**
* Update broadcast cache
+ *
* @param data
* @return true if there is a cache hit
- * false if there is no cache hit.
+ * false if there is no cache hit.
*/
public boolean updateBroadcastCache(Long entry, Short port);
-
+
/**
* Get the portBroadcastCacheHits
+ *
* @return
*/
public Map<Short, Long> getPortBroadcastHits();
@@ -360,21 +389,22 @@
/**
* Send a flow statistics request to the switch. This call returns after
* sending the stats. request to the switch.
+ *
* @param request flow statistics request message
- * @param xid transaction id, must be obtained by using the getXid() API.
- * @param caller the caller of the API. receive() callback of this
- * caller would be called when the reply from the switch is received.
- * @return the transaction id for the message sent to the switch. The
+ * @param xid transaction id, must be obtained by using the getXid() API.
+ * @param caller the caller of the API. receive() callback of this
+ * caller would be called when the reply from the switch is received.
+ * @return the transaction id for the message sent to the switch. The
* transaction id can be used to match the response with the request. Note
* that the transaction id is unique only within the scope of this switch.
* @throws IOException
*/
public void sendStatsQuery(OFStatisticsRequest request, int xid,
- IOFMessageListener caller) throws IOException;
+ IOFMessageListener caller) throws IOException;
/**
* Flush all flows queued for this switch in the current thread.
* NOTE: The contract is limited to the current thread
*/
- public void flush();
+ public void flush();
}
diff --git a/src/main/java/net/floodlightcontroller/core/IOFSwitchFilter.java b/src/main/java/net/floodlightcontroller/core/IOFSwitchFilter.java
index 134ba98..3bb4d10 100644
--- a/src/main/java/net/floodlightcontroller/core/IOFSwitchFilter.java
+++ b/src/main/java/net/floodlightcontroller/core/IOFSwitchFilter.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core;
diff --git a/src/main/java/net/floodlightcontroller/core/IOFSwitchListener.java b/src/main/java/net/floodlightcontroller/core/IOFSwitchListener.java
index 1bc258b..1a5cd4a 100644
--- a/src/main/java/net/floodlightcontroller/core/IOFSwitchListener.java
+++ b/src/main/java/net/floodlightcontroller/core/IOFSwitchListener.java
@@ -1,25 +1,23 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core;
/**
- *
- *
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public interface IOFSwitchListener {
@@ -27,24 +25,27 @@
/**
* Fired when a switch is connected to the controller, and has sent
* a features reply.
+ *
* @param sw
*/
public void addedSwitch(IOFSwitch sw);
/**
* Fired when a switch is disconnected from the controller.
+ *
* @param sw
*/
public void removedSwitch(IOFSwitch sw);
-
+
/**
* Fired when ports on a switch change (any change to the collection
* of OFPhysicalPorts and/or to a particular port)
*/
public void switchPortChanged(Long switchId);
-
+
/**
* The name assigned to this listener
+ *
* @return
*/
public String getName();
diff --git a/src/main/java/net/floodlightcontroller/core/IUpdate.java b/src/main/java/net/floodlightcontroller/core/IUpdate.java
index 950bc0f..f0f866d 100644
--- a/src/main/java/net/floodlightcontroller/core/IUpdate.java
+++ b/src/main/java/net/floodlightcontroller/core/IUpdate.java
@@ -1,8 +1,8 @@
package net.floodlightcontroller.core;
public interface IUpdate {
-
- /**
+
+ /**
* Calls the appropriate listeners
*/
public void dispatch();
diff --git a/src/main/java/net/floodlightcontroller/core/annotations/LogMessageCategory.java b/src/main/java/net/floodlightcontroller/core/annotations/LogMessageCategory.java
index e9abf02..37f850b 100644
--- a/src/main/java/net/floodlightcontroller/core/annotations/LogMessageCategory.java
+++ b/src/main/java/net/floodlightcontroller/core/annotations/LogMessageCategory.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2012, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2012, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.annotations;
@@ -22,12 +22,14 @@
/**
* Annotation used to set the category for log messages for a class
+ *
* @author readams
*/
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface LogMessageCategory {
/**
* The category for the log messages for this class
+ *
* @return
*/
String value() default "Core";
diff --git a/src/main/java/net/floodlightcontroller/core/annotations/LogMessageDoc.java b/src/main/java/net/floodlightcontroller/core/annotations/LogMessageDoc.java
index 80af1a7..6b5d6b8 100644
--- a/src/main/java/net/floodlightcontroller/core/annotations/LogMessageDoc.java
+++ b/src/main/java/net/floodlightcontroller/core/annotations/LogMessageDoc.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2012, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2012, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.annotations;
@@ -23,48 +23,56 @@
/**
* Annotation used to document log messages. This can be used to generate
* documentation on syslog output.
+ *
* @author readams
*/
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface LogMessageDoc {
public static final String NO_ACTION = "No action is required.";
public static final String UNKNOWN_ERROR = "An unknown error occured";
- public static final String GENERIC_ACTION =
+ public static final String GENERIC_ACTION =
"Examine the returned error or exception and take " +
- "appropriate action.";
- public static final String CHECK_SWITCH =
- "Check the health of the indicated switch. " +
- "Test and troubleshoot IP connectivity.";
- public static final String CHECK_CONTROLLER =
- "Verify controller system health, CPU usage, and memory. " +
- "Rebooting the controller node may help if the controller " +
- "node is in a distressed state.";
+ "appropriate action.";
+ public static final String CHECK_SWITCH =
+ "Check the health of the indicated switch. " +
+ "Test and troubleshoot IP connectivity.";
+ public static final String CHECK_CONTROLLER =
+ "Verify controller system health, CPU usage, and memory. " +
+ "Rebooting the controller node may help if the controller " +
+ "node is in a distressed state.";
public static final String REPORT_CONTROLLER_BUG =
"This is likely a defect in the controller. Please report this " +
- "issue. Restarting the controller or switch may help to " +
- "alleviate.";
+ "issue. Restarting the controller or switch may help to " +
+ "alleviate.";
public static final String REPORT_SWITCH_BUG =
"This is likely a defect in the switch. Please report this " +
- "issue. Restarting the controller or switch may help to " +
- "alleviate.";
+ "issue. Restarting the controller or switch may help to " +
+ "alleviate.";
/**
* The log level for the log message
+ *
* @return the log level as a tring
*/
String level() default "INFO";
+
/**
* The message that will be printed
+ *
* @return the message
*/
String message() default UNKNOWN_ERROR;
+
/**
* An explanation of the meaning of the log message
+ *
* @return the explanation
*/
String explanation() default UNKNOWN_ERROR;
+
/**
* The recommendated action associated with the log message
+ *
* @return the recommendation
*/
String recommendation() default NO_ACTION;
diff --git a/src/main/java/net/floodlightcontroller/core/annotations/LogMessageDocs.java b/src/main/java/net/floodlightcontroller/core/annotations/LogMessageDocs.java
index 663baf0..aeedf4d 100644
--- a/src/main/java/net/floodlightcontroller/core/annotations/LogMessageDocs.java
+++ b/src/main/java/net/floodlightcontroller/core/annotations/LogMessageDocs.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2012, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2012, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.annotations;
@@ -24,12 +24,14 @@
* Annotation used to document log messages. This can be used to generate
* documentation on syslog output. This version allows multiple log messages
* to be documentated on an interface.
+ *
* @author readams
*/
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface LogMessageDocs {
/**
* A list of {@link LogMessageDoc} elements
+ *
* @return the list of log message doc
*/
LogMessageDoc[] value();
diff --git a/src/main/java/net/floodlightcontroller/core/internal/CmdLineSettings.java b/src/main/java/net/floodlightcontroller/core/internal/CmdLineSettings.java
index 7641a7c..d2d74c4 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/CmdLineSettings.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/CmdLineSettings.java
@@ -8,10 +8,10 @@
public class CmdLineSettings {
public static final String DEFAULT_CONFIG_FILE = "config/floodlight.properties";
- @Option(name="-cf", aliases="--configFile", metaVar="FILE", usage="Floodlight configuration file")
+ @Option(name = "-cf", aliases = "--configFile", metaVar = "FILE", usage = "Floodlight configuration file")
private String configFile = DEFAULT_CONFIG_FILE;
-
+
public String getModuleFile() {
- return configFile;
+ return configFile;
}
}
diff --git a/src/main/java/net/floodlightcontroller/core/internal/Controller.java b/src/main/java/net/floodlightcontroller/core/internal/Controller.java
index d475fa6..74f0802 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/Controller.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/Controller.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.internal;
@@ -124,26 +124,26 @@
/**
* The main controller class. Handles all setup and network listeners
- *
+ * <p/>
* Extensions made by ONOS are:
- * - Detailed Port event: PORTCHANGED -> {PORTCHANGED, PORTADDED, PORTREMOVED}
- * Available as net.onrc.onos.core.main.IOFSwitchPortListener
+ * - Detailed Port event: PORTCHANGED -> {PORTCHANGED, PORTADDED, PORTREMOVED}
+ * Available as net.onrc.onos.core.main.IOFSwitchPortListener
* - Distributed ownership control of switch through RegistryService(IControllerRegistryService)
* - Register ONOS services. (IControllerRegistryService)
* - Additional DEBUG logs
* - Try using hostname as controller ID, when ID was not explicitly given.
*/
public class Controller implements IFloodlightProviderService {
-
+
protected final static Logger log = LoggerFactory.getLogger(Controller.class);
- private static final String ERROR_DATABASE =
+ private static final String ERROR_DATABASE =
"The controller could not communicate with the system database.";
-
+
protected BasicFactory factory;
protected ConcurrentMap<OFType,
- ListenerDispatcher<OFType,IOFMessageListener>>
- messageListeners;
+ ListenerDispatcher<OFType, IOFMessageListener>>
+ messageListeners;
// The activeSwitches map contains only those switches that are actively
// being controlled by us -- it doesn't contain switches that are
// in the slave role
@@ -154,45 +154,45 @@
// We add a switch to this set after it successfully completes the
// handshake. Access to this Set needs to be synchronized with roleChanger
protected HashSet<OFSwitchImpl> connectedSwitches;
-
+
// The controllerNodeIPsCache maps Controller IDs to their IP address.
// It's only used by handleControllerNodeIPsChanged
protected HashMap<String, String> controllerNodeIPsCache;
-
+
protected Set<IOFSwitchListener> switchListeners;
protected BlockingQueue<IUpdate> updates;
-
+
// Module dependencies
protected IRestApiService restApi;
protected IThreadPoolService threadPool;
protected IControllerRegistryService registryService;
-
+
protected ILinkDiscoveryService linkDiscovery;
-
+
// Configuration options
protected int openFlowPort = 6633;
protected int workerThreads = 0;
// The id for this controller node. Should be unique for each controller
// node in a controller cluster.
protected String controllerId = "localhost";
-
+
// The current role of the controller.
// If the controller isn't configured to support roles, then this is null.
protected Role role;
// A helper that handles sending and timeout handling for role requests
protected RoleChanger roleChanger;
-
+
// Start time of the controller
protected long systemStartTime;
-
+
// Flag to always flush flow table on switch reconnect (HA or otherwise)
protected boolean alwaysClearFlowsOnSwAdd = false;
-
+
// Perf. related configuration
protected static final int SEND_BUFFER_SIZE = 4 * 1024 * 1024;
protected static final int BATCH_MAX_SIZE = 100;
- protected static final boolean ALWAYS_DECODE_ETH = true;
-
+ protected static final boolean ALWAYS_DECODE_ETH = true;
+
public enum SwitchUpdateType {
ADDED,
REMOVED,
@@ -200,24 +200,27 @@
PORTADDED,
PORTREMOVED
}
-
+
/**
- * Update message indicating a switch was added or removed
+ * Update message indicating a switch was added or removed
* ONOS: This message extended to indicate Port add or removed event.
*/
protected class SwitchUpdate implements IUpdate {
public IOFSwitch sw;
public OFPhysicalPort port; // Added by ONOS
public SwitchUpdateType switchUpdateType;
+
public SwitchUpdate(IOFSwitch sw, SwitchUpdateType switchUpdateType) {
this.sw = sw;
this.switchUpdateType = switchUpdateType;
}
+
public SwitchUpdate(IOFSwitch sw, OFPhysicalPort port, SwitchUpdateType switchUpdateType) {
this.sw = sw;
this.port = port;
this.switchUpdateType = switchUpdateType;
}
+
public void dispatch() {
if (log.isTraceEnabled()) {
log.trace("Dispatching switch update {} {}",
@@ -225,7 +228,7 @@
}
if (switchListeners != null) {
for (IOFSwitchListener listener : switchListeners) {
- switch(switchUpdateType) {
+ switch (switchUpdateType) {
case ADDED:
listener.addedSwitch(sw);
break;
@@ -236,138 +239,139 @@
listener.switchPortChanged(sw.getId());
break;
case PORTADDED:
- if (listener instanceof IOFSwitchPortListener) {
- ((IOFSwitchPortListener) listener).switchPortAdded(sw.getId(), port);
- }
- break;
+ if (listener instanceof IOFSwitchPortListener) {
+ ((IOFSwitchPortListener) listener).switchPortAdded(sw.getId(), port);
+ }
+ break;
case PORTREMOVED:
- if (listener instanceof IOFSwitchPortListener) {
- ((IOFSwitchPortListener) listener).switchPortRemoved(sw.getId(), port);
- }
- break;
+ if (listener instanceof IOFSwitchPortListener) {
+ ((IOFSwitchPortListener) listener).switchPortRemoved(sw.getId(), port);
+ }
+ break;
default:
- break;
+ break;
}
}
}
}
}
-
+
// ***************
// Getters/Setters
// ***************
-
+
public void setRestApiService(IRestApiService restApi) {
this.restApi = restApi;
}
-
+
public void setThreadPoolService(IThreadPoolService tp) {
this.threadPool = tp;
}
- public void setMastershipService(IControllerRegistryService serviceImpl) {
- this.registryService = serviceImpl;
- }
-
- public void setLinkDiscoveryService(ILinkDiscoveryService linkDiscovery) {
- this.linkDiscovery = linkDiscovery;
- }
-
- public void publishUpdate(IUpdate update) {
- try {
- this.updates.put(update);
- } catch (InterruptedException e) {
- log.error("Failure adding update to queue", e);
- }
+ public void setMastershipService(IControllerRegistryService serviceImpl) {
+ this.registryService = serviceImpl;
}
-
+
+ public void setLinkDiscoveryService(ILinkDiscoveryService linkDiscovery) {
+ this.linkDiscovery = linkDiscovery;
+ }
+
+ public void publishUpdate(IUpdate update) {
+ try {
+ this.updates.put(update);
+ } catch (InterruptedException e) {
+ log.error("Failure adding update to queue", e);
+ }
+ }
+
// **********************
// ChannelUpstreamHandler
// **********************
-
+
/**
* Return a new channel handler for processing a switch connections
+ *
* @param state The channel state object for the connection
* @return the new channel handler
*/
protected ChannelUpstreamHandler getChannelHandler(OFChannelState state) {
return new OFChannelHandler(state);
}
-
+
protected class RoleChangeCallback implements ControlChangeCallback {
- @Override
- public void controlChanged(long dpid, boolean hasControl) {
- log.info("Role change callback for switch {}, hasControl {}",
- HexString.toHexString(dpid), hasControl);
-
- synchronized(roleChanger){
- OFSwitchImpl sw = null;
- for (OFSwitchImpl connectedSw : connectedSwitches){
- if (connectedSw.getId() == dpid){
- sw = connectedSw;
- break;
- }
- }
- if (sw == null){
- log.warn("Switch {} not found in connected switches",
- HexString.toHexString(dpid));
- return;
- }
-
- Role role = null;
-
- /*
- * issue #229
- * Cannot rely on sw.getRole() as it can be behind due to pending
- * role changes in the queue. Just submit it and late the RoleChanger
- * handle duplicates.
- */
+ @Override
+ public void controlChanged(long dpid, boolean hasControl) {
+ log.info("Role change callback for switch {}, hasControl {}",
+ HexString.toHexString(dpid), hasControl);
- if (hasControl){
- role = Role.MASTER;
- }
- else {
- role = Role.SLAVE;
- }
+ synchronized (roleChanger) {
+ OFSwitchImpl sw = null;
+ for (OFSwitchImpl connectedSw : connectedSwitches) {
+ if (connectedSw.getId() == dpid) {
+ sw = connectedSw;
+ break;
+ }
+ }
+ if (sw == null) {
+ log.warn("Switch {} not found in connected switches",
+ HexString.toHexString(dpid));
+ return;
+ }
- log.debug("Sending role request {} msg to {}", role, sw);
- Collection<OFSwitchImpl> swList = new ArrayList<OFSwitchImpl>(1);
- swList.add(sw);
- roleChanger.submitRequest(swList, role);
+ Role role = null;
+
+ /*
+ * issue #229
+ * Cannot rely on sw.getRole() as it can be behind due to pending
+ * role changes in the queue. Just submit it and late the RoleChanger
+ * handle duplicates.
+ */
- }
-
- }
+ if (hasControl) {
+ role = Role.MASTER;
+ } else {
+ role = Role.SLAVE;
+ }
+
+ log.debug("Sending role request {} msg to {}", role, sw);
+ Collection<OFSwitchImpl> swList = new ArrayList<OFSwitchImpl>(1);
+ swList.add(sw);
+ roleChanger.submitRequest(swList, role);
+
+ }
+
+ }
}
-
+
/**
* Channel handler deals with the switch connection and dispatches
* switch messages to the appropriate locations.
+ *
* @author readams
*/
- protected class OFChannelHandler
- extends IdleStateAwareChannelUpstreamHandler {
+ protected class OFChannelHandler
+ extends IdleStateAwareChannelUpstreamHandler {
protected OFSwitchImpl sw;
protected OFChannelState state;
-
+
public OFChannelHandler(OFChannelState state) {
this.state = state;
}
@Override
- @LogMessageDoc(message="New switch connection from {ip address}",
- explanation="A new switch has connected from the " +
- "specified IP address")
+ @LogMessageDoc(message = "New switch connection from {ip address}",
+ explanation = "A new switch has connected from the " +
+ "specified IP address")
public void channelConnected(ChannelHandlerContext ctx,
ChannelStateEvent e) throws Exception {
log.info("New switch connection from {}",
- e.getChannel().getRemoteAddress());
-
+ e.getChannel().getRemoteAddress());
+
sw = new OFSwitchImpl();
sw.setChannel(e.getChannel());
sw.setFloodlightProvider(Controller.this);
sw.setThreadPoolService(threadPool);
-
+
List<OFMessage> msglist = new ArrayList<OFMessage>(1);
msglist.add(factory.getMessage(OFType.HELLO));
e.getChannel().write(msglist);
@@ -375,8 +379,8 @@
}
@Override
- @LogMessageDoc(message="Disconnected switch {switch information}",
- explanation="The specified switch has disconnected.")
+ @LogMessageDoc(message = "Disconnected switch {switch information}",
+ explanation = "The specified switch has disconnected.")
public void channelDisconnected(ChannelHandlerContext ctx,
ChannelStateEvent e) throws Exception {
if (sw != null && state.hsState == HandshakeState.READY) {
@@ -386,10 +390,10 @@
// same DPID
removeSwitch(sw);
}
- synchronized(roleChanger) {
- if (controlRequested) {
- registryService.releaseControl(sw.getId());
- }
+ synchronized (roleChanger) {
+ if (controlRequested) {
+ registryService.releaseControl(sw.getId());
+ }
connectedSwitches.remove(sw);
}
sw.setConnected(false);
@@ -399,41 +403,41 @@
@Override
@LogMessageDocs({
- @LogMessageDoc(level="ERROR",
- message="Disconnecting switch {switch} due to read timeout",
- explanation="The connected switch has failed to send any " +
+ @LogMessageDoc(level = "ERROR",
+ message = "Disconnecting switch {switch} due to read timeout",
+ explanation = "The connected switch has failed to send any " +
"messages or respond to echo requests",
- recommendation=LogMessageDoc.CHECK_SWITCH),
- @LogMessageDoc(level="ERROR",
- message="Disconnecting switch {switch}: failed to " +
- "complete handshake",
- explanation="The switch did not respond correctly " +
+ recommendation = LogMessageDoc.CHECK_SWITCH),
+ @LogMessageDoc(level = "ERROR",
+ message = "Disconnecting switch {switch}: failed to " +
+ "complete handshake",
+ explanation = "The switch did not respond correctly " +
"to handshake messages",
- recommendation=LogMessageDoc.CHECK_SWITCH),
- @LogMessageDoc(level="ERROR",
- message="Disconnecting switch {switch} due to IO Error: {}",
- explanation="There was an error communicating with the switch",
- recommendation=LogMessageDoc.CHECK_SWITCH),
- @LogMessageDoc(level="ERROR",
- message="Disconnecting switch {switch} due to switch " +
- "state error: {error}",
- explanation="The switch sent an unexpected message",
- recommendation=LogMessageDoc.CHECK_SWITCH),
- @LogMessageDoc(level="ERROR",
- message="Disconnecting switch {switch} due to " +
- "message parse failure",
- explanation="Could not parse a message from the switch",
- recommendation=LogMessageDoc.CHECK_SWITCH),
- @LogMessageDoc(level="ERROR",
- message="Could not process message: queue full",
- explanation="OpenFlow messages are arriving faster than " +
+ recommendation = LogMessageDoc.CHECK_SWITCH),
+ @LogMessageDoc(level = "ERROR",
+ message = "Disconnecting switch {switch} due to IO Error: {}",
+ explanation = "There was an error communicating with the switch",
+ recommendation = LogMessageDoc.CHECK_SWITCH),
+ @LogMessageDoc(level = "ERROR",
+ message = "Disconnecting switch {switch} due to switch " +
+ "state error: {error}",
+ explanation = "The switch sent an unexpected message",
+ recommendation = LogMessageDoc.CHECK_SWITCH),
+ @LogMessageDoc(level = "ERROR",
+ message = "Disconnecting switch {switch} due to " +
+ "message parse failure",
+ explanation = "Could not parse a message from the switch",
+ recommendation = LogMessageDoc.CHECK_SWITCH),
+ @LogMessageDoc(level = "ERROR",
+ message = "Could not process message: queue full",
+ explanation = "OpenFlow messages are arriving faster than " +
" the controller can process them.",
- recommendation=LogMessageDoc.CHECK_CONTROLLER),
- @LogMessageDoc(level="ERROR",
- message="Error while processing message " +
- "from switch {switch} {cause}",
- explanation="An error occurred processing the switch message",
- recommendation=LogMessageDoc.GENERIC_ACTION)
+ recommendation = LogMessageDoc.CHECK_CONTROLLER),
+ @LogMessageDoc(level = "ERROR",
+ message = "Error while processing message " +
+ "from switch {switch} {cause}",
+ explanation = "An error occurred processing the switch message",
+ recommendation = LogMessageDoc.GENERIC_ACTION)
})
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
@@ -442,29 +446,29 @@
log.error("Disconnecting switch {} due to read timeout", sw);
ctx.getChannel().close();
} else if (e.getCause() instanceof HandshakeTimeoutException) {
- log.error("Disconnecting switch {}: failed to complete handshake",
- sw);
+ log.error("Disconnecting switch {}: failed to complete handshake",
+ sw);
ctx.getChannel().close();
} else if (e.getCause() instanceof ClosedChannelException) {
//log.warn("Channel for sw {} already closed", sw);
} else if (e.getCause() instanceof IOException) {
log.error("Disconnecting switch {} due to IO Error: {}",
- sw, e.getCause().getMessage());
+ sw, e.getCause().getMessage());
ctx.getChannel().close();
} else if (e.getCause() instanceof SwitchStateException) {
- log.error("Disconnecting switch {} due to switch state error: {}",
- sw, e.getCause().getMessage());
+ log.error("Disconnecting switch {} due to switch state error: {}",
+ sw, e.getCause().getMessage());
ctx.getChannel().close();
} else if (e.getCause() instanceof MessageParseException) {
log.error("Disconnecting switch " + sw +
- " due to message parse failure",
- e.getCause());
+ " due to message parse failure",
+ e.getCause());
ctx.getChannel().close();
} else if (e.getCause() instanceof RejectedExecutionException) {
log.warn("Could not process message: queue full");
} else {
log.error("Error while processing message from switch " + sw,
- e.getCause());
+ e.getCause());
ctx.getChannel().close();
}
}
@@ -482,13 +486,12 @@
throws Exception {
if (e.getMessage() instanceof List) {
@SuppressWarnings("unchecked")
- List<OFMessage> msglist = (List<OFMessage>)e.getMessage();
+ List<OFMessage> msglist = (List<OFMessage>) e.getMessage();
for (OFMessage ofm : msglist) {
try {
processOFMessage(ofm);
- }
- catch (Exception ex) {
+ } catch (Exception ex) {
// We are the last handler in the stream, so run the
// exception through the channel again by passing in
// ctx.getChannel().
@@ -500,78 +503,78 @@
OFSwitchImpl.flush_all();
}
}
-
+
/**
* Process the request for the switch description
*/
- @LogMessageDoc(level="ERROR",
- message="Exception in reading description " +
+ @LogMessageDoc(level = "ERROR",
+ message = "Exception in reading description " +
" during handshake {exception}",
- explanation="Could not process the switch description string",
- recommendation=LogMessageDoc.CHECK_SWITCH)
+ explanation = "Could not process the switch description string",
+ recommendation = LogMessageDoc.CHECK_SWITCH)
void processSwitchDescReply() {
try {
// Read description, if it has been updated
@SuppressWarnings("unchecked")
Future<List<OFStatistics>> desc_future =
- (Future<List<OFStatistics>>)sw.
- getAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE);
- List<OFStatistics> values =
+ (Future<List<OFStatistics>>) sw.
+ getAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE);
+ List<OFStatistics> values =
desc_future.get(0, TimeUnit.MILLISECONDS);
if (values != null) {
- OFDescriptionStatistics description =
+ OFDescriptionStatistics description =
new OFDescriptionStatistics();
- ChannelBuffer data =
+ ChannelBuffer data =
ChannelBuffers.buffer(description.getLength());
for (OFStatistics f : values) {
f.writeTo(data);
description.readFrom(data);
break; // SHOULD be a list of length 1
}
- sw.setAttribute(IOFSwitch.SWITCH_DESCRIPTION_DATA,
- description);
+ sw.setAttribute(IOFSwitch.SWITCH_DESCRIPTION_DATA,
+ description);
sw.setSwitchProperties(description);
data = null;
}
-
+
sw.removeAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE);
state.hasDescription = true;
checkSwitchReady();
- }
- catch (InterruptedException ex) {
+ } catch (InterruptedException ex) {
// Ignore
- }
- catch (TimeoutException ex) {
+ } catch (TimeoutException ex) {
// Ignore
} catch (Exception ex) {
- log.error("Exception in reading description " +
- " during handshake", ex);
+ log.error("Exception in reading description " +
+ " during handshake", ex);
}
}
/**
* Send initial switch setup information that we need before adding
* the switch
+ *
* @throws IOException
*/
void sendHelloConfiguration() throws IOException {
// Send initial Features Request
- log.debug("Sending FEATURES_REQUEST to {}", sw);
+ log.debug("Sending FEATURES_REQUEST to {}", sw);
sw.write(factory.getMessage(OFType.FEATURES_REQUEST), null);
}
-
+
/**
* Send the configuration requests we can only do after we have
* the features reply
+ *
* @throws IOException
*/
void sendFeatureReplyConfiguration() throws IOException {
- log.debug("Sending CONFIG_REQUEST to {}", sw);
+ log.debug("Sending CONFIG_REQUEST to {}", sw);
// Ensure we receive the full packet via PacketIn
OFSetConfig config = (OFSetConfig) factory
.getMessage(OFType.SET_CONFIG);
config.setMissSendLength((short) 0xffff)
- .setLengthU(OFSwitchConfig.MINIMUM_LENGTH);
+ .setLengthU(OFSwitchConfig.MINIMUM_LENGTH);
sw.write(config, null);
sw.write(factory.getMessage(OFType.GET_CONFIG_REQUEST),
null);
@@ -580,22 +583,23 @@
OFStatisticsRequest req = new OFStatisticsRequest();
req.setStatisticType(OFStatisticsType.DESC);
req.setLengthU(req.getLengthU());
- Future<List<OFStatistics>> dfuture =
+ Future<List<OFStatistics>> dfuture =
sw.getStatistics(req);
sw.setAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE,
dfuture);
}
-
- volatile Boolean controlRequested = Boolean.FALSE;
+
+ volatile Boolean controlRequested = Boolean.FALSE;
+
protected void checkSwitchReady() {
if (state.hsState == HandshakeState.FEATURES_REPLY &&
state.hasDescription && state.hasGetConfigReply) {
-
+
state.hsState = HandshakeState.READY;
log.debug("Handshake with {} complete", sw);
-
- synchronized(roleChanger) {
+
+ synchronized (roleChanger) {
// We need to keep track of all of the switches that are connected
// to the controller, in any role, so that we can later send the
// role request messages when the controller role changes.
@@ -604,26 +608,25 @@
// we were able to add this new switch to connectedSwitches
// *and* send the current role to the new switch.
connectedSwitches.add(sw);
-
+
if (role != null) {
- //Put the switch in SLAVE mode until we know we have control
- log.debug("Setting new switch {} to SLAVE", sw.getStringId());
- Collection<OFSwitchImpl> swList = new ArrayList<OFSwitchImpl>(1);
- swList.add(sw);
- roleChanger.submitRequest(swList, Role.SLAVE);
-
- //Request control of the switch from the global registry
- try {
- controlRequested = Boolean.TRUE;
- registryService.requestControl(sw.getId(),
- new RoleChangeCallback());
- } catch (RegistryException e) {
- log.debug("Registry error: {}", e.getMessage());
- controlRequested = Boolean.FALSE;
- }
-
-
-
+ //Put the switch in SLAVE mode until we know we have control
+ log.debug("Setting new switch {} to SLAVE", sw.getStringId());
+ Collection<OFSwitchImpl> swList = new ArrayList<OFSwitchImpl>(1);
+ swList.add(sw);
+ roleChanger.submitRequest(swList, Role.SLAVE);
+
+ //Request control of the switch from the global registry
+ try {
+ controlRequested = Boolean.TRUE;
+ registryService.requestControl(sw.getId(),
+ new RoleChangeCallback());
+ } catch (RegistryException e) {
+ log.debug("Registry error: {}", e.getMessage());
+ controlRequested = Boolean.FALSE;
+ }
+
+
// Send a role request if role support is enabled for the controller
// This is a probe that we'll use to determine if the switch
// actually supports the role request message. If it does we'll
@@ -639,11 +642,10 @@
swList.add(sw);
roleChanger.submitRequest(swList, role);
*/
- }
- else {
+ } else {
// Role supported not enabled on controller (for now)
// automatically promote switch to active state.
- log.debug("This controller's role is {}, " +
+ log.debug("This controller's role is {}, " +
"not sending role request msg to {}",
role, sw);
// Need to clear FlowMods before we add the switch
@@ -654,20 +656,20 @@
}
}
if (!controlRequested) {
- // yield to allow other thread(s) to release control
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- // Ignore interruptions
- }
- // safer to bounce the switch to reconnect here than proceeding further
- log.debug("Closing {} because we weren't able to request control " +
- "successfully" + sw);
- sw.channel.close();
+ // yield to allow other thread(s) to release control
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException e) {
+ // Ignore interruptions
+ }
+ // safer to bounce the switch to reconnect here than proceeding further
+ log.debug("Closing {} because we weren't able to request control " +
+ "successfully" + sw);
+ sw.channel.close();
}
}
}
-
+
/* Handle a role reply message we received from the switch. Since
* netty serializes message dispatch we don't need to synchronize
* against other receive operations from the same switch, so no need
@@ -679,13 +681,13 @@
* removedSwitch notification):1
*
*/
- @LogMessageDoc(level="ERROR",
- message="Invalid role value in role reply message",
- explanation="Was unable to set the HA role (master or slave) " +
+ @LogMessageDoc(level = "ERROR",
+ message = "Invalid role value in role reply message",
+ explanation = "Was unable to set the HA role (master or slave) " +
"for the controller.",
- recommendation=LogMessageDoc.CHECK_CONTROLLER)
+ recommendation = LogMessageDoc.CHECK_CONTROLLER)
protected void handleRoleReplyMessage(OFVendor vendorMessage,
- OFRoleReplyVendorData roleReplyVendorData) {
+ OFRoleReplyVendorData roleReplyVendorData) {
// Map from the role code in the message to our role enum
int nxRole = roleReplyVendorData.getRole();
Role role = null;
@@ -704,20 +706,20 @@
sw.getChannel().close();
return;
}
-
+
log.debug("Handling role reply for role {} from {}. " +
- "Controller's role is {} ",
- new Object[] { role, sw, Controller.this.role}
- );
-
+ "Controller's role is {} ",
+ new Object[]{role, sw, Controller.this.role}
+ );
+
sw.deliverRoleReply(vendorMessage.getXid(), role);
-
+
boolean isActive = activeSwitches.containsKey(sw.getId());
if (!isActive && sw.isActive()) {
// Transition from SLAVE to MASTER.
-
- if (!state.firstRoleReplyReceived ||
- getAlwaysClearFlowsOnSwAdd()) {
+
+ if (!state.firstRoleReplyReceived ||
+ getAlwaysClearFlowsOnSwAdd()) {
// This is the first role-reply message we receive from
// this switch or roles were disabled when the switch
// connected:
@@ -740,14 +742,14 @@
// flushed. Not sure how to handle that case though...
sw.clearAllFlowMods();
log.debug("First role reply from master switch {}, " +
- "clear FlowTable to active switch list",
- HexString.toHexString(sw.getId()));
+ "clear FlowTable to active switch list",
+ HexString.toHexString(sw.getId()));
}
-
+
// Some switches don't seem to update us with port
// status messages while in slave role.
//readSwitchPortStateFromStorage(sw);
-
+
// Only add the switch to the active switch list if
// we're not in the slave role. Note that if the role
// attribute is null, then that means that the switch
@@ -756,17 +758,16 @@
// switch should be included in the active switch list.
addSwitch(sw);
log.debug("Added master switch {} to active switch list",
- HexString.toHexString(sw.getId()));
+ HexString.toHexString(sw.getId()));
- }
- else if (isActive && !sw.isActive()) {
+ } else if (isActive && !sw.isActive()) {
// Transition from MASTER to SLAVE: remove switch
// from active switch list.
log.debug("Removed slave switch {} from active switch" +
- " list", HexString.toHexString(sw.getId()));
+ " list", HexString.toHexString(sw.getId()));
removeSwitch(sw);
}
-
+
// Indicate that we have received a role reply message.
state.firstRoleReplyReceived = true;
}
@@ -777,18 +778,18 @@
switch (vendor) {
case OFNiciraVendorData.NX_VENDOR_ID:
OFNiciraVendorData niciraVendorData =
- (OFNiciraVendorData)vendorMessage.getVendorData();
+ (OFNiciraVendorData) vendorMessage.getVendorData();
int dataType = niciraVendorData.getDataType();
switch (dataType) {
case OFRoleReplyVendorData.NXT_ROLE_REPLY:
OFRoleReplyVendorData roleReplyVendorData =
(OFRoleReplyVendorData) niciraVendorData;
- handleRoleReplyMessage(vendorMessage,
- roleReplyVendorData);
+ handleRoleReplyMessage(vendorMessage,
+ roleReplyVendorData);
break;
default:
log.warn("Unhandled Nicira VENDOR message; " +
- "data type = {}", dataType);
+ "data type = {}", dataType);
break;
}
break;
@@ -796,54 +797,55 @@
log.warn("Unhandled VENDOR message; vendor id = {}", vendor);
break;
}
-
+
return shouldHandleMessage;
}
/**
* Dispatch an Openflow message from a switch to the appropriate
* handler.
+ *
* @param m The message to process
* @throws IOException
- * @throws SwitchStateException
+ * @throws SwitchStateException
*/
@LogMessageDocs({
- @LogMessageDoc(level="WARN",
- message="Config Reply from {switch} has " +
- "miss length set to {length}",
- explanation="The controller requires that the switch " +
- "use a miss length of 0xffff for correct " +
- "function",
- recommendation="Use a different switch to ensure " +
- "correct function"),
- @LogMessageDoc(level="WARN",
- message="Received ERROR from sw {switch} that "
- +"indicates roles are not supported "
- +"but we have received a valid "
- +"role reply earlier",
- explanation="The switch sent a confusing message to the" +
- "controller")
+ @LogMessageDoc(level = "WARN",
+ message = "Config Reply from {switch} has " +
+ "miss length set to {length}",
+ explanation = "The controller requires that the switch " +
+ "use a miss length of 0xffff for correct " +
+ "function",
+ recommendation = "Use a different switch to ensure " +
+ "correct function"),
+ @LogMessageDoc(level = "WARN",
+ message = "Received ERROR from sw {switch} that "
+ + "indicates roles are not supported "
+ + "but we have received a valid "
+ + "role reply earlier",
+ explanation = "The switch sent a confusing message to the" +
+ "controller")
})
protected void processOFMessage(OFMessage m)
throws IOException, SwitchStateException {
boolean shouldHandleMessage = false;
-
+
switch (m.getType()) {
case HELLO:
if (log.isTraceEnabled())
log.trace("HELLO from {}", sw);
-
+
if (state.hsState.equals(HandshakeState.START)) {
state.hsState = HandshakeState.HELLO;
sendHelloConfiguration();
} else {
- throw new SwitchStateException("Unexpected HELLO from "
- + sw);
+ throw new SwitchStateException("Unexpected HELLO from "
+ + sw);
}
break;
case ECHO_REQUEST:
OFEchoReply reply =
- (OFEchoReply) factory.getMessage(OFType.ECHO_REPLY);
+ (OFEchoReply) factory.getMessage(OFType.ECHO_REPLY);
reply.setXid(m.getXid());
sw.write(reply, null);
break;
@@ -852,7 +854,7 @@
case FEATURES_REPLY:
if (log.isTraceEnabled())
log.trace("Features Reply from {}", sw);
-
+
sw.setFeaturesReply((OFFeaturesReply) m);
if (state.hsState.equals(HandshakeState.HELLO)) {
sendFeatureReplyConfiguration();
@@ -870,28 +872,28 @@
case GET_CONFIG_REPLY:
if (log.isTraceEnabled())
log.trace("Get config reply from {}", sw);
-
+
if (!state.hsState.equals(HandshakeState.FEATURES_REPLY)) {
String em = "Unexpected GET_CONFIG_REPLY from " + sw;
throw new SwitchStateException(em);
}
OFGetConfigReply cr = (OFGetConfigReply) m;
- if (cr.getMissSendLength() == (short)0xffff) {
- log.trace("Config Reply from {} confirms " +
- "miss length set to 0xffff", sw);
+ if (cr.getMissSendLength() == (short) 0xffff) {
+ log.trace("Config Reply from {} confirms " +
+ "miss length set to 0xffff", sw);
} else {
log.warn("Config Reply from {} has " +
- "miss length set to {}",
- sw, cr.getMissSendLength() & 0xffff);
+ "miss length set to {}",
+ sw, cr.getMissSendLength() & 0xffff);
}
state.hasGetConfigReply = true;
checkSwitchReady();
break;
case VENDOR:
- shouldHandleMessage = handleVendorMessage((OFVendor)m);
+ shouldHandleMessage = handleVendorMessage((OFVendor) m);
break;
case ERROR:
- log.debug("Recieved ERROR message from switch {}: {}", sw, m);
+ log.debug("Recieved ERROR message from switch {}: {}", sw, m);
// TODO: we need better error handling. Especially for
// request/reply style message (stats, roles) we should have
// a unified way to lookup the xid in the error message.
@@ -903,8 +905,8 @@
// i.e., check only whether the first request fails?
if (sw.checkFirstPendingRoleRequestXid(error.getXid())) {
boolean isBadVendorError =
- (error.getErrorType() == OFError.OFErrorType.
- OFPET_BAD_REQUEST.getValue());
+ (error.getErrorType() == OFError.OFErrorType.
+ OFPET_BAD_REQUEST.getValue());
// We expect to receive a bad vendor error when
// we're connected to a switch that doesn't support
// the Nicira vendor extensions (i.e. not OVS or
@@ -915,31 +917,30 @@
// is not a spurious error
shouldLogError = !isBadVendorError;
if (isBadVendorError) {
- log.debug("Handling bad vendor error for {}", sw);
+ log.debug("Handling bad vendor error for {}", sw);
if (state.firstRoleReplyReceived && (role != null)) {
log.warn("Received ERROR from sw {} that "
- +"indicates roles are not supported "
- +"but we have received a valid "
- +"role reply earlier", sw);
+ + "indicates roles are not supported "
+ + "but we have received a valid "
+ + "role reply earlier", sw);
}
state.firstRoleReplyReceived = true;
- Role requestedRole =
- sw.deliverRoleRequestNotSupportedEx(error.getXid());
- synchronized(roleChanger) {
- if (sw.role == null && Controller.this.role==Role.SLAVE) {
- //This will now never happen. The Controller's role
- //is now never SLAVE, always MASTER.
+ Role requestedRole =
+ sw.deliverRoleRequestNotSupportedEx(error.getXid());
+ synchronized (roleChanger) {
+ if (sw.role == null && Controller.this.role == Role.SLAVE) {
+ //This will now never happen. The Controller's role
+ //is now never SLAVE, always MASTER.
// the switch doesn't understand role request
// messages and the current controller role is
// slave. We need to disconnect the switch.
// @see RoleChanger for rationale
- log.warn("Closing {} channel because controller's role " +
- "is SLAVE", sw);
+ log.warn("Closing {} channel because controller's role " +
+ "is SLAVE", sw);
sw.getChannel().close();
- }
- else if (sw.role == null && requestedRole == Role.MASTER) {
- log.debug("Adding switch {} because we got an error" +
- " returned from a MASTER role request", sw);
+ } else if (sw.role == null && requestedRole == Role.MASTER) {
+ log.debug("Adding switch {} because we got an error" +
+ " returned from a MASTER role request", sw);
// Controller's role is master: add to
// active
// TODO: check if clearing flow table is
@@ -952,8 +953,7 @@
addSwitch(sw);
}
}
- }
- else {
+ } else {
// TODO: Is this the right thing to do if we receive
// some other error besides a bad vendor error?
// Presumably that means the switch did actually
@@ -972,8 +972,8 @@
// to make sure that the switch eventually accepts one
// of our requests or disconnect the switch. This feels
// cumbersome.
- log.debug("Closing {} channel because we recieved an " +
- "error other than BAD_VENDOR", sw);
+ log.debug("Closing {} channel because we recieved an " +
+ "error other than BAD_VENDOR", sw);
sw.getChannel().close();
}
}
@@ -984,8 +984,8 @@
logError(sw, error);
break;
case STATS_REPLY:
- if (state.hsState.ordinal() <
- HandshakeState.FEATURES_REPLY.ordinal()) {
+ if (state.hsState.ordinal() <
+ HandshakeState.FEATURES_REPLY.ordinal()) {
String em = "Unexpected STATS_REPLY from " + sw;
throw new SwitchStateException(em);
}
@@ -999,9 +999,9 @@
// the slave role, but we only want to update storage if
// we're the master (or equal).
boolean updateStorage = state.hsState.
- equals(HandshakeState.READY) &&
- (sw.getRole() != Role.SLAVE);
- handlePortStatusMessage(sw, (OFPortStatus)m, updateStorage);
+ equals(HandshakeState.READY) &&
+ (sw.getRole() != Role.SLAVE);
+ handlePortStatusMessage(sw, (OFPortStatus) m, updateStorage);
shouldHandleMessage = true;
break;
@@ -1009,15 +1009,15 @@
shouldHandleMessage = true;
break;
}
-
+
if (shouldHandleMessage) {
sw.getListenerReadLock().lock();
try {
if (sw.isConnected()) {
if (!state.hsState.equals(HandshakeState.READY)) {
- log.debug("Ignoring message type {} received " +
- "from switch {} before switch is " +
- "fully configured.", m.getType(), sw);
+ log.debug("Ignoring message type {} received " +
+ "from switch {} before switch is " +
+ "fully configured.", m.getType(), sw);
}
// Check if the controller is in the slave role for the
// switch. If it is, then don't dispatch the message to
@@ -1043,8 +1043,7 @@
handleMessage(sw, m, null);
}
}
- }
- finally {
+ } finally {
sw.getListenerReadLock().unlock();
}
}
@@ -1054,41 +1053,41 @@
// ****************
// Message handlers
// ****************
-
+
protected void handlePortStatusMessage(IOFSwitch sw,
OFPortStatus m,
boolean updateStorage) {
short portNumber = m.getDesc().getPortNumber();
OFPhysicalPort port = m.getDesc();
- if (m.getReason() == (byte)OFPortReason.OFPPR_MODIFY.ordinal()) {
- boolean portDown = ((OFPortConfig.OFPPC_PORT_DOWN.getValue() & port.getConfig()) > 0) ||
- ((OFPortState.OFPPS_LINK_DOWN.getValue() & port.getState()) > 0);
+ if (m.getReason() == (byte) OFPortReason.OFPPR_MODIFY.ordinal()) {
+ boolean portDown = ((OFPortConfig.OFPPC_PORT_DOWN.getValue() & port.getConfig()) > 0) ||
+ ((OFPortState.OFPPS_LINK_DOWN.getValue() & port.getState()) > 0);
sw.setPort(port);
- if (!portDown) {
- SwitchUpdate update = new SwitchUpdate(sw, port, SwitchUpdateType.PORTADDED);
- try {
- this.updates.put(update);
- } catch (InterruptedException e) {
- log.error("Failure adding update to queue", e);
- }
- } else {
- SwitchUpdate update = new SwitchUpdate(sw, port, SwitchUpdateType.PORTREMOVED);
- try {
- this.updates.put(update);
- } catch (InterruptedException e) {
- log.error("Failure adding update to queue", e);
- }
- }
+ if (!portDown) {
+ SwitchUpdate update = new SwitchUpdate(sw, port, SwitchUpdateType.PORTADDED);
+ try {
+ this.updates.put(update);
+ } catch (InterruptedException e) {
+ log.error("Failure adding update to queue", e);
+ }
+ } else {
+ SwitchUpdate update = new SwitchUpdate(sw, port, SwitchUpdateType.PORTREMOVED);
+ try {
+ this.updates.put(update);
+ } catch (InterruptedException e) {
+ log.error("Failure adding update to queue", e);
+ }
+ }
//if (updateStorage)
- //updatePortInfo(sw, port);
+ //updatePortInfo(sw, port);
log.debug("Port #{} modified for {}", portNumber, sw);
- } else if (m.getReason() == (byte)OFPortReason.OFPPR_ADD.ordinal()) {
- // XXX Workaround to prevent race condition where a link is detected
- // and attempted to be written to the database before the port is in
- // the database. We now suppress link discovery on ports until we're
- // sure they're in the database.
- linkDiscovery.AddToSuppressLLDPs(sw.getId(), port.getPortNumber());
-
+ } else if (m.getReason() == (byte) OFPortReason.OFPPR_ADD.ordinal()) {
+ // XXX Workaround to prevent race condition where a link is detected
+ // and attempted to be written to the database before the port is in
+ // the database. We now suppress link discovery on ports until we're
+ // sure they're in the database.
+ linkDiscovery.AddToSuppressLLDPs(sw.getId(), port.getPortNumber());
+
sw.setPort(port);
SwitchUpdate update = new SwitchUpdate(sw, port, SwitchUpdateType.PORTADDED);
try {
@@ -1097,10 +1096,10 @@
log.error("Failure adding update to queue", e);
}
//if (updateStorage)
- //updatePortInfo(sw, port);
+ //updatePortInfo(sw, port);
log.debug("Port #{} added for {}", portNumber, sw);
- } else if (m.getReason() ==
- (byte)OFPortReason.OFPPR_DELETE.ordinal()) {
+ } else if (m.getReason() ==
+ (byte) OFPortReason.OFPPR_DELETE.ordinal()) {
sw.deletePort(portNumber);
SwitchUpdate update = new SwitchUpdate(sw, port, SwitchUpdateType.PORTREMOVED);
try {
@@ -1109,7 +1108,7 @@
log.error("Failure adding update to queue", e);
}
//if (updateStorage)
- //removePortInfo(sw, portNumber);
+ //removePortInfo(sw, portNumber);
log.debug("Port #{} deleted for {}", portNumber, sw);
}
SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.PORTCHANGED);
@@ -1119,20 +1118,21 @@
log.error("Failure adding update to queue", e);
}
}
-
+
/**
* flcontext_cache - Keep a thread local stack of contexts
*/
protected static final ThreadLocal<Stack<FloodlightContext>> flcontext_cache =
- new ThreadLocal <Stack<FloodlightContext>> () {
- @Override
- protected Stack<FloodlightContext> initialValue() {
- return new Stack<FloodlightContext>();
- }
- };
+ new ThreadLocal<Stack<FloodlightContext>>() {
+ @Override
+ protected Stack<FloodlightContext> initialValue() {
+ return new Stack<FloodlightContext>();
+ }
+ };
/**
* flcontext_alloc - pop a context off the stack, if required create a new one
+ *
* @return FloodlightContext
*/
protected static FloodlightContext flcontext_alloc() {
@@ -1140,8 +1140,7 @@
if (flcontext_cache.get().empty()) {
flcontext = new FloodlightContext();
- }
- else {
+ } else {
flcontext = flcontext_cache.get().pop();
}
@@ -1150,6 +1149,7 @@
/**
* flcontext_free - Free the context to the current thread
+ *
* @param flcontext
*/
protected void flcontext_free(FloodlightContext flcontext) {
@@ -1159,23 +1159,24 @@
/**
* Handle replies to certain OFMessages, and pass others off to listeners
- * @param sw The switch for the message
- * @param m The message
+ *
+ * @param sw The switch for the message
+ * @param m The message
* @param bContext The floodlight context. If null then floodlight context would
- * be allocated in this function
+ * be allocated in this function
* @throws IOException
*/
@LogMessageDocs({
- @LogMessageDoc(level="ERROR",
- message="Ignoring PacketIn (Xid = {xid}) because the data" +
- " field is empty.",
- explanation="The switch sent an improperly-formatted PacketIn" +
- " message",
- recommendation=LogMessageDoc.CHECK_SWITCH),
- @LogMessageDoc(level="WARN",
- message="Unhandled OF Message: {} from {}",
- explanation="The switch sent a message not handled by " +
- "the controller")
+ @LogMessageDoc(level = "ERROR",
+ message = "Ignoring PacketIn (Xid = {xid}) because the data" +
+ " field is empty.",
+ explanation = "The switch sent an improperly-formatted PacketIn" +
+ " message",
+ recommendation = LogMessageDoc.CHECK_SWITCH),
+ @LogMessageDoc(level = "WARN",
+ message = "Unhandled OF Message: {} from {}",
+ explanation = "The switch sent a message not handled by " +
+ "the controller")
})
protected void handleMessage(IOFSwitch sw, OFMessage m,
FloodlightContext bContext)
@@ -1184,14 +1185,14 @@
switch (m.getType()) {
case PACKET_IN:
- OFPacketIn pi = (OFPacketIn)m;
-
+ OFPacketIn pi = (OFPacketIn) m;
+
if (pi.getPacketData().length <= 0) {
- log.error("Ignoring PacketIn (Xid = " + pi.getXid() +
- ") because the data field is empty.");
+ log.error("Ignoring PacketIn (Xid = " + pi.getXid() +
+ ") because the data field is empty.");
return;
}
-
+
if (Controller.ALWAYS_DECODE_ETH) {
eth = new Ethernet();
eth.deserialize(pi.getPacketData(), 0,
@@ -1200,13 +1201,13 @@
// fall through to default case...
default:
-
+
List<IOFMessageListener> listeners = null;
if (messageListeners.containsKey(m.getType())) {
listeners = messageListeners.get(m.getType()).
getOrderedListeners();
}
-
+
FloodlightContext bc = null;
if (listeners != null) {
// Check if floodlight context is passed from the calling
@@ -1218,19 +1219,19 @@
bc = bContext;
}
if (eth != null) {
- IFloodlightProviderService.bcStore.put(bc,
- IFloodlightProviderService.CONTEXT_PI_PAYLOAD,
+ IFloodlightProviderService.bcStore.put(bc,
+ IFloodlightProviderService.CONTEXT_PI_PAYLOAD,
eth);
}
-
+
// Get the starting time (overall and per-component) of
// the processing chain for this packet if performance
// monitoring is turned on
-
+
Command cmd;
for (IOFMessageListener listener : listeners) {
if (listener instanceof IOFSwitchFilter) {
- if (!((IOFSwitchFilter)listener).isInterested(sw)) {
+ if (!((IOFSwitchFilter) listener).isInterested(sw)) {
continue;
}
}
@@ -1238,7 +1239,7 @@
cmd = listener.receive(sw, m, bc);
-
+
if (Command.STOP.equals(cmd)) {
break;
}
@@ -1247,24 +1248,25 @@
} else {
log.warn("Unhandled OF Message: {} from {}", m, sw);
}
-
+
if ((bContext == null) && (bc != null)) flcontext_free(bc);
}
}
-
+
/**
* Log an OpenFlow error message from a switch
- * @param sw The switch that sent the error
+ *
+ * @param sw The switch that sent the error
* @param error The error message
*/
- @LogMessageDoc(level="ERROR",
- message="Error {error type} {error code} from {switch}",
- explanation="The switch responded with an unexpected error" +
+ @LogMessageDoc(level = "ERROR",
+ message = "Error {error type} {error code} from {switch}",
+ explanation = "The switch responded with an unexpected error" +
"to an OpenFlow message from the controller",
- recommendation="This could indicate improper network operation. " +
+ recommendation = "This could indicate improper network operation. " +
"If the problem persists restarting the switch and " +
"controller may help."
- )
+ )
protected void logError(IOFSwitch sw, OFError error) {
int etint = 0xffff & error.getErrorType();
if (etint < 0 || etint >= OFErrorType.values().length) {
@@ -1273,71 +1275,72 @@
OFErrorType et = OFErrorType.values()[etint];
switch (et) {
case OFPET_HELLO_FAILED:
- OFHelloFailedCode hfc =
- OFHelloFailedCode.values()[0xffff & error.getErrorCode()];
- log.error("Error {} {} from {}", new Object[] {et, hfc, sw});
+ OFHelloFailedCode hfc =
+ OFHelloFailedCode.values()[0xffff & error.getErrorCode()];
+ log.error("Error {} {} from {}", new Object[]{et, hfc, sw});
break;
case OFPET_BAD_REQUEST:
- OFBadRequestCode brc =
- OFBadRequestCode.values()[0xffff & error.getErrorCode()];
- log.error("Error {} {} from {}", new Object[] {et, brc, sw});
+ OFBadRequestCode brc =
+ OFBadRequestCode.values()[0xffff & error.getErrorCode()];
+ log.error("Error {} {} from {}", new Object[]{et, brc, sw});
break;
case OFPET_BAD_ACTION:
OFBadActionCode bac =
- OFBadActionCode.values()[0xffff & error.getErrorCode()];
- log.error("Error {} {} from {}", new Object[] {et, bac, sw});
+ OFBadActionCode.values()[0xffff & error.getErrorCode()];
+ log.error("Error {} {} from {}", new Object[]{et, bac, sw});
break;
case OFPET_FLOW_MOD_FAILED:
OFFlowModFailedCode fmfc =
- OFFlowModFailedCode.values()[0xffff & error.getErrorCode()];
- log.error("Error {} {} from {}", new Object[] {et, fmfc, sw});
+ OFFlowModFailedCode.values()[0xffff & error.getErrorCode()];
+ log.error("Error {} {} from {}", new Object[]{et, fmfc, sw});
break;
case OFPET_PORT_MOD_FAILED:
OFPortModFailedCode pmfc =
- OFPortModFailedCode.values()[0xffff & error.getErrorCode()];
- log.error("Error {} {} from {}", new Object[] {et, pmfc, sw});
+ OFPortModFailedCode.values()[0xffff & error.getErrorCode()];
+ log.error("Error {} {} from {}", new Object[]{et, pmfc, sw});
break;
case OFPET_QUEUE_OP_FAILED:
OFQueueOpFailedCode qofc =
- OFQueueOpFailedCode.values()[0xffff & error.getErrorCode()];
- log.error("Error {} {} from {}", new Object[] {et, qofc, sw});
+ OFQueueOpFailedCode.values()[0xffff & error.getErrorCode()];
+ log.error("Error {} {} from {}", new Object[]{et, qofc, sw});
break;
default:
break;
}
}
-
+
/**
* Add a switch to the active switch list and call the switch listeners.
* This happens either when a switch first connects (and the controller is
* not in the slave role) or when the role of the controller changes from
* slave to master.
+ *
* @param sw the switch that has been added
*/
// TODO: need to rethink locking and the synchronous switch update.
// We can / should also handle duplicate DPIDs in connectedSwitches
- @LogMessageDoc(level="ERROR",
- message="New switch added {switch} for already-added switch {switch}",
- explanation="A switch with the same DPID as another switch " +
+ @LogMessageDoc(level = "ERROR",
+ message = "New switch added {switch} for already-added switch {switch}",
+ explanation = "A switch with the same DPID as another switch " +
"connected to the controller. This can be caused by " +
"multiple switches configured with the same DPID, or " +
"by a switch reconnected very quickly after " +
"disconnecting.",
- recommendation="If this happens repeatedly, it is likely there " +
+ recommendation = "If this happens repeatedly, it is likely there " +
"are switches with duplicate DPIDs on the network. " +
"Reconfigure the appropriate switches. If it happens " +
"very rarely, then it is likely this is a transient " +
"network problem that can be ignored."
- )
+ )
protected void addSwitch(IOFSwitch sw) {
- // XXX Workaround to prevent race condition where a link is detected
- // and attempted to be written to the database before the port is in
- // the database. We now suppress link discovery on ports until we're
- // sure they're in the database.
- for (OFPhysicalPort port : sw.getPorts()) {
- linkDiscovery.AddToSuppressLLDPs(sw.getId(), port.getPortNumber());
- }
-
+ // XXX Workaround to prevent race condition where a link is detected
+ // and attempted to be written to the database before the port is in
+ // the database. We now suppress link discovery on ports until we're
+ // sure they're in the database.
+ for (OFPhysicalPort port : sw.getPorts()) {
+ linkDiscovery.AddToSuppressLLDPs(sw.getId(), port.getPortNumber());
+ }
+
// TODO: is it safe to modify the HashMap without holding
// the old switch's lock?
OFSwitchImpl oldSw = (OFSwitchImpl) this.activeSwitches.put(sw.getId(), sw);
@@ -1346,20 +1349,20 @@
log.info("New add switch for pre-existing switch {}", sw);
return;
}
-
+
if (oldSw != null) {
oldSw.getListenerWriteLock().lock();
try {
log.error("New switch added {} for already-added switch {}",
- sw, oldSw);
+ sw, oldSw);
// Set the connected flag to false to suppress calling
// the listeners for this switch in processOFMessage
oldSw.setConnected(false);
-
+
oldSw.cancelAllStatisticsReplies();
-
+
//updateInactiveSwitchInfo(oldSw);
-
+
// we need to clean out old switch state definitively
// before adding the new switch
// FIXME: It seems not completely kosher to call the
@@ -1378,14 +1381,13 @@
// TODO: Figure out a way to handle this that avoids the
// spurious debug message.
log.debug("Closing {} because a new IOFSwitch got added " +
- "for this dpid", oldSw);
+ "for this dpid", oldSw);
oldSw.getChannel().close();
- }
- finally {
+ } finally {
oldSw.getListenerWriteLock().unlock();
}
}
-
+
//updateActiveSwitchInfo(sw);
SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.ADDED);
try {
@@ -1399,6 +1401,7 @@
* Remove a switch from the active switch list and call the switch listeners.
* This happens either when the switch is disconnected or when the
* controller's role for the switch changes from master to slave.
+ *
* @param sw the switch that has been removed
*/
protected void removeSwitch(IOFSwitch sw) {
@@ -1415,7 +1418,7 @@
// from slave controllers. Then we need to move this cancelation
// to switch disconnect
sw.cancelAllStatisticsReplies();
-
+
// FIXME: I think there's a race condition if we call updateInactiveSwitchInfo
// here if role support is enabled. In that case if the switch is being
// removed because we've been switched to being in the slave role, then I think
@@ -1424,7 +1427,7 @@
// updateInactiveSwitchInfo we may wipe out all of the state that was
// written out by the new master. Maybe need to revisit how we handle all
// of the switch state that's written to storage.
-
+
//updateInactiveSwitchInfo(sw);
SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.REMOVED);
try {
@@ -1433,16 +1436,16 @@
log.error("Failure adding update to queue", e);
}
}
-
+
// ***************
// IFloodlightProvider
// ***************
-
+
@Override
- public synchronized void addOFMessageListener(OFType type,
+ public synchronized void addOFMessageListener(OFType type,
IOFMessageListener listener) {
- ListenerDispatcher<OFType, IOFMessageListener> ldd =
- messageListeners.get(type);
+ ListenerDispatcher<OFType, IOFMessageListener> ldd =
+ messageListeners.get(type);
if (ldd == null) {
ldd = new ListenerDispatcher<OFType, IOFMessageListener>();
messageListeners.put(type, ldd);
@@ -1453,23 +1456,23 @@
@Override
public synchronized void removeOFMessageListener(OFType type,
IOFMessageListener listener) {
- ListenerDispatcher<OFType, IOFMessageListener> ldd =
- messageListeners.get(type);
+ ListenerDispatcher<OFType, IOFMessageListener> ldd =
+ messageListeners.get(type);
if (ldd != null) {
ldd.removeListener(listener);
}
}
-
+
private void logListeners() {
for (Map.Entry<OFType,
- ListenerDispatcher<OFType,
- IOFMessageListener>> entry
- : messageListeners.entrySet()) {
-
+ ListenerDispatcher<OFType,
+ IOFMessageListener>> entry
+ : messageListeners.entrySet()) {
+
OFType type = entry.getKey();
- ListenerDispatcher<OFType, IOFMessageListener> ldd =
+ ListenerDispatcher<OFType, IOFMessageListener> ldd =
entry.getValue();
-
+
StringBuffer sb = new StringBuffer();
sb.append("OFListeners for ");
sb.append(type);
@@ -1478,10 +1481,10 @@
sb.append(l.getName());
sb.append(",");
}
- log.debug(sb.toString());
+ log.debug(sb.toString());
}
}
-
+
public void removeOFMessageListeners(OFType type) {
messageListeners.remove(type);
}
@@ -1503,26 +1506,26 @@
@Override
public Map<OFType, List<IOFMessageListener>> getListeners() {
- Map<OFType, List<IOFMessageListener>> lers =
- new HashMap<OFType, List<IOFMessageListener>>();
- for(Entry<OFType, ListenerDispatcher<OFType, IOFMessageListener>> e :
- messageListeners.entrySet()) {
+ Map<OFType, List<IOFMessageListener>> lers =
+ new HashMap<OFType, List<IOFMessageListener>>();
+ for (Entry<OFType, ListenerDispatcher<OFType, IOFMessageListener>> e :
+ messageListeners.entrySet()) {
lers.put(e.getKey(), e.getValue().getOrderedListeners());
}
return Collections.unmodifiableMap(lers);
}
-
+
@Override
@LogMessageDocs({
- @LogMessageDoc(message="Failed to inject OFMessage {message} onto " +
- "a null switch",
- explanation="Failed to process a message because the switch " +
- " is no longer connected."),
- @LogMessageDoc(level="ERROR",
- message="Error reinjecting OFMessage on switch {switch}",
- explanation="An I/O error occured while attempting to " +
- "process an OpenFlow message",
- recommendation=LogMessageDoc.CHECK_SWITCH)
+ @LogMessageDoc(message = "Failed to inject OFMessage {message} onto " +
+ "a null switch",
+ explanation = "Failed to process a message because the switch " +
+ " is no longer connected."),
+ @LogMessageDoc(level = "ERROR",
+ message = "Error reinjecting OFMessage on switch {switch}",
+ explanation = "An I/O error occured while attempting to " +
+ "process an OpenFlow message",
+ recommendation = LogMessageDoc.CHECK_SWITCH)
})
public boolean injectOfMessage(IOFSwitch sw, OFMessage msg,
FloodlightContext bc) {
@@ -1530,7 +1533,7 @@
log.info("Failed to inject OFMessage {} onto a null switch", msg);
return false;
}
-
+
// FIXME: Do we need to be able to inject messages to switches
// where we're the slave controller (i.e. they're connected but
// not active)?
@@ -1541,32 +1544,32 @@
// through the normal netty event processing, including being
// handled
if (!activeSwitches.containsKey(sw.getId())) return false;
-
+
try {
// Pass Floodlight context to the handleMessages()
handleMessage(sw, msg, bc);
} catch (IOException e) {
- log.error("Error reinjecting OFMessage on switch {}",
- HexString.toHexString(sw.getId()));
+ log.error("Error reinjecting OFMessage on switch {}",
+ HexString.toHexString(sw.getId()));
return false;
}
return true;
}
@Override
- @LogMessageDoc(message="Calling System.exit",
- explanation="The controller is terminating")
+ @LogMessageDoc(message = "Calling System.exit",
+ explanation = "The controller is terminating")
public synchronized void terminate() {
log.info("Calling System.exit");
System.exit(1);
}
-
+
@Override
public boolean injectOfMessage(IOFSwitch sw, OFMessage msg) {
// call the overloaded version with floodlight context set to null
return injectOfMessage(sw, msg, null);
}
-
+
@Override
public void handleOutgoingMessage(IOFSwitch sw, OFMessage m,
FloodlightContext bc) {
@@ -1577,14 +1580,14 @@
List<IOFMessageListener> listeners = null;
if (messageListeners.containsKey(m.getType())) {
- listeners =
+ listeners =
messageListeners.get(m.getType()).getOrderedListeners();
}
-
- if (listeners != null) {
+
+ if (listeners != null) {
for (IOFMessageListener listener : listeners) {
if (listener instanceof IOFSwitchFilter) {
- if (!((IOFSwitchFilter)listener).isInterested(sw)) {
+ if (!((IOFSwitchFilter) listener).isInterested(sw)) {
continue;
}
}
@@ -1599,12 +1602,12 @@
public BasicFactory getOFMessageFactory() {
return factory;
}
-
+
@Override
public String getControllerId() {
return controllerId;
}
-
+
// **************
// Initialization
// **************
@@ -1625,18 +1628,19 @@
* it updates the current role in the file specified by the "role.path"
* file. Then if floodlight restarts for some reason it can get the
* correct current role of the controller from the file.
+ *
* @param configParams The config params for the FloodlightProvider service
* @return A valid role if role information is specified in the
- * config params, otherwise null
+ * config params, otherwise null
*/
@LogMessageDocs({
- @LogMessageDoc(message="Controller role set to {role}",
- explanation="Setting the initial HA role to "),
- @LogMessageDoc(level="ERROR",
- message="Invalid current role value: {role}",
- explanation="An invalid HA role value was read from the " +
+ @LogMessageDoc(message = "Controller role set to {role}",
+ explanation = "Setting the initial HA role to "),
+ @LogMessageDoc(level = "ERROR",
+ message = "Invalid current role value: {role}",
+ explanation = "An invalid HA role value was read from the " +
"properties file",
- recommendation=LogMessageDoc.CHECK_CONTROLLER)
+ recommendation = LogMessageDoc.CHECK_CONTROLLER)
})
protected Role getInitialRole(Map<String, String> configParams) {
Role role = null;
@@ -1648,8 +1652,7 @@
try {
properties.load(new FileInputStream(rolePath));
roleString = properties.getProperty("floodlight.role");
- }
- catch (IOException exc) {
+ } catch (IOException exc) {
// Don't treat it as an error if the file specified by the
// rolepath property doesn't exist. This lets us enable the
// HA mechanism by just creating/setting the floodlight.role
@@ -1658,60 +1661,60 @@
}
}
}
-
+
if (roleString != null) {
// Canonicalize the string to the form used for the enum constants
roleString = roleString.trim().toUpperCase();
try {
role = Role.valueOf(roleString);
- }
- catch (IllegalArgumentException exc) {
+ } catch (IllegalArgumentException exc) {
log.error("Invalid current role value: {}", roleString);
}
}
-
+
log.info("Controller role set to {}", role);
-
+
return role;
}
-
+
/**
* Tell controller that we're ready to accept switches loop
- * @throws IOException
+ *
+ * @throws IOException
*/
@LogMessageDocs({
- @LogMessageDoc(message="Listening for switch connections on {address}",
- explanation="The controller is ready and listening for new" +
- " switch connections"),
- @LogMessageDoc(message="Storage exception in controller " +
- "updates loop; terminating process",
- explanation=ERROR_DATABASE,
- recommendation=LogMessageDoc.CHECK_CONTROLLER),
- @LogMessageDoc(level="ERROR",
- message="Exception in controller updates loop",
- explanation="Failed to dispatch controller event",
- recommendation=LogMessageDoc.GENERIC_ACTION)
+ @LogMessageDoc(message = "Listening for switch connections on {address}",
+ explanation = "The controller is ready and listening for new" +
+ " switch connections"),
+ @LogMessageDoc(message = "Storage exception in controller " +
+ "updates loop; terminating process",
+ explanation = ERROR_DATABASE,
+ recommendation = LogMessageDoc.CHECK_CONTROLLER),
+ @LogMessageDoc(level = "ERROR",
+ message = "Exception in controller updates loop",
+ explanation = "Failed to dispatch controller event",
+ recommendation = LogMessageDoc.GENERIC_ACTION)
})
public void run() {
if (log.isDebugEnabled()) {
logListeners();
}
-
- try {
- final ServerBootstrap bootstrap = createServerBootStrap();
+
+ try {
+ final ServerBootstrap bootstrap = createServerBootStrap();
bootstrap.setOption("reuseAddr", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.sendBufferSize", Controller.SEND_BUFFER_SIZE);
- ChannelPipelineFactory pfact =
+ ChannelPipelineFactory pfact =
new OpenflowPipelineFactory(this, null);
bootstrap.setPipelineFactory(pfact);
InetSocketAddress sa = new InetSocketAddress(openFlowPort);
final ChannelGroup cg = new DefaultChannelGroup();
cg.add(bootstrap.bind(sa));
-
+
log.info("Listening for switch connections on {}", sa);
} catch (Exception e) {
throw new RuntimeException(e);
@@ -1743,7 +1746,7 @@
Executors.newCachedThreadPool(), workerThreads));
}
}
-
+
public void setConfigParams(Map<String, String> configParams) {
String ofPort = configParams.get("openflowport");
if (ofPort != null) {
@@ -1758,17 +1761,16 @@
String controllerId = configParams.get("controllerid");
if (controllerId != null) {
this.controllerId = controllerId;
+ } else {
+ //Try to get the hostname of the machine and use that for controller ID
+ try {
+ String hostname = java.net.InetAddress.getLocalHost().getHostName();
+ this.controllerId = hostname;
+ } catch (UnknownHostException e) {
+ // Can't get hostname, we'll just use the default
+ }
}
- else {
- //Try to get the hostname of the machine and use that for controller ID
- try {
- String hostname = java.net.InetAddress.getLocalHost().getHostName();
- this.controllerId = hostname;
- } catch (UnknownHostException e) {
- // Can't get hostname, we'll just use the default
- }
- }
-
+
log.debug("ControllerId set to {}", this.controllerId);
}
@@ -1787,9 +1789,9 @@
new OFBasicVendorDataType(
OFRoleReplyVendorData.NXT_ROLE_REPLY,
OFRoleReplyVendorData.getInstantiable());
- niciraVendorId.registerVendorDataType(roleReplyVendorData);
+ niciraVendorId.registerVendorDataType(roleReplyVendorData);
}
-
+
/**
* Initialize internal data structures
*/
@@ -1797,9 +1799,9 @@
// These data structures are initialized here because other
// module's startUp() might be called before ours
this.messageListeners =
- new ConcurrentHashMap<OFType,
- ListenerDispatcher<OFType,
- IOFMessageListener>>();
+ new ConcurrentHashMap<OFType,
+ ListenerDispatcher<OFType,
+ IOFMessageListener>>();
this.switchListeners = new CopyOnWriteArraySet<IOFSwitchListener>();
this.activeSwitches = new ConcurrentHashMap<Long, IOFSwitch>();
this.connectedSwitches = new HashSet<OFSwitchImpl>();
@@ -1813,33 +1815,33 @@
initVendorMessages();
this.systemStartTime = System.currentTimeMillis();
}
-
+
/**
* Startup all of the controller's components
*/
- @LogMessageDoc(message="Waiting for storage source",
- explanation="The system database is not yet ready",
- recommendation="If this message persists, this indicates " +
- "that the system database has failed to start. " +
- LogMessageDoc.CHECK_CONTROLLER)
+ @LogMessageDoc(message = "Waiting for storage source",
+ explanation = "The system database is not yet ready",
+ recommendation = "If this message persists, this indicates " +
+ "that the system database has failed to start. " +
+ LogMessageDoc.CHECK_CONTROLLER)
public void startupComponents() {
- try {
- registryService.registerController(controllerId);
- } catch (RegistryException e) {
- log.warn("Registry service error: {}", e.getMessage());
- }
-
+ try {
+ registryService.registerController(controllerId);
+ } catch (RegistryException e) {
+ log.warn("Registry service error: {}", e.getMessage());
+ }
+
// Add our REST API
restApi.addRestletRoutable(new CoreWebRoutable());
}
-
+
@Override
public Map<String, String> getControllerNodeIPs() {
// We return a copy of the mapping so we can guarantee that
// the mapping return is the same as one that will be (or was)
// dispatched to IHAListeners
- HashMap<String,String> retval = new HashMap<String,String>();
- synchronized(controllerNodeIPsCache) {
+ HashMap<String, String> retval = new HashMap<String, String>();
+ synchronized (controllerNodeIPsCache) {
retval.putAll(controllerNodeIPsCache);
}
return retval;
@@ -1854,7 +1856,7 @@
public void setAlwaysClearFlowsOnSwAdd(boolean value) {
this.alwaysClearFlowsOnSwAdd = value;
}
-
+
public boolean getAlwaysClearFlowsOnSwAdd() {
return this.alwaysClearFlowsOnSwAdd;
}
diff --git a/src/main/java/net/floodlightcontroller/core/internal/HandshakeTimeoutException.java b/src/main/java/net/floodlightcontroller/core/internal/HandshakeTimeoutException.java
index 421ec1a..57fa279 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/HandshakeTimeoutException.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/HandshakeTimeoutException.java
@@ -1,25 +1,26 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.internal;
/**
- * Exception is thrown when the handshake fails to complete
+ * Exception is thrown when the handshake fails to complete
* before a specified time
+ *
* @author readams
*/
public class HandshakeTimeoutException extends Exception {
diff --git a/src/main/java/net/floodlightcontroller/core/internal/HandshakeTimeoutHandler.java b/src/main/java/net/floodlightcontroller/core/internal/HandshakeTimeoutHandler.java
index 6d3335f..d5950b4 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/HandshakeTimeoutHandler.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/HandshakeTimeoutHandler.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.internal;
@@ -33,17 +33,17 @@
/**
* Trigger a timeout if a switch fails to complete handshake soon enough
*/
-public class HandshakeTimeoutHandler
- extends SimpleChannelUpstreamHandler
- implements ExternalResourceReleasable {
- static final HandshakeTimeoutException EXCEPTION =
+public class HandshakeTimeoutHandler
+ extends SimpleChannelUpstreamHandler
+ implements ExternalResourceReleasable {
+ static final HandshakeTimeoutException EXCEPTION =
new HandshakeTimeoutException();
-
+
final OFChannelState state;
final Timer timer;
final long timeoutNanos;
volatile Timeout timeout;
-
+
public HandshakeTimeoutHandler(OFChannelState state, Timer timer,
long timeoutSeconds) {
super();
@@ -52,17 +52,17 @@
this.timeoutNanos = TimeUnit.SECONDS.toNanos(timeoutSeconds);
}
-
+
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
if (timeoutNanos > 0) {
- timeout = timer.newTimeout(new HandshakeTimeoutTask(ctx),
- timeoutNanos, TimeUnit.NANOSECONDS);
+ timeout = timer.newTimeout(new HandshakeTimeoutTask(ctx),
+ timeoutNanos, TimeUnit.NANOSECONDS);
}
ctx.sendUpstream(e);
}
-
+
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
@@ -76,7 +76,7 @@
public void releaseExternalResources() {
timer.stop();
}
-
+
private final class HandshakeTimeoutTask implements TimerTask {
private final ChannelHandlerContext ctx;
diff --git a/src/main/java/net/floodlightcontroller/core/internal/OFChannelState.java b/src/main/java/net/floodlightcontroller/core/internal/OFChannelState.java
index ad5a377..8130c0a 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/OFChannelState.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/OFChannelState.java
@@ -1,24 +1,25 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.internal;
/**
* Wrapper class to hold state for the OpenFlow switch connection
+ *
* @author readams
*/
class OFChannelState {
@@ -53,7 +54,7 @@
protected volatile HandshakeState hsState = HandshakeState.START;
protected boolean hasGetConfigReply = false;
protected boolean hasDescription = false;
-
+
// The firstRoleReplyRecevied flag indicates if we have received the
// first role reply message on this connection (in response to the
// role request sent after the handshake). If role support is disabled
diff --git a/src/main/java/net/floodlightcontroller/core/internal/OFFeaturesReplyFuture.java b/src/main/java/net/floodlightcontroller/core/internal/OFFeaturesReplyFuture.java
index eca67bd..70ab58e 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/OFFeaturesReplyFuture.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/OFFeaturesReplyFuture.java
@@ -1,6 +1,6 @@
/**
* Copyright 2012, Big Switch Networks, Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
@@ -28,7 +28,7 @@
/**
* A concrete implementation that handles asynchronously receiving
* OFFeaturesReply
- *
+ *
* @author Shudong Zhou
*/
public class OFFeaturesReplyFuture extends
@@ -37,13 +37,13 @@
protected volatile boolean finished;
public OFFeaturesReplyFuture(IThreadPoolService tp,
- IOFSwitch sw, int transactionId) {
+ IOFSwitch sw, int transactionId) {
super(tp, sw, OFType.FEATURES_REPLY, transactionId);
init();
}
public OFFeaturesReplyFuture(IThreadPoolService tp,
- IOFSwitch sw, int transactionId, long timeout, TimeUnit unit) {
+ IOFSwitch sw, int transactionId, long timeout, TimeUnit unit) {
super(tp, sw, OFType.FEATURES_REPLY, transactionId, timeout, unit);
init();
}
diff --git a/src/main/java/net/floodlightcontroller/core/internal/OFMessageDecoder.java b/src/main/java/net/floodlightcontroller/core/internal/OFMessageDecoder.java
index 295e967..54fafd5 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/OFMessageDecoder.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/OFMessageDecoder.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.internal;
@@ -30,12 +30,13 @@
/**
* Decode an openflow message from a Channel, for use in a netty
* pipeline
+ *
* @author readams
*/
public class OFMessageDecoder extends FrameDecoder {
OFMessageFactory factory = new BasicFactory();
-
+
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel,
ChannelBuffer buffer) throws Exception {
@@ -51,7 +52,7 @@
@Override
protected Object decodeLast(ChannelHandlerContext ctx, Channel channel,
- ChannelBuffer buffer) throws Exception {
+ ChannelBuffer buffer) throws Exception {
// This is not strictly needed atthis time. It is used to detect
// connection reset detection from netty (for debug)
return null;
diff --git a/src/main/java/net/floodlightcontroller/core/internal/OFMessageEncoder.java b/src/main/java/net/floodlightcontroller/core/internal/OFMessageEncoder.java
index 6be5f9a..d61f17e 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/OFMessageEncoder.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/OFMessageEncoder.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.internal;
@@ -29,6 +29,7 @@
/**
* Encode an openflow message for output into a ChannelBuffer, for use in a
* netty pipeline
+ *
* @author readams
*/
public class OFMessageEncoder extends OneToOneEncoder {
@@ -36,18 +37,19 @@
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel,
Object msg) throws Exception {
- if (!( msg instanceof List))
+ if (!(msg instanceof List))
return msg;
@SuppressWarnings("unchecked")
- List<OFMessage> msglist = (List<OFMessage>)msg;
+ List<OFMessage> msglist = (List<OFMessage>) msg;
int size = 0;
- for (OFMessage ofm : msglist) {
- size += ofm.getLengthU();
+ for (OFMessage ofm : msglist) {
+ size += ofm.getLengthU();
}
- ChannelBuffer buf = ChannelBuffers.buffer(size);;
- for (OFMessage ofm : msglist) {
+ ChannelBuffer buf = ChannelBuffers.buffer(size);
+ ;
+ for (OFMessage ofm : msglist) {
ofm.writeTo(buf);
}
return buf;
diff --git a/src/main/java/net/floodlightcontroller/core/internal/OFMessageFuture.java b/src/main/java/net/floodlightcontroller/core/internal/OFMessageFuture.java
index 60b932f..bd8456f 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/OFMessageFuture.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/OFMessageFuture.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.internal;
@@ -51,13 +51,13 @@
protected static final TimeUnit DEFAULT_TIMEOUT_UNIT = TimeUnit.SECONDS;
public OFMessageFuture(IThreadPoolService tp,
- IOFSwitch sw, OFType responseType, int transactionId) {
- this(tp, sw, responseType, transactionId,
- DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT);
+ IOFSwitch sw, OFType responseType, int transactionId) {
+ this(tp, sw, responseType, transactionId,
+ DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT);
}
public OFMessageFuture(IThreadPoolService tp,
- IOFSwitch sw, OFType responseType, int transactionId, long timeout, TimeUnit unit) {
+ IOFSwitch sw, OFType responseType, int transactionId, long timeout, TimeUnit unit) {
this.threadPool = tp;
this.canceled = false;
this.latch = new CountDownLatch(1);
@@ -80,7 +80,7 @@
this.timeoutTimer = null;
}
-
+
public void deliverFuture(IOFSwitch sw, OFMessage msg) {
if (transactionId == msg.getXid()) {
handleReply(sw, msg);
@@ -95,6 +95,7 @@
* Used to handle the specific expected message this Future was reigstered
* for, the specified msg parameter is guaranteed to match the type and
* transaction id specified.
+ *
* @param sw
* @param msg
* @return
@@ -106,6 +107,7 @@
* indicate when the future can deregister itself from receiving future
* messages, and when it is safe to return the results to any waiting
* threads.
+ *
* @return when this Future has completed its work
*/
protected abstract boolean isFinished();
diff --git a/src/main/java/net/floodlightcontroller/core/internal/OFStatisticsFuture.java b/src/main/java/net/floodlightcontroller/core/internal/OFStatisticsFuture.java
index 4d3f733..4651c74 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/OFStatisticsFuture.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/OFStatisticsFuture.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.internal;
@@ -31,7 +31,7 @@
/**
* A concrete implementation that handles asynchronously receiving OFStatistics
- *
+ *
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public class OFStatisticsFuture extends
@@ -40,13 +40,13 @@
protected volatile boolean finished;
public OFStatisticsFuture(IThreadPoolService tp,
- IOFSwitch sw, int transactionId) {
+ IOFSwitch sw, int transactionId) {
super(tp, sw, OFType.STATS_REPLY, transactionId);
init();
}
public OFStatisticsFuture(IThreadPoolService tp,
- IOFSwitch sw, int transactionId, long timeout, TimeUnit unit) {
+ IOFSwitch sw, int transactionId, long timeout, TimeUnit unit) {
super(tp, sw, OFType.STATS_REPLY, transactionId, timeout, unit);
init();
}
@@ -71,7 +71,7 @@
protected boolean isFinished() {
return finished;
}
-
+
@Override
protected void unRegister() {
super.unRegister();
diff --git a/src/main/java/net/floodlightcontroller/core/internal/OFSwitchImpl.java b/src/main/java/net/floodlightcontroller/core/internal/OFSwitchImpl.java
index 3164381..96ddc7c 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/OFSwitchImpl.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/OFSwitchImpl.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2012, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2012, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.internal;
@@ -82,11 +82,11 @@
// exception that can then be handled by callers?
protected final static Logger log = LoggerFactory.getLogger(OFSwitchImpl.class);
- private static final String HA_CHECK_SWITCH =
+ private static final String HA_CHECK_SWITCH =
"Check the health of the indicated switch. If the problem " +
- "persists or occurs repeatedly, it likely indicates a defect " +
- "in the switch HA implementation.";
-
+ "persists or occurs repeatedly, it likely indicates a defect " +
+ "in the switch HA implementation.";
+
protected ConcurrentMap<Object, Object> attributes;
protected IFloodlightProviderService floodlightProvider;
protected IThreadPoolService threadPool;
@@ -104,9 +104,9 @@
// XXX: The OF spec doesn't specify if port names need to be unique but
// according it's always the case in practice.
protected ConcurrentHashMap<String, OFPhysicalPort> portsByName;
- protected Map<Integer,OFStatisticsFuture> statsFutureMap;
+ protected Map<Integer, OFStatisticsFuture> statsFutureMap;
protected Map<Integer, IOFMessageListener> iofMsgListenersMap;
- protected Map<Integer,OFFeaturesReplyFuture> featuresFutureMap;
+ protected Map<Integer, OFFeaturesReplyFuture> featuresFutureMap;
protected boolean connected;
protected Role role;
protected TimedCache<Long> timedCache;
@@ -114,16 +114,16 @@
protected ConcurrentMap<Short, Long> portBroadcastCacheHitMap;
/**
* When sending a role request message, the role request is added
- * to this queue. If a role reply is received this queue is checked to
+ * to this queue. If a role reply is received this queue is checked to
* verify that the reply matches the expected reply. We require in order
- * delivery of replies. That's why we use a Queue.
+ * delivery of replies. That's why we use a Queue.
* The RoleChanger uses a timeout to ensure we receive a timely reply.
- *
- * Need to synchronize on this instance if a request is sent, received,
- * checked.
+ * <p/>
+ * Need to synchronize on this instance if a request is sent, received,
+ * checked.
*/
protected LinkedList<PendingRoleRequestEntry> pendingRoleRequests;
-
+
/* Switch features from initial featuresReply */
protected int capabilities;
protected int buffers;
@@ -132,29 +132,30 @@
protected long datapathId;
public static IOFSwitchFeatures switchFeatures;
- protected static final ThreadLocal<Map<OFSwitchImpl,List<OFMessage>>> local_msg_buffer =
- new ThreadLocal<Map<OFSwitchImpl,List<OFMessage>>>() {
- @Override
- protected Map<OFSwitchImpl,List<OFMessage>> initialValue() {
- return new HashMap<OFSwitchImpl,List<OFMessage>>();
- }
- };
-
+ protected static final ThreadLocal<Map<OFSwitchImpl, List<OFMessage>>> local_msg_buffer =
+ new ThreadLocal<Map<OFSwitchImpl, List<OFMessage>>>() {
+ @Override
+ protected Map<OFSwitchImpl, List<OFMessage>> initialValue() {
+ return new HashMap<OFSwitchImpl, List<OFMessage>>();
+ }
+ };
+
// for managing our map sizes
- protected static final int MAX_MACS_PER_SWITCH = 1000;
-
+ protected static final int MAX_MACS_PER_SWITCH = 1000;
+
protected static class PendingRoleRequestEntry {
protected int xid;
protected Role role;
// cookie is used to identify the role "generation". roleChanger uses
protected long cookie;
+
public PendingRoleRequestEntry(int xid, Role role, long cookie) {
this.xid = xid;
this.role = role;
this.cookie = cookie;
}
}
-
+
public OFSwitchImpl() {
this.stringId = null;
this.attributes = new ConcurrentHashMap<Object, Object>();
@@ -164,21 +165,21 @@
this.portsByNumber = new ConcurrentHashMap<Short, OFPhysicalPort>();
this.portsByName = new ConcurrentHashMap<String, OFPhysicalPort>();
this.connected = true;
- this.statsFutureMap = new ConcurrentHashMap<Integer,OFStatisticsFuture>();
- this.featuresFutureMap = new ConcurrentHashMap<Integer,OFFeaturesReplyFuture>();
- this.iofMsgListenersMap = new ConcurrentHashMap<Integer,IOFMessageListener>();
+ this.statsFutureMap = new ConcurrentHashMap<Integer, OFStatisticsFuture>();
+ this.featuresFutureMap = new ConcurrentHashMap<Integer, OFFeaturesReplyFuture>();
+ this.iofMsgListenersMap = new ConcurrentHashMap<Integer, IOFMessageListener>();
this.role = null;
- this.timedCache = new TimedCache<Long>(100, 5*1000 ); // 5 seconds interval
+ this.timedCache = new TimedCache<Long>(100, 5 * 1000); // 5 seconds interval
this.listenerLock = new ReentrantReadWriteLock();
this.portBroadcastCacheHitMap = new ConcurrentHashMap<Short, Long>();
this.pendingRoleRequests = new LinkedList<OFSwitchImpl.PendingRoleRequestEntry>();
-
+
// Defaults properties for an ideal switch
this.setAttribute(PROP_FASTWILDCARDS, OFMatch.OFPFW_ALL);
this.setAttribute(PROP_SUPPORTS_OFPP_FLOOD, new Boolean(true));
this.setAttribute(PROP_SUPPORTS_OFPP_TABLE, new Boolean(true));
}
-
+
@Override
public Object getAttribute(String name) {
@@ -187,7 +188,7 @@
}
return null;
}
-
+
@Override
public void setAttribute(String name, Object value) {
this.attributes.put(name, value);
@@ -198,12 +199,12 @@
public Object removeAttribute(String name) {
return this.attributes.remove(name);
}
-
+
@Override
public boolean hasAttribute(String name) {
return this.attributes.containsKey(name);
}
-
+
@Override
@JsonIgnore
public Channel getChannel() {
@@ -214,10 +215,10 @@
public void setChannel(Channel channel) {
this.channel = channel;
}
-
+
@Override
public void write(OFMessage m, FloodlightContext bc) throws IOException {
- Map<OFSwitchImpl,List<OFMessage>> msg_buffer_map = local_msg_buffer.get();
+ Map<OFSwitchImpl, List<OFMessage>> msg_buffer_map = local_msg_buffer.get();
List<OFMessage> msg_buffer = msg_buffer_map.get(this);
if (msg_buffer == null) {
msg_buffer = new ArrayList<OFMessage>();
@@ -228,20 +229,20 @@
msg_buffer.add(m);
if ((msg_buffer.size() >= Controller.BATCH_MAX_SIZE) ||
- ((m.getType() != OFType.PACKET_OUT) && (m.getType() != OFType.FLOW_MOD))) {
+ ((m.getType() != OFType.PACKET_OUT) && (m.getType() != OFType.FLOW_MOD))) {
this.write(msg_buffer);
msg_buffer.clear();
}
}
@Override
- @LogMessageDoc(level="WARN",
- message="Sending OF message that modifies switch " +
- "state while in the slave role: {switch}",
- explanation="An application has sent a message to a switch " +
- "that is not valid when the switch is in a slave role",
- recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG)
- public void write(List<OFMessage> msglist,
+ @LogMessageDoc(level = "WARN",
+ message = "Sending OF message that modifies switch " +
+ "state while in the slave role: {switch}",
+ explanation = "An application has sent a message to a switch " +
+ "that is not valid when the switch is in a slave role",
+ recommendation = LogMessageDoc.REPORT_CONTROLLER_BUG)
+ public void write(List<OFMessage> msglist,
FloodlightContext bc) throws IOException {
for (OFMessage m : msglist) {
if (role == Role.SLAVE) {
@@ -250,8 +251,8 @@
case FLOW_MOD:
case PORT_MOD:
log.warn("Sending OF message that modifies switch " +
- "state while in the slave role: {}",
- m.getType().name());
+ "state while in the slave role: {}",
+ m.getType().name());
break;
default:
break;
@@ -265,7 +266,7 @@
public void write(List<OFMessage> msglist) throws IOException {
this.channel.write(msglist);
}
-
+
@Override
public void disconnectOutputStream() {
channel.close();
@@ -274,7 +275,7 @@
@Override
@JsonIgnore
public void setFeaturesReply(OFFeaturesReply featuresReply) {
- synchronized(portLock) {
+ synchronized (portLock) {
if (stringId == null) {
/* ports are updated via port status message, so we
* only fill in ports on initial connection.
@@ -303,7 +304,7 @@
}
return result;
}
-
+
@Override
@JsonIgnore
public Collection<Short> getEnabledPortNumbers() {
@@ -320,7 +321,7 @@
public OFPhysicalPort getPort(short portNumber) {
return portsByNumber.get(portNumber);
}
-
+
@Override
public OFPhysicalPort getPort(String portName) {
return portsByName.get(portName);
@@ -329,29 +330,29 @@
@Override
@JsonIgnore
public void setPort(OFPhysicalPort port) {
- synchronized(portLock) {
+ synchronized (portLock) {
portsByNumber.put(port.getPortNumber(), port);
portsByName.put(port.getName(), port);
}
}
-
+
@Override
@JsonProperty("ports")
public Collection<OFPhysicalPort> getPorts() {
return Collections.unmodifiableCollection(portsByNumber.values());
}
-
+
@Override
public void deletePort(short portNumber) {
- synchronized(portLock) {
+ synchronized (portLock) {
portsByName.remove(portsByNumber.get(portNumber).getName());
portsByNumber.remove(portNumber);
}
}
-
+
@Override
public void deletePort(String portName) {
- synchronized(portLock) {
+ synchronized (portLock) {
portsByNumber.remove(portsByName.get(portName).getPortNumber());
portsByName.remove(portName);
}
@@ -362,13 +363,13 @@
if (portsByNumber.get(portNumber) == null) return false;
return portEnabled(portsByNumber.get(portNumber));
}
-
+
@Override
public boolean portEnabled(String portName) {
if (portsByName.get(portName) == null) return false;
return portEnabled(portsByName.get(portName));
}
-
+
@Override
public boolean portEnabled(OFPhysicalPort port) {
if (port == null)
@@ -382,9 +383,9 @@
// return false;
return true;
}
-
+
@Override
- @JsonSerialize(using=DPIDSerializer.class)
+ @JsonSerialize(using = DPIDSerializer.class)
@JsonProperty("dpid")
public long getId() {
if (this.stringId == null)
@@ -424,7 +425,7 @@
@Override
public void sendStatsQuery(OFStatisticsRequest request, int xid,
- IOFMessageListener caller) throws IOException {
+ IOFMessageListener caller) throws IOException {
request.setXid(xid);
this.iofMsgListenersMap.put(xid, caller);
List<OFMessage> msglist = new ArrayList<OFMessage>(1);
@@ -462,7 +463,7 @@
@Override
public void cancelStatisticsReply(int transactionId) {
- if (null == this.statsFutureMap.remove(transactionId)) {
+ if (null == this.statsFutureMap.remove(transactionId)) {
this.iofMsgListenersMap.remove(transactionId);
}
}
@@ -478,8 +479,8 @@
statsFutureMap.clear();
iofMsgListenersMap.clear();
}
-
-
+
+
/**
* @param floodlightProvider the floodlightProvider to set
*/
@@ -487,7 +488,7 @@
public void setFloodlightProvider(IFloodlightProviderService floodlightProvider) {
this.floodlightProvider = floodlightProvider;
}
-
+
@JsonIgnore
public void setThreadPoolService(IThreadPoolService tp) {
this.threadPool = tp;
@@ -504,18 +505,18 @@
public synchronized void setConnected(boolean connected) {
this.connected = connected;
}
-
+
@Override
public Role getRole() {
return role;
}
-
+
@JsonIgnore
@Override
public boolean isActive() {
return (role != Role.SLAVE);
}
-
+
@Override
@JsonIgnore
public void setSwitchProperties(OFDescriptionStatistics description) {
@@ -525,20 +526,20 @@
}
@Override
- @LogMessageDoc(level="ERROR",
- message="Failed to clear all flows on switch {switch}",
- explanation="An I/O error occured while trying to clear " +
- "flows on the switch.",
- recommendation=LogMessageDoc.CHECK_SWITCH)
+ @LogMessageDoc(level = "ERROR",
+ message = "Failed to clear all flows on switch {switch}",
+ explanation = "An I/O error occured while trying to clear " +
+ "flows on the switch.",
+ recommendation = LogMessageDoc.CHECK_SWITCH)
public void clearAllFlowMods() {
// Delete all pre-existing flows
OFMatch match = new OFMatch().setWildcards(OFMatch.OFPFW_ALL);
OFMessage fm = ((OFFlowMod) floodlightProvider.getOFMessageFactory()
- .getMessage(OFType.FLOW_MOD))
+ .getMessage(OFType.FLOW_MOD))
.setMatch(match)
- .setCommand(OFFlowMod.OFPFC_DELETE)
- .setOutPort(OFPort.OFPP_NONE)
- .setLength(U16.t(OFFlowMod.MINIMUM_LENGTH));
+ .setCommand(OFFlowMod.OFPFC_DELETE)
+ .setOutPort(OFPort.OFPP_NONE)
+ .setLength(U16.t(OFFlowMod.MINIMUM_LENGTH));
try {
List<OFMessage> msglist = new ArrayList<OFMessage>(1);
msglist.add(fm);
@@ -564,13 +565,13 @@
@Override
@JsonIgnore
public Map<Short, Long> getPortBroadcastHits() {
- return this.portBroadcastCacheHitMap;
+ return this.portBroadcastCacheHitMap;
}
-
+
@Override
public void flush() {
- Map<OFSwitchImpl,List<OFMessage>> msg_buffer_map = local_msg_buffer.get();
+ Map<OFSwitchImpl, List<OFMessage>> msg_buffer_map = local_msg_buffer.get();
List<OFMessage> msglist = msg_buffer_map.get(this);
if ((msglist != null) && (msglist.size() > 0)) {
try {
@@ -584,7 +585,7 @@
}
public static void flush_all() {
- Map<OFSwitchImpl,List<OFMessage>> msg_buffer_map = local_msg_buffer.get();
+ Map<OFSwitchImpl, List<OFMessage>> msg_buffer_map = local_msg_buffer.get();
for (OFSwitchImpl sw : msg_buffer_map.keySet()) {
sw.flush();
}
@@ -594,7 +595,8 @@
* Return a read lock that must be held while calling the listeners for
* messages from the switch. Holding the read lock prevents the active
* switch list from being modified out from under the listeners.
- * @return
+ *
+ * @return
*/
@JsonIgnore
public Lock getListenerReadLock() {
@@ -606,6 +608,7 @@
* list of active switches. This is to ensure that the active switch list
* doesn't change out from under the listeners as they are handling a
* message from the switch.
+ *
* @return
*/
@JsonIgnore
@@ -615,29 +618,31 @@
/**
* Get the IP Address for the switch
+ *
* @return the inet address
*/
- @JsonSerialize(using=ToStringSerializer.class)
+ @JsonSerialize(using = ToStringSerializer.class)
public SocketAddress getInetAddress() {
return channel.getRemoteAddress();
}
-
+
/**
* Send NX role request message to the switch requesting the specified role.
- *
- * This method should ONLY be called by @see RoleChanger.submitRequest().
- *
+ * <p/>
+ * This method should ONLY be called by @see RoleChanger.submitRequest().
+ * <p/>
* After sending the request add it to the queue of pending request. We
* use the queue to later verify that we indeed receive the correct reply.
- * @param sw switch to send the role request message to
- * @param role role to request
+ *
+ * @param sw switch to send the role request message to
+ * @param role role to request
* @param cookie an opaque value that will be stored in the pending queue so
- * RoleChanger can check for timeouts.
+ * RoleChanger can check for timeouts.
* @return transaction id of the role request message that was sent
*/
protected int sendNxRoleRequest(Role role, long cookie)
throws IOException {
- synchronized(pendingRoleRequests) {
+ synchronized (pendingRoleRequests) {
// Convert the role enum to the appropriate integer constant used
// in the NX role request message
int nxRole = 0;
@@ -653,13 +658,13 @@
break;
default:
log.error("Invalid Role specified for switch {}."
- + " Disconnecting.", this);
+ + " Disconnecting.", this);
// TODO: should throw an error
return 0;
}
-
+
// Construct the role request message
- OFVendor roleRequest = (OFVendor)floodlightProvider.
+ OFVendor roleRequest = (OFVendor) floodlightProvider.
getOFMessageFactory().getMessage(OFType.VENDOR);
int xid = this.getNextTransactionId();
roleRequest.setXid(xid);
@@ -667,79 +672,76 @@
OFRoleRequestVendorData roleRequestData = new OFRoleRequestVendorData();
roleRequestData.setRole(nxRole);
roleRequest.setVendorData(roleRequestData);
- roleRequest.setLengthU(OFVendor.MINIMUM_LENGTH +
- roleRequestData.getLength());
-
+ roleRequest.setLengthU(OFVendor.MINIMUM_LENGTH +
+ roleRequestData.getLength());
+
// Send it to the switch
List<OFMessage> msglist = new ArrayList<OFMessage>(1);
msglist.add(roleRequest);
// FIXME: should this use this.write() in order for messages to
// be processed by handleOutgoingMessage()
this.channel.write(msglist);
-
+
pendingRoleRequests.add(new PendingRoleRequestEntry(xid, role, cookie));
return xid;
}
}
-
- /**
- * Deliver a RoleReply message to this switch. Checks if the reply
- * message matches the expected reply (head of the pending request queue).
+
+ /**
+ * Deliver a RoleReply message to this switch. Checks if the reply
+ * message matches the expected reply (head of the pending request queue).
* We require in-order delivery of replies. If there's any deviation from
- * our expectations we disconnect the switch.
- *
+ * our expectations we disconnect the switch.
+ * <p/>
* We must not check the received role against the controller's current
* role because there's no synchronization but that's fine @see RoleChanger
- *
+ * <p/>
* Will be called by the OFChannelHandler's receive loop
- *
- * @param xid Xid of the reply message
+ *
+ * @param xid Xid of the reply message
* @param role The Role in the the reply message
*/
@LogMessageDocs({
- @LogMessageDoc(level="ERROR",
- message="Switch {switch}: received unexpected role reply for " +
- "Role {role}" +
- " Disconnecting switch",
- explanation="The switch sent an unexpected HA role reply",
- recommendation=HA_CHECK_SWITCH),
- @LogMessageDoc(level="ERROR",
- message="Switch {switch}: expected role reply with " +
- "Xid {xid}, got {xid}. Disconnecting switch",
- explanation="The switch sent an unexpected HA role reply",
- recommendation=HA_CHECK_SWITCH),
- @LogMessageDoc(level="ERROR",
- message="Switch {switch}: expected role reply with " +
- "Role {role}, got {role}. Disconnecting switch",
- explanation="The switch sent an unexpected HA role reply",
- recommendation=HA_CHECK_SWITCH)
+ @LogMessageDoc(level = "ERROR",
+ message = "Switch {switch}: received unexpected role reply for " +
+ "Role {role}" +
+ " Disconnecting switch",
+ explanation = "The switch sent an unexpected HA role reply",
+ recommendation = HA_CHECK_SWITCH),
+ @LogMessageDoc(level = "ERROR",
+ message = "Switch {switch}: expected role reply with " +
+ "Xid {xid}, got {xid}. Disconnecting switch",
+ explanation = "The switch sent an unexpected HA role reply",
+ recommendation = HA_CHECK_SWITCH),
+ @LogMessageDoc(level = "ERROR",
+ message = "Switch {switch}: expected role reply with " +
+ "Role {role}, got {role}. Disconnecting switch",
+ explanation = "The switch sent an unexpected HA role reply",
+ recommendation = HA_CHECK_SWITCH)
})
protected void deliverRoleReply(int xid, Role role) {
- synchronized(pendingRoleRequests) {
+ synchronized (pendingRoleRequests) {
PendingRoleRequestEntry head = pendingRoleRequests.poll();
if (head == null) {
// Maybe don't disconnect if the role reply we received is
// for the same role we are already in.
- log.error("Switch {}: received unexpected role reply for Role {}" +
- " Disconnecting switch", this, role );
+ log.error("Switch {}: received unexpected role reply for Role {}" +
+ " Disconnecting switch", this, role);
this.channel.close();
- }
- else if (head.xid != xid) {
+ } else if (head.xid != xid) {
// check xid before role!!
log.error("Switch {}: expected role reply with " +
- "Xid {}, got {}. Disconnecting switch",
- new Object[] { this, head.xid, xid } );
+ "Xid {}, got {}. Disconnecting switch",
+ new Object[]{this, head.xid, xid});
this.channel.close();
- }
- else if (head.role != role) {
+ } else if (head.role != role) {
log.error("Switch {}: expected role reply with " +
- "Role {}, got {}. Disconnecting switch",
- new Object[] { this, head.role, role } );
+ "Role {}, got {}. Disconnecting switch",
+ new Object[]{this, head.role, role});
this.channel.close();
- }
- else {
+ } else {
log.debug("Received role reply message from {}, setting role to {}",
- this, role);
+ this, role);
if (this.role == null && getAttribute(SWITCH_SUPPORTS_NX_ROLE) == null) {
// The first role reply we received. Set the attribute
// that the switch supports roles
@@ -749,44 +751,47 @@
}
}
}
-
- /**
+
+ /**
* Checks whether the given xid matches the xid of the first pending
- * role request.
+ * role request.
+ *
* @param xid
- * @return
+ * @return
*/
- protected boolean checkFirstPendingRoleRequestXid (int xid) {
- synchronized(pendingRoleRequests) {
+ protected boolean checkFirstPendingRoleRequestXid(int xid) {
+ synchronized (pendingRoleRequests) {
PendingRoleRequestEntry head = pendingRoleRequests.peek();
if (head == null)
return false;
- else
+ else
return head.xid == xid;
}
}
-
+
/**
- * Checks whether the given request cookie matches the cookie of the first
+ * Checks whether the given request cookie matches the cookie of the first
* pending request
+ *
* @param cookie
* @return
*/
protected boolean checkFirstPendingRoleRequestCookie(long cookie) {
- synchronized(pendingRoleRequests) {
+ synchronized (pendingRoleRequests) {
PendingRoleRequestEntry head = pendingRoleRequests.peek();
if (head == null)
return false;
- else
+ else
return head.cookie == cookie;
}
}
-
+
/**
* Called if we receive a vendor error message indicating that roles
* are not supported by the switch. If the xid matches the first pending
* one, we'll mark the switch as not supporting roles and remove the head.
* Otherwise we ignore it.
+ *
* @param xid
*/
protected void deliverRoleRequestNotSupported(int xid) {
@@ -796,21 +801,21 @@
/**
* ONOS Extension to deliverRoleRequestNotSupported().
* This version return the Roll request made.
- * @see deliverRoleRequestNotSupported
+ *
* @param xid
* @return Role of attempted RoleRequest.
+ * @see deliverRoleRequestNotSupported
*/
protected Role deliverRoleRequestNotSupportedEx(int xid) {
- synchronized(pendingRoleRequests) {
+ synchronized (pendingRoleRequests) {
PendingRoleRequestEntry head = pendingRoleRequests.poll();
this.role = null;
- if (head!=null && head.xid == xid) {
+ if (head != null && head.xid == xid) {
setAttribute(SWITCH_SUPPORTS_NX_ROLE, false);
return head.role;
- }
- else {
- log.debug("Closing {} because a role request error didn't match " +
- "head of pendingRoleRequests queue", this);
+ } else {
+ log.debug("Closing {} because a role request error didn't match " +
+ "head of pendingRoleRequests queue", this);
this.channel.close();
return null;
}
@@ -873,9 +878,9 @@
}
- @Override
- public void setupRemoteSwitch(Long dpid) {
- this.datapathId = dpid;
- this.stringId = HexString.toHexString(this.datapathId);
- }
+ @Override
+ public void setupRemoteSwitch(Long dpid) {
+ this.datapathId = dpid;
+ this.stringId = HexString.toHexString(this.datapathId);
+ }
}
diff --git a/src/main/java/net/floodlightcontroller/core/internal/OpenflowPipelineFactory.java b/src/main/java/net/floodlightcontroller/core/internal/OpenflowPipelineFactory.java
index 4485709..e87989d 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/OpenflowPipelineFactory.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/OpenflowPipelineFactory.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.internal;
@@ -30,6 +30,7 @@
/**
* Creates a ChannelPipeline for a server-side openflow channel
+ *
* @author readams
*/
public class OpenflowPipelineFactory implements ChannelPipelineFactory {
@@ -39,7 +40,7 @@
protected Timer timer;
protected IdleStateHandler idleHandler;
protected ReadTimeoutHandler readTimeoutHandler;
-
+
public OpenflowPipelineFactory(Controller controller,
ThreadPoolExecutor pipelineExecutor) {
super();
@@ -49,21 +50,21 @@
this.idleHandler = new IdleStateHandler(timer, 20, 25, 0);
this.readTimeoutHandler = new ReadTimeoutHandler(timer, 30);
}
-
+
@Override
public ChannelPipeline getPipeline() throws Exception {
OFChannelState state = new OFChannelState();
-
+
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("ofmessagedecoder", new OFMessageDecoder());
pipeline.addLast("ofmessageencoder", new OFMessageEncoder());
pipeline.addLast("idle", idleHandler);
pipeline.addLast("timeout", readTimeoutHandler);
pipeline.addLast("handshaketimeout",
- new HandshakeTimeoutHandler(state, timer, 60)); // ONOS: was 15 increased it to fix Issue #296
+ new HandshakeTimeoutHandler(state, timer, 60)); // ONOS: was 15 increased it to fix Issue #296
if (pipelineExecutor != null)
pipeline.addLast("pipelineExecutor",
- new ExecutionHandler(pipelineExecutor));
+ new ExecutionHandler(pipelineExecutor));
pipeline.addLast("handler", controller.getChannelHandler(state));
return pipeline;
}
diff --git a/src/main/java/net/floodlightcontroller/core/internal/RoleChanger.java b/src/main/java/net/floodlightcontroller/core/internal/RoleChanger.java
index 4a21cad..6f1a350 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/RoleChanger.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/RoleChanger.java
@@ -15,93 +15,92 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-/**
+/**
* This class handles sending of RoleRequest messages to all connected switches.
- *
+ * <p/>
* Handling Role Requests is tricky. Roles are hard state on the switch and
* we can't query it so we need to make sure that we have consistent states
- * on the switches. Whenever we send a role request to the set of connected
- * switches we need to make sure that we've sent the request to all of them
- * before we process the next change request. If a new switch connects, we
+ * on the switches. Whenever we send a role request to the set of connected
+ * switches we need to make sure that we've sent the request to all of them
+ * before we process the next change request. If a new switch connects, we
* need to send it the current role and need to make sure that the current
* role doesn't change while we are doing it. We achieve this by synchronizing
* all these actions on Controller.roleChanger
- * On the receive side: we need to make sure that we receive a reply for each
- * request we send and that the reply is consistent with the request we sent.
+ * On the receive side: we need to make sure that we receive a reply for each
+ * request we send and that the reply is consistent with the request we sent.
* We'd also like to send the role request to the switch asynchronously in a
* separate thread so we don't block the REST API or other callers.
- *
+ * <p/>
* There are potential ways to relax these synchronization requirements:
* - "Generation ID" for each role request. However, this would be most useful
- * if it were global for the whole cluster
+ * if it were global for the whole cluster
* - Regularly resend the controller's current role. Don't know whether this
- * might have adverse effects on the switch.
- *
+ * might have adverse effects on the switch.
+ * <p/>
* Caveats:
- * - No way to know if another controller (not in our controller cluster)
- * sends MASTER requests to connected switches. Then we would drop to
- * slave role without knowing it. Could regularly resend the current role.
- * Ideally the switch would notify us if it demoted us. What happens if
- * the other controller also regularly resends the same role request?
- * Or if the health check determines that
- * a controller is dead but the controller is still talking to switches (maybe
- * just its health check failed) and resending the master role request....
- * We could try to detect if a switch demoted us to slave even if we think
- * we are master (error messages on packet outs, e.g., when sending LLDPs)
- *
- *
+ * - No way to know if another controller (not in our controller cluster)
+ * sends MASTER requests to connected switches. Then we would drop to
+ * slave role without knowing it. Could regularly resend the current role.
+ * Ideally the switch would notify us if it demoted us. What happens if
+ * the other controller also regularly resends the same role request?
+ * Or if the health check determines that
+ * a controller is dead but the controller is still talking to switches (maybe
+ * just its health check failed) and resending the master role request....
+ * We could try to detect if a switch demoted us to slave even if we think
+ * we are master (error messages on packet outs, e.g., when sending LLDPs)
+ * <p/>
+ * <p/>
* The general model of Role Request handling is as follows:
- *
- * - All role request messages are handled by this class. Class Controller
- * submits a role change request and the request gets queued. submitRequest
- * takes a Collection of switches to which to send the request. We make a copy
- * of this list.
- * - A thread takes these change requests from the queue and sends them to
- * all the switches (using our copy of the switch list).
+ * <p/>
+ * - All role request messages are handled by this class. Class Controller
+ * submits a role change request and the request gets queued. submitRequest
+ * takes a Collection of switches to which to send the request. We make a copy
+ * of this list.
+ * - A thread takes these change requests from the queue and sends them to
+ * all the switches (using our copy of the switch list).
* - The OFSwitchImpl sends the request over the wire and puts the request
- * into a queue of pending request (storing xid and role). We start a timeout
- * to make sure we eventually receive a reply from the switch. We use a single
- * timeout for each request submitted using submitRequest()
+ * into a queue of pending request (storing xid and role). We start a timeout
+ * to make sure we eventually receive a reply from the switch. We use a single
+ * timeout for each request submitted using submitRequest()
* - After the timeout triggers we go over the list of switches again and
- * check that a response has been received (by checking the head of the
- * OFSwitchImpl's queue of pending requests)
+ * check that a response has been received (by checking the head of the
+ * OFSwitchImpl's queue of pending requests)
* - We handle requests and timeouts in the same thread. We use a priority queue
- * to schedule them so we are guaranteed that they are processed in
- * the same order as they are submitted. If a request times out we drop
- * the connection to this switch.
+ * to schedule them so we are guaranteed that they are processed in
+ * the same order as they are submitted. If a request times out we drop
+ * the connection to this switch.
* - Since we decouple submission of role change requests and actually sending
- * them we cannot check a received role reply against the controller's current
- * role because the controller's current role could have changed again.
+ * them we cannot check a received role reply against the controller's current
+ * role because the controller's current role could have changed again.
* - Receiving Role Reply messages is handled by OFChannelHandler and
- * OFSwitchImpl directly. The OFSwitchImpl checks if the received request
- * is as expected (xid and role match the head of the pending queue in
- * OFSwitchImpl). If so
- * the switch updates its role. Otherwise the connection is dropped. If this
- * is the first reply, the SWITCH_SUPPORTS_NX_ROLE attribute is set.
- * Next, we call addSwitch(), removeSwitch() to update the list of active
- * switches if appropriate.
- * - If we receive an Error indicating that roles are not supported by the
- * switch, we set the SWITCH_SUPPORTS_NX_ROLE to false. We keep the
- * switch connection alive while in MASTER and EQUAL role.
- * (TODO: is this the right behavior for EQUAL??). If the role changes to
- * SLAVE the switch connection is dropped (remember: only if the switch
- * doesn't support role requests)
- * The expected behavior is that the switch will probably try to reconnect
- * repeatedly (with some sort of exponential backoff), but after a while
- * will give-up and move on to the next controller-IP configured on the
- * switch. This is the serial failover mechanism from OpenFlow spec v1.0.
- *
+ * OFSwitchImpl directly. The OFSwitchImpl checks if the received request
+ * is as expected (xid and role match the head of the pending queue in
+ * OFSwitchImpl). If so
+ * the switch updates its role. Otherwise the connection is dropped. If this
+ * is the first reply, the SWITCH_SUPPORTS_NX_ROLE attribute is set.
+ * Next, we call addSwitch(), removeSwitch() to update the list of active
+ * switches if appropriate.
+ * - If we receive an Error indicating that roles are not supported by the
+ * switch, we set the SWITCH_SUPPORTS_NX_ROLE to false. We keep the
+ * switch connection alive while in MASTER and EQUAL role.
+ * (TODO: is this the right behavior for EQUAL??). If the role changes to
+ * SLAVE the switch connection is dropped (remember: only if the switch
+ * doesn't support role requests)
+ * The expected behavior is that the switch will probably try to reconnect
+ * repeatedly (with some sort of exponential backoff), but after a while
+ * will give-up and move on to the next controller-IP configured on the
+ * switch. This is the serial failover mechanism from OpenFlow spec v1.0.
+ * <p/>
* New switch connection:
* - Switch handshake is done without sending any role request messages.
* - After handshake completes, switch is added to the list of connected switches
- * and we send the first role request message if role
- * requests are enabled. If roles are disabled automatically promote switch to
- * active switch list and clear FlowTable.
+ * and we send the first role request message if role
+ * requests are enabled. If roles are disabled automatically promote switch to
+ * active switch list and clear FlowTable.
* - When we receive the first reply we proceed as above. In addition, if
- * the role request is for MASTER we wipe the flow table. We do not wipe
- * the flow table if the switch connected while role supported was disabled
- * on the controller.
- *
+ * the role request is for MASTER we wipe the flow table. We do not wipe
+ * the flow table if the switch connected while role supported was disabled
+ * on the controller.
*/
public class RoleChanger {
// FIXME: Upon closer inspection DelayQueue seems to be somewhat broken.
@@ -119,49 +118,58 @@
protected long lastSubmitTime;
protected Thread workerThread;
protected long timeout;
- protected static long DEFAULT_TIMEOUT = 15L*1000*1000*1000L; // 15s
+ protected static long DEFAULT_TIMEOUT = 15L * 1000 * 1000 * 1000L; // 15s
protected final static Logger log = LoggerFactory.getLogger(RoleChanger.class);
- /**
- * A queued task to be handled by the Role changer thread.
+
+ /**
+ * A queued task to be handled by the Role changer thread.
*/
protected static class RoleChangeTask implements Delayed {
- protected enum Type {
- /** This is a request. Dispatch the role update to switches */
+ protected enum Type {
+ /**
+ * This is a request. Dispatch the role update to switches
+ */
REQUEST,
- /** This is a timeout task. Check if all switches have
- correctly replied to the previously dispatched role request */
+ /**
+ * This is a timeout task. Check if all switches have
+ * correctly replied to the previously dispatched role request
+ */
TIMEOUT
}
+
// The set of switches to work on
public Collection<OFSwitchImpl> switches;
public Role role;
public Type type;
// the time when the task should run as nanoTime()
public long deadline;
+
public RoleChangeTask(Collection<OFSwitchImpl> switches, Role role, long deadline) {
this.switches = switches;
this.role = role;
this.type = Type.REQUEST;
this.deadline = deadline;
}
+
@Override
public int compareTo(Delayed o) {
Long timeRemaining = getDelay(TimeUnit.NANOSECONDS);
return timeRemaining.compareTo(o.getDelay(TimeUnit.NANOSECONDS));
}
+
@Override
public long getDelay(TimeUnit tu) {
long timeRemaining = deadline - System.nanoTime();
return tu.convert(timeRemaining, TimeUnit.NANOSECONDS);
}
}
-
- @LogMessageDoc(level="ERROR",
- message="RoleRequestWorker task had an uncaught exception.",
- explanation="An unknown occured while processing an HA " +
- "role change event.",
- recommendation=LogMessageDoc.GENERIC_ACTION)
- protected class RoleRequestWorker extends Thread {
+
+ @LogMessageDoc(level = "ERROR",
+ message = "RoleRequestWorker task had an uncaught exception.",
+ explanation = "An unknown occured while processing an HA " +
+ "role change event.",
+ recommendation = LogMessageDoc.GENERIC_ACTION)
+ protected class RoleRequestWorker extends Thread {
@Override
public void run() {
RoleChangeTask t;
@@ -182,61 +190,59 @@
t.type = RoleChangeTask.Type.TIMEOUT;
t.deadline += timeout;
pendingTasks.put(t);
- }
- else {
+ } else {
verifyRoleReplyReceived(t.switches, t.deadline);
}
}
- }
- catch (Exception e) {
+ } catch (Exception e) {
// Should never get here
- log.error("RoleRequestWorker task had an uncaught exception. ",
- e);
- }
- finally {
+ log.error("RoleRequestWorker task had an uncaught exception. ",
+ e);
+ } finally {
// Be nice in case we earlier caught InterruptedExecution
if (interrupted)
Thread.currentThread().interrupt();
}
} // end loop
}
-
+
public RoleChanger() {
this.pendingTasks = new DelayQueue<RoleChangeTask>();
this.workerThread = new Thread(new RoleRequestWorker());
this.timeout = DEFAULT_TIMEOUT;
this.workerThread.start();
}
-
-
+
+
public synchronized void submitRequest(Collection<OFSwitchImpl> switches, Role role) {
long deadline = System.nanoTime();
// Grrr. stupid DelayQueue. Make sre we have at least 10ms between
// role request messages.
- if (deadline - lastSubmitTime < 10 * 1000*1000)
- deadline = lastSubmitTime + 10 * 1000*1000;
+ if (deadline - lastSubmitTime < 10 * 1000 * 1000)
+ deadline = lastSubmitTime + 10 * 1000 * 1000;
// make a copy of the list
ArrayList<OFSwitchImpl> switches_copy = new ArrayList<OFSwitchImpl>(switches);
RoleChangeTask req = new RoleChangeTask(switches_copy, role, deadline);
pendingTasks.put(req);
lastSubmitTime = deadline;
}
-
+
/**
- * Send a role request message to switches. This checks the capabilities
- * of the switch for understanding role request messaging. Currently we only
- * support the OVS-style role request message, but once the controller
- * supports OF 1.2, this function will also handle sending out the
+ * Send a role request message to switches. This checks the capabilities
+ * of the switch for understanding role request messaging. Currently we only
+ * support the OVS-style role request message, but once the controller
+ * supports OF 1.2, this function will also handle sending out the
* OF 1.2-style role request message.
- * @param switches the collection of switches to send the request too
- * @param role the role to request
+ *
+ * @param switches the collection of switches to send the request too
+ * @param role the role to request
*/
- @LogMessageDoc(level="WARN",
- message="Failed to send role request message " +
+ @LogMessageDoc(level = "WARN",
+ message = "Failed to send role request message " +
"to switch {switch}: {message}. Disconnecting",
- explanation="An I/O error occurred while attempting to change " +
- "the switch HA role.",
- recommendation=LogMessageDoc.CHECK_SWITCH)
+ explanation = "An I/O error occurred while attempting to change " +
+ "the switch HA role.",
+ recommendation = LogMessageDoc.CHECK_SWITCH)
protected void sendRoleRequest(Collection<OFSwitchImpl> switches,
Role role, long cookie) {
// There are three cases to consider:
@@ -268,33 +274,33 @@
// things are configured correctly) it will walk down its list of
// controllers and connect to the current master controller.
Iterator<OFSwitchImpl> iter = switches.iterator();
- while(iter.hasNext()) {
+ while (iter.hasNext()) {
OFSwitchImpl sw = iter.next();
try {
Boolean supportsNxRole = (Boolean)
sw.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE);
if ((supportsNxRole == null) || supportsNxRole) {
// Handle cases #1 and #2
- log.debug("Sending NxRoleRequest to {}", sw);
+ log.debug("Sending NxRoleRequest to {}", sw);
sw.sendNxRoleRequest(role, cookie);
} else {
- if (role == Role.MASTER) {
- // ONOS extension:
- log.debug("Switch {} doesn't support NxRoleRequests, but sending " +
- "{} request anyway", sw, role);
- //Send the role request anyway, even though we know the switch
- //doesn't support it. The switch will give an error and in our
- //error handling code we will add the switch.
- //NOTE we *could* just add the switch right away rather than
- //going through the overhead of sending a role request - however
- //we then have to deal with concurrency issues resulting from
- //calling addSwitch outside of a netty handler.
- sw.sendNxRoleRequest(role, cookie);
- }
- // Handle case #3
- else if (role == Role.SLAVE) {
+ if (role == Role.MASTER) {
+ // ONOS extension:
+ log.debug("Switch {} doesn't support NxRoleRequests, but sending " +
+ "{} request anyway", sw, role);
+ //Send the role request anyway, even though we know the switch
+ //doesn't support it. The switch will give an error and in our
+ //error handling code we will add the switch.
+ //NOTE we *could* just add the switch right away rather than
+ //going through the overhead of sending a role request - however
+ //we then have to deal with concurrency issues resulting from
+ //calling addSwitch outside of a netty handler.
+ sw.sendNxRoleRequest(role, cookie);
+ }
+ // Handle case #3
+ else if (role == Role.SLAVE) {
log.debug("Disconnecting switch {} that doesn't support " +
- "role request messages from a controller that went to SLAVE mode");
+ "role request messages from a controller that went to SLAVE mode");
// Closing the channel should result in a call to
// channelDisconnect which updates all state
sw.getChannel().close();
@@ -302,33 +308,34 @@
}
}
} catch (IOException e) {
- log.warn("Failed to send role request message " +
- "to switch {}: {}. Disconnecting",
- sw, e);
+ log.warn("Failed to send role request message " +
+ "to switch {}: {}. Disconnecting",
+ sw, e);
sw.getChannel().close();
iter.remove();
}
}
}
-
+
/**
* Verify that switches have received a role reply message we sent earlier
+ *
* @param switches the collection of switches to send the request too
- * @param cookie the cookie of the request
+ * @param cookie the cookie of the request
*/
- @LogMessageDoc(level="WARN",
- message="Timeout while waiting for role reply from switch {switch}."
+ @LogMessageDoc(level = "WARN",
+ message = "Timeout while waiting for role reply from switch {switch}."
+ " Disconnecting",
- explanation="Timed out waiting for the switch to respond to " +
- "a request to change the HA role.",
- recommendation=LogMessageDoc.CHECK_SWITCH)
+ explanation = "Timed out waiting for the switch to respond to " +
+ "a request to change the HA role.",
+ recommendation = LogMessageDoc.CHECK_SWITCH)
protected void verifyRoleReplyReceived(Collection<OFSwitchImpl> switches,
- long cookie) {
- for (OFSwitchImpl sw: switches) {
+ long cookie) {
+ for (OFSwitchImpl sw : switches) {
if (sw.checkFirstPendingRoleRequestCookie(cookie)) {
sw.getChannel().close();
log.warn("Timeout while waiting for role reply from switch {}."
- + " Disconnecting", sw);
+ + " Disconnecting", sw);
}
}
}
diff --git a/src/main/java/net/floodlightcontroller/core/internal/SwitchStateException.java b/src/main/java/net/floodlightcontroller/core/internal/SwitchStateException.java
index d2a928e..8e49799 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/SwitchStateException.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/SwitchStateException.java
@@ -1,24 +1,24 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.internal;
/**
- *
+ *
*/
public class SwitchStateException extends Exception {
diff --git a/src/main/java/net/floodlightcontroller/core/module/FloodlightModuleContext.java b/src/main/java/net/floodlightcontroller/core/module/FloodlightModuleContext.java
index 0cbae32..5b311a1 100644
--- a/src/main/java/net/floodlightcontroller/core/module/FloodlightModuleContext.java
+++ b/src/main/java/net/floodlightcontroller/core/module/FloodlightModuleContext.java
@@ -6,99 +6,103 @@
/**
* The service registry for an IFloodlightProvider.
+ *
* @author alexreimers
*/
public class FloodlightModuleContext implements IFloodlightModuleContext {
- protected Map<Class<? extends IFloodlightService>, IFloodlightService> serviceMap;
- protected Map<Class<? extends IFloodlightModule>, Map<String, String>> configParams;
- protected Collection<IFloodlightModule> moduleSet;
-
- /**
- * Creates the ModuleContext for use with this IFloodlightProvider.
- * This will be used as a module registry for all IFloodlightModule(s).
- */
- public FloodlightModuleContext() {
- serviceMap =
- new HashMap<Class<? extends IFloodlightService>,
- IFloodlightService>();
- configParams =
- new HashMap<Class<? extends IFloodlightModule>,
- Map<String, String>>();
- }
-
- /**
- * Adds a IFloodlightModule for this Context.
- * @param clazz the service class
- * @param service The IFloodlightService to add to the registry
- */
- public void addService(Class<? extends IFloodlightService> clazz,
- IFloodlightService service) {
- serviceMap.put(clazz, service);
- }
-
- @SuppressWarnings("unchecked")
+ protected Map<Class<? extends IFloodlightService>, IFloodlightService> serviceMap;
+ protected Map<Class<? extends IFloodlightModule>, Map<String, String>> configParams;
+ protected Collection<IFloodlightModule> moduleSet;
+
+ /**
+ * Creates the ModuleContext for use with this IFloodlightProvider.
+ * This will be used as a module registry for all IFloodlightModule(s).
+ */
+ public FloodlightModuleContext() {
+ serviceMap =
+ new HashMap<Class<? extends IFloodlightService>,
+ IFloodlightService>();
+ configParams =
+ new HashMap<Class<? extends IFloodlightModule>,
+ Map<String, String>>();
+ }
+
+ /**
+ * Adds a IFloodlightModule for this Context.
+ *
+ * @param clazz the service class
+ * @param service The IFloodlightService to add to the registry
+ */
+ public void addService(Class<? extends IFloodlightService> clazz,
+ IFloodlightService service) {
+ serviceMap.put(clazz, service);
+ }
+
+ @SuppressWarnings("unchecked")
@Override
- public <T extends IFloodlightService> T getServiceImpl(Class<T> service) {
- IFloodlightService s = serviceMap.get(service);
- return (T)s;
- }
-
- @Override
- public Collection<Class<? extends IFloodlightService>> getAllServices() {
- return serviceMap.keySet();
- }
-
- @Override
- public Collection<IFloodlightModule> getAllModules() {
- return moduleSet;
- }
-
- public void setModuleSet(Collection<IFloodlightModule> modSet) {
- this.moduleSet = modSet;
- }
-
- /**
- * Gets the configuration parameter map for a module
- * @param module The module to get the configuration map for, usually yourself
- * @return A map containing all the configuration parameters for the module, may be empty
- */
- @Override
- public Map<String, String> getConfigParams(IFloodlightModule module) {
- Map<String, String> retMap = configParams.get(module.getClass());
- if (retMap == null) {
- // Return an empty map if none exists so the module does not
- // need to null check the map
- retMap = new HashMap<String, String>();
- configParams.put(module.getClass(), retMap);
- }
+ public <T extends IFloodlightService> T getServiceImpl(Class<T> service) {
+ IFloodlightService s = serviceMap.get(service);
+ return (T) s;
+ }
- // also add any configuration parameters for superclasses, but
- // only if more specific configuration does not override it
- for (Class<? extends IFloodlightModule> c : configParams.keySet()) {
- if (c.isInstance(module)) {
- for (Map.Entry<String, String> ent : configParams.get(c).entrySet()) {
- if (!retMap.containsKey(ent.getKey())) {
- retMap.put(ent.getKey(), ent.getValue());
- }
- }
- }
- }
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getAllServices() {
+ return serviceMap.keySet();
+ }
- return retMap;
- }
-
- /**
- * Adds a configuration parameter for a module
- * @param mod The fully qualified module name to add the parameter to
- * @param key The configuration parameter key
- * @param value The configuration parameter value
- */
- public void addConfigParam(IFloodlightModule mod, String key, String value) {
- Map<String, String> moduleParams = configParams.get(mod.getClass());
- if (moduleParams == null) {
- moduleParams = new HashMap<String, String>();
- configParams.put(mod.getClass(), moduleParams);
- }
- moduleParams.put(key, value);
- }
- }
+ @Override
+ public Collection<IFloodlightModule> getAllModules() {
+ return moduleSet;
+ }
+
+ public void setModuleSet(Collection<IFloodlightModule> modSet) {
+ this.moduleSet = modSet;
+ }
+
+ /**
+ * Gets the configuration parameter map for a module
+ *
+ * @param module The module to get the configuration map for, usually yourself
+ * @return A map containing all the configuration parameters for the module, may be empty
+ */
+ @Override
+ public Map<String, String> getConfigParams(IFloodlightModule module) {
+ Map<String, String> retMap = configParams.get(module.getClass());
+ if (retMap == null) {
+ // Return an empty map if none exists so the module does not
+ // need to null check the map
+ retMap = new HashMap<String, String>();
+ configParams.put(module.getClass(), retMap);
+ }
+
+ // also add any configuration parameters for superclasses, but
+ // only if more specific configuration does not override it
+ for (Class<? extends IFloodlightModule> c : configParams.keySet()) {
+ if (c.isInstance(module)) {
+ for (Map.Entry<String, String> ent : configParams.get(c).entrySet()) {
+ if (!retMap.containsKey(ent.getKey())) {
+ retMap.put(ent.getKey(), ent.getValue());
+ }
+ }
+ }
+ }
+
+ return retMap;
+ }
+
+ /**
+ * Adds a configuration parameter for a module
+ *
+ * @param mod The fully qualified module name to add the parameter to
+ * @param key The configuration parameter key
+ * @param value The configuration parameter value
+ */
+ public void addConfigParam(IFloodlightModule mod, String key, String value) {
+ Map<String, String> moduleParams = configParams.get(mod.getClass());
+ if (moduleParams == null) {
+ moduleParams = new HashMap<String, String>();
+ configParams.put(mod.getClass(), moduleParams);
+ }
+ moduleParams.put(key, value);
+ }
+}
diff --git a/src/main/java/net/floodlightcontroller/core/module/FloodlightModuleException.java b/src/main/java/net/floodlightcontroller/core/module/FloodlightModuleException.java
index 20ccc86..8519a3c 100644
--- a/src/main/java/net/floodlightcontroller/core/module/FloodlightModuleException.java
+++ b/src/main/java/net/floodlightcontroller/core/module/FloodlightModuleException.java
@@ -1,9 +1,9 @@
package net.floodlightcontroller.core.module;
public class FloodlightModuleException extends Exception {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- public FloodlightModuleException(String error) {
- super(error);
- }
+ public FloodlightModuleException(String error) {
+ super(error);
+ }
}
diff --git a/src/main/java/net/floodlightcontroller/core/module/FloodlightModuleLoader.java b/src/main/java/net/floodlightcontroller/core/module/FloodlightModuleLoader.java
index 5ae7914..6913b1c 100644
--- a/src/main/java/net/floodlightcontroller/core/module/FloodlightModuleLoader.java
+++ b/src/main/java/net/floodlightcontroller/core/module/FloodlightModuleLoader.java
@@ -26,143 +26,145 @@
/**
* Finds all Floodlight modules in the class path and loads/starts them.
- * @author alexreimers
*
+ * @author alexreimers
*/
public class FloodlightModuleLoader {
- protected final static Logger logger =
+ protected final static Logger logger =
LoggerFactory.getLogger(FloodlightModuleLoader.class);
protected static Map<Class<? extends IFloodlightService>,
- Collection<IFloodlightModule>> serviceMap;
+ Collection<IFloodlightModule>> serviceMap;
protected static Map<IFloodlightModule,
- Collection<Class<? extends
- IFloodlightService>>> moduleServiceMap;
+ Collection<Class<? extends
+ IFloodlightService>>> moduleServiceMap;
protected static Map<String, IFloodlightModule> moduleNameMap;
protected static Object lock = new Object();
-
+
protected FloodlightModuleContext floodlightModuleContext;
public static final String FLOODLIGHT_MODULES_KEY =
"floodlight.modules";
-
- public FloodlightModuleLoader() {
- floodlightModuleContext = new FloodlightModuleContext();
- }
-
- /**
- * Finds all IFloodlightModule(s) in the classpath. It creates 3 Maps.
- * serviceMap -> Maps a service to a module
- * moduleServiceMap -> Maps a module to all the services it provides
- * moduleNameMap -> Maps the string name to the module
- * @throws FloodlightModuleException If two modules are specified in the configuration
- * that provide the same service.
- */
- protected static void findAllModules(Collection<String> mList) throws FloodlightModuleException {
- synchronized (lock) {
- if (serviceMap != null) return;
- serviceMap =
- new HashMap<Class<? extends IFloodlightService>,
- Collection<IFloodlightModule>>();
- moduleServiceMap =
- new HashMap<IFloodlightModule,
- Collection<Class<? extends
- IFloodlightService>>>();
- moduleNameMap = new HashMap<String, IFloodlightModule>();
-
- // Get all the current modules in the classpath
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- ServiceLoader<IFloodlightModule> moduleLoader
- = ServiceLoader.load(IFloodlightModule.class, cl);
- // Iterate for each module, iterate through and add it's services
- Iterator<IFloodlightModule> moduleIter = moduleLoader.iterator();
- while (moduleIter.hasNext()) {
- IFloodlightModule m = null;
- try {
- m = moduleIter.next();
- } catch (ServiceConfigurationError sce) {
- logger.debug("Could not find module: {}", sce.getMessage());
- //moduleIter.remove();
- continue;
- }
- //}
- //for (IFloodlightModule m : moduleLoader) {
- if (logger.isDebugEnabled()) {
- logger.debug("Found module " + m.getClass().getName());
- }
- // Set up moduleNameMap
- moduleNameMap.put(m.getClass().getCanonicalName(), m);
+ public FloodlightModuleLoader() {
+ floodlightModuleContext = new FloodlightModuleContext();
+ }
- // Set up serviceMap
- Collection<Class<? extends IFloodlightService>> servs =
- m.getModuleServices();
- if (servs != null) {
- moduleServiceMap.put(m, servs);
- for (Class<? extends IFloodlightService> s : servs) {
- Collection<IFloodlightModule> mods =
- serviceMap.get(s);
- if (mods == null) {
- mods = new ArrayList<IFloodlightModule>();
- serviceMap.put(s, mods);
- }
- mods.add(m);
- // Make sure they haven't specified duplicate modules in the config
- int dupInConf = 0;
- for (IFloodlightModule cMod : mods) {
- if (mList.contains(cMod.getClass().getCanonicalName()))
- dupInConf += 1;
- }
-
- if (dupInConf > 1) {
- String duplicateMods = "";
+ /**
+ * Finds all IFloodlightModule(s) in the classpath. It creates 3 Maps.
+ * serviceMap -> Maps a service to a module
+ * moduleServiceMap -> Maps a module to all the services it provides
+ * moduleNameMap -> Maps the string name to the module
+ *
+ * @throws FloodlightModuleException If two modules are specified in the configuration
+ * that provide the same service.
+ */
+ protected static void findAllModules(Collection<String> mList) throws FloodlightModuleException {
+ synchronized (lock) {
+ if (serviceMap != null) return;
+ serviceMap =
+ new HashMap<Class<? extends IFloodlightService>,
+ Collection<IFloodlightModule>>();
+ moduleServiceMap =
+ new HashMap<IFloodlightModule,
+ Collection<Class<? extends
+ IFloodlightService>>>();
+ moduleNameMap = new HashMap<String, IFloodlightModule>();
+
+ // Get all the current modules in the classpath
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ ServiceLoader<IFloodlightModule> moduleLoader
+ = ServiceLoader.load(IFloodlightModule.class, cl);
+ // Iterate for each module, iterate through and add it's services
+ Iterator<IFloodlightModule> moduleIter = moduleLoader.iterator();
+ while (moduleIter.hasNext()) {
+ IFloodlightModule m = null;
+ try {
+ m = moduleIter.next();
+ } catch (ServiceConfigurationError sce) {
+ logger.debug("Could not find module: {}", sce.getMessage());
+ //moduleIter.remove();
+ continue;
+ }
+ //}
+ //for (IFloodlightModule m : moduleLoader) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Found module " + m.getClass().getName());
+ }
+
+ // Set up moduleNameMap
+ moduleNameMap.put(m.getClass().getCanonicalName(), m);
+
+ // Set up serviceMap
+ Collection<Class<? extends IFloodlightService>> servs =
+ m.getModuleServices();
+ if (servs != null) {
+ moduleServiceMap.put(m, servs);
+ for (Class<? extends IFloodlightService> s : servs) {
+ Collection<IFloodlightModule> mods =
+ serviceMap.get(s);
+ if (mods == null) {
+ mods = new ArrayList<IFloodlightModule>();
+ serviceMap.put(s, mods);
+ }
+ mods.add(m);
+ // Make sure they haven't specified duplicate modules in the config
+ int dupInConf = 0;
+ for (IFloodlightModule cMod : mods) {
+ if (mList.contains(cMod.getClass().getCanonicalName()))
+ dupInConf += 1;
+ }
+
+ if (dupInConf > 1) {
+ String duplicateMods = "";
for (IFloodlightModule mod : mods) {
duplicateMods += mod.getClass().getCanonicalName() + ", ";
}
- throw new FloodlightModuleException("ERROR! The configuraiton" +
- " file specifies more than one module that provides the service " +
- s.getCanonicalName() +". Please specify only ONE of the " +
- "following modules in the config file: " + duplicateMods);
- }
- }
- }
- }
- }
- }
-
- /**
- * Loads the modules from a specified configuration file.
- * @param fName The configuration file path
- * @return An IFloodlightModuleContext with all the modules to be started
- * @throws FloodlightModuleException
- */
- @LogMessageDocs({
- @LogMessageDoc(level="INFO",
- message="Loading modules from file {file name}",
- explanation="The controller is initializing its module " +
- "configuration from the specified properties file"),
- @LogMessageDoc(level="INFO",
- message="Loading default modules",
- explanation="The controller is initializing its module " +
- "configuration to the default configuration"),
- @LogMessageDoc(level="ERROR",
- message="Could not load module configuration file",
- explanation="The controller failed to read the " +
- "module configuration file",
- recommendation="Verify that the module configuration is " +
- "present. " + LogMessageDoc.CHECK_CONTROLLER),
- @LogMessageDoc(level="ERROR",
- message="Could not load default modules",
- explanation="The controller failed to read the default " +
- "module configuration",
- recommendation=LogMessageDoc.CHECK_CONTROLLER)
- })
- public IFloodlightModuleContext loadModulesFromConfig(String fName)
- throws FloodlightModuleException {
- Properties prop = new Properties();
-
- File f = new File(fName);
- if (f.isFile()) {
+ throw new FloodlightModuleException("ERROR! The configuraiton" +
+ " file specifies more than one module that provides the service " +
+ s.getCanonicalName() + ". Please specify only ONE of the " +
+ "following modules in the config file: " + duplicateMods);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Loads the modules from a specified configuration file.
+ *
+ * @param fName The configuration file path
+ * @return An IFloodlightModuleContext with all the modules to be started
+ * @throws FloodlightModuleException
+ */
+ @LogMessageDocs({
+ @LogMessageDoc(level = "INFO",
+ message = "Loading modules from file {file name}",
+ explanation = "The controller is initializing its module " +
+ "configuration from the specified properties file"),
+ @LogMessageDoc(level = "INFO",
+ message = "Loading default modules",
+ explanation = "The controller is initializing its module " +
+ "configuration to the default configuration"),
+ @LogMessageDoc(level = "ERROR",
+ message = "Could not load module configuration file",
+ explanation = "The controller failed to read the " +
+ "module configuration file",
+ recommendation = "Verify that the module configuration is " +
+ "present. " + LogMessageDoc.CHECK_CONTROLLER),
+ @LogMessageDoc(level = "ERROR",
+ message = "Could not load default modules",
+ explanation = "The controller failed to read the default " +
+ "module configuration",
+ recommendation = LogMessageDoc.CHECK_CONTROLLER)
+ })
+ public IFloodlightModuleContext loadModulesFromConfig(String fName)
+ throws FloodlightModuleException {
+ Properties prop = new Properties();
+
+ File f = new File(fName);
+ if (f.isFile()) {
logger.info("Loading modules from file {}", fName);
try {
prop.load(new FileInputStream(fName));
@@ -174,40 +176,41 @@
logger.error("No configuration file specified");
System.exit(1);
}
-
+
String moduleList = prop.getProperty(FLOODLIGHT_MODULES_KEY)
- .replaceAll("\\s", "");
+ .replaceAll("\\s", "");
Collection<String> configMods = new ArrayList<String>();
configMods.addAll(Arrays.asList(moduleList.split(",")));
return loadModulesFromList(configMods, prop);
- }
-
- /**
- * Loads modules (and their dependencies) specified in the list
- * @param mList The array of fully qualified module names
- * @param ignoreList The list of Floodlight services NOT to
- * load modules for. Used for unit testing.
- * @return The ModuleContext containing all the loaded modules
- * @throws FloodlightModuleException
- */
- protected IFloodlightModuleContext loadModulesFromList(Collection<String> configMods, Properties prop,
- Collection<IFloodlightService> ignoreList) throws FloodlightModuleException {
- logger.debug("Starting module loader");
- if (logger.isDebugEnabled() && ignoreList != null)
- logger.debug("Not loading module services " + ignoreList.toString());
+ }
+
+ /**
+ * Loads modules (and their dependencies) specified in the list
+ *
+ * @param mList The array of fully qualified module names
+ * @param ignoreList The list of Floodlight services NOT to
+ * load modules for. Used for unit testing.
+ * @return The ModuleContext containing all the loaded modules
+ * @throws FloodlightModuleException
+ */
+ protected IFloodlightModuleContext loadModulesFromList(Collection<String> configMods, Properties prop,
+ Collection<IFloodlightService> ignoreList) throws FloodlightModuleException {
+ logger.debug("Starting module loader");
+ if (logger.isDebugEnabled() && ignoreList != null)
+ logger.debug("Not loading module services " + ignoreList.toString());
findAllModules(configMods);
-
+
Collection<IFloodlightModule> moduleSet = new ArrayList<IFloodlightModule>();
Map<Class<? extends IFloodlightService>, IFloodlightModule> moduleMap =
new HashMap<Class<? extends IFloodlightService>,
- IFloodlightModule>();
+ IFloodlightModule>();
Queue<String> moduleQ = new LinkedList<String>();
// Add the explicitly configured modules to the q
moduleQ.addAll(configMods);
Set<String> modsVisited = new HashSet<String>();
-
+
while (!moduleQ.isEmpty()) {
String moduleName = moduleQ.remove();
if (modsVisited.contains(moduleName))
@@ -215,37 +218,37 @@
modsVisited.add(moduleName);
IFloodlightModule module = moduleNameMap.get(moduleName);
if (module == null) {
- throw new FloodlightModuleException("Module " +
+ throw new FloodlightModuleException("Module " +
moduleName + " not found");
}
// If the module provies a service that is in the
// services ignorelist don't load it.
if ((ignoreList != null) && (module.getModuleServices() != null)) {
- for (IFloodlightService ifs : ignoreList) {
- for (Class<?> intsIgnore : ifs.getClass().getInterfaces()) {
- //System.out.println(intsIgnore.getName());
- // Check that the interface extends IFloodlightService
- //if (intsIgnore.isAssignableFrom(IFloodlightService.class)) {
- //System.out.println(module.getClass().getName());
- if (intsIgnore.isAssignableFrom(module.getClass())) {
- // We now ignore loading this module.
- logger.debug("Not loading module " +
- module.getClass().getCanonicalName() +
- " because interface " +
- intsIgnore.getCanonicalName() +
- " is in the ignore list.");
-
- continue;
- }
- //}
- }
- }
+ for (IFloodlightService ifs : ignoreList) {
+ for (Class<?> intsIgnore : ifs.getClass().getInterfaces()) {
+ //System.out.println(intsIgnore.getName());
+ // Check that the interface extends IFloodlightService
+ //if (intsIgnore.isAssignableFrom(IFloodlightService.class)) {
+ //System.out.println(module.getClass().getName());
+ if (intsIgnore.isAssignableFrom(module.getClass())) {
+ // We now ignore loading this module.
+ logger.debug("Not loading module " +
+ module.getClass().getCanonicalName() +
+ " because interface " +
+ intsIgnore.getCanonicalName() +
+ " is in the ignore list.");
+
+ continue;
+ }
+ //}
+ }
+ }
}
-
+
// Add the module to be loaded
addModule(moduleMap, moduleSet, module);
// Add it's dep's to the queue
- Collection<Class<? extends IFloodlightService>> deps =
+ Collection<Class<? extends IFloodlightService>> deps =
module.getModuleDependencies();
if (deps != null) {
for (Class<? extends IFloodlightService> c : deps) {
@@ -275,11 +278,11 @@
for (IFloodlightModule mod : mods) {
duplicateMods += mod.getClass().getCanonicalName() + ", ";
}
- throw new FloodlightModuleException("ERROR! Found more " +
- "than one (" + mods.size() + ") IFloodlightModules that provides " +
- "service " + c.toString() +
- ". Please specify one of the following modules in the config: " +
- duplicateMods);
+ throw new FloodlightModuleException("ERROR! Found more " +
+ "than one (" + mods.size() + ") IFloodlightModules that provides " +
+ "service " + c.toString() +
+ ". Please specify one of the following modules in the config: " +
+ duplicateMods);
}
}
}
@@ -287,93 +290,95 @@
}
}
- //
- // Reorder the moduleSet to take into account the module dependencies:
- // If a module depends on the service provided by another module, the
- // latter should be included before the former.
- //
- Collection<IFloodlightModule> orderedModuleSet =
- new ArrayList<IFloodlightModule>();
- while (! moduleSet.isEmpty()) {
- //
- // Evaluate each module in the unsorted collection: if all its
- // dependencies are in the orderedModuleSet, then add it to the
- // orderedModuleSet.
- //
- boolean moduleWasSorted = false;
- for (IFloodlightModule module : moduleSet) {
- Collection<Class<? extends IFloodlightService>> deps =
- module.getModuleDependencies();
- boolean allDepsFound = true;
- if (deps != null) {
- for (Class<? extends IFloodlightService> c : deps) {
- IFloodlightModule m = moduleMap.get(c);
- // NOTE: Earlier we checked that the module exists
- assert(m != null);
- if (! orderedModuleSet.contains(m)) {
- allDepsFound = false;
- break;
- }
- }
- }
+ //
+ // Reorder the moduleSet to take into account the module dependencies:
+ // If a module depends on the service provided by another module, the
+ // latter should be included before the former.
+ //
+ Collection<IFloodlightModule> orderedModuleSet =
+ new ArrayList<IFloodlightModule>();
+ while (!moduleSet.isEmpty()) {
+ //
+ // Evaluate each module in the unsorted collection: if all its
+ // dependencies are in the orderedModuleSet, then add it to the
+ // orderedModuleSet.
+ //
+ boolean moduleWasSorted = false;
+ for (IFloodlightModule module : moduleSet) {
+ Collection<Class<? extends IFloodlightService>> deps =
+ module.getModuleDependencies();
+ boolean allDepsFound = true;
+ if (deps != null) {
+ for (Class<? extends IFloodlightService> c : deps) {
+ IFloodlightModule m = moduleMap.get(c);
+ // NOTE: Earlier we checked that the module exists
+ assert (m != null);
+ if (!orderedModuleSet.contains(m)) {
+ allDepsFound = false;
+ break;
+ }
+ }
+ }
- // Move the module to the sorted collection
- if (allDepsFound) {
- orderedModuleSet.add(module);
- moduleSet.remove(module);
- moduleWasSorted = true;
- break;
- }
- }
+ // Move the module to the sorted collection
+ if (allDepsFound) {
+ orderedModuleSet.add(module);
+ moduleSet.remove(module);
+ moduleWasSorted = true;
+ break;
+ }
+ }
- //
- // Test for cyclic depenency:
- // If no module was sorted, but there are still unsorted modules
- // then there is cyclic dependency.
- //
- if ((! moduleWasSorted) && (! moduleSet.isEmpty())) {
- String errorMsg = "";
- for (IFloodlightModule module : moduleSet) {
- if (! errorMsg.isEmpty())
- errorMsg += ", ";
- errorMsg += module.getClass().getName();
- }
- errorMsg = "ERROR! Cyclic service dependency/dependencies among the following modules: " + errorMsg;
- throw new FloodlightModuleException(errorMsg);
- }
- }
- moduleSet = orderedModuleSet;
+ //
+ // Test for cyclic depenency:
+ // If no module was sorted, but there are still unsorted modules
+ // then there is cyclic dependency.
+ //
+ if ((!moduleWasSorted) && (!moduleSet.isEmpty())) {
+ String errorMsg = "";
+ for (IFloodlightModule module : moduleSet) {
+ if (!errorMsg.isEmpty())
+ errorMsg += ", ";
+ errorMsg += module.getClass().getName();
+ }
+ errorMsg = "ERROR! Cyclic service dependency/dependencies among the following modules: " + errorMsg;
+ throw new FloodlightModuleException(errorMsg);
+ }
+ }
+ moduleSet = orderedModuleSet;
floodlightModuleContext.setModuleSet(moduleSet);
parseConfigParameters(prop);
initModules(moduleSet);
startupModules(moduleSet);
-
+
return floodlightModuleContext;
- }
-
- /**
- * Loads modules (and their dependencies) specified in the list.
- * @param configMods The collection of fully qualified module names to load.
- * @param prop The list of properties that are configuration options.
- * @return The ModuleContext containing all the loaded modules.
- * @throws FloodlightModuleException
- */
- public IFloodlightModuleContext loadModulesFromList(Collection<String> configMods, Properties prop)
- throws FloodlightModuleException {
- return loadModulesFromList(configMods, prop, null);
}
-
- /**
- * Add a module to the set of modules to load and register its services
- * @param moduleMap the module map
- * @param moduleSet the module set
- * @param module the module to add
- */
- protected void addModule(Map<Class<? extends IFloodlightService>,
- IFloodlightModule> moduleMap,
- Collection<IFloodlightModule> moduleSet,
- IFloodlightModule module) {
+
+ /**
+ * Loads modules (and their dependencies) specified in the list.
+ *
+ * @param configMods The collection of fully qualified module names to load.
+ * @param prop The list of properties that are configuration options.
+ * @return The ModuleContext containing all the loaded modules.
+ * @throws FloodlightModuleException
+ */
+ public IFloodlightModuleContext loadModulesFromList(Collection<String> configMods, Properties prop)
+ throws FloodlightModuleException {
+ return loadModulesFromList(configMods, prop, null);
+ }
+
+ /**
+ * Add a module to the set of modules to load and register its services
+ *
+ * @param moduleMap the module map
+ * @param moduleSet the module set
+ * @param module the module to add
+ */
+ protected void addModule(Map<Class<? extends IFloodlightService>,
+ IFloodlightModule> moduleMap,
+ Collection<IFloodlightModule> moduleSet,
+ IFloodlightModule module) {
if (!moduleSet.contains(module)) {
Collection<Class<? extends IFloodlightService>> servs =
moduleServiceMap.get(module);
@@ -383,57 +388,59 @@
}
moduleSet.add(module);
}
- }
+ }
/**
* Allocate service implementations and then init all the modules
+ *
* @param moduleSet The set of modules to call their init function on
* @throws FloodlightModuleException If a module can not properly be loaded
*/
- protected void initModules(Collection<IFloodlightModule> moduleSet)
- throws FloodlightModuleException {
- for (IFloodlightModule module : moduleSet) {
+ protected void initModules(Collection<IFloodlightModule> moduleSet)
+ throws FloodlightModuleException {
+ for (IFloodlightModule module : moduleSet) {
// Get the module's service instance(s)
- Map<Class<? extends IFloodlightService>,
- IFloodlightService> simpls = module.getServiceImpls();
+ Map<Class<? extends IFloodlightService>,
+ IFloodlightService> simpls = module.getServiceImpls();
// add its services to the context
if (simpls != null) {
- for (Entry<Class<? extends IFloodlightService>,
+ for (Entry<Class<? extends IFloodlightService>,
IFloodlightService> s : simpls.entrySet()) {
if (logger.isDebugEnabled()) {
- logger.debug("Setting " + s.getValue() +
- " as provider for " +
- s.getKey().getCanonicalName());
+ logger.debug("Setting " + s.getValue() +
+ " as provider for " +
+ s.getKey().getCanonicalName());
}
if (floodlightModuleContext.getServiceImpl(s.getKey()) == null) {
floodlightModuleContext.addService(s.getKey(),
- s.getValue());
+ s.getValue());
} else {
throw new FloodlightModuleException("Cannot set "
- + s.getValue()
- + " as the provider for "
- + s.getKey().getCanonicalName()
- + " because "
- + floodlightModuleContext.getServiceImpl(s.getKey())
- + " already provides it");
+ + s.getValue()
+ + " as the provider for "
+ + s.getKey().getCanonicalName()
+ + " because "
+ + floodlightModuleContext.getServiceImpl(s.getKey())
+ + " already provides it");
}
}
}
}
-
+
for (IFloodlightModule module : moduleSet) {
// init the module
if (logger.isDebugEnabled()) {
- logger.debug("Initializing " +
- module.getClass().getCanonicalName());
+ logger.debug("Initializing " +
+ module.getClass().getCanonicalName());
}
module.init(floodlightModuleContext);
}
}
-
+
/**
* Call each loaded module's startup method
+ *
* @param moduleSet the module set to start up
*/
protected void startupModules(Collection<IFloodlightModule> moduleSet) {
@@ -444,19 +451,20 @@
m.startUp(floodlightModuleContext);
}
}
-
+
/**
* Parses configuration parameters for each module
+ *
* @param prop The properties file to use
*/
- @LogMessageDoc(level="WARN",
- message="Module {module} not found or loaded. " +
- "Not adding configuration option {key} = {value}",
- explanation="Ignoring a configuration parameter for a " +
- "module that is not loaded.")
+ @LogMessageDoc(level = "WARN",
+ message = "Module {module} not found or loaded. " +
+ "Not adding configuration option {key} = {value}",
+ explanation = "Ignoring a configuration parameter for a " +
+ "module that is not loaded.")
protected void parseConfigParameters(Properties prop) {
- if (prop == null) return;
-
+ if (prop == null) return;
+
Enumeration<?> e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
@@ -464,7 +472,7 @@
if (key.equals(FLOODLIGHT_MODULES_KEY)) {
continue;
}
-
+
String configValue = null;
int lastPeriod = key.lastIndexOf(".");
String moduleName = key.substring(0, lastPeriod);
@@ -476,12 +484,12 @@
} else {
configValue = prop.getProperty(key);
}
-
+
IFloodlightModule mod = moduleNameMap.get(moduleName);
if (mod == null) {
logger.warn("Module {} not found or loaded. " +
- "Not adding configuration option {} = {}",
- new Object[]{moduleName, configKey, configValue});
+ "Not adding configuration option {} = {}",
+ new Object[]{moduleName, configKey, configValue});
} else {
floodlightModuleContext.addConfigParam(mod, configKey, configValue);
}
diff --git a/src/main/java/net/floodlightcontroller/core/module/IFloodlightModule.java b/src/main/java/net/floodlightcontroller/core/module/IFloodlightModule.java
index f8b196b..c616bc0 100644
--- a/src/main/java/net/floodlightcontroller/core/module/IFloodlightModule.java
+++ b/src/main/java/net/floodlightcontroller/core/module/IFloodlightModule.java
@@ -6,7 +6,7 @@
/**
* Defines an interface for loadable Floodlight modules.
- *
+ * <p/>
* At a high level, these functions are called in the following order:
* <ol>
* <li> getServices() : what services does this module provide
@@ -14,61 +14,64 @@
* <li> init() : internal initializations (don't touch other modules)
* <li> startUp() : external initializations (<em>do</em> touch other modules)
* </ol>
- *
+ *
* @author alexreimers
*/
public interface IFloodlightModule {
-
- /**
- * Return the list of interfaces that this module implements.
- * All interfaces must inherit IFloodlightService
- * @return
- */
-
- public Collection<Class<? extends IFloodlightService>> getModuleServices();
-
- /**
- * Instantiate (as needed) and return objects that implement each
- * of the services exported by this module. The map returned maps
- * the implemented service to the object. The object could be the
- * same object or different objects for different exported services.
- * @return The map from service interface class to service implementation
- */
- public Map<Class<? extends IFloodlightService>,
- IFloodlightService> getServiceImpls();
-
- /**
- * Get a list of Modules that this module depends on. The module system
- * will ensure that each these dependencies is resolved before the
- * subsequent calls to init().
- * @return The Collection of IFloodlightServices that this module depends
- * on.
- */
-
- public Collection<Class<? extends IFloodlightService>> getModuleDependencies();
-
- /**
- * This is a hook for each module to do its <em>internal</em> initialization,
- * e.g., call setService(context.getService("Service"))
- *
- * All module dependencies are resolved when this is called, but not every module
- * is initialized.
- *
- * @param context
- * @throws FloodlightModuleException
- */
-
- void init(FloodlightModuleContext context) throws FloodlightModuleException;
-
- /**
- * This is a hook for each module to do its <em>external</em> initializations,
- * e.g., register for callbacks or query for state in other modules
- *
- * It is expected that this function will not block and that modules that want
- * non-event driven CPU will spawn their own threads.
- *
- * @param context
- */
-
- void startUp(FloodlightModuleContext context);
+
+ /**
+ * Return the list of interfaces that this module implements.
+ * All interfaces must inherit IFloodlightService
+ *
+ * @return
+ */
+
+ public Collection<Class<? extends IFloodlightService>> getModuleServices();
+
+ /**
+ * Instantiate (as needed) and return objects that implement each
+ * of the services exported by this module. The map returned maps
+ * the implemented service to the object. The object could be the
+ * same object or different objects for different exported services.
+ *
+ * @return The map from service interface class to service implementation
+ */
+ public Map<Class<? extends IFloodlightService>,
+ IFloodlightService> getServiceImpls();
+
+ /**
+ * Get a list of Modules that this module depends on. The module system
+ * will ensure that each these dependencies is resolved before the
+ * subsequent calls to init().
+ *
+ * @return The Collection of IFloodlightServices that this module depends
+ * on.
+ */
+
+ public Collection<Class<? extends IFloodlightService>> getModuleDependencies();
+
+ /**
+ * This is a hook for each module to do its <em>internal</em> initialization,
+ * e.g., call setService(context.getService("Service"))
+ * <p/>
+ * All module dependencies are resolved when this is called, but not every module
+ * is initialized.
+ *
+ * @param context
+ * @throws FloodlightModuleException
+ */
+
+ void init(FloodlightModuleContext context) throws FloodlightModuleException;
+
+ /**
+ * This is a hook for each module to do its <em>external</em> initializations,
+ * e.g., register for callbacks or query for state in other modules
+ * <p/>
+ * It is expected that this function will not block and that modules that want
+ * non-event driven CPU will spawn their own threads.
+ *
+ * @param context
+ */
+
+ void startUp(FloodlightModuleContext context);
}
diff --git a/src/main/java/net/floodlightcontroller/core/module/IFloodlightModuleContext.java b/src/main/java/net/floodlightcontroller/core/module/IFloodlightModuleContext.java
index 2c058a7..cdaadc3 100644
--- a/src/main/java/net/floodlightcontroller/core/module/IFloodlightModuleContext.java
+++ b/src/main/java/net/floodlightcontroller/core/module/IFloodlightModuleContext.java
@@ -3,31 +3,35 @@
import java.util.Collection;
import java.util.Map;
-
-public interface IFloodlightModuleContext {
+
+public interface IFloodlightModuleContext {
/**
* Retrieves a casted version of a module from the registry.
+ *
* @param name The IFloodlightService object type
* @return The IFloodlightService
- * @throws FloodlightModuleException If the module was not found
- * or a ClassCastException was encountered.
+ * @throws FloodlightModuleException If the module was not found
+ * or a ClassCastException was encountered.
*/
public <T extends IFloodlightService> T getServiceImpl(Class<T> service);
-
+
/**
* Returns all loaded services
+ *
* @return A collection of service classes that have been loaded
*/
public Collection<Class<? extends IFloodlightService>> getAllServices();
-
+
/**
* Returns all loaded modules
+ *
* @return All Floodlight modules that are going to be loaded
*/
public Collection<IFloodlightModule> getAllModules();
-
+
/**
* Gets module specific configuration parameters.
+ *
* @param module The module to get the configuration parameters for
* @return A key, value map of the configuration options
*/
diff --git a/src/main/java/net/floodlightcontroller/core/module/IFloodlightService.java b/src/main/java/net/floodlightcontroller/core/module/IFloodlightService.java
index 5974b3a..b59c62b 100644
--- a/src/main/java/net/floodlightcontroller/core/module/IFloodlightService.java
+++ b/src/main/java/net/floodlightcontroller/core/module/IFloodlightService.java
@@ -1,10 +1,10 @@
package net.floodlightcontroller.core.module;
/**
- * This is the base interface for any IFloodlightModule package that provides
+ * This is the base interface for any IFloodlightModule package that provides
* a service.
- * @author alexreimers
*
+ * @author alexreimers
*/
public abstract interface IFloodlightService {
// This space is intentionally left blank....don't touch it
diff --git a/src/main/java/net/floodlightcontroller/core/module/ModuleLoaderResource.java b/src/main/java/net/floodlightcontroller/core/module/ModuleLoaderResource.java
index 556b26d..21cbfc3 100644
--- a/src/main/java/net/floodlightcontroller/core/module/ModuleLoaderResource.java
+++ b/src/main/java/net/floodlightcontroller/core/module/ModuleLoaderResource.java
@@ -13,91 +13,94 @@
/**
* Returns list of modules loaded by Floodlight.
+ *
* @author Rob Sherwood
*/
public class ModuleLoaderResource extends ServerResource {
- protected final static Logger log =
+ protected final static Logger log =
LoggerFactory.getLogger(ModuleLoaderResource.class);
-
+
/**
* Retrieves information about loaded modules.
+ *
* @return Information about loaded modules.
*/
@Get("json")
public Map<String, Object> retrieve() {
- return retrieveInternal(false);
+ return retrieveInternal(false);
}
-
+
/**
* Retrieves all modules and their dependencies available
* to Floodlight.
+ *
* @param loadedOnly Whether to return all modules available or only the ones loaded.
* @return Information about modules available or loaded.
*/
- public Map<String, Object> retrieveInternal(boolean loadedOnly) {
+ public Map<String, Object> retrieveInternal(boolean loadedOnly) {
Map<String, Object> model = new HashMap<String, Object>();
Set<String> loadedModules = new HashSet<String>();
for (Object val : getContext().getAttributes().values()) {
- if ((val instanceof IFloodlightModule) || (val instanceof IFloodlightService)) {
- String serviceImpl = val.getClass().getCanonicalName();
- loadedModules.add(serviceImpl);
- // log.debug("Tracking serviceImpl " + serviceImpl);
- }
+ if ((val instanceof IFloodlightModule) || (val instanceof IFloodlightService)) {
+ String serviceImpl = val.getClass().getCanonicalName();
+ loadedModules.add(serviceImpl);
+ // log.debug("Tracking serviceImpl " + serviceImpl);
+ }
}
- for (String moduleName :
- FloodlightModuleLoader.moduleNameMap.keySet() ) {
- Map<String,Object> moduleInfo = new HashMap<String, Object>();
+ for (String moduleName :
+ FloodlightModuleLoader.moduleNameMap.keySet()) {
+ Map<String, Object> moduleInfo = new HashMap<String, Object>();
- IFloodlightModule module =
- FloodlightModuleLoader.moduleNameMap.get(
- moduleName);
-
- Collection<Class<? extends IFloodlightService>> deps =
- module.getModuleDependencies();
- if ( deps == null)
- deps = new HashSet<Class<? extends IFloodlightService>>();
- Map<String,Object> depsMap = new HashMap<String, Object> ();
- for (Class<? extends IFloodlightService> service : deps) {
- Object serviceImpl = getContext().getAttributes().get(service.getCanonicalName());
- if (serviceImpl != null)
- depsMap.put(service.getCanonicalName(), serviceImpl.getClass().getCanonicalName());
- else
- depsMap.put(service.getCanonicalName(), "<unresolved>");
+ IFloodlightModule module =
+ FloodlightModuleLoader.moduleNameMap.get(
+ moduleName);
- }
+ Collection<Class<? extends IFloodlightService>> deps =
+ module.getModuleDependencies();
+ if (deps == null)
+ deps = new HashSet<Class<? extends IFloodlightService>>();
+ Map<String, Object> depsMap = new HashMap<String, Object>();
+ for (Class<? extends IFloodlightService> service : deps) {
+ Object serviceImpl = getContext().getAttributes().get(service.getCanonicalName());
+ if (serviceImpl != null)
+ depsMap.put(service.getCanonicalName(), serviceImpl.getClass().getCanonicalName());
+ else
+ depsMap.put(service.getCanonicalName(), "<unresolved>");
+
+ }
moduleInfo.put("depends", depsMap);
-
- Collection<Class<? extends IFloodlightService>> provides =
- module.getModuleServices();
- if ( provides == null)
- provides = new HashSet<Class<? extends IFloodlightService>>();
- Map<String,Object> providesMap = new HashMap<String,Object>();
- for (Class<? extends IFloodlightService> service : provides) {
- providesMap.put(service.getCanonicalName(), module.getServiceImpls().get(service).getClass().getCanonicalName());
- }
- moduleInfo.put("provides", providesMap);
- moduleInfo.put("loaded", false); // not loaded, by default
+ Collection<Class<? extends IFloodlightService>> provides =
+ module.getModuleServices();
+ if (provides == null)
+ provides = new HashSet<Class<? extends IFloodlightService>>();
+ Map<String, Object> providesMap = new HashMap<String, Object>();
+ for (Class<? extends IFloodlightService> service : provides) {
+ providesMap.put(service.getCanonicalName(), module.getServiceImpls().get(service).getClass().getCanonicalName());
+ }
+ moduleInfo.put("provides", providesMap);
- // check if this module is loaded directly
- if (loadedModules.contains(module.getClass().getCanonicalName())) {
- moduleInfo.put("loaded", true);
- } else {
- // if not, then maybe one of the services it exports is loaded
- for (Class<? extends IFloodlightService> service : provides) {
- String modString = module.getServiceImpls().get(service).getClass().getCanonicalName();
- if (loadedModules.contains(modString))
- moduleInfo.put("loaded", true);
- /* else
- log.debug("ServiceImpl not loaded " + modString); */
- }
- }
+ moduleInfo.put("loaded", false); // not loaded, by default
- if ((Boolean)moduleInfo.get("loaded")|| !loadedOnly )
- model.put(moduleName, moduleInfo);
- }
+ // check if this module is loaded directly
+ if (loadedModules.contains(module.getClass().getCanonicalName())) {
+ moduleInfo.put("loaded", true);
+ } else {
+ // if not, then maybe one of the services it exports is loaded
+ for (Class<? extends IFloodlightService> service : provides) {
+ String modString = module.getServiceImpls().get(service).getClass().getCanonicalName();
+ if (loadedModules.contains(modString))
+ moduleInfo.put("loaded", true);
+ /* else
+ log.debug("ServiceImpl not loaded " + modString); */
+ }
+ }
+
+ if ((Boolean) moduleInfo.get("loaded") || !loadedOnly)
+ model.put(moduleName, moduleInfo);
+ }
return model;
}
}
diff --git a/src/main/java/net/floodlightcontroller/core/util/AppCookie.java b/src/main/java/net/floodlightcontroller/core/util/AppCookie.java
index 210823e..3ec3bd8 100644
--- a/src/main/java/net/floodlightcontroller/core/util/AppCookie.java
+++ b/src/main/java/net/floodlightcontroller/core/util/AppCookie.java
@@ -1,27 +1,26 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.util;
-/***
+/**
* FIXME Need a system for registering/binding applications to a unique ID
- *
- * @author capveg
*
+ * @author capveg
*/
public class AppCookie {
@@ -34,21 +33,21 @@
/**
* Encapsulate an application ID and a user block of stuff into a cookie
- *
+ *
* @param application An ID to identify the application
- * @param user Some application specific data
+ * @param user Some application specific data
* @return a cookie for use in OFFlowMod.setCookie()
*/
-
+
static public long makeCookie(int application, int user) {
return ((application & ((1L << APP_ID_BITS) - 1)) << APP_ID_SHIFT) | user;
}
-
+
static public int extractApp(long cookie) {
- return (int)((cookie>> APP_ID_SHIFT) & ((1L << APP_ID_BITS) - 1));
+ return (int) ((cookie >> APP_ID_SHIFT) & ((1L << APP_ID_BITS) - 1));
}
-
+
static public int extractUser(long cookie) {
- return (int)((cookie>> USER_SHIFT) & ((1L << USER_BITS) - 1));
+ return (int) ((cookie >> USER_SHIFT) & ((1L << USER_BITS) - 1));
}
}
diff --git a/src/main/java/net/floodlightcontroller/core/util/ListenerDispatcher.java b/src/main/java/net/floodlightcontroller/core/util/ListenerDispatcher.java
index 911284e..f716f4b 100644
--- a/src/main/java/net/floodlightcontroller/core/util/ListenerDispatcher.java
+++ b/src/main/java/net/floodlightcontroller/core/util/ListenerDispatcher.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.util;
@@ -28,20 +28,19 @@
import org.slf4j.LoggerFactory;
/**
- * Maintain lists of listeners ordered by dependency.
- *
- * @author readams
+ * Maintain lists of listeners ordered by dependency.
*
+ * @author readams
*/
public class ListenerDispatcher<U, T extends IListener<U>> {
protected final static Logger logger = LoggerFactory.getLogger(ListenerDispatcher.class);
List<T> listeners = null;
-
- private void visit(List<T> newlisteners, U type, HashSet<T> visited,
+
+ private void visit(List<T> newlisteners, U type, HashSet<T> visited,
List<T> ordering, T listener) {
if (!visited.contains(listener)) {
visited.add(listener);
-
+
for (T i : newlisteners) {
if (ispre(type, i, listener)) {
visit(newlisteners, type, visited, ordering, i);
@@ -50,24 +49,25 @@
ordering.add(listener);
}
}
-
+
private boolean ispre(U type, T l1, T l2) {
return (l2.isCallbackOrderingPrereq(type, l1.getName()) ||
l1.isCallbackOrderingPostreq(type, l2.getName()));
}
-
+
/**
* Add a listener to the list of listeners
+ *
* @param listener
*/
- @LogMessageDoc(level="ERROR",
- message="No listener dependency solution: " +
- "No listeners without incoming dependencies",
- explanation="The set of listeners installed " +
- "have dependencies with no solution",
- recommendation="Install a different set of listeners " +
- "or install all dependencies. This is a defect in " +
- "the controller installation.")
+ @LogMessageDoc(level = "ERROR",
+ message = "No listener dependency solution: " +
+ "No listeners without incoming dependencies",
+ explanation = "The set of listeners installed " +
+ "have dependencies with no solution",
+ recommendation = "Install a different set of listeners " +
+ "or install all dependencies. This is a defect in " +
+ "the controller installation.")
public void addListener(U type, T listener) {
List<T> newlisteners = new ArrayList<T>();
if (listeners != null)
@@ -75,7 +75,7 @@
newlisteners.add(listener);
// Find nodes without outgoing edges
- List<T> terminals = new ArrayList<T>();
+ List<T> terminals = new ArrayList<T>();
for (T i : newlisteners) {
boolean isterm = true;
for (T j : newlisteners) {
@@ -88,18 +88,18 @@
terminals.add(i);
}
}
-
+
if (terminals.size() == 0) {
logger.error("No listener dependency solution: " +
- "No listeners without incoming dependencies");
+ "No listeners without incoming dependencies");
listeners = newlisteners;
return;
}
-
+
// visit depth-first traversing in the opposite order from
// the dependencies. Note we will not generally detect cycles
HashSet<T> visited = new HashSet<T>();
- List<T> ordering = new ArrayList<T>();
+ List<T> ordering = new ArrayList<T>();
for (T term : terminals) {
visit(newlisteners, type, visited, ordering, term);
}
@@ -108,6 +108,7 @@
/**
* Remove the given listener
+ *
* @param listener the listener to remove
*/
public void removeListener(T listener) {
@@ -118,16 +119,17 @@
listeners = newlisteners;
}
}
-
+
/**
* Clear all listeners
*/
public void clearListeners() {
listeners = new ArrayList<T>();
}
-
- /**
- * Get the ordered list of listeners ordered by dependencies
+
+ /**
+ * Get the ordered list of listeners ordered by dependencies
+ *
* @return
*/
public List<T> getOrderedListeners() {
diff --git a/src/main/java/net/floodlightcontroller/core/util/MutableInteger.java b/src/main/java/net/floodlightcontroller/core/util/MutableInteger.java
index 0f070fa..6ac3231 100644
--- a/src/main/java/net/floodlightcontroller/core/util/MutableInteger.java
+++ b/src/main/java/net/floodlightcontroller/core/util/MutableInteger.java
@@ -1,34 +1,34 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.util;
public class MutableInteger extends Number {
private static final long serialVersionUID = 1L;
int mutableInt;
-
+
public MutableInteger(int value) {
this.mutableInt = value;
}
-
+
public void setValue(int value) {
this.mutableInt = value;
}
-
+
@Override
public double doubleValue() {
return (double) mutableInt;
diff --git a/src/main/java/net/floodlightcontroller/core/util/SingletonTask.java b/src/main/java/net/floodlightcontroller/core/util/SingletonTask.java
index 0e03144..2338acc 100644
--- a/src/main/java/net/floodlightcontroller/core/util/SingletonTask.java
+++ b/src/main/java/net/floodlightcontroller/core/util/SingletonTask.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.util;
@@ -27,26 +27,26 @@
/**
* This allows you to represent a task that should be queued for future execution
- * but where you only want the task to complete once in response to some sequence
+ * but where you only want the task to complete once in response to some sequence
* of events. For example, if you get a change notification and want to reload state,
* you only want to reload the state once, at the end, and don't want to queue
* an update for every notification that might come in.
- *
+ * <p/>
* The semantics are as follows:
* * If the task hasn't begun yet, do not queue a new task
* * If the task has begun, set a bit to restart it after the current task finishes
*/
public class SingletonTask {
protected final static Logger logger = LoggerFactory.getLogger(SingletonTask.class);
-
- protected static class SingletonTaskContext {
+
+ protected static class SingletonTaskContext {
protected boolean taskShouldRun = false;
protected boolean taskRunning = false;
protected SingletonTaskWorker waitingTask = null;
}
- protected static class SingletonTaskWorker implements Runnable {
+ protected static class SingletonTaskWorker implements Runnable {
SingletonTask parent;
boolean canceled = false;
long nextschedule = 0;
@@ -57,9 +57,9 @@
}
@Override
- @LogMessageDoc(level="ERROR",
- message="Exception while executing task",
- recommendation=LogMessageDoc.GENERIC_ACTION)
+ @LogMessageDoc(level = "ERROR",
+ message = "Exception while executing task",
+ recommendation = LogMessageDoc.GENERIC_ACTION)
public void run() {
synchronized (parent.context) {
if (canceled || !parent.context.taskShouldRun)
@@ -83,9 +83,9 @@
if ((nextschedule <= 0 || (nextschedule - now) <= 0)) {
parent.ses.execute(this);
} else {
- parent.ses.schedule(this,
- nextschedule-now,
- TimeUnit.NANOSECONDS);
+ parent.ses.schedule(this,
+ nextschedule - now,
+ TimeUnit.NANOSECONDS);
}
}
}
@@ -101,11 +101,12 @@
* Construct a new SingletonTask for the given runnable. The context
* is used to manage the state of the task execution and can be shared
* by more than one instance of the runnable.
+ *
* @param context
* @param Task
*/
public SingletonTask(ScheduledExecutorService ses,
- Runnable task) {
+ Runnable task) {
super();
this.task = task;
this.ses = ses;
@@ -117,9 +118,9 @@
* cancel that task and reschedule it to run at the given time. If the
* task is already started, it will cause the task to be rescheduled once
* it completes to run after delay from the time of reschedule.
- *
+ *
* @param delay the delay in scheduling
- * @param unit the timeunit of the delay
+ * @param unit the timeunit of the delay
*/
public void reschedule(long delay, TimeUnit unit) {
boolean needQueue = true;
@@ -131,8 +132,8 @@
// schedule to restart at the right time
if (delay > 0) {
long now = System.nanoTime();
- long then =
- now + TimeUnit.NANOSECONDS.convert(delay, unit);
+ long then =
+ now + TimeUnit.NANOSECONDS.convert(delay, unit);
context.waitingTask.nextschedule = then;
} else {
context.waitingTask.nextschedule = 0;
@@ -148,7 +149,7 @@
context.taskShouldRun = true;
if (needQueue) {
- stw = context.waitingTask = new SingletonTaskWorker(this);
+ stw = context.waitingTask = new SingletonTaskWorker(this);
}
}
diff --git a/src/main/java/net/floodlightcontroller/core/web/AllSwitchStatisticsResource.java b/src/main/java/net/floodlightcontroller/core/web/AllSwitchStatisticsResource.java
index 5d70cee..276215b 100644
--- a/src/main/java/net/floodlightcontroller/core/web/AllSwitchStatisticsResource.java
+++ b/src/main/java/net/floodlightcontroller/core/web/AllSwitchStatisticsResource.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.web;
@@ -35,24 +35,25 @@
/**
* Return switch statistics information for all switches
+ *
* @author readams
*/
public class AllSwitchStatisticsResource extends SwitchResourceBase {
- protected final static Logger log =
- LoggerFactory.getLogger(AllSwitchStatisticsResource.class);
-
+ protected final static Logger log =
+ LoggerFactory.getLogger(AllSwitchStatisticsResource.class);
+
@Get("json")
- public Map<String, Object> retrieve() {
+ public Map<String, Object> retrieve() {
String statType = (String) getRequestAttributes().get("statType");
return retrieveInternal(statType);
}
-
+
public Map<String, Object> retrieveInternal(String statType) {
HashMap<String, Object> model = new HashMap<String, Object>();
OFStatisticsType type = null;
REQUESTTYPE rType = null;
-
+
if (statType.equals("port")) {
type = OFStatisticsType.PORT;
rType = REQUESTTYPE.OFSTATS;
@@ -76,10 +77,10 @@
} else {
return model;
}
-
- IFloodlightProviderService floodlightProvider =
- (IFloodlightProviderService)getContext().getAttributes().
- get(IFloodlightProviderService.class.getCanonicalName());
+
+ IFloodlightProviderService floodlightProvider =
+ (IFloodlightProviderService) getContext().getAttributes().
+ get(IFloodlightProviderService.class.getCanonicalName());
Long[] switchDpids = floodlightProvider.getSwitches().keySet().toArray(new Long[0]);
List<GetConcurrentStatsThread> activeThreads = new ArrayList<GetConcurrentStatsThread>(switchDpids.length);
List<GetConcurrentStatsThread> pendingRemovalThreads = new ArrayList<GetConcurrentStatsThread>();
@@ -89,7 +90,7 @@
activeThreads.add(t);
t.start();
}
-
+
// Join all the threads after the timeout. Set a hard timeout
// of 12 seconds for the threads to finish. If the thread has not
// finished the switch has not replied yet and therefore we won't
@@ -105,19 +106,19 @@
pendingRemovalThreads.add(curThread);
}
}
-
+
// remove the threads that have completed the queries to the switches
for (GetConcurrentStatsThread curThread : pendingRemovalThreads) {
activeThreads.remove(curThread);
}
// clear the list so we don't try to double remove them
pendingRemovalThreads.clear();
-
+
// if we are done finish early so we don't always get the worst case
if (activeThreads.isEmpty()) {
break;
}
-
+
// sleep for 1 s here
try {
Thread.sleep(1000);
@@ -125,17 +126,17 @@
log.error("Interrupted while waiting for statistics", e);
}
}
-
+
return model;
}
-
+
protected class GetConcurrentStatsThread extends Thread {
private List<OFStatistics> switchReply;
private long switchId;
private OFStatisticsType statType;
private REQUESTTYPE requestType;
private OFFeaturesReply featuresReply;
-
+
public GetConcurrentStatsThread(long switchId, REQUESTTYPE requestType, OFStatisticsType statType) {
this.switchId = switchId;
this.requestType = requestType;
@@ -143,19 +144,19 @@
this.switchReply = null;
this.featuresReply = null;
}
-
+
public List<OFStatistics> getStatisticsReply() {
return switchReply;
}
-
+
public OFFeaturesReply getFeaturesReply() {
return featuresReply;
}
-
+
public long getSwitchId() {
return switchId;
}
-
+
public void run() {
if ((requestType == REQUESTTYPE.OFSTATS) && (statType != null)) {
switchReply = getSwitchStatistics(switchId, statType);
diff --git a/src/main/java/net/floodlightcontroller/core/web/ControllerMemoryResource.java b/src/main/java/net/floodlightcontroller/core/web/ControllerMemoryResource.java
index bcb2bd1..371a38f 100644
--- a/src/main/java/net/floodlightcontroller/core/web/ControllerMemoryResource.java
+++ b/src/main/java/net/floodlightcontroller/core/web/ControllerMemoryResource.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.web;
@@ -25,6 +25,7 @@
/**
* Retrieve floodlight memory state
+ *
* @author readams
*/
public class ControllerMemoryResource extends ServerResource {
diff --git a/src/main/java/net/floodlightcontroller/core/web/ControllerSwitchesResource.java b/src/main/java/net/floodlightcontroller/core/web/ControllerSwitchesResource.java
index 454f566..223da56 100644
--- a/src/main/java/net/floodlightcontroller/core/web/ControllerSwitchesResource.java
+++ b/src/main/java/net/floodlightcontroller/core/web/ControllerSwitchesResource.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.web;
@@ -32,21 +32,22 @@
/**
* Get a list of switches connected to the controller
+ *
* @author readams
*/
public class ControllerSwitchesResource extends ServerResource {
- public static final String DPID_ERROR =
- "Invalid Switch DPID: must be a 64-bit quantity, expressed in " +
- "hex as AA:BB:CC:DD:EE:FF:00:11";
-
+ public static final String DPID_ERROR =
+ "Invalid Switch DPID: must be a 64-bit quantity, expressed in " +
+ "hex as AA:BB:CC:DD:EE:FF:00:11";
+
@Get("json")
public Iterator<IOFSwitch> retrieve() {
- IFloodlightProviderService floodlightProvider =
- (IFloodlightProviderService)getContext().getAttributes().
- get(IFloodlightProviderService.class.getCanonicalName());
+ IFloodlightProviderService floodlightProvider =
+ (IFloodlightProviderService) getContext().getAttributes().
+ get(IFloodlightProviderService.class.getCanonicalName());
Long switchDPID = null;
-
+
Form form = getQuery();
String dpid = form.getFirstValue("dpid", true);
if (dpid != null) {
@@ -58,15 +59,15 @@
}
}
if (switchDPID != null) {
- IOFSwitch sw =
+ IOFSwitch sw =
floodlightProvider.getSwitches().get(switchDPID);
if (sw != null)
return Collections.singleton(sw).iterator();
return Collections.<IOFSwitch>emptySet().iterator();
}
- final String dpidStartsWith =
+ final String dpidStartsWith =
form.getFirstValue("dpid__startswith", true);
- Iterator<IOFSwitch> switer =
+ Iterator<IOFSwitch> switer =
floodlightProvider.getSwitches().values().iterator();
if (dpidStartsWith != null) {
return new FilterIterator<IOFSwitch>(switer) {
@@ -75,7 +76,7 @@
return value.getStringId().startsWith(dpidStartsWith);
}
};
- }
+ }
return switer;
}
}
diff --git a/src/main/java/net/floodlightcontroller/core/web/CoreWebRoutable.java b/src/main/java/net/floodlightcontroller/core/web/CoreWebRoutable.java
index 0e48975..4492643 100644
--- a/src/main/java/net/floodlightcontroller/core/web/CoreWebRoutable.java
+++ b/src/main/java/net/floodlightcontroller/core/web/CoreWebRoutable.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.web;
@@ -26,6 +26,7 @@
/**
* Creates a router to handle all the core web URIs
+ *
* @author readams
*/
public class CoreWebRoutable implements RestletRoutable {
diff --git a/src/main/java/net/floodlightcontroller/core/web/EventHistoryTopologyClusterResource.java b/src/main/java/net/floodlightcontroller/core/web/EventHistoryTopologyClusterResource.java
index 56ff6d9..2bbb1bd 100644
--- a/src/main/java/net/floodlightcontroller/core/web/EventHistoryTopologyClusterResource.java
+++ b/src/main/java/net/floodlightcontroller/core/web/EventHistoryTopologyClusterResource.java
@@ -12,34 +12,32 @@
/**
* @author subrata
- *
*/
public class EventHistoryTopologyClusterResource extends ServerResource {
// TODO - Move this to the LinkDiscovery rest API
- protected final static Logger log =
+ protected final static Logger log =
LoggerFactory.getLogger(EventHistoryTopologyClusterResource.class);
@Get("json")
public EventHistory<EventHistoryTopologyCluster> handleEvHistReq() {
// Get the event history count. Last <count> events would be returned
- String evHistCount = (String)getRequestAttributes().get("count");
- int count = EventHistory.EV_HISTORY_DEFAULT_SIZE;
+ String evHistCount = (String) getRequestAttributes().get("count");
+ int count = EventHistory.EV_HISTORY_DEFAULT_SIZE;
try {
count = Integer.parseInt(evHistCount);
- }
- catch(NumberFormatException nFE) {
+ } catch (NumberFormatException nFE) {
// Invalid input for event count - use default value
}
LinkDiscoveryManager topoManager =
- (LinkDiscoveryManager)getContext().getAttributes().
- get(ILinkDiscoveryService.class.getCanonicalName());
+ (LinkDiscoveryManager) getContext().getAttributes().
+ get(ILinkDiscoveryService.class.getCanonicalName());
if (topoManager != null) {
return new EventHistory<EventHistoryTopologyCluster>(
topoManager.evHistTopologyCluster, count);
}
-
+
return null;
}
}
diff --git a/src/main/java/net/floodlightcontroller/core/web/EventHistoryTopologyLinkResource.java b/src/main/java/net/floodlightcontroller/core/web/EventHistoryTopologyLinkResource.java
index fbb2e76..90d9198 100644
--- a/src/main/java/net/floodlightcontroller/core/web/EventHistoryTopologyLinkResource.java
+++ b/src/main/java/net/floodlightcontroller/core/web/EventHistoryTopologyLinkResource.java
@@ -12,34 +12,32 @@
/**
* @author subrata
- *
*/
public class EventHistoryTopologyLinkResource extends ServerResource {
// TODO - Move this to the DeviceManager Rest API
- protected final static Logger log =
+ protected final static Logger log =
LoggerFactory.getLogger(EventHistoryTopologyLinkResource.class);
@Get("json")
public EventHistory<EventHistoryTopologyLink> handleEvHistReq() {
// Get the event history count. Last <count> events would be returned
- String evHistCount = (String)getRequestAttributes().get("count");
- int count = EventHistory.EV_HISTORY_DEFAULT_SIZE;
+ String evHistCount = (String) getRequestAttributes().get("count");
+ int count = EventHistory.EV_HISTORY_DEFAULT_SIZE;
try {
count = Integer.parseInt(evHistCount);
- }
- catch(NumberFormatException nFE) {
+ } catch (NumberFormatException nFE) {
// Invalid input for event count - use default value
}
LinkDiscoveryManager linkDiscoveryManager =
- (LinkDiscoveryManager)getContext().getAttributes().
- get(ILinkDiscoveryService.class.getCanonicalName());
+ (LinkDiscoveryManager) getContext().getAttributes().
+ get(ILinkDiscoveryService.class.getCanonicalName());
if (linkDiscoveryManager != null) {
return new EventHistory<EventHistoryTopologyLink>(
linkDiscoveryManager.evHistTopologyLink, count);
}
-
+
return null;
}
}
diff --git a/src/main/java/net/floodlightcontroller/core/web/EventHistoryTopologySwitchResource.java b/src/main/java/net/floodlightcontroller/core/web/EventHistoryTopologySwitchResource.java
index 345020b..e1fbb1b 100644
--- a/src/main/java/net/floodlightcontroller/core/web/EventHistoryTopologySwitchResource.java
+++ b/src/main/java/net/floodlightcontroller/core/web/EventHistoryTopologySwitchResource.java
@@ -10,7 +10,6 @@
/**
* @author subrata
- *
*/
public class EventHistoryTopologySwitchResource extends ServerResource {
@@ -18,20 +17,19 @@
public EventHistory<EventHistoryTopologySwitch> handleEvHistReq() {
// Get the event history count. Last <count> events would be returned
- String evHistCount = (String)getRequestAttributes().get("count");
- int count = EventHistory.EV_HISTORY_DEFAULT_SIZE;
+ String evHistCount = (String) getRequestAttributes().get("count");
+ int count = EventHistory.EV_HISTORY_DEFAULT_SIZE;
try {
count = Integer.parseInt(evHistCount);
- }
- catch(NumberFormatException nFE) {
+ } catch (NumberFormatException nFE) {
// Invalid input for event count - use default value
}
LinkDiscoveryManager topoManager =
- (LinkDiscoveryManager)getContext().getAttributes().
- get(ILinkDiscoveryService.class.getCanonicalName());
+ (LinkDiscoveryManager) getContext().getAttributes().
+ get(ILinkDiscoveryService.class.getCanonicalName());
return new EventHistory<EventHistoryTopologySwitch>(
- topoManager.evHistTopologySwitch, count);
+ topoManager.evHistTopologySwitch, count);
}
}
diff --git a/src/main/java/net/floodlightcontroller/core/web/HealthCheckResource.java b/src/main/java/net/floodlightcontroller/core/web/HealthCheckResource.java
index 12ee545..a0d5c0c 100644
--- a/src/main/java/net/floodlightcontroller/core/web/HealthCheckResource.java
+++ b/src/main/java/net/floodlightcontroller/core/web/HealthCheckResource.java
@@ -4,24 +4,24 @@
import org.restlet.resource.ServerResource;
public class HealthCheckResource extends ServerResource {
-
+
public static class HealthCheckInfo {
-
+
protected boolean healthy;
-
+
public HealthCheckInfo() {
this.healthy = true;
}
-
+
public boolean isHealthy() {
return healthy;
}
-
+
public void setHealthy(boolean healthy) {
this.healthy = healthy;
}
}
-
+
@Get("json")
public HealthCheckInfo healthCheck() {
// Currently this is the simplest possible health check -- basically
diff --git a/src/main/java/net/floodlightcontroller/core/web/LoadedModuleLoaderResource.java b/src/main/java/net/floodlightcontroller/core/web/LoadedModuleLoaderResource.java
index 22bdb77..0ffc7b0 100644
--- a/src/main/java/net/floodlightcontroller/core/web/LoadedModuleLoaderResource.java
+++ b/src/main/java/net/floodlightcontroller/core/web/LoadedModuleLoaderResource.java
@@ -7,13 +7,14 @@
import org.restlet.resource.Get;
public class LoadedModuleLoaderResource extends ModuleLoaderResource {
- /**
- * Retrieves information about all modules available
- * to Floodlight.
- * @return Information about all modules available.
- */
+ /**
+ * Retrieves information about all modules available
+ * to Floodlight.
+ *
+ * @return Information about all modules available.
+ */
@Get("json")
public Map<String, Object> retrieve() {
- return retrieveInternal(true);
+ return retrieveInternal(true);
}
}
diff --git a/src/main/java/net/floodlightcontroller/core/web/RoleInfo.java b/src/main/java/net/floodlightcontroller/core/web/RoleInfo.java
index e600ea0..879eb04 100644
--- a/src/main/java/net/floodlightcontroller/core/web/RoleInfo.java
+++ b/src/main/java/net/floodlightcontroller/core/web/RoleInfo.java
@@ -4,22 +4,22 @@
public class RoleInfo {
protected String role;
-
+
public RoleInfo() {
}
-
+
public RoleInfo(String role) {
setRole(role);
}
-
+
public RoleInfo(Role role) {
this.role = (role != null) ? role.name() : "DISABLED";
}
-
+
public String getRole() {
return role;
}
-
+
public void setRole(String role) {
this.role = role;
}
diff --git a/src/main/java/net/floodlightcontroller/core/web/SwitchResourceBase.java b/src/main/java/net/floodlightcontroller/core/web/SwitchResourceBase.java
index 1c138f6..835cb17 100644
--- a/src/main/java/net/floodlightcontroller/core/web/SwitchResourceBase.java
+++ b/src/main/java/net/floodlightcontroller/core/web/SwitchResourceBase.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.web;
@@ -44,35 +44,35 @@
/**
* Base class for server resources related to switches
- * @author readams
*
+ * @author readams
*/
public class SwitchResourceBase extends ServerResource {
protected final static Logger log = LoggerFactory.getLogger(SwitchResourceBase.class);
-
+
public enum REQUESTTYPE {
OFSTATS,
OFFEATURES
}
-
+
@Override
protected void doInit() throws ResourceException {
super.doInit();
-
+
}
-
- @LogMessageDoc(level="ERROR",
- message="Failure retrieving statistics from switch {switch}",
- explanation="An error occurred while retrieving statistics" +
- "from the switch",
- recommendation=LogMessageDoc.CHECK_SWITCH + " " +
- LogMessageDoc.GENERIC_ACTION)
- protected List<OFStatistics> getSwitchStatistics(long switchId,
+
+ @LogMessageDoc(level = "ERROR",
+ message = "Failure retrieving statistics from switch {switch}",
+ explanation = "An error occurred while retrieving statistics" +
+ "from the switch",
+ recommendation = LogMessageDoc.CHECK_SWITCH + " " +
+ LogMessageDoc.GENERIC_ACTION)
+ protected List<OFStatistics> getSwitchStatistics(long switchId,
OFStatisticsType statType) {
- IFloodlightProviderService floodlightProvider =
- (IFloodlightProviderService)getContext().getAttributes().
- get(IFloodlightProviderService.class.getCanonicalName());
-
+ IFloodlightProviderService floodlightProvider =
+ (IFloodlightProviderService) getContext().getAttributes().
+ get(IFloodlightProviderService.class.getCanonicalName());
+
IOFSwitch sw = floodlightProvider.getSwitches().get(switchId);
Future<List<OFStatistics>> future;
List<OFStatistics> values = null;
@@ -87,7 +87,7 @@
specificReq.setMatch(match);
specificReq.setOutPort(OFPort.OFPP_NONE.getValue());
specificReq.setTableId((byte) 0xff);
- req.setStatistics(Collections.singletonList((OFStatistics)specificReq));
+ req.setStatistics(Collections.singletonList((OFStatistics) specificReq));
requestLength += specificReq.getLength();
} else if (statType == OFStatisticsType.AGGREGATE) {
OFAggregateStatisticsRequest specificReq = new OFAggregateStatisticsRequest();
@@ -96,23 +96,23 @@
specificReq.setMatch(match);
specificReq.setOutPort(OFPort.OFPP_NONE.getValue());
specificReq.setTableId((byte) 0xff);
- req.setStatistics(Collections.singletonList((OFStatistics)specificReq));
+ req.setStatistics(Collections.singletonList((OFStatistics) specificReq));
requestLength += specificReq.getLength();
} else if (statType == OFStatisticsType.PORT) {
OFPortStatisticsRequest specificReq = new OFPortStatisticsRequest();
- specificReq.setPortNumber((short)OFPort.OFPP_NONE.getValue());
- req.setStatistics(Collections.singletonList((OFStatistics)specificReq));
+ specificReq.setPortNumber((short) OFPort.OFPP_NONE.getValue());
+ req.setStatistics(Collections.singletonList((OFStatistics) specificReq));
requestLength += specificReq.getLength();
} else if (statType == OFStatisticsType.QUEUE) {
OFQueueStatisticsRequest specificReq = new OFQueueStatisticsRequest();
- specificReq.setPortNumber((short)OFPort.OFPP_ALL.getValue());
+ specificReq.setPortNumber((short) OFPort.OFPP_ALL.getValue());
// LOOK! openflowj does not define OFPQ_ALL! pulled this from openflow.h
// note that I haven't seen this work yet though...
specificReq.setQueueId(0xffffffff);
- req.setStatistics(Collections.singletonList((OFStatistics)specificReq));
+ req.setStatistics(Collections.singletonList((OFStatistics) specificReq));
requestLength += specificReq.getLength();
} else if (statType == OFStatisticsType.DESC ||
- statType == OFStatisticsType.TABLE) {
+ statType == OFStatisticsType.TABLE) {
// pass - nothing todo besides set the type above
}
req.setLengthU(requestLength);
@@ -129,11 +129,11 @@
protected List<OFStatistics> getSwitchStatistics(String switchId, OFStatisticsType statType) {
return getSwitchStatistics(HexString.toLong(switchId), statType);
}
-
+
protected OFFeaturesReply getSwitchFeaturesReply(long switchId) {
- IFloodlightProviderService floodlightProvider =
- (IFloodlightProviderService)getContext().getAttributes().
- get(IFloodlightProviderService.class.getCanonicalName());
+ IFloodlightProviderService floodlightProvider =
+ (IFloodlightProviderService) getContext().getAttributes().
+ get(IFloodlightProviderService.class.getCanonicalName());
IOFSwitch sw = floodlightProvider.getSwitches().get(switchId);
Future<OFFeaturesReply> future;
diff --git a/src/main/java/net/floodlightcontroller/core/web/SwitchRoleResource.java b/src/main/java/net/floodlightcontroller/core/web/SwitchRoleResource.java
index f9eb877..d598005 100644
--- a/src/main/java/net/floodlightcontroller/core/web/SwitchRoleResource.java
+++ b/src/main/java/net/floodlightcontroller/core/web/SwitchRoleResource.java
@@ -17,29 +17,29 @@
@Get("json")
public Object getRole() {
- IFloodlightProviderService floodlightProvider =
- (IFloodlightProviderService)getContext().getAttributes().
- get(IFloodlightProviderService.class.getCanonicalName());
+ IFloodlightProviderService floodlightProvider =
+ (IFloodlightProviderService) getContext().getAttributes().
+ get(IFloodlightProviderService.class.getCanonicalName());
String switchId = (String) getRequestAttributes().get("switchId");
-
+
RoleInfo roleInfo;
-
+
if (switchId.equalsIgnoreCase("all")) {
- HashMap<String,RoleInfo> model = new HashMap<String,RoleInfo>();
- for (IOFSwitch sw: floodlightProvider.getSwitches().values()) {
- switchId = sw.getStringId();
- roleInfo = new RoleInfo(sw.getRole());
- model.put(switchId, roleInfo);
+ HashMap<String, RoleInfo> model = new HashMap<String, RoleInfo>();
+ for (IOFSwitch sw : floodlightProvider.getSwitches().values()) {
+ switchId = sw.getStringId();
+ roleInfo = new RoleInfo(sw.getRole());
+ model.put(switchId, roleInfo);
}
return model;
}
-
- Long dpid = HexString.toLong(switchId);
- IOFSwitch sw = floodlightProvider.getSwitches().get(dpid);
- if (sw == null)
- return null;
- roleInfo = new RoleInfo(sw.getRole());
- return roleInfo;
+
+ Long dpid = HexString.toLong(switchId);
+ IOFSwitch sw = floodlightProvider.getSwitches().get(dpid);
+ if (sw == null)
+ return null;
+ roleInfo = new RoleInfo(sw.getRole());
+ return roleInfo;
}
}
diff --git a/src/main/java/net/floodlightcontroller/core/web/SwitchStatisticsResource.java b/src/main/java/net/floodlightcontroller/core/web/SwitchStatisticsResource.java
index a0cada7..468a50e 100644
--- a/src/main/java/net/floodlightcontroller/core/web/SwitchStatisticsResource.java
+++ b/src/main/java/net/floodlightcontroller/core/web/SwitchStatisticsResource.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.web;
@@ -27,20 +27,21 @@
/**
* Return switch statistics information for specific switches
+ *
* @author readams
*/
public class SwitchStatisticsResource extends SwitchResourceBase {
- protected final static Logger log =
- LoggerFactory.getLogger(SwitchStatisticsResource.class);
+ protected final static Logger log =
+ LoggerFactory.getLogger(SwitchStatisticsResource.class);
@Get("json")
public Map<String, Object> retrieve() {
- HashMap<String,Object> result = new HashMap<String,Object>();
+ HashMap<String, Object> result = new HashMap<String, Object>();
Object values = null;
-
+
String switchId = (String) getRequestAttributes().get("switchId");
String statType = (String) getRequestAttributes().get("statType");
-
+
if (statType.equals("port")) {
values = getSwitchStatistics(switchId, OFStatisticsType.PORT);
} else if (statType.equals("queue")) {
diff --git a/src/main/java/net/floodlightcontroller/core/web/SystemUptimeResource.java b/src/main/java/net/floodlightcontroller/core/web/SystemUptimeResource.java
index a125979..1ea4aa5 100644
--- a/src/main/java/net/floodlightcontroller/core/web/SystemUptimeResource.java
+++ b/src/main/java/net/floodlightcontroller/core/web/SystemUptimeResource.java
@@ -6,27 +6,26 @@
import org.restlet.resource.ServerResource;
-
public class SystemUptimeResource extends ServerResource {
-
- public class UptimeRest {
- long systemUptimeMsec;
- public long getSystemUptimeMsec() {
- return systemUptimeMsec;
- }
- }
-
- @Get("json")
- public UptimeRest retrieve() {
- IFloodlightProviderService floodlightProvider =
- (IFloodlightProviderService)getContext().getAttributes().
- get(IFloodlightProviderService.class.getCanonicalName());
-
- UptimeRest uptime = new UptimeRest();
- uptime.systemUptimeMsec =
- System.currentTimeMillis() - floodlightProvider.getSystemStartTime();
-
- return (uptime);
- }
+ public class UptimeRest {
+ long systemUptimeMsec;
+
+ public long getSystemUptimeMsec() {
+ return systemUptimeMsec;
+ }
+ }
+
+ @Get("json")
+ public UptimeRest retrieve() {
+ IFloodlightProviderService floodlightProvider =
+ (IFloodlightProviderService) getContext().getAttributes().
+ get(IFloodlightProviderService.class.getCanonicalName());
+
+ UptimeRest uptime = new UptimeRest();
+ uptime.systemUptimeMsec =
+ System.currentTimeMillis() - floodlightProvider.getSystemStartTime();
+
+ return (uptime);
+ }
}
diff --git a/src/main/java/net/floodlightcontroller/core/web/serializers/ByteArrayMACSerializer.java b/src/main/java/net/floodlightcontroller/core/web/serializers/ByteArrayMACSerializer.java
index 66c33f5..35f810b 100644
--- a/src/main/java/net/floodlightcontroller/core/web/serializers/ByteArrayMACSerializer.java
+++ b/src/main/java/net/floodlightcontroller/core/web/serializers/ByteArrayMACSerializer.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011,2012 Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011,2012 Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.web.serializers;
@@ -33,7 +33,7 @@
@Override
public void serialize(byte[] mac, JsonGenerator jGen,
SerializerProvider serializer)
- throws IOException, JsonProcessingException {
+ throws IOException, JsonProcessingException {
jGen.writeString(HexString.toHexString(mac));
}
diff --git a/src/main/java/net/floodlightcontroller/core/web/serializers/DPIDSerializer.java b/src/main/java/net/floodlightcontroller/core/web/serializers/DPIDSerializer.java
index e74cc01..304e835 100644
--- a/src/main/java/net/floodlightcontroller/core/web/serializers/DPIDSerializer.java
+++ b/src/main/java/net/floodlightcontroller/core/web/serializers/DPIDSerializer.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011,2012 Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011,2012 Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.web.serializers;
@@ -33,7 +33,7 @@
@Override
public void serialize(Long dpid, JsonGenerator jGen,
SerializerProvider serializer)
- throws IOException, JsonProcessingException {
+ throws IOException, JsonProcessingException {
jGen.writeString(HexString.toHexString(dpid, 8));
}
diff --git a/src/main/java/net/floodlightcontroller/core/web/serializers/IPv4Serializer.java b/src/main/java/net/floodlightcontroller/core/web/serializers/IPv4Serializer.java
index 1bd7caf..d6bc9ba 100644
--- a/src/main/java/net/floodlightcontroller/core/web/serializers/IPv4Serializer.java
+++ b/src/main/java/net/floodlightcontroller/core/web/serializers/IPv4Serializer.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011,2012 Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011,2012 Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.web.serializers;
@@ -34,7 +34,7 @@
@Override
public void serialize(Integer i, JsonGenerator jGen,
SerializerProvider serializer)
- throws IOException, JsonProcessingException {
+ throws IOException, JsonProcessingException {
jGen.writeString(IPv4.fromIPv4Address(i));
}
diff --git a/src/main/java/net/floodlightcontroller/core/web/serializers/MACSerializer.java b/src/main/java/net/floodlightcontroller/core/web/serializers/MACSerializer.java
index a7c9fb7..eacf515 100644
--- a/src/main/java/net/floodlightcontroller/core/web/serializers/MACSerializer.java
+++ b/src/main/java/net/floodlightcontroller/core/web/serializers/MACSerializer.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011,2012 Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011,2012 Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.web.serializers;
@@ -33,7 +33,7 @@
@Override
public void serialize(Long dpid, JsonGenerator jGen,
SerializerProvider serializer)
- throws IOException, JsonProcessingException {
+ throws IOException, JsonProcessingException {
jGen.writeString(HexString.toHexString(dpid, 6));
}
diff --git a/src/main/java/net/floodlightcontroller/core/web/serializers/UShortSerializer.java b/src/main/java/net/floodlightcontroller/core/web/serializers/UShortSerializer.java
index c125c76..0c4fa22 100644
--- a/src/main/java/net/floodlightcontroller/core/web/serializers/UShortSerializer.java
+++ b/src/main/java/net/floodlightcontroller/core/web/serializers/UShortSerializer.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011,2012 Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011,2012 Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.core.web.serializers;
@@ -32,7 +32,7 @@
@Override
public void serialize(Short s, JsonGenerator jGen,
SerializerProvider serializer) throws IOException,
- JsonProcessingException {
+ JsonProcessingException {
if (s == null) jGen.writeNull();
else jGen.writeNumber(s.shortValue() & 0xffff);
}
diff --git a/src/main/java/net/floodlightcontroller/restserver/IRestApiService.java b/src/main/java/net/floodlightcontroller/restserver/IRestApiService.java
index d906795..ff8b3fc 100644
--- a/src/main/java/net/floodlightcontroller/restserver/IRestApiService.java
+++ b/src/main/java/net/floodlightcontroller/restserver/IRestApiService.java
@@ -5,6 +5,7 @@
public interface IRestApiService extends IFloodlightService {
/**
* Adds a REST API
+ *
* @param routeable
*/
public void addRestletRoutable(RestletRoutable routable);
diff --git a/src/main/java/net/floodlightcontroller/restserver/RestApiServer.java b/src/main/java/net/floodlightcontroller/restserver/RestApiServer.java
index a51e499..031a239 100644
--- a/src/main/java/net/floodlightcontroller/restserver/RestApiServer.java
+++ b/src/main/java/net/floodlightcontroller/restserver/RestApiServer.java
@@ -31,25 +31,25 @@
import org.slf4j.LoggerFactory;
public class RestApiServer
- implements IFloodlightModule, IRestApiService {
+ implements IFloodlightModule, IRestApiService {
protected final static Logger logger = LoggerFactory.getLogger(RestApiServer.class);
protected List<RestletRoutable> restlets;
protected FloodlightModuleContext fmlContext;
protected int restPort = 8080;
protected String numThreads = null;
-
+
// ***********
// Application
// ***********
-
+
protected class RestApplication extends Application {
protected Context context;
-
+
public RestApplication() {
super(new Context());
this.context = getContext();
}
-
+
@Override
public Restlet createInboundRoot() {
Router baseRouter = new Router(context);
@@ -58,13 +58,12 @@
baseRouter.attach(rr.basePath(), rr.getRestlet(context));
}
- Filter slashFilter = new Filter() {
+ Filter slashFilter = new Filter() {
@Override
protected int beforeHandle(Request request, Response response) {
Reference ref = request.getResourceRef();
String originalPath = ref.getPath();
- if (originalPath.contains("//"))
- {
+ if (originalPath.contains("//")) {
String newPath = originalPath.replaceAll("/+", "/");
ref.setPath(newPath);
}
@@ -73,10 +72,10 @@
};
slashFilter.setNext(baseRouter);
-
+
return slashFilter;
}
-
+
public void run(FloodlightModuleContext fmlContext, int restPort) {
setStatusService(new StatusService() {
@Override
@@ -84,26 +83,26 @@
Request request,
Response response) {
return new JacksonRepresentation<Status>(status);
- }
+ }
});
-
+
// Add everything in the module context to the rest
for (Class<? extends IFloodlightService> s : fmlContext.getAllServices()) {
if (logger.isTraceEnabled()) {
logger.trace("Adding {} for service {} into context",
- s.getCanonicalName(), fmlContext.getServiceImpl(s));
+ s.getCanonicalName(), fmlContext.getServiceImpl(s));
}
- context.getAttributes().put(s.getCanonicalName(),
- fmlContext.getServiceImpl(s));
+ context.getAttributes().put(s.getCanonicalName(),
+ fmlContext.getServiceImpl(s));
}
-
+
// Start listening for REST requests
try {
final Component component = new Component();
Server server = component.getServers().add(Protocol.HTTP, restPort);
- if (numThreads != null){
- logger.debug("Setting number of REST API threads to {}", numThreads);
- server.getContext().getParameters().add("defaultThreads", numThreads);
+ if (numThreads != null) {
+ logger.debug("Setting number of REST API threads to {}", numThreads);
+ server.getContext().getParameters().add("defaultThreads", numThreads);
}
component.getDefaultHost().attach(this);
component.start();
@@ -112,11 +111,11 @@
}
}
}
-
+
// ***************
// IRestApiService
// ***************
-
+
@Override
public void addRestletRoutable(RestletRoutable routable) {
restlets.add(routable);
@@ -135,15 +134,15 @@
}
logger.debug(sb.toString());
}
-
+
RestApplication restApp = new RestApplication();
restApp.run(fmlContext, restPort);
}
-
+
// *****************
// IFloodlightModule
// *****************
-
+
@Override
public Collection<Class<? extends IFloodlightService>> getModuleServices() {
Collection<Class<? extends IFloodlightService>> services =
@@ -154,10 +153,10 @@
@Override
public Map<Class<? extends IFloodlightService>, IFloodlightService>
- getServiceImpls() {
+ getServiceImpls() {
Map<Class<? extends IFloodlightService>,
- IFloodlightService> m =
- new HashMap<Class<? extends IFloodlightService>,
+ IFloodlightService> m =
+ new HashMap<Class<? extends IFloodlightService>,
IFloodlightService>();
m.put(IRestApiService.class, this);
return m;
@@ -176,7 +175,7 @@
// startUp methods will be called
this.restlets = new ArrayList<RestletRoutable>();
this.fmlContext = context;
-
+
// read our config options
Map<String, String> configOptions = context.getConfigParams(this);
String port = configOptions.get("port");
@@ -184,10 +183,10 @@
restPort = Integer.parseInt(port);
}
logger.debug("REST port set to {}", restPort);
-
+
String numThreads = configOptions.get("dispatcherthreads");
if (numThreads != null) {
- this.numThreads = numThreads;
+ this.numThreads = numThreads;
}
}
diff --git a/src/main/java/net/floodlightcontroller/restserver/RestletRoutable.java b/src/main/java/net/floodlightcontroller/restserver/RestletRoutable.java
index cb7dfce..751a567 100644
--- a/src/main/java/net/floodlightcontroller/restserver/RestletRoutable.java
+++ b/src/main/java/net/floodlightcontroller/restserver/RestletRoutable.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.restserver;
@@ -22,18 +22,21 @@
/**
* Register a set of REST resources with the central controller
+ *
* @author readams
*/
public interface RestletRoutable {
/**
* Get the restlet that will map to the resources
+ *
* @param context the context for constructing the restlet
* @return the restlet
*/
Restlet getRestlet(Context context);
-
+
/**
* Get the base path URL where the router should be registered
+ *
* @return the base path URL where the router should be registered
*/
String basePath();
diff --git a/src/main/java/net/floodlightcontroller/threadpool/IThreadPoolService.java b/src/main/java/net/floodlightcontroller/threadpool/IThreadPoolService.java
index a537a3a..f9460cb 100644
--- a/src/main/java/net/floodlightcontroller/threadpool/IThreadPoolService.java
+++ b/src/main/java/net/floodlightcontroller/threadpool/IThreadPoolService.java
@@ -9,6 +9,7 @@
* Get the master scheduled thread pool executor maintained by the
* ThreadPool provider. This can be used by other modules as a centralized
* way to schedule tasks.
+ *
* @return
*/
public ScheduledExecutorService getScheduledExecutor();
diff --git a/src/main/java/net/floodlightcontroller/threadpool/ThreadPool.java b/src/main/java/net/floodlightcontroller/threadpool/ThreadPool.java
index aa426a7..6314a77 100644
--- a/src/main/java/net/floodlightcontroller/threadpool/ThreadPool.java
+++ b/src/main/java/net/floodlightcontroller/threadpool/ThreadPool.java
@@ -14,19 +14,19 @@
public class ThreadPool implements IThreadPoolService, IFloodlightModule {
protected ScheduledExecutorService executor = null;
-
+
// IThreadPoolService
@Override
public ScheduledExecutorService getScheduledExecutor() {
return executor;
}
-
+
// IFloodlightModule
-
+
@Override
public Collection<Class<? extends IFloodlightService>> getModuleServices() {
- Collection<Class<? extends IFloodlightService>> l =
+ Collection<Class<? extends IFloodlightService>> l =
new ArrayList<Class<? extends IFloodlightService>>();
l.add(IThreadPoolService.class);
return l;
@@ -34,11 +34,11 @@
@Override
public Map<Class<? extends IFloodlightService>, IFloodlightService>
- getServiceImpls() {
+ getServiceImpls() {
Map<Class<? extends IFloodlightService>,
- IFloodlightService> m =
+ IFloodlightService> m =
new HashMap<Class<? extends IFloodlightService>,
- IFloodlightService>();
+ IFloodlightService>();
m.put(IThreadPoolService.class, this);
// We are the class that implements the service
return m;
@@ -46,14 +46,14 @@
@Override
public Collection<Class<? extends IFloodlightService>>
- getModuleDependencies() {
+ getModuleDependencies() {
// No dependencies
return null;
}
@Override
public void init(FloodlightModuleContext context)
- throws FloodlightModuleException {
+ throws FloodlightModuleException {
executor = Executors.newScheduledThreadPool(15);
}
diff --git a/src/main/java/net/floodlightcontroller/util/BundleAction.java b/src/main/java/net/floodlightcontroller/util/BundleAction.java
index 0d82275..ea797a8 100644
--- a/src/main/java/net/floodlightcontroller/util/BundleAction.java
+++ b/src/main/java/net/floodlightcontroller/util/BundleAction.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.util;
@@ -22,7 +22,6 @@
import java.util.List;
/**
- *
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public enum BundleAction {
@@ -33,16 +32,16 @@
public static List<BundleAction> getAvailableActions(BundleState state) {
List<BundleAction> actions = new ArrayList<BundleAction>();
- if (Arrays.binarySearch(new BundleState[] {
+ if (Arrays.binarySearch(new BundleState[]{
BundleState.ACTIVE, BundleState.STARTING,
- BundleState.UNINSTALLED }, state) < 0) {
+ BundleState.UNINSTALLED}, state) < 0) {
actions.add(START);
}
- if (Arrays.binarySearch(new BundleState[] {
+ if (Arrays.binarySearch(new BundleState[]{
BundleState.ACTIVE}, state) >= 0) {
actions.add(STOP);
}
- if (Arrays.binarySearch(new BundleState[] {
+ if (Arrays.binarySearch(new BundleState[]{
BundleState.UNINSTALLED}, state) < 0) {
actions.add(UNINSTALL);
}
diff --git a/src/main/java/net/floodlightcontroller/util/BundleState.java b/src/main/java/net/floodlightcontroller/util/BundleState.java
index f89bc0b..ef32958 100644
--- a/src/main/java/net/floodlightcontroller/util/BundleState.java
+++ b/src/main/java/net/floodlightcontroller/util/BundleState.java
@@ -1,33 +1,32 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.util;
/**
- *
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public enum BundleState {
- ACTIVE (32),
- INSTALLED (2),
- RESOLVED (4),
- STARTING (8),
- STOPPING (16),
- UNINSTALLED (1);
+ ACTIVE(32),
+ INSTALLED(2),
+ RESOLVED(4),
+ STARTING(8),
+ STOPPING(16),
+ UNINSTALLED(1);
protected int value;
diff --git a/src/main/java/net/floodlightcontroller/util/EventHistory.java b/src/main/java/net/floodlightcontroller/util/EventHistory.java
index 69031ba..40c9a36 100644
--- a/src/main/java/net/floodlightcontroller/util/EventHistory.java
+++ b/src/main/java/net/floodlightcontroller/util/EventHistory.java
@@ -1,5 +1,5 @@
/**
- *
+ *
*/
package net.floodlightcontroller.util;
@@ -7,30 +7,33 @@
/**
* @author subrata
- *
*/
public class EventHistory<T> {
public static final int EV_HISTORY_DEFAULT_SIZE = 1024;
- public String description;
- public int event_history_size;
- public int current_index;
+ public String description;
+ public int event_history_size;
+ public int current_index;
public boolean full; // true if all are in use
public ArrayList<Event> events;
public String getDescription() {
return description;
}
+
public int getEvent_history_size() {
return event_history_size;
}
+
public int getCurrent_index() {
return current_index;
}
+
public boolean isFull() {
return full;
}
+
public ArrayList<Event> getEvents() {
return events;
}
@@ -69,18 +72,18 @@
events = new ArrayList<Event>(maxEvents);
for (int idx = 0; idx < maxEvents; idx++) {
- Event evH = new Event();
+ Event evH = new Event();
evH.base_info = new EventHistoryBaseInfo();
- evH.info = null;
+ evH.info = null;
evH.base_info.state = EvState.FREE;
- evH.base_info.idx = idx;
+ evH.base_info.idx = idx;
events.add(idx, evH);
}
description = "Event-History:" + desc;
- event_history_size = maxEvents;
- current_index = 0;
- full = false;
+ event_history_size = maxEvents;
+ current_index = 0;
+ full = false;
}
// Constructor for default size
@@ -95,11 +98,11 @@
description = "No event found";
return;
}
- int curSize = (eventHist.full)?eventHist.event_history_size:
- eventHist.current_index;
- int size = (latestK < curSize)?latestK:curSize;
+ int curSize = (eventHist.full) ? eventHist.event_history_size :
+ eventHist.current_index;
+ int size = (latestK < curSize) ? latestK : curSize;
int evIdx = eventHist.current_index;
- int topSz = (evIdx >= size)?size:evIdx;
+ int topSz = (evIdx >= size) ? size : evIdx;
// Need to create a new one since size is different
events = new ArrayList<Event>(size);
@@ -107,7 +110,7 @@
// Get the top part
int origIdx = evIdx;
for (int idx = 0; idx < topSz; idx++) {
- Event evH = eventHist.events.get(--origIdx);
+ Event evH = eventHist.events.get(--origIdx);
evH.base_info.idx = idx;
events.add(idx, evH);
}
@@ -121,9 +124,9 @@
}
description = eventHist.description;
- event_history_size = size;
- current_index = 0; // since it is full
- full = true;
+ event_history_size = size;
+ current_index = 0; // since it is full
+ full = true;
}
// Get an index for writing a new event. This method is synchronized for
@@ -131,13 +134,13 @@
// by the caller event at the index is updated without any lock
public synchronized int NextIdx() {
// curIdx should be in the 0 to evArraySz-1
- if (current_index == (event_history_size-1)) {
+ if (current_index == (event_history_size - 1)) {
current_index = 0;
full = true;
- return (event_history_size-1);
+ return (event_history_size - 1);
} else {
current_index++;
- return (current_index-1);
+ return (current_index - 1);
}
}
@@ -148,6 +151,7 @@
* and the current object at that array location is returned to the
* calling process so that the calling process can use that object
* for the next event of the same type
+ *
* @param t
* @param op
* @return
@@ -165,7 +169,7 @@
return temp;
}
- /***
+ /**
* Clear the event history, needs to be done under lock
*/
public void clear() {
diff --git a/src/main/java/net/floodlightcontroller/util/EventHistoryBaseInfo.java b/src/main/java/net/floodlightcontroller/util/EventHistoryBaseInfo.java
index 74fc973..52b623d 100644
--- a/src/main/java/net/floodlightcontroller/util/EventHistoryBaseInfo.java
+++ b/src/main/java/net/floodlightcontroller/util/EventHistoryBaseInfo.java
@@ -3,23 +3,26 @@
import org.codehaus.jackson.map.annotate.JsonSerialize;
-@JsonSerialize(using=EventHistoryBaseInfoJSONSerializer.class)
+@JsonSerialize(using = EventHistoryBaseInfoJSONSerializer.class)
public class EventHistoryBaseInfo {
- public int idx;
- public long time_ms; // timestamp in milliseconds
- public EventHistory.EvState state;
- public EventHistory.EvAction action;
+ public int idx;
+ public long time_ms; // timestamp in milliseconds
+ public EventHistory.EvState state;
+ public EventHistory.EvAction action;
// Getters
public int getIdx() {
return idx;
}
+
public long getTime_ms() {
return time_ms;
}
+
public EventHistory.EvState getState() {
return state;
}
+
public EventHistory.EvAction getAction() {
return action;
}
diff --git a/src/main/java/net/floodlightcontroller/util/EventHistoryBaseInfoJSONSerializer.java b/src/main/java/net/floodlightcontroller/util/EventHistoryBaseInfoJSONSerializer.java
index 3916282..0fe4b17 100644
--- a/src/main/java/net/floodlightcontroller/util/EventHistoryBaseInfoJSONSerializer.java
+++ b/src/main/java/net/floodlightcontroller/util/EventHistoryBaseInfoJSONSerializer.java
@@ -1,18 +1,18 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.util;
@@ -27,32 +27,31 @@
/**
* @author subrata
- *
*/
-public class EventHistoryBaseInfoJSONSerializer extends
- JsonSerializer<EventHistoryBaseInfo> {
+public class EventHistoryBaseInfoJSONSerializer extends
+ JsonSerializer<EventHistoryBaseInfo> {
-
+
/**
* Performs the serialization of a EventHistory.BaseInfo object
*/
@Override
public void serialize(EventHistoryBaseInfo base_info, JsonGenerator jGen,
- SerializerProvider serializer)
- throws IOException, JsonProcessingException {
+ SerializerProvider serializer)
+ throws IOException, JsonProcessingException {
jGen.writeStartObject();
- jGen.writeNumberField("Idx", base_info.getIdx());
+ jGen.writeNumberField("Idx", base_info.getIdx());
Timestamp ts = new Timestamp(base_info.getTime_ms());
String tsStr = ts.toString();
while (tsStr.length() < 23) {
tsStr = tsStr.concat("0");
}
jGen.writeStringField("Time", tsStr);
- jGen.writeStringField("State", base_info.getState().name());
+ jGen.writeStringField("State", base_info.getState().name());
String acStr = base_info.getAction().name().toLowerCase();
// Capitalize the first letter
- acStr = acStr.substring(0,1).toUpperCase().concat(acStr.substring(1));
+ acStr = acStr.substring(0, 1).toUpperCase().concat(acStr.substring(1));
jGen.writeStringField("Action", acStr);
jGen.writeEndObject();
}
diff --git a/src/main/java/net/floodlightcontroller/util/FilterIterator.java b/src/main/java/net/floodlightcontroller/util/FilterIterator.java
index 47cd5c9..fac4e7a 100644
--- a/src/main/java/net/floodlightcontroller/util/FilterIterator.java
+++ b/src/main/java/net/floodlightcontroller/util/FilterIterator.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2012, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2012, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.util;
@@ -30,6 +30,7 @@
/**
* Construct a filter iterator from the given sub iterator
+ *
* @param subIterator the sub iterator over which we'll filter
*/
public FilterIterator(Iterator<T> subIterator) {
@@ -40,11 +41,12 @@
/**
* Check whether the given value should be returned by the
* filter
+ *
* @param value the value to check
* @return true if the value should be included
*/
protected abstract boolean matches(T value);
-
+
// ***********
// Iterator<T>
// ***********
@@ -52,7 +54,7 @@
@Override
public boolean hasNext() {
if (next != null) return true;
-
+
while (subIterator.hasNext()) {
next = subIterator.next();
if (matches(next))
diff --git a/src/main/java/net/floodlightcontroller/util/IterableIterator.java b/src/main/java/net/floodlightcontroller/util/IterableIterator.java
index 584de08..b71404a 100644
--- a/src/main/java/net/floodlightcontroller/util/IterableIterator.java
+++ b/src/main/java/net/floodlightcontroller/util/IterableIterator.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2012 Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2012 Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.util;
@@ -28,7 +28,7 @@
public class IterableIterator<T> implements Iterator<T> {
Iterator<? extends Iterable<T>> subIterator;
Iterator<T> current = null;
-
+
public IterableIterator(Iterator<? extends Iterable<T>> subIterator) {
super();
this.subIterator = subIterator;
@@ -46,7 +46,7 @@
while (!current.hasNext() && subIterator.hasNext()) {
current = subIterator.next().iterator();
}
-
+
return current.hasNext();
}
diff --git a/src/main/java/net/floodlightcontroller/util/LRUHashMap.java b/src/main/java/net/floodlightcontroller/util/LRUHashMap.java
index 477e886..7b8d536 100644
--- a/src/main/java/net/floodlightcontroller/util/LRUHashMap.java
+++ b/src/main/java/net/floodlightcontroller/util/LRUHashMap.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.util;
@@ -21,18 +21,18 @@
import java.util.Map;
public class LRUHashMap<K, V> extends LinkedHashMap<K, V> {
-
+
private static final long serialVersionUID = 1L;
-
+
private final int capacity;
- public LRUHashMap(int capacity)
- {
- super(capacity+1, 0.75f, true);
+
+ public LRUHashMap(int capacity) {
+ super(capacity + 1, 0.75f, true);
this.capacity = capacity;
}
-
- protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
- return size() > capacity;
+
+ protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
+ return size() > capacity;
}
}
diff --git a/src/main/java/net/floodlightcontroller/util/MACAddress.java b/src/main/java/net/floodlightcontroller/util/MACAddress.java
index 13d83d1..f3ac52b 100644
--- a/src/main/java/net/floodlightcontroller/util/MACAddress.java
+++ b/src/main/java/net/floodlightcontroller/util/MACAddress.java
@@ -15,9 +15,9 @@
*
* @author Sho Shimizu (sho.shimizu@gmail.com)
*/
-@JsonDeserialize(using=MACAddressDeserializer.class)
-@JsonSerialize(using=MACAddressSerializer.class)
-public class MACAddress implements Serializable{
+@JsonDeserialize(using = MACAddressDeserializer.class)
+@JsonSerialize(using = MACAddressSerializer.class)
+public class MACAddress implements Serializable {
private static final long serialVersionUID = 10000L;
public static final int MAC_ADDRESS_LENGTH = 6;
private byte[] address = new byte[MAC_ADDRESS_LENGTH];
@@ -26,7 +26,7 @@
* Default constructor.
*/
public MACAddress() {
- this.address = new byte[] { 0, 0, 0, 0, 0, 0};
+ this.address = new byte[]{0, 0, 0, 0, 0, 0};
}
/**
@@ -40,6 +40,7 @@
/**
* Returns a MAC address instance representing the value of the specified {@code String}.
+ *
* @param address the String representation of the MAC Address to be parsed.
* @return a MAC Address instance representing the value of the specified {@code String}.
* @throws IllegalArgumentException if the string cannot be parsed as a MAC address.
@@ -49,13 +50,13 @@
if (elements.length != MAC_ADDRESS_LENGTH) {
throw new IllegalArgumentException(
"Specified MAC Address must contain 12 hex digits" +
- " separated pairwise by :'s.");
+ " separated pairwise by :'s.");
}
byte[] addressInBytes = new byte[MAC_ADDRESS_LENGTH];
for (int i = 0; i < MAC_ADDRESS_LENGTH; i++) {
String element = elements[i];
- addressInBytes[i] = (byte)Integer.parseInt(element, 16);
+ addressInBytes[i] = (byte) Integer.parseInt(element, 16);
}
return new MACAddress(addressInBytes);
@@ -63,6 +64,7 @@
/**
* Returns a MAC address instance representing the specified {@code byte} array.
+ *
* @param address the byte array to be parsed.
* @return a MAC address instance representing the specified {@code byte} array.
* @throws IllegalArgumentException if the byte array cannot be parsed as a MAC address.
@@ -78,18 +80,19 @@
/**
* Returns a MAC address instance representing the specified {@code long} value.
* The lower 48 bits of the long value are used to parse as a MAC address.
+ *
* @param address the long value to be parsed. The lower 48 bits are used for a MAC address.
* @return a MAC address instance representing the specified {@code long} value.
* @throws IllegalArgumentException if the long value cannot be parsed as a MAC address.
*/
public static MACAddress valueOf(long address) {
- byte[] addressInBytes = new byte[] {
- (byte)((address >> 40) & 0xff),
- (byte)((address >> 32) & 0xff),
- (byte)((address >> 24) & 0xff),
- (byte)((address >> 16) & 0xff),
- (byte)((address >> 8 ) & 0xff),
- (byte)((address >> 0) & 0xff)
+ byte[] addressInBytes = new byte[]{
+ (byte) ((address >> 40) & 0xff),
+ (byte) ((address >> 32) & 0xff),
+ (byte) ((address >> 24) & 0xff),
+ (byte) ((address >> 16) & 0xff),
+ (byte) ((address >> 8) & 0xff),
+ (byte) ((address >> 0) & 0xff)
};
return new MACAddress(addressInBytes);
@@ -97,6 +100,7 @@
/**
* Returns the length of the {@code MACAddress}.
+ *
* @return the length of the {@code MACAddress}.
*/
public int length() {
@@ -105,6 +109,7 @@
/**
* Returns the value of the {@code MACAddress} as a {@code byte} array.
+ *
* @return the numeric value represented by this object after conversion to type {@code byte} array.
*/
public byte[] toBytes() {
@@ -113,6 +118,7 @@
/**
* Returns the value of the {@code MACAddress} as a {@code long}.
+ *
* @return the numeric value represented by this object after conversion to type {@code long}.
*/
public long toLong() {
@@ -126,6 +132,7 @@
/**
* Returns {@code true} if the MAC address is the broadcast address.
+ *
* @return {@code true} if the MAC address is the broadcast address.
*/
public boolean isBroadcast() {
@@ -138,6 +145,7 @@
/**
* Returns {@code true} if the MAC address is the multicast address.
+ *
* @return {@code true} if the MAC address is the multicast address.
*/
public boolean isMulticast() {
@@ -157,7 +165,7 @@
return false;
}
- MACAddress other = (MACAddress)o;
+ MACAddress other = (MACAddress) o;
return Arrays.equals(this.address, other.address);
}
@@ -168,6 +176,6 @@
@Override
public String toString() {
- return HexString.toHexString(address);
+ return HexString.toHexString(address);
}
}
diff --git a/src/main/java/net/floodlightcontroller/util/MultiIterator.java b/src/main/java/net/floodlightcontroller/util/MultiIterator.java
index bcbc916..347ff10 100644
--- a/src/main/java/net/floodlightcontroller/util/MultiIterator.java
+++ b/src/main/java/net/floodlightcontroller/util/MultiIterator.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2012 Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2012 Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.util;
@@ -28,7 +28,7 @@
public class MultiIterator<T> implements Iterator<T> {
Iterator<Iterator<T>> subIterator;
Iterator<T> current = null;
-
+
public MultiIterator(Iterator<Iterator<T>> subIterator) {
super();
this.subIterator = subIterator;
@@ -46,7 +46,7 @@
while (!current.hasNext() && subIterator.hasNext()) {
current = subIterator.next();
}
-
+
return current.hasNext();
}
diff --git a/src/main/java/net/floodlightcontroller/util/OFMessageDamper.java b/src/main/java/net/floodlightcontroller/util/OFMessageDamper.java
index 4dfb60b..47a92a9 100644
--- a/src/main/java/net/floodlightcontroller/util/OFMessageDamper.java
+++ b/src/main/java/net/floodlightcontroller/util/OFMessageDamper.java
@@ -15,35 +15,37 @@
import org.openflow.protocol.OFType;
/**
- * Dampens OFMessages sent to an OF switch. A message is only written to
+ * Dampens OFMessages sent to an OF switch. A message is only written to
* a switch if the same message (as defined by .equals()) has not been written
* in the last n milliseconds. Timer granularity is based on TimedCache
- * @author gregor
*
+ * @author gregor
*/
public class OFMessageDamper {
/**
* An entry in the TimedCache. A cache entry consists of the sent message
- * as well as the switch to which the message was sent.
- *
- * NOTE: We currently use the full OFMessage object. To save space, we
- * could use a cryptographic hash (e.g., SHA-1). However, this would
- * obviously be more time-consuming....
- *
+ * as well as the switch to which the message was sent.
+ * <p/>
+ * NOTE: We currently use the full OFMessage object. To save space, we
+ * could use a cryptographic hash (e.g., SHA-1). However, this would
+ * obviously be more time-consuming....
+ * <p/>
* We also store a reference to the actual IOFSwitch object and /not/
* the switch DPID. This way we are guarnteed to not dampen messages if
* a switch disconnects and then reconnects.
- *
+ *
* @author gregor
*/
protected static class DamperEntry {
OFMessage msg;
IOFSwitch sw;
+
public DamperEntry(OFMessage msg, IOFSwitch sw) {
super();
this.msg = msg;
this.sw = sw;
}
+
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@@ -55,6 +57,7 @@
result = prime * result + ((sw == null) ? 0 : sw.hashCode());
return result;
}
+
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@@ -72,67 +75,70 @@
} else if (!sw.equals(other.sw)) return false;
return true;
}
-
-
+
+
}
+
TimedCache<DamperEntry> cache;
EnumSet<OFType> msgTypesToCache;
+
/**
- *
- * @param capacity the maximum number of messages that should be
- * kept
- * @param typesToDampen The set of OFMessageTypes that should be
- * dampened by this instance. Other types will be passed through
- * @param timeout The dampening timeout. A message will only be
- * written if the last write for the an equal message more than
- * timeout ms ago.
+ * @param capacity the maximum number of messages that should be
+ * kept
+ * @param typesToDampen The set of OFMessageTypes that should be
+ * dampened by this instance. Other types will be passed through
+ * @param timeout The dampening timeout. A message will only be
+ * written if the last write for the an equal message more than
+ * timeout ms ago.
*/
- public OFMessageDamper(int capacity,
- Set<OFType> typesToDampen,
+ public OFMessageDamper(int capacity,
+ Set<OFType> typesToDampen,
int timeout) {
cache = new TimedCache<DamperEntry>(capacity, timeout);
msgTypesToCache = EnumSet.copyOf(typesToDampen);
- }
-
+ }
+
/**
* write the messag to the switch according to our dampening settings
+ *
* @param sw
* @param msg
* @param cntx
* @return true if the message was written to the switch, false if
- * the message was dampened.
+ * the message was dampened.
* @throws IOException
*/
public boolean write(IOFSwitch sw, OFMessage msg, FloodlightContext cntx)
- throws IOException {
+ throws IOException {
return write(sw, msg, cntx, false);
}
-
+
/**
* write the messag to the switch according to our dampening settings
+ *
* @param sw
* @param msg
* @param cntx
* @param flush true to flush the packet immidiately
* @return true if the message was written to the switch, false if
- * the message was dampened.
+ * the message was dampened.
* @throws IOException
*/
public boolean write(IOFSwitch sw, OFMessage msg,
- FloodlightContext cntx, boolean flush)
+ FloodlightContext cntx, boolean flush)
throws IOException {
- if (! msgTypesToCache.contains(msg.getType())) {
+ if (!msgTypesToCache.contains(msg.getType())) {
sw.write(msg, cntx);
if (flush) {
sw.flush();
}
return true;
}
-
+
DamperEntry entry = new DamperEntry(msg, sw);
if (cache.update(entry)) {
// entry exists in cache. Dampening.
- return false;
+ return false;
} else {
sw.write(msg, cntx);
if (flush) {
diff --git a/src/main/java/net/floodlightcontroller/util/TimedCache.java b/src/main/java/net/floodlightcontroller/util/TimedCache.java
index 3a44556..2a90f0b 100644
--- a/src/main/java/net/floodlightcontroller/util/TimedCache.java
+++ b/src/main/java/net/floodlightcontroller/util/TimedCache.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.floodlightcontroller.util;
@@ -26,55 +26,53 @@
* The value is time-stamp in milliseconds
* The time interval denotes the interval for which the entry should remain in the hashmap.
* If an entry is present in the Linkedhashmap, it does not mean that it's valid (recently seen)
- *
+ *
* @param <K> Type of the values in this cache
*/
-public class TimedCache<K> {
+public class TimedCache<K> {
private final long timeoutInterval; //specified in milliseconds.
- private ConcurrentMap<K, Long> cache;
-
+ private ConcurrentMap<K, Long> cache;
+
/**
- *
- * @param capacity the maximum number of entries in the cache before the
- * oldest entry is evicted.
+ * @param capacity the maximum number of entries in the cache before the
+ * oldest entry is evicted.
* @param timeToLive specified in milliseconds
*/
- public TimedCache(int capacity, int timeToLive) {
+ public TimedCache(int capacity, int timeToLive) {
cache = new ConcurrentLinkedHashMap.Builder<K, Long>()
- .maximumWeightedCapacity(capacity)
- .build();
+ .maximumWeightedCapacity(capacity)
+ .build();
this.timeoutInterval = timeToLive;
}
-
+
public long getTimeoutInterval() {
return this.timeoutInterval;
}
-
+
/**
* Always try to update the cache and set the last-seen value for this key.
- *
+ * <p/>
* Return true, if a valid existing field was updated, else return false.
* (note: if multiple threads update simultaneously, one of them will succeed,
- * other wills return false)
- *
+ * other wills return false)
+ *
* @param key
* @return boolean
*/
- public boolean update(K key)
- {
+ public boolean update(K key) {
Long curr = new Long(System.currentTimeMillis());
Long prev = cache.putIfAbsent(key, curr);
-
+
if (prev == null) {
- return false;
+ return false;
}
if (curr - prev > this.timeoutInterval) {
if (cache.replace(key, prev, curr)) {
- return false;
+ return false;
}
}
-
+
return true;
}
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/BgpPeer.java b/src/main/java/net/onrc/onos/apps/bgproute/BgpPeer.java
index 32ea288..d103918 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/BgpPeer.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/BgpPeer.java
@@ -7,20 +7,20 @@
import com.google.common.net.InetAddresses;
public class BgpPeer {
- private final String interfaceName;
- private final InetAddress ipAddress;
-
- public BgpPeer(@JsonProperty("interface") String interfaceName,
- @JsonProperty("ipAddress") String ipAddress) {
- this.interfaceName = interfaceName;
- this.ipAddress = InetAddresses.forString(ipAddress);
- }
-
- public String getInterfaceName() {
- return interfaceName;
- }
+ private final String interfaceName;
+ private final InetAddress ipAddress;
- public InetAddress getIpAddress() {
- return ipAddress;
- }
+ public BgpPeer(@JsonProperty("interface") String interfaceName,
+ @JsonProperty("ipAddress") String ipAddress) {
+ this.interfaceName = interfaceName;
+ this.ipAddress = InetAddresses.forString(ipAddress);
+ }
+
+ public String getInterfaceName() {
+ return interfaceName;
+ }
+
+ public InetAddress getIpAddress() {
+ return ipAddress;
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/BgpRoute.java b/src/main/java/net/onrc/onos/apps/bgproute/BgpRoute.java
index 881e925..b2fcbc0 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/BgpRoute.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/BgpRoute.java
@@ -73,1318 +73,1310 @@
import com.google.common.util.concurrent.ThreadFactoryBuilder;
public class BgpRoute implements IFloodlightModule, IBgpRouteService,
- IArpRequester,
- IOFSwitchListener, IConfigInfoService {
+ IArpRequester,
+ IOFSwitchListener, IConfigInfoService {
- private final static Logger log = LoggerFactory.getLogger(BgpRoute.class);
+ private final static Logger log = LoggerFactory.getLogger(BgpRoute.class);
- private IFloodlightProviderService floodlightProvider;
- private ILinkDiscoveryService linkDiscoveryService;
- private IRestApiService restApi;
- private IProxyArpService proxyArp;
+ private IFloodlightProviderService floodlightProvider;
+ private ILinkDiscoveryService linkDiscoveryService;
+ private IRestApiService restApi;
+ private IProxyArpService proxyArp;
- private IPatriciaTrie<RibEntry> ptree;
- private IPatriciaTrie<Interface> interfacePtrie;
- private BlockingQueue<RibUpdate> ribUpdates;
+ private IPatriciaTrie<RibEntry> ptree;
+ private IPatriciaTrie<Interface> interfacePtrie;
+ private BlockingQueue<RibUpdate> ribUpdates;
- private String bgpdRestIp;
- private String routerId;
- private String configFilename = "config.json";
+ private String bgpdRestIp;
+ private String routerId;
+ private String configFilename = "config.json";
- //We need to identify our flows somehow. But like it says in LearningSwitch.java,
- //the controller/OS should hand out cookie IDs to prevent conflicts.
- private final long APP_COOKIE = 0xa0000000000000L;
- //Cookie for flows that do L2 forwarding within SDN domain to egress routers
- private final long L2_FWD_COOKIE = APP_COOKIE + 1;
- //Cookie for flows in ingress switches that rewrite the MAC address
- private final long MAC_RW_COOKIE = APP_COOKIE + 2;
- //Cookie for flows that setup BGP paths
- private final long BGP_COOKIE = APP_COOKIE + 3;
- //Forwarding uses priority 0, and the mac rewrite entries in ingress switches
- //need to be higher priority than this otherwise the rewrite may not get done
- private final short SDNIP_PRIORITY = 10;
- private final short ARP_PRIORITY = 20;
+ //We need to identify our flows somehow. But like it says in LearningSwitch.java,
+ //the controller/OS should hand out cookie IDs to prevent conflicts.
+ private final long APP_COOKIE = 0xa0000000000000L;
+ //Cookie for flows that do L2 forwarding within SDN domain to egress routers
+ private final long L2_FWD_COOKIE = APP_COOKIE + 1;
+ //Cookie for flows in ingress switches that rewrite the MAC address
+ private final long MAC_RW_COOKIE = APP_COOKIE + 2;
+ //Cookie for flows that setup BGP paths
+ private final long BGP_COOKIE = APP_COOKIE + 3;
+ //Forwarding uses priority 0, and the mac rewrite entries in ingress switches
+ //need to be higher priority than this otherwise the rewrite may not get done
+ private final short SDNIP_PRIORITY = 10;
+ private final short ARP_PRIORITY = 20;
- private final short BGP_PORT = 179;
+ private final short BGP_PORT = 179;
- private final int TOPO_DETECTION_WAIT = 2; //seconds
+ private final int TOPO_DETECTION_WAIT = 2; //seconds
- //Configuration stuff
- private List<String> switches;
- private Map<String, Interface> interfaces;
- private Map<InetAddress, BgpPeer> bgpPeers;
- private SwitchPort bgpdAttachmentPoint;
- private MACAddress bgpdMacAddress;
- private short vlan;
+ //Configuration stuff
+ private List<String> switches;
+ private Map<String, Interface> interfaces;
+ private Map<InetAddress, BgpPeer> bgpPeers;
+ private SwitchPort bgpdAttachmentPoint;
+ private MACAddress bgpdMacAddress;
+ private short vlan;
- //True when all switches have connected
- private volatile boolean switchesConnected = false;
- //True when we have a full mesh of shortest paths between gateways
- private volatile boolean topologyReady = false;
+ //True when all switches have connected
+ private volatile boolean switchesConnected = false;
+ //True when we have a full mesh of shortest paths between gateways
+ private volatile boolean topologyReady = false;
- private ArrayList<LDUpdate> linkUpdates;
- private SingletonTask topologyChangeDetectorTask;
+ private ArrayList<LDUpdate> linkUpdates;
+ private SingletonTask topologyChangeDetectorTask;
- private SetMultimap<InetAddress, RibUpdate> prefixesWaitingOnArp;
+ private SetMultimap<InetAddress, RibUpdate> prefixesWaitingOnArp;
- private Map<InetAddress, Path> pathsWaitingOnArp;
+ private Map<InetAddress, Path> pathsWaitingOnArp;
- private ExecutorService bgpUpdatesExecutor;
+ private ExecutorService bgpUpdatesExecutor;
- private Map<InetAddress, Path> pushedPaths;
- private Map<Prefix, Path> prefixToPath;
-// private Multimap<Prefix, PushedFlowMod> pushedFlows;
- private Multimap<Prefix, FlowId> pushedFlowIds;
+ private Map<InetAddress, Path> pushedPaths;
+ private Map<Prefix, Path> prefixToPath;
+ // private Multimap<Prefix, PushedFlowMod> pushedFlows;
+ private Multimap<Prefix, FlowId> pushedFlowIds;
- private FlowCache flowCache;
+ private FlowCache flowCache;
- // TODO: Fix for the new Topology Network Graph
- // private volatile Topology topology = null;
+ // TODO: Fix for the new Topology Network Graph
+ // private volatile Topology topology = null;
- private class TopologyChangeDetector implements Runnable {
- @Override
- public void run() {
- log.debug("Running topology change detection task");
- synchronized (linkUpdates) {
- //This is the model the REST API uses to retrieve network graph info
- // TODO: Fix the code below after topoLinkService was removed
- /*
- ITopoLinkService topoLinkService = new TopoLinkServiceImpl();
+ private class TopologyChangeDetector implements Runnable {
+ @Override
+ public void run() {
+ log.debug("Running topology change detection task");
+ synchronized (linkUpdates) {
+ //This is the model the REST API uses to retrieve network graph info
+ // TODO: Fix the code below after topoLinkService was removed
+ /*
+ ITopoLinkService topoLinkService = new TopoLinkServiceImpl();
- List<Link> activeLinks = topoLinkService.getActiveLinks();
+ List<Link> activeLinks = topoLinkService.getActiveLinks();
- Iterator<LDUpdate> it = linkUpdates.iterator();
- while (it.hasNext()){
- LDUpdate ldu = it.next();
- Link l = new Link(ldu.getSrc(), ldu.getSrcPort(),
- ldu.getDst(), ldu.getDstPort());
+ Iterator<LDUpdate> it = linkUpdates.iterator();
+ while (it.hasNext()){
+ LDUpdate ldu = it.next();
+ Link l = new Link(ldu.getSrc(), ldu.getSrcPort(),
+ ldu.getDst(), ldu.getDstPort());
- if (activeLinks.contains(l)){
- it.remove();
- }
- }
- */
- }
+ if (activeLinks.contains(l)){
+ it.remove();
+ }
+ }
+ */
+ }
- if (!topologyReady) {
- if (linkUpdates.isEmpty()){
- //All updates have been seen in network map.
- //We can check if topology is ready
- log.debug("No known changes outstanding. Checking topology now");
- checkStatus();
- }
- else {
- //We know of some link updates that haven't propagated to the database yet
- log.debug("Some changes not found in network map - {} links missing", linkUpdates.size());
- topologyChangeDetectorTask.reschedule(TOPO_DETECTION_WAIT, TimeUnit.SECONDS);
- }
- }
- }
- }
+ if (!topologyReady) {
+ if (linkUpdates.isEmpty()) {
+ //All updates have been seen in network map.
+ //We can check if topology is ready
+ log.debug("No known changes outstanding. Checking topology now");
+ checkStatus();
+ } else {
+ //We know of some link updates that haven't propagated to the database yet
+ log.debug("Some changes not found in network map - {} links missing", linkUpdates.size());
+ topologyChangeDetectorTask.reschedule(TOPO_DETECTION_WAIT, TimeUnit.SECONDS);
+ }
+ }
+ }
+ }
- private void readConfiguration(String configFilename){
- File gatewaysFile = new File(configFilename);
- ObjectMapper mapper = new ObjectMapper();
+ private void readConfiguration(String configFilename) {
+ File gatewaysFile = new File(configFilename);
+ ObjectMapper mapper = new ObjectMapper();
- try {
- Configuration config = mapper.readValue(gatewaysFile, Configuration.class);
+ try {
+ Configuration config = mapper.readValue(gatewaysFile, Configuration.class);
- switches = config.getSwitches();
- interfaces = new HashMap<String, Interface>();
- for (Interface intf : config.getInterfaces()){
- interfaces.put(intf.getName(), intf);
- }
- bgpPeers = new HashMap<InetAddress, BgpPeer>();
- for (BgpPeer peer : config.getPeers()){
- bgpPeers.put(peer.getIpAddress(), peer);
- }
+ switches = config.getSwitches();
+ interfaces = new HashMap<String, Interface>();
+ for (Interface intf : config.getInterfaces()) {
+ interfaces.put(intf.getName(), intf);
+ }
+ bgpPeers = new HashMap<InetAddress, BgpPeer>();
+ for (BgpPeer peer : config.getPeers()) {
+ bgpPeers.put(peer.getIpAddress(), peer);
+ }
- bgpdAttachmentPoint = new SwitchPort(
- new Dpid(config.getBgpdAttachmentDpid()),
- new Port(config.getBgpdAttachmentPort()));
+ bgpdAttachmentPoint = new SwitchPort(
+ new Dpid(config.getBgpdAttachmentDpid()),
+ new Port(config.getBgpdAttachmentPort()));
- bgpdMacAddress = config.getBgpdMacAddress();
- vlan = config.getVlan();
- } catch (JsonParseException e) {
- log.error("Error in JSON file", e);
- System.exit(1);
- } catch (JsonMappingException e) {
- log.error("Error in JSON file", e);
- System.exit(1);
- } catch (IOException e) {
- log.error("Error reading JSON file", e);
- System.exit(1);
- }
+ bgpdMacAddress = config.getBgpdMacAddress();
+ vlan = config.getVlan();
+ } catch (JsonParseException e) {
+ log.error("Error in JSON file", e);
+ System.exit(1);
+ } catch (JsonMappingException e) {
+ log.error("Error in JSON file", e);
+ System.exit(1);
+ } catch (IOException e) {
+ log.error("Error reading JSON file", e);
+ System.exit(1);
+ }
- //Populate the interface Patricia Trie
- for (Interface intf : interfaces.values()) {
- Prefix prefix = new Prefix(intf.getIpAddress().getAddress(), intf.getPrefixLength());
- interfacePtrie.put(prefix, intf);
- }
- }
+ //Populate the interface Patricia Trie
+ for (Interface intf : interfaces.values()) {
+ Prefix prefix = new Prefix(intf.getIpAddress().getAddress(), intf.getPrefixLength());
+ interfacePtrie.put(prefix, intf);
+ }
+ }
- @Override
- public Collection<Class<? extends IFloodlightService>> getModuleServices() {
- Collection<Class<? extends IFloodlightService>> l
- = new ArrayList<Class<? extends IFloodlightService>>();
- l.add(IBgpRouteService.class);
- l.add(IConfigInfoService.class);
- return l;
- }
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleServices() {
+ Collection<Class<? extends IFloodlightService>> l
+ = new ArrayList<Class<? extends IFloodlightService>>();
+ l.add(IBgpRouteService.class);
+ l.add(IConfigInfoService.class);
+ return l;
+ }
- @Override
- public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
- Map<Class<? extends IFloodlightService>, IFloodlightService> m
- = new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
- m.put(IBgpRouteService.class, this);
- m.put(IConfigInfoService.class, this);
- return m;
- }
+ @Override
+ public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
+ Map<Class<? extends IFloodlightService>, IFloodlightService> m
+ = new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
+ m.put(IBgpRouteService.class, this);
+ m.put(IConfigInfoService.class, this);
+ return m;
+ }
- @Override
- public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
- Collection<Class<? extends IFloodlightService>> l
- = new ArrayList<Class<? extends IFloodlightService>>();
- l.add(IFloodlightProviderService.class);
- l.add(IRestApiService.class);
- return l;
- }
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
+ Collection<Class<? extends IFloodlightService>> l
+ = new ArrayList<Class<? extends IFloodlightService>>();
+ l.add(IFloodlightProviderService.class);
+ l.add(IRestApiService.class);
+ return l;
+ }
- @Override
- public void init(FloodlightModuleContext context)
- throws FloodlightModuleException {
+ @Override
+ public void init(FloodlightModuleContext context)
+ throws FloodlightModuleException {
- ptree = new PatriciaTrie<RibEntry>(32);
- interfacePtrie = new PatriciaTrie<Interface>(32);
+ ptree = new PatriciaTrie<RibEntry>(32);
+ interfacePtrie = new PatriciaTrie<Interface>(32);
- ribUpdates = new LinkedBlockingQueue<RibUpdate>();
+ ribUpdates = new LinkedBlockingQueue<RibUpdate>();
- // Register floodlight provider and REST handler.
- floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
- linkDiscoveryService = context.getServiceImpl(ILinkDiscoveryService.class);
- restApi = context.getServiceImpl(IRestApiService.class);
- proxyArp = context.getServiceImpl(IProxyArpService.class);
+ // Register floodlight provider and REST handler.
+ floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
+ linkDiscoveryService = context.getServiceImpl(ILinkDiscoveryService.class);
+ restApi = context.getServiceImpl(IRestApiService.class);
+ proxyArp = context.getServiceImpl(IProxyArpService.class);
- linkUpdates = new ArrayList<LDUpdate>();
- ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
- topologyChangeDetectorTask = new SingletonTask(executor, new TopologyChangeDetector());
+ linkUpdates = new ArrayList<LDUpdate>();
+ ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
+ topologyChangeDetectorTask = new SingletonTask(executor, new TopologyChangeDetector());
- pathsWaitingOnArp = new HashMap<InetAddress, Path>();
- prefixesWaitingOnArp = Multimaps.synchronizedSetMultimap(
- HashMultimap.<InetAddress, RibUpdate>create());
+ pathsWaitingOnArp = new HashMap<InetAddress, Path>();
+ prefixesWaitingOnArp = Multimaps.synchronizedSetMultimap(
+ HashMultimap.<InetAddress, RibUpdate>create());
- pushedPaths = new HashMap<InetAddress, Path>();
- prefixToPath = new HashMap<Prefix, Path>();
-// pushedFlows = HashMultimap.<Prefix, PushedFlowMod>create();
- pushedFlowIds = HashMultimap.<Prefix, FlowId>create();
+ pushedPaths = new HashMap<InetAddress, Path>();
+ prefixToPath = new HashMap<Prefix, Path>();
+// pushedFlows = HashMultimap.<Prefix, PushedFlowMod>create();
+ pushedFlowIds = HashMultimap.<Prefix, FlowId>create();
- flowCache = new FlowCache(floodlightProvider);
+ flowCache = new FlowCache(floodlightProvider);
- bgpUpdatesExecutor = Executors.newSingleThreadExecutor(
- new ThreadFactoryBuilder().setNameFormat("bgp-updates-%d").build());
+ bgpUpdatesExecutor = Executors.newSingleThreadExecutor(
+ new ThreadFactoryBuilder().setNameFormat("bgp-updates-%d").build());
- //Read in config values
- bgpdRestIp = context.getConfigParams(this).get("BgpdRestIp");
- if (bgpdRestIp == null){
- log.error("BgpdRestIp property not found in config file");
- System.exit(1);
- }
- else {
- log.info("BgpdRestIp set to {}", bgpdRestIp);
- }
+ //Read in config values
+ bgpdRestIp = context.getConfigParams(this).get("BgpdRestIp");
+ if (bgpdRestIp == null) {
+ log.error("BgpdRestIp property not found in config file");
+ System.exit(1);
+ } else {
+ log.info("BgpdRestIp set to {}", bgpdRestIp);
+ }
- routerId = context.getConfigParams(this).get("RouterId");
- if (routerId == null){
- log.error("RouterId property not found in config file");
- System.exit(1);
- }
- else {
- log.info("RouterId set to {}", routerId);
- }
+ routerId = context.getConfigParams(this).get("RouterId");
+ if (routerId == null) {
+ log.error("RouterId property not found in config file");
+ System.exit(1);
+ } else {
+ log.info("RouterId set to {}", routerId);
+ }
- String configFilenameParameter = context.getConfigParams(this).get("configfile");
- if (configFilenameParameter != null){
- configFilename = configFilenameParameter;
- }
- log.debug("Config file set to {}", configFilename);
+ String configFilenameParameter = context.getConfigParams(this).get("configfile");
+ if (configFilenameParameter != null) {
+ configFilename = configFilenameParameter;
+ }
+ log.debug("Config file set to {}", configFilename);
- readConfiguration(configFilename);
- }
+ readConfiguration(configFilename);
+ }
- @Override
- public void startUp(FloodlightModuleContext context) {
- restApi.addRestletRoutable(new BgpRouteWebRoutable());
- floodlightProvider.addOFSwitchListener(this);
+ @Override
+ public void startUp(FloodlightModuleContext context) {
+ restApi.addRestletRoutable(new BgpRouteWebRoutable());
+ floodlightProvider.addOFSwitchListener(this);
- //Retrieve the RIB from BGPd during startup
- retrieveRib();
- }
+ //Retrieve the RIB from BGPd during startup
+ retrieveRib();
+ }
- @Override
- public IPatriciaTrie<RibEntry> getPtree() {
- return ptree;
- }
+ @Override
+ public IPatriciaTrie<RibEntry> getPtree() {
+ return ptree;
+ }
- @Override
- public void clearPtree() {
- ptree = new PatriciaTrie<RibEntry>(32);
- }
+ @Override
+ public void clearPtree() {
+ ptree = new PatriciaTrie<RibEntry>(32);
+ }
- @Override
- public String getBGPdRestIp() {
- return bgpdRestIp;
- }
+ @Override
+ public String getBGPdRestIp() {
+ return bgpdRestIp;
+ }
- @Override
- public String getRouterId() {
- return routerId;
- }
+ @Override
+ public String getRouterId() {
+ return routerId;
+ }
- private void retrieveRib(){
- String url = "http://" + bgpdRestIp + "/wm/bgp/" + routerId;
- String response = RestClient.get(url);
+ private void retrieveRib() {
+ String url = "http://" + bgpdRestIp + "/wm/bgp/" + routerId;
+ String response = RestClient.get(url);
- if (response.equals("")){
- return;
- }
+ if (response.equals("")) {
+ return;
+ }
- response = response.replaceAll("\"", "'");
- JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(response);
- JSONArray rib_json_array = jsonObj.getJSONArray("rib");
- String router_id = jsonObj.getString("router-id");
+ response = response.replaceAll("\"", "'");
+ JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(response);
+ JSONArray rib_json_array = jsonObj.getJSONArray("rib");
+ String router_id = jsonObj.getString("router-id");
- int size = rib_json_array.size();
+ int size = rib_json_array.size();
- log.info("Retrived RIB of {} entries from BGPd", size);
+ log.info("Retrived RIB of {} entries from BGPd", size);
- for (int j = 0; j < size; j++) {
- JSONObject second_json_object = rib_json_array.getJSONObject(j);
- String prefix = second_json_object.getString("prefix");
- String nexthop = second_json_object.getString("nexthop");
+ for (int j = 0; j < size; j++) {
+ JSONObject second_json_object = rib_json_array.getJSONObject(j);
+ String prefix = second_json_object.getString("prefix");
+ String nexthop = second_json_object.getString("nexthop");
- //insert each rib entry into the local rib;
- String[] substring = prefix.split("/");
- String prefix1 = substring[0];
- String mask1 = substring[1];
+ //insert each rib entry into the local rib;
+ String[] substring = prefix.split("/");
+ String prefix1 = substring[0];
+ String mask1 = substring[1];
- Prefix p;
- try {
- p = new Prefix(prefix1, Integer.valueOf(mask1));
- } catch (NumberFormatException e) {
- log.warn("Wrong mask format in RIB JSON: {}", mask1);
- continue;
- } catch (IllegalArgumentException e1) {
- log.warn("Wrong prefix format in RIB JSON: {}", prefix1);
- continue;
- }
+ Prefix p;
+ try {
+ p = new Prefix(prefix1, Integer.valueOf(mask1));
+ } catch (NumberFormatException e) {
+ log.warn("Wrong mask format in RIB JSON: {}", mask1);
+ continue;
+ } catch (IllegalArgumentException e1) {
+ log.warn("Wrong prefix format in RIB JSON: {}", prefix1);
+ continue;
+ }
- RibEntry rib = new RibEntry(router_id, nexthop);
+ RibEntry rib = new RibEntry(router_id, nexthop);
- try {
- ribUpdates.put(new RibUpdate(Operation.UPDATE, p, rib));
- } catch (InterruptedException e) {
- log.debug("Interrupted while pushing onto update queue");
- }
- }
- }
+ try {
+ ribUpdates.put(new RibUpdate(Operation.UPDATE, p, rib));
+ } catch (InterruptedException e) {
+ log.debug("Interrupted while pushing onto update queue");
+ }
+ }
+ }
- @Override
- public void newRibUpdate(RibUpdate update) {
- try {
- ribUpdates.put(update);
- } catch (InterruptedException e) {
- log.debug("Interrupted while putting on ribUpdates queue", e);
- Thread.currentThread().interrupt();
- }
- }
+ @Override
+ public void newRibUpdate(RibUpdate update) {
+ try {
+ ribUpdates.put(update);
+ } catch (InterruptedException e) {
+ log.debug("Interrupted while putting on ribUpdates queue", e);
+ Thread.currentThread().interrupt();
+ }
+ }
- public synchronized void processRibAdd(RibUpdate update) {
- Prefix prefix = update.getPrefix();
+ public synchronized void processRibAdd(RibUpdate update) {
+ Prefix prefix = update.getPrefix();
- log.debug("Processing prefix add {}", prefix);
+ log.debug("Processing prefix add {}", prefix);
- RibEntry rib = ptree.put(prefix, update.getRibEntry());
+ RibEntry rib = ptree.put(prefix, update.getRibEntry());
- if (rib != null && !rib.equals(update.getRibEntry())) {
- //There was an existing nexthop for this prefix. This update supersedes that,
- //so we need to remove the old flows for this prefix from the switches
- _processDeletePrefix(prefix, rib);
- }
+ if (rib != null && !rib.equals(update.getRibEntry())) {
+ //There was an existing nexthop for this prefix. This update supersedes that,
+ //so we need to remove the old flows for this prefix from the switches
+ _processDeletePrefix(prefix, rib);
+ }
- if (update.getRibEntry().getNextHop().equals(
- InetAddresses.forString("0.0.0.0"))) {
- //Route originated by SDN domain
- //We don't handle these at the moment
- log.debug("Own route {} to {}", prefix,
- update.getRibEntry().getNextHop().getHostAddress());
- return;
- }
+ if (update.getRibEntry().getNextHop().equals(
+ InetAddresses.forString("0.0.0.0"))) {
+ //Route originated by SDN domain
+ //We don't handle these at the moment
+ log.debug("Own route {} to {}", prefix,
+ update.getRibEntry().getNextHop().getHostAddress());
+ return;
+ }
- _processRibAdd(update);
- }
+ _processRibAdd(update);
+ }
- private void _processRibAdd(RibUpdate update) {
- Prefix prefix = update.getPrefix();
- RibEntry rib = update.getRibEntry();
+ private void _processRibAdd(RibUpdate update) {
+ Prefix prefix = update.getPrefix();
+ RibEntry rib = update.getRibEntry();
- InetAddress dstIpAddress = rib.getNextHop();
- MACAddress nextHopMacAddress = null;
+ InetAddress dstIpAddress = rib.getNextHop();
+ MACAddress nextHopMacAddress = null;
- // See if we know the MAC address of the next hop
- // TODO if we do not treat the next hop as a device in the future, we need to update this
- // TODO: Fix the code below after deviceStorage was removed
- /*
- IDeviceObject nextHopDevice =
- deviceStorage.getDeviceByIP(InetAddresses.coerceToInteger(dstIpAddress));
+ // See if we know the MAC address of the next hop
+ // TODO if we do not treat the next hop as a device in the future, we need to update this
+ // TODO: Fix the code below after deviceStorage was removed
+ /*
+ IDeviceObject nextHopDevice =
+ deviceStorage.getDeviceByIP(InetAddresses.coerceToInteger(dstIpAddress));
- if (nextHopDevice == null){
- log.debug("NextHopDevice for IP: {} is null", dstIpAddress);
- prefixesWaitingOnArp.put(dstIpAddress,
- new RibUpdate(Operation.UPDATE, prefix, rib));
- proxyArp.sendArpRequest(dstIpAddress, this, true);
- return;
+ if (nextHopDevice == null){
+ log.debug("NextHopDevice for IP: {} is null", dstIpAddress);
+ prefixesWaitingOnArp.put(dstIpAddress,
+ new RibUpdate(Operation.UPDATE, prefix, rib));
+ proxyArp.sendArpRequest(dstIpAddress, this, true);
+ return;
- }
- nextHopMacAddress = MACAddress.valueOf(nextHopDevice.getMACAddress());
- */
+ }
+ nextHopMacAddress = MACAddress.valueOf(nextHopDevice.getMACAddress());
+ */
- // Find the attachment point (egress interface) of the next hop
- Interface egressInterface = null;
- if (bgpPeers.containsKey(dstIpAddress)) {
- //Route to a peer
- log.debug("Route to peer {}", dstIpAddress);
- BgpPeer peer = bgpPeers.get(dstIpAddress);
- egressInterface = interfaces.get(peer.getInterfaceName());
- }
- else {
- //Route to non-peer
- log.debug("Route to non-peer {}", dstIpAddress);
- egressInterface = interfacePtrie.match(
- new Prefix(dstIpAddress.getAddress(), 32));
- if (egressInterface == null) {
- log.warn("No outgoing interface found for {}", dstIpAddress.getHostAddress());
- return;
- }
- }
+ // Find the attachment point (egress interface) of the next hop
+ Interface egressInterface = null;
+ if (bgpPeers.containsKey(dstIpAddress)) {
+ //Route to a peer
+ log.debug("Route to peer {}", dstIpAddress);
+ BgpPeer peer = bgpPeers.get(dstIpAddress);
+ egressInterface = interfaces.get(peer.getInterfaceName());
+ } else {
+ //Route to non-peer
+ log.debug("Route to non-peer {}", dstIpAddress);
+ egressInterface = interfacePtrie.match(
+ new Prefix(dstIpAddress.getAddress(), 32));
+ if (egressInterface == null) {
+ log.warn("No outgoing interface found for {}", dstIpAddress.getHostAddress());
+ return;
+ }
+ }
- if (nextHopMacAddress == null) {
- prefixesWaitingOnArp.put(dstIpAddress,
- new RibUpdate(Operation.UPDATE, prefix, rib));
- proxyArp.sendArpRequest(dstIpAddress, this, true);
- return;
- }
- else {
- if (!bgpPeers.containsKey(dstIpAddress)) {
- //If the prefix is for a non-peer we need to ensure there's a path,
- //and push one if there isn't.
- Path path = pushedPaths.get(dstIpAddress);
- if (path == null) {
- path = new Path(egressInterface, dstIpAddress);
- calculateAndPushPath(path, nextHopMacAddress);
- pushedPaths.put(dstIpAddress, path);
- }
+ if (nextHopMacAddress == null) {
+ prefixesWaitingOnArp.put(dstIpAddress,
+ new RibUpdate(Operation.UPDATE, prefix, rib));
+ proxyArp.sendArpRequest(dstIpAddress, this, true);
+ return;
+ } else {
+ if (!bgpPeers.containsKey(dstIpAddress)) {
+ //If the prefix is for a non-peer we need to ensure there's a path,
+ //and push one if there isn't.
+ Path path = pushedPaths.get(dstIpAddress);
+ if (path == null) {
+ path = new Path(egressInterface, dstIpAddress);
+ calculateAndPushPath(path, nextHopMacAddress);
+ pushedPaths.put(dstIpAddress, path);
+ }
- path.incrementUsers();
- prefixToPath.put(prefix, path);
- }
+ path.incrementUsers();
+ prefixToPath.put(prefix, path);
+ }
- //For all prefixes we need to add the first-hop mac-rewriting flows
- addPrefixFlows(prefix, egressInterface, nextHopMacAddress);
- }
- }
+ //For all prefixes we need to add the first-hop mac-rewriting flows
+ addPrefixFlows(prefix, egressInterface, nextHopMacAddress);
+ }
+ }
- /**
- * Add a flow to match dst-IP prefix and rewrite MAC for one IP prefix
- * to all other border switches
- */
- private void addPrefixFlows(Prefix prefix, Interface egressInterface,
- MACAddress nextHopMacAddress) {
- log.debug("Adding flows for prefix {}, next hop mac {}",
- prefix, nextHopMacAddress);
+ /**
+ * Add a flow to match dst-IP prefix and rewrite MAC for one IP prefix
+ * to all other border switches
+ */
+ private void addPrefixFlows(Prefix prefix, Interface egressInterface,
+ MACAddress nextHopMacAddress) {
+ log.debug("Adding flows for prefix {}, next hop mac {}",
+ prefix, nextHopMacAddress);
- FlowPath flowPath = new FlowPath();
- flowPath.setInstallerId(new CallerId("SDNIP"));
+ FlowPath flowPath = new FlowPath();
+ flowPath.setInstallerId(new CallerId("SDNIP"));
- // Set flowPath FlowPathType and FlowPathUserState
- flowPath.setFlowPathType(FlowPathType.FP_TYPE_SHORTEST_PATH);
- flowPath.setFlowPathUserState(FlowPathUserState.FP_USER_ADD);
+ // Set flowPath FlowPathType and FlowPathUserState
+ flowPath.setFlowPathType(FlowPathType.FP_TYPE_SHORTEST_PATH);
+ flowPath.setFlowPathUserState(FlowPathUserState.FP_USER_ADD);
- // Insert dst-ip prefix based forwarding and MAC rewrite flow entry
- // only to the first-host switches
- FlowPathFlags flowPathFlags = new FlowPathFlags();
- flowPathFlags.setFlags(FlowPathFlags.KEEP_ONLY_FIRST_HOP_ENTRY);
- flowPath.setFlowPathFlags(flowPathFlags);
+ // Insert dst-ip prefix based forwarding and MAC rewrite flow entry
+ // only to the first-host switches
+ FlowPathFlags flowPathFlags = new FlowPathFlags();
+ flowPathFlags.setFlags(FlowPathFlags.KEEP_ONLY_FIRST_HOP_ENTRY);
+ flowPath.setFlowPathFlags(flowPathFlags);
- // Create the DataPath object: dstSwitchPort
- SwitchPort dstPort = new SwitchPort();
- dstPort.setDpid(new Dpid(egressInterface.getDpid()));
- dstPort.setPort(new Port(egressInterface.getPort()));
+ // Create the DataPath object: dstSwitchPort
+ SwitchPort dstPort = new SwitchPort();
+ dstPort.setDpid(new Dpid(egressInterface.getDpid()));
+ dstPort.setPort(new Port(egressInterface.getPort()));
- // We only need one flow mod per switch, so pick one interface on each switch
- Map<Long, Interface> srcInterfaces = new HashMap<Long, Interface>();
- for (Interface intf : interfaces.values()) {
- if (!srcInterfaces.containsKey(intf.getDpid())
- && !intf.equals(egressInterface)) {
- srcInterfaces.put(intf.getDpid(), intf);
- }
- }
- for (Interface srcInterface : srcInterfaces.values()) {
+ // We only need one flow mod per switch, so pick one interface on each switch
+ Map<Long, Interface> srcInterfaces = new HashMap<Long, Interface>();
+ for (Interface intf : interfaces.values()) {
+ if (!srcInterfaces.containsKey(intf.getDpid())
+ && !intf.equals(egressInterface)) {
+ srcInterfaces.put(intf.getDpid(), intf);
+ }
+ }
+ for (Interface srcInterface : srcInterfaces.values()) {
- if (egressInterface.equals(srcInterface)){
- continue;
- }
+ if (egressInterface.equals(srcInterface)) {
+ continue;
+ }
- // Create flowPath FlowId
- flowPath.setFlowId(new FlowId());
+ // Create flowPath FlowId
+ flowPath.setFlowId(new FlowId());
- // Create DataPath object: srcSwitchPort
- SwitchPort srcPort = new SwitchPort();
- srcPort.setDpid(new Dpid(srcInterface.getDpid()));
- srcPort.setPort(new Port(srcInterface.getPort()));
+ // Create DataPath object: srcSwitchPort
+ SwitchPort srcPort = new SwitchPort();
+ srcPort.setDpid(new Dpid(srcInterface.getDpid()));
+ srcPort.setPort(new Port(srcInterface.getPort()));
- DataPath dataPath = new DataPath();
- dataPath.setSrcPort(srcPort);
- dataPath.setDstPort(dstPort);
- flowPath.setDataPath(dataPath);
+ DataPath dataPath = new DataPath();
+ dataPath.setSrcPort(srcPort);
+ dataPath.setDstPort(dstPort);
+ flowPath.setDataPath(dataPath);
- // Create flow path matching condition(s): IPv4 Prefix
- FlowEntryMatch flowEntryMatch = new FlowEntryMatch();
- flowEntryMatch.enableEthernetFrameType(Ethernet.TYPE_IPv4);
- IPv4Net dstIPv4Net= new IPv4Net(prefix.toString());
- flowEntryMatch.enableDstIPv4Net(dstIPv4Net);
- flowPath.setFlowEntryMatch(flowEntryMatch);
+ // Create flow path matching condition(s): IPv4 Prefix
+ FlowEntryMatch flowEntryMatch = new FlowEntryMatch();
+ flowEntryMatch.enableEthernetFrameType(Ethernet.TYPE_IPv4);
+ IPv4Net dstIPv4Net = new IPv4Net(prefix.toString());
+ flowEntryMatch.enableDstIPv4Net(dstIPv4Net);
+ flowPath.setFlowEntryMatch(flowEntryMatch);
- /*
- * Create the Flow Entry Action(s): dst-MAC rewrite action
- */
- FlowEntryActions flowEntryActions = new FlowEntryActions();
- FlowEntryAction flowEntryAction1 = new FlowEntryAction();
- flowEntryAction1.setActionSetEthernetDstAddr(nextHopMacAddress);
- // flowEntryAction1.actionSetEthernetDstAddr(nextHopMacAddress);
- flowEntryActions.addAction(flowEntryAction1);
- flowPath.setFlowEntryActions(flowEntryActions);
+ /*
+ * Create the Flow Entry Action(s): dst-MAC rewrite action
+ */
+ FlowEntryActions flowEntryActions = new FlowEntryActions();
+ FlowEntryAction flowEntryAction1 = new FlowEntryAction();
+ flowEntryAction1.setActionSetEthernetDstAddr(nextHopMacAddress);
+ // flowEntryAction1.actionSetEthernetDstAddr(nextHopMacAddress);
+ flowEntryActions.addAction(flowEntryAction1);
+ flowPath.setFlowEntryActions(flowEntryActions);
- // Flow Path installation, only to first hop switches
- // TODO: Add the flow by using the new Path Intent framework
- /*
- if (flowManagerService.addFlow(flowPath) == null) {
- log.error("Failed to install flow path to the first hop for " +
- "prefix: {}, nextHopMacAddress: {}", prefix.getAddress(),
- nextHopMacAddress);
- }
- else {
- log.debug("Successfully installed flow path to the first hop " +
- "for prefix: {}, nextHopMacAddress: {}", prefix.getAddress(),
- nextHopMacAddress);
+ // Flow Path installation, only to first hop switches
+ // TODO: Add the flow by using the new Path Intent framework
+ /*
+ if (flowManagerService.addFlow(flowPath) == null) {
+ log.error("Failed to install flow path to the first hop for " +
+ "prefix: {}, nextHopMacAddress: {}", prefix.getAddress(),
+ nextHopMacAddress);
+ }
+ else {
+ log.debug("Successfully installed flow path to the first hop " +
+ "for prefix: {}, nextHopMacAddress: {}", prefix.getAddress(),
+ nextHopMacAddress);
- pushedFlowIds.put(prefix, flowPath.flowId());
- }
- */
- }
- }
+ pushedFlowIds.put(prefix, flowPath.flowId());
+ }
+ */
+ }
+ }
- public synchronized void processRibDelete(RibUpdate update) {
- Prefix prefix = update.getPrefix();
+ public synchronized void processRibDelete(RibUpdate update) {
+ Prefix prefix = update.getPrefix();
- if (ptree.remove(prefix, update.getRibEntry())) {
- /*
- * Only delete flows if an entry was actually removed from the trie.
- * If no entry was removed, the <prefix, nexthop> wasn't there so
- * it's probably already been removed and we don't need to do anything
- */
- _processDeletePrefix(prefix, update.getRibEntry());
- }
- }
+ if (ptree.remove(prefix, update.getRibEntry())) {
+ /*
+ * Only delete flows if an entry was actually removed from the trie.
+ * If no entry was removed, the <prefix, nexthop> wasn't there so
+ * it's probably already been removed and we don't need to do anything
+ */
+ _processDeletePrefix(prefix, update.getRibEntry());
+ }
+ }
- private void _processDeletePrefix(Prefix prefix, RibEntry ribEntry) {
- deletePrefixFlows(prefix);
+ private void _processDeletePrefix(Prefix prefix, RibEntry ribEntry) {
+ deletePrefixFlows(prefix);
- log.debug("Deleting {} to {}", prefix, ribEntry.getNextHop());
+ log.debug("Deleting {} to {}", prefix, ribEntry.getNextHop());
- if (!bgpPeers.containsKey(ribEntry.getNextHop())) {
- log.debug("Getting path for route with non-peer nexthop");
- Path path = prefixToPath.remove(prefix);
+ if (!bgpPeers.containsKey(ribEntry.getNextHop())) {
+ log.debug("Getting path for route with non-peer nexthop");
+ Path path = prefixToPath.remove(prefix);
- if (path != null) {
- //path could be null if we added to the Ptree but didn't push
- //flows yet because we were waiting to resolve ARP
+ if (path != null) {
+ //path could be null if we added to the Ptree but didn't push
+ //flows yet because we were waiting to resolve ARP
- path.decrementUsers();
- if (path.getUsers() <= 0 && !path.isPermanent()) {
- deletePath(path);
- pushedPaths.remove(path.getDstIpAddress());
- }
- }
- }
- }
+ path.decrementUsers();
+ if (path.getUsers() <= 0 && !path.isPermanent()) {
+ deletePath(path);
+ pushedPaths.remove(path.getDstIpAddress());
+ }
+ }
+ }
+ }
- // TODO have not tested this module
- private void deletePrefixFlows(Prefix prefix) {
- log.debug("Deleting flows for prefix {}", prefix);
+ // TODO have not tested this module
+ private void deletePrefixFlows(Prefix prefix) {
+ log.debug("Deleting flows for prefix {}", prefix);
- Collection<FlowId> flowIds = pushedFlowIds.removeAll(prefix);
- for (FlowId flowId : flowIds) {
- // TODO: Delete the flow by using the new Path Intent framework
- /*
- if (log.isTraceEnabled()) {
- //Trace the flow status by flowPath in the switch before deleting it
- log.trace("Pushing a DELETE flow mod to flowPath : {}",
- flowManagerService.getFlow(flowId).toString());
- }
+ Collection<FlowId> flowIds = pushedFlowIds.removeAll(prefix);
+ for (FlowId flowId : flowIds) {
+ // TODO: Delete the flow by using the new Path Intent framework
+ /*
+ if (log.isTraceEnabled()) {
+ //Trace the flow status by flowPath in the switch before deleting it
+ log.trace("Pushing a DELETE flow mod to flowPath : {}",
+ flowManagerService.getFlow(flowId).toString());
+ }
- if( flowManagerService.deleteFlow(flowId))
- {
- log.debug("Successfully deleted FlowId: {}",flowId);
- }
- else
- {
- log.debug("Failed to delete FlowId: {}",flowId);
- }
- */
- }
- }
+ if( flowManagerService.deleteFlow(flowId))
+ {
+ log.debug("Successfully deleted FlowId: {}",flowId);
+ }
+ else
+ {
+ log.debug("Failed to delete FlowId: {}",flowId);
+ }
+ */
+ }
+ }
- // TODO need to record the path and then delete here
- private void deletePath(Path path) {
- log.debug("Deleting flows for path to {}",
- path.getDstIpAddress().getHostAddress());
+ // TODO need to record the path and then delete here
+ private void deletePath(Path path) {
+ log.debug("Deleting flows for path to {}",
+ path.getDstIpAddress().getHostAddress());
- // TODO need update
- /*for (PushedFlowMod pfm : path.getFlowMods()) {
- if (log.isTraceEnabled()) {
- log.trace("Pushing a DELETE flow mod to {}, dst MAC {}",
- new Object[] {HexString.toHexString(pfm.getDpid()),
- HexString.toHexString(pfm.getFlowMod().getMatch().getDataLayerDestination())
- });
- }
+ // TODO need update
+ /*for (PushedFlowMod pfm : path.getFlowMods()) {
+ if (log.isTraceEnabled()) {
+ log.trace("Pushing a DELETE flow mod to {}, dst MAC {}",
+ new Object[] {HexString.toHexString(pfm.getDpid()),
+ HexString.toHexString(pfm.getFlowMod().getMatch().getDataLayerDestination())
+ });
+ }
- sendDeleteFlowMod(pfm.getFlowMod(), pfm.getDpid());
- }*/
- }
+ sendDeleteFlowMod(pfm.getFlowMod(), pfm.getDpid());
+ }*/
+ }
- //TODO test next-hop changes
- //TODO check delete/add synchronization
+ //TODO test next-hop changes
+ //TODO check delete/add synchronization
- /**
- * On startup, we need to calculate a full mesh of paths between all gateway
- * switches
- */
- private void setupFullMesh(){
- //For each border router, calculate and install a path from every other
- //border switch to said border router. However, don't install the entry
- //in to the first hop switch, as we need to install an entry to rewrite
- //for each prefix received. This will be done later when prefixes have
- //actually been received.
+ /**
+ * On startup, we need to calculate a full mesh of paths between all gateway
+ * switches
+ */
+ private void setupFullMesh() {
+ //For each border router, calculate and install a path from every other
+ //border switch to said border router. However, don't install the entry
+ //in to the first hop switch, as we need to install an entry to rewrite
+ //for each prefix received. This will be done later when prefixes have
+ //actually been received.
- for (BgpPeer peer : bgpPeers.values()) {
- Interface peerInterface = interfaces.get(peer.getInterfaceName());
+ for (BgpPeer peer : bgpPeers.values()) {
+ Interface peerInterface = interfaces.get(peer.getInterfaceName());
- //We know there's not already a Path here pushed, because this is
- //called before all other routing
- Path path = new Path(peerInterface, peer.getIpAddress());
- path.setPermanent();
+ //We know there's not already a Path here pushed, because this is
+ //called before all other routing
+ Path path = new Path(peerInterface, peer.getIpAddress());
+ path.setPermanent();
- //See if we know the MAC address of the peer. If not we can't
- //do anything until we learn it
- // TODO: Fix the code below after deviceStorage was removed
- MACAddress macAddress = null;
- /*
- IDeviceObject nextHopDevice =
- deviceStorage.getDeviceByIP(InetAddresses.coerceToInteger(peer.getIpAddress()));
+ //See if we know the MAC address of the peer. If not we can't
+ //do anything until we learn it
+ // TODO: Fix the code below after deviceStorage was removed
+ MACAddress macAddress = null;
+ /*
+ IDeviceObject nextHopDevice =
+ deviceStorage.getDeviceByIP(InetAddresses.coerceToInteger(peer.getIpAddress()));
- if(nextHopDevice == null){
- log.debug("There is no DeviceObject for {}", peer.getIpAddress().getHostAddress());
- //Put in the pending paths list first
- pathsWaitingOnArp.put(peer.getIpAddress(), path);
- proxyArp.sendArpRequest(peer.getIpAddress(), this, true);
- continue;
- }
+ if(nextHopDevice == null){
+ log.debug("There is no DeviceObject for {}", peer.getIpAddress().getHostAddress());
+ //Put in the pending paths list first
+ pathsWaitingOnArp.put(peer.getIpAddress(), path);
+ proxyArp.sendArpRequest(peer.getIpAddress(), this, true);
+ continue;
+ }
- macAddress = MACAddress.valueOf(nextHopDevice.getMACAddress());
- */
+ macAddress = MACAddress.valueOf(nextHopDevice.getMACAddress());
+ */
- if (macAddress == null) {
- log.debug("Don't know MAC for {}", peer.getIpAddress().getHostAddress());
- //Put in the pending paths list first
- pathsWaitingOnArp.put(peer.getIpAddress(), path);
- proxyArp.sendArpRequest(peer.getIpAddress(), this, true);
- continue;
- }
+ if (macAddress == null) {
+ log.debug("Don't know MAC for {}", peer.getIpAddress().getHostAddress());
+ //Put in the pending paths list first
+ pathsWaitingOnArp.put(peer.getIpAddress(), path);
+ proxyArp.sendArpRequest(peer.getIpAddress(), this, true);
+ continue;
+ }
- //If we know the MAC, lets go ahead and push the paths to this peer
- calculateAndPushPath(path, macAddress);
- }
- }
+ //If we know the MAC, lets go ahead and push the paths to this peer
+ calculateAndPushPath(path, macAddress);
+ }
+ }
- private void calculateAndPushPath(Path path, MACAddress dstMacAddress) {
- Interface dstInterface = path.getDstInterface();
+ private void calculateAndPushPath(Path path, MACAddress dstMacAddress) {
+ Interface dstInterface = path.getDstInterface();
- log.debug("Setting up path to {}, {}", path.getDstIpAddress().getHostAddress(),
- dstMacAddress);
+ log.debug("Setting up path to {}, {}", path.getDstIpAddress().getHostAddress(),
+ dstMacAddress);
- FlowPath flowPath = new FlowPath();
+ FlowPath flowPath = new FlowPath();
- flowPath.setInstallerId(new CallerId("SDNIP"));
+ flowPath.setInstallerId(new CallerId("SDNIP"));
- // Set flowPath FlowPathType and FlowPathUserState
- flowPath.setFlowPathType(FlowPathType.FP_TYPE_SHORTEST_PATH);
- flowPath.setFlowPathUserState(FlowPathUserState.FP_USER_ADD);
+ // Set flowPath FlowPathType and FlowPathUserState
+ flowPath.setFlowPathType(FlowPathType.FP_TYPE_SHORTEST_PATH);
+ flowPath.setFlowPathUserState(FlowPathUserState.FP_USER_ADD);
- // Insert the dest-mac based forwarding flow entry to the non-first-hop switches
- FlowPathFlags flowPathFlags = new FlowPathFlags();
- flowPathFlags.setFlags(FlowPathFlags.DISCARD_FIRST_HOP_ENTRY);
- flowPath.setFlowPathFlags(flowPathFlags);
+ // Insert the dest-mac based forwarding flow entry to the non-first-hop switches
+ FlowPathFlags flowPathFlags = new FlowPathFlags();
+ flowPathFlags.setFlags(FlowPathFlags.DISCARD_FIRST_HOP_ENTRY);
+ flowPath.setFlowPathFlags(flowPathFlags);
+
+ // Create the DataPath object: dstSwitchPort
+ SwitchPort dstPort = new SwitchPort();
+ dstPort.setDpid(new Dpid(dstInterface.getDpid()));
+ dstPort.setPort(new Port(dstInterface.getPort()));
- // Create the DataPath object: dstSwitchPort
- SwitchPort dstPort = new SwitchPort();
- dstPort.setDpid(new Dpid(dstInterface.getDpid()));
- dstPort.setPort(new Port(dstInterface.getPort()));
+ for (Interface srcInterface : interfaces.values()) {
- for (Interface srcInterface : interfaces.values()) {
+ if (dstInterface.equals(srcInterface)) {
+ continue;
+ }
- if (dstInterface.equals(srcInterface)){
- continue;
- }
+ // Create flowPath FlowId
+ flowPath.setFlowId(new FlowId());
- // Create flowPath FlowId
- flowPath.setFlowId(new FlowId());
+ // Create the DataPath object: srcSwitchPort
+ SwitchPort srcPort = new SwitchPort();
+ srcPort.setDpid(new Dpid(srcInterface.getDpid()));
+ srcPort.setPort(new Port(srcInterface.getPort()));
- // Create the DataPath object: srcSwitchPort
- SwitchPort srcPort = new SwitchPort();
- srcPort.setDpid(new Dpid(srcInterface.getDpid()));
- srcPort.setPort(new Port(srcInterface.getPort()));
+ DataPath dataPath = new DataPath();
+ dataPath.setSrcPort(srcPort);
+ dataPath.setDstPort(dstPort);
+ flowPath.setDataPath(dataPath);
- DataPath dataPath = new DataPath();
- dataPath.setSrcPort(srcPort);
- dataPath.setDstPort(dstPort);
- flowPath.setDataPath(dataPath);
+ // Create the Flow Path Match condition(s)
+ FlowEntryMatch flowEntryMatch = new FlowEntryMatch();
+ flowEntryMatch.enableEthernetFrameType(Ethernet.TYPE_IPv4);
+ flowEntryMatch.enableDstMac(dstMacAddress);
+ flowPath.setFlowEntryMatch(flowEntryMatch);
- // Create the Flow Path Match condition(s)
- FlowEntryMatch flowEntryMatch = new FlowEntryMatch();
- flowEntryMatch.enableEthernetFrameType(Ethernet.TYPE_IPv4);
- flowEntryMatch.enableDstMac(dstMacAddress);
- flowPath.setFlowEntryMatch(flowEntryMatch);
+ // NOTE: No need to add ACTION_OUTPUT. It is implied when creating
+ // Shortest Path Flow, and is always the last action for the Flow Entries
+ log.debug("FlowPath of MAC based forwarding: {}", flowPath.toString());
+ // TODO: Add the flow by using the new Path Intent framework
+ /*
+ if (flowManagerService.addFlow(flowPath) == null) {
+ log.error("Failed to set up MAC based forwarding path to {}, {}",
+ path.getDstIpAddress().getHostAddress(),dstMacAddress);
+ }
+ else {
+ log.debug("Successfully set up MAC based forwarding path to {}, {}",
+ path.getDstIpAddress().getHostAddress(),dstMacAddress);
+ }
+ */
+ }
+ }
- // NOTE: No need to add ACTION_OUTPUT. It is implied when creating
- // Shortest Path Flow, and is always the last action for the Flow Entries
- log.debug("FlowPath of MAC based forwarding: {}", flowPath.toString());
- // TODO: Add the flow by using the new Path Intent framework
- /*
- if (flowManagerService.addFlow(flowPath) == null) {
- log.error("Failed to set up MAC based forwarding path to {}, {}",
- path.getDstIpAddress().getHostAddress(),dstMacAddress);
- }
- else {
- log.debug("Successfully set up MAC based forwarding path to {}, {}",
- path.getDstIpAddress().getHostAddress(),dstMacAddress);
- }
- */
- }
- }
+ /**
+ * Pre-actively install all BGP traffic paths from BGP host attachment point
+ * in SDN network to all the virtual gateways to BGP peers in other networks
+ */
+ private void setupBgpPaths() {
- /**
- * Pre-actively install all BGP traffic paths from BGP host attachment point
- * in SDN network to all the virtual gateways to BGP peers in other networks
- */
- private void setupBgpPaths(){
+ for (BgpPeer bgpPeer : bgpPeers.values()) {
- for (BgpPeer bgpPeer : bgpPeers.values()){
+ FlowPath flowPath = new FlowPath();
+ flowPath.setInstallerId(new CallerId("SDNIP"));
- FlowPath flowPath = new FlowPath();
- flowPath.setInstallerId(new CallerId("SDNIP"));
+ // Set flowPath FlowPathType and FlowPathUserState
+ flowPath.setFlowPathType(FlowPathType.FP_TYPE_SHORTEST_PATH);
+ flowPath.setFlowPathUserState(FlowPathUserState.FP_USER_ADD);
- // Set flowPath FlowPathType and FlowPathUserState
- flowPath.setFlowPathType(FlowPathType.FP_TYPE_SHORTEST_PATH);
- flowPath.setFlowPathUserState(FlowPathUserState.FP_USER_ADD);
+ // Install flow paths between BGPd and its peers
+ // There is no need to set the FlowPathFlags
+ flowPath.setFlowPathFlags(new FlowPathFlags(0));
- // Install flow paths between BGPd and its peers
- // There is no need to set the FlowPathFlags
- flowPath.setFlowPathFlags(new FlowPathFlags(0));
+ Interface peerInterface = interfaces.get(bgpPeer.getInterfaceName());
- Interface peerInterface = interfaces.get(bgpPeer.getInterfaceName());
+ // Create the Flow Path Match condition(s)
+ FlowEntryMatch flowEntryMatch = new FlowEntryMatch();
+ flowEntryMatch.enableEthernetFrameType(Ethernet.TYPE_IPv4);
- // Create the Flow Path Match condition(s)
- FlowEntryMatch flowEntryMatch = new FlowEntryMatch();
- flowEntryMatch.enableEthernetFrameType(Ethernet.TYPE_IPv4);
+ // Match both source address and dest address
+ IPv4Net dstIPv4Net = new IPv4Net(bgpPeer.getIpAddress().getHostAddress() + "/32");
+ flowEntryMatch.enableDstIPv4Net(dstIPv4Net);
- // Match both source address and dest address
- IPv4Net dstIPv4Net= new IPv4Net(bgpPeer.getIpAddress().getHostAddress()+"/32");
- flowEntryMatch.enableDstIPv4Net(dstIPv4Net);
+ IPv4Net srcIPv4Net = new IPv4Net(peerInterface.getIpAddress().getHostAddress() + "/32");
+ flowEntryMatch.enableSrcIPv4Net(srcIPv4Net);
- IPv4Net srcIPv4Net= new IPv4Net(peerInterface.getIpAddress().getHostAddress()+"/32");
- flowEntryMatch.enableSrcIPv4Net(srcIPv4Net);
+ // Match TCP protocol
+ flowEntryMatch.enableIpProto(IPv4.PROTOCOL_TCP);
- // Match TCP protocol
- flowEntryMatch.enableIpProto(IPv4.PROTOCOL_TCP);
+ // Match destination TCP port
+ flowEntryMatch.enableDstTcpUdpPort(BGP_PORT);
+ flowPath.setFlowEntryMatch(flowEntryMatch);
- // Match destination TCP port
- flowEntryMatch.enableDstTcpUdpPort(BGP_PORT);
- flowPath.setFlowEntryMatch(flowEntryMatch);
+ /**
+ * Create the DataPath: BGP -> BGP peer
+ */
+ // Flow path for src-TCP-port
+ DataPath dataPath = new DataPath();
- /**
- * Create the DataPath: BGP -> BGP peer
- */
- // Flow path for src-TCP-port
- DataPath dataPath = new DataPath();
+ SwitchPort srcPort = new SwitchPort();
+ srcPort.setDpid(bgpdAttachmentPoint.dpid());
+ srcPort.setPort(bgpdAttachmentPoint.port());
+ dataPath.setSrcPort(srcPort);
- SwitchPort srcPort = new SwitchPort();
- srcPort.setDpid(bgpdAttachmentPoint.dpid());
- srcPort.setPort(bgpdAttachmentPoint.port());
- dataPath.setSrcPort(srcPort);
+ SwitchPort dstPort = new SwitchPort();
+ dstPort.setDpid(new Dpid(peerInterface.getDpid()));
+ dstPort.setPort(new Port(peerInterface.getSwitchPort().port()));
+ dataPath.setDstPort(dstPort);
- SwitchPort dstPort = new SwitchPort();
- dstPort.setDpid(new Dpid(peerInterface.getDpid()));
- dstPort.setPort(new Port(peerInterface.getSwitchPort().port()));
- dataPath.setDstPort(dstPort);
+ flowPath.setDataPath(dataPath);
- flowPath.setDataPath(dataPath);
+ // TODO: Add the flow by using the new Path Intent framework
+ /*
+ if (flowManagerService.addFlow(flowPath) == null) {
+ log.error("Failed to set up path BGP -> peer {}"+"; dst-TCP-port:179",
+ bgpPeer.getIpAddress().getHostAddress());
+ }
+ else {
+ log.debug("Successfully set up path BGP -> peer {}"+"; dst-TCP-port:179",
+ bgpPeer.getIpAddress().getHostAddress());
+ }
+ */
- // TODO: Add the flow by using the new Path Intent framework
- /*
- if (flowManagerService.addFlow(flowPath) == null) {
- log.error("Failed to set up path BGP -> peer {}"+"; dst-TCP-port:179",
- bgpPeer.getIpAddress().getHostAddress());
- }
- else {
- log.debug("Successfully set up path BGP -> peer {}"+"; dst-TCP-port:179",
- bgpPeer.getIpAddress().getHostAddress());
- }
- */
+ // Disable dst-TCP-port, and set src-TCP-port
+ flowEntryMatch.disableDstTcpUdpPort();
+ flowEntryMatch.enableSrcTcpUdpPort(BGP_PORT);
+ flowPath.setFlowEntryMatch(flowEntryMatch);
- // Disable dst-TCP-port, and set src-TCP-port
- flowEntryMatch.disableDstTcpUdpPort();
- flowEntryMatch.enableSrcTcpUdpPort(BGP_PORT);
- flowPath.setFlowEntryMatch(flowEntryMatch);
+ // Create a new FlowId
+ flowPath.setFlowId(new FlowId());
- // Create a new FlowId
- flowPath.setFlowId(new FlowId());
+ // TODO: Add the flow by using the new Path Intent framework
+ /*
+ if (flowManagerService.addFlow(flowPath) == null) {
+ log.error("Failed to set up path BGP -> Peer {}" + "; src-TCP-port:179",
+ bgpPeer.getIpAddress().getHostAddress());
+ }
+ else {
+ log.debug("Successfully set up path BGP -> Peer {}" + "; src-TCP-port:179",
+ bgpPeer.getIpAddress().getHostAddress());
+ }
+ */
- // TODO: Add the flow by using the new Path Intent framework
- /*
- if (flowManagerService.addFlow(flowPath) == null) {
- log.error("Failed to set up path BGP -> Peer {}" + "; src-TCP-port:179",
- bgpPeer.getIpAddress().getHostAddress());
- }
- else {
- log.debug("Successfully set up path BGP -> Peer {}" + "; src-TCP-port:179",
- bgpPeer.getIpAddress().getHostAddress());
- }
- */
+ /**
+ * Create the DataPath: BGP <-BGP peer
+ */
+ // Reversed BGP flow path for src-TCP-port
+ flowPath.setFlowId(new FlowId());
- /**
- * Create the DataPath: BGP <-BGP peer
- */
- // Reversed BGP flow path for src-TCP-port
- flowPath.setFlowId(new FlowId());
+ DataPath reverse_dataPath = new DataPath();
- DataPath reverse_dataPath = new DataPath();
+ SwitchPort reverse_dstPort = new SwitchPort();
+ reverse_dstPort.setDpid(bgpdAttachmentPoint.dpid());
+ reverse_dstPort.setPort(bgpdAttachmentPoint.port());
+ reverse_dataPath.setDstPort(reverse_dstPort);
- SwitchPort reverse_dstPort = new SwitchPort();
- reverse_dstPort.setDpid(bgpdAttachmentPoint.dpid());
- reverse_dstPort.setPort(bgpdAttachmentPoint.port());
- reverse_dataPath.setDstPort(reverse_dstPort);
+ SwitchPort reverse_srcPort = new SwitchPort();
+ reverse_srcPort.setDpid(new Dpid(peerInterface.getDpid()));
+ reverse_srcPort.setPort(new Port(peerInterface.getSwitchPort().port()));
+ reverse_dataPath.setSrcPort(reverse_srcPort);
+ flowPath.setDataPath(reverse_dataPath);
- SwitchPort reverse_srcPort = new SwitchPort();
- reverse_srcPort.setDpid(new Dpid(peerInterface.getDpid()));
- reverse_srcPort.setPort(new Port(peerInterface.getSwitchPort().port()));
- reverse_dataPath.setSrcPort(reverse_srcPort);
- flowPath.setDataPath(reverse_dataPath);
+ // reverse the dst IP and src IP addresses
+ flowEntryMatch.enableDstIPv4Net(srcIPv4Net);
+ flowEntryMatch.enableSrcIPv4Net(dstIPv4Net);
+ flowPath.setFlowEntryMatch(flowEntryMatch);
- // reverse the dst IP and src IP addresses
- flowEntryMatch.enableDstIPv4Net(srcIPv4Net);
- flowEntryMatch.enableSrcIPv4Net(dstIPv4Net);
- flowPath.setFlowEntryMatch(flowEntryMatch);
+ log.debug("Reversed BGP FlowPath: {}", flowPath.toString());
- log.debug("Reversed BGP FlowPath: {}", flowPath.toString());
+ // TODO: Add the flow by using the new Path Intent framework
+ /*
+ if (flowManagerService.addFlow(flowPath) == null) {
- // TODO: Add the flow by using the new Path Intent framework
- /*
- if (flowManagerService.addFlow(flowPath) == null) {
+ log.error("Failed to set up path BGP <- Peer {}" + "; src-TCP-port:179",
+ bgpPeer.getIpAddress().getHostAddress());
+ }
+ else {
+ log.debug("Successfully set up path BGP <- Peer {}" + "; src-TCP-port:179",
+ bgpPeer.getIpAddress().getHostAddress());
+ }
+ */
- log.error("Failed to set up path BGP <- Peer {}" + "; src-TCP-port:179",
- bgpPeer.getIpAddress().getHostAddress());
- }
- else {
- log.debug("Successfully set up path BGP <- Peer {}" + "; src-TCP-port:179",
- bgpPeer.getIpAddress().getHostAddress());
- }
- */
+ // Reversed BGP flow path for dst-TCP-port
+ flowPath.setFlowId(new FlowId());
- // Reversed BGP flow path for dst-TCP-port
- flowPath.setFlowId(new FlowId());
+ // Disable src-TCP-port, and set the dst-TCP-port
+ flowEntryMatch.disableSrcTcpUdpPort();
+ flowEntryMatch.enableDstTcpUdpPort(BGP_PORT);
+ flowPath.setFlowEntryMatch(flowEntryMatch);
- // Disable src-TCP-port, and set the dst-TCP-port
- flowEntryMatch.disableSrcTcpUdpPort();
- flowEntryMatch.enableDstTcpUdpPort(BGP_PORT);
- flowPath.setFlowEntryMatch(flowEntryMatch);
+ log.debug("Reversed BGP FlowPath: {}", flowPath.toString());
- log.debug("Reversed BGP FlowPath: {}", flowPath.toString());
+ // TODO: Add the flow by using the new Path Intent framework
+ /*
+ if (flowManagerService.addFlow(flowPath) == null) {
+ log.error("Failed to setting up path BGP <- Peer {}" + "; dst-TCP-port:179",
+ bgpPeer.getIpAddress().getHostAddress());
+ }
+ else {
+ log.debug("Successfully setting up path BGP <- Peer {}" + "; dst-TCP-port:179",
+ bgpPeer.getIpAddress().getHostAddress());
+ }
+ */
- // TODO: Add the flow by using the new Path Intent framework
- /*
- if (flowManagerService.addFlow(flowPath) == null) {
- log.error("Failed to setting up path BGP <- Peer {}" + "; dst-TCP-port:179",
- bgpPeer.getIpAddress().getHostAddress());
- }
- else {
- log.debug("Successfully setting up path BGP <- Peer {}" + "; dst-TCP-port:179",
- bgpPeer.getIpAddress().getHostAddress());
- }
- */
+ /**
+ * ICMP paths between BGPd and its peers
+ */
+ //match ICMP protocol BGP <- Peer
+ flowPath.setFlowId(new FlowId());
- /**
- * ICMP paths between BGPd and its peers
- */
- //match ICMP protocol BGP <- Peer
- flowPath.setFlowId(new FlowId());
+ flowEntryMatch.enableIpProto(IPv4.PROTOCOL_ICMP);
+ flowEntryMatch.disableSrcTcpUdpPort();
+ flowEntryMatch.disableDstTcpUdpPort();
- flowEntryMatch.enableIpProto(IPv4.PROTOCOL_ICMP);
- flowEntryMatch.disableSrcTcpUdpPort();
- flowEntryMatch.disableDstTcpUdpPort();
+ flowPath.setFlowEntryMatch(flowEntryMatch);
- flowPath.setFlowEntryMatch(flowEntryMatch);
+ flowPath.setDataPath(reverse_dataPath);
- flowPath.setDataPath(reverse_dataPath);
+ log.debug("Reversed ICMP FlowPath: {}", flowPath.toString());
- log.debug("Reversed ICMP FlowPath: {}", flowPath.toString());
+ // TODO: Add the flow by using the new Path Intent framework
+ /*
+ if (flowManagerService.addFlow(flowPath) == null) {
- // TODO: Add the flow by using the new Path Intent framework
- /*
- if (flowManagerService.addFlow(flowPath) == null) {
+ log.error("Failed to set up ICMP path BGP <- Peer {}",
+ bgpPeer.getIpAddress().getHostAddress());
+ }
+ else {
+ log.debug("Successfully set up ICMP path BGP <- Peer {}",
+ bgpPeer.getIpAddress().getHostAddress());
+ }
+ */
- log.error("Failed to set up ICMP path BGP <- Peer {}",
- bgpPeer.getIpAddress().getHostAddress());
- }
- else {
- log.debug("Successfully set up ICMP path BGP <- Peer {}",
- bgpPeer.getIpAddress().getHostAddress());
- }
- */
+ //match ICMP protocol BGP -> Peer
+ flowPath.setFlowId(new FlowId());
- //match ICMP protocol BGP -> Peer
- flowPath.setFlowId(new FlowId());
+ flowEntryMatch.enableDstIPv4Net(dstIPv4Net);
+ flowEntryMatch.enableSrcIPv4Net(srcIPv4Net);
+ flowPath.setFlowEntryMatch(flowEntryMatch);
- flowEntryMatch.enableDstIPv4Net(dstIPv4Net);
- flowEntryMatch.enableSrcIPv4Net(srcIPv4Net);
- flowPath.setFlowEntryMatch(flowEntryMatch);
+ flowPath.setDataPath(dataPath);
- flowPath.setDataPath(dataPath);
+ log.debug("ICMP flowPath: {}", flowPath.toString());
- log.debug("ICMP flowPath: {}", flowPath.toString());
+ // TODO: Add the flow by using the new Path Intent framework
+ /*
+ if (flowManagerService.addFlow(flowPath) == null) {
- // TODO: Add the flow by using the new Path Intent framework
- /*
- if (flowManagerService.addFlow(flowPath) == null) {
+ log.error("Failed to set up ICMP path BGP -> Peer {}",
+ bgpPeer.getIpAddress().getHostAddress());
+ }
+ else {
+ log.debug("Successfully set up ICMP path BGP -> Peer {}",
+ bgpPeer.getIpAddress().getHostAddress());
+ }
+ */
+ }
+ }
- log.error("Failed to set up ICMP path BGP -> Peer {}",
- bgpPeer.getIpAddress().getHostAddress());
- }
- else {
- log.debug("Successfully set up ICMP path BGP -> Peer {}",
- bgpPeer.getIpAddress().getHostAddress());
- }
- */
- }
- }
+ @Override
+ public void arpResponse(InetAddress ipAddress, MACAddress macAddress) {
+ log.debug("Received ARP response: {} => {}",
+ ipAddress.getHostAddress(), macAddress);
- @Override
- public void arpResponse(InetAddress ipAddress, MACAddress macAddress) {
- log.debug("Received ARP response: {} => {}",
- ipAddress.getHostAddress(), macAddress);
+ /*
+ * We synchronize on this to prevent changes to the ptree while we're pushing
+ * flows to the switches. If the ptree changes, the ptree and switches
+ * could get out of sync.
+ */
+ synchronized (this) {
+ Path path = pathsWaitingOnArp.remove(ipAddress);
- /*
- * We synchronize on this to prevent changes to the ptree while we're pushing
- * flows to the switches. If the ptree changes, the ptree and switches
- * could get out of sync.
- */
- synchronized (this) {
- Path path = pathsWaitingOnArp.remove(ipAddress);
+ if (path != null) {
+ log.debug("Pushing path to {} at {} on {}", new Object[]{
+ path.getDstIpAddress().getHostAddress(), macAddress,
+ path.getDstInterface().getSwitchPort()});
+ //These paths should always be to BGP peers. Paths to non-peers are
+ //handled once the first prefix is ready to push
+ if (pushedPaths.containsKey(path.getDstIpAddress())) {
+ //A path already got pushed to this endpoint while we were waiting
+ //for ARP. We'll copy over the permanent attribute if it is set on this path.
+ if (path.isPermanent()) {
+ pushedPaths.get(path.getDstIpAddress()).setPermanent();
+ }
+ } else {
+ calculateAndPushPath(path, macAddress);
+ pushedPaths.put(path.getDstIpAddress(), path);
+ }
+ }
- if (path != null) {
- log.debug("Pushing path to {} at {} on {}", new Object[] {
- path.getDstIpAddress().getHostAddress(), macAddress,
- path.getDstInterface().getSwitchPort()});
- //These paths should always be to BGP peers. Paths to non-peers are
- //handled once the first prefix is ready to push
- if (pushedPaths.containsKey(path.getDstIpAddress())) {
- //A path already got pushed to this endpoint while we were waiting
- //for ARP. We'll copy over the permanent attribute if it is set on this path.
- if (path.isPermanent()) {
- pushedPaths.get(path.getDstIpAddress()).setPermanent();
- }
- }
- else {
- calculateAndPushPath(path, macAddress);
- pushedPaths.put(path.getDstIpAddress(), path);
- }
- }
+ Set<RibUpdate> prefixesToPush = prefixesWaitingOnArp.removeAll(ipAddress);
- Set<RibUpdate> prefixesToPush = prefixesWaitingOnArp.removeAll(ipAddress);
+ for (RibUpdate update : prefixesToPush) {
+ //These will always be adds
- for (RibUpdate update : prefixesToPush) {
- //These will always be adds
+ RibEntry rib = ptree.lookup(update.getPrefix());
+ if (rib != null && rib.equals(update.getRibEntry())) {
+ log.debug("Pushing prefix {} next hop {}", update.getPrefix(),
+ rib.getNextHop().getHostAddress());
+ //We only push prefix flows if the prefix is still in the ptree
+ //and the next hop is the same as our update. The prefix could
+ //have been removed while we were waiting for the ARP, or the
+ //next hop could have changed.
+ _processRibAdd(update);
+ } else {
+ log.debug("Received ARP response, but {},{} is no longer in ptree",
+ update.getPrefix(), update.getRibEntry());
+ }
+ }
+ }
+ }
- RibEntry rib = ptree.lookup(update.getPrefix());
- if (rib != null && rib.equals(update.getRibEntry())) {
- log.debug("Pushing prefix {} next hop {}", update.getPrefix(),
- rib.getNextHop().getHostAddress());
- //We only push prefix flows if the prefix is still in the ptree
- //and the next hop is the same as our update. The prefix could
- //have been removed while we were waiting for the ARP, or the
- //next hop could have changed.
- _processRibAdd(update);
- } else {
- log.debug("Received ARP response, but {},{} is no longer in ptree",
- update.getPrefix(), update.getRibEntry());
- }
- }
- }
- }
+ //TODO wait the priority module of the flow Manager
+ private void setupArpFlows() {
+ OFMatch match = new OFMatch();
+ match.setDataLayerType(Ethernet.TYPE_ARP);
+ match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
- //TODO wait the priority module of the flow Manager
- private void setupArpFlows() {
- OFMatch match = new OFMatch();
- match.setDataLayerType(Ethernet.TYPE_ARP);
- match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
+ OFFlowMod fm = new OFFlowMod();
+ fm.setMatch(match);
- OFFlowMod fm = new OFFlowMod();
- fm.setMatch(match);
+ OFActionOutput action = new OFActionOutput();
+ action.setPort(OFPort.OFPP_CONTROLLER.getValue());
+ action.setMaxLength((short) 0xffff);
+ List<OFAction> actions = new ArrayList<OFAction>(1);
+ actions.add(action);
+ fm.setActions(actions);
- OFActionOutput action = new OFActionOutput();
- action.setPort(OFPort.OFPP_CONTROLLER.getValue());
- action.setMaxLength((short)0xffff);
- List<OFAction> actions = new ArrayList<OFAction>(1);
- actions.add(action);
- fm.setActions(actions);
+ fm.setIdleTimeout((short) 0)
+ .setHardTimeout((short) 0)
+ .setBufferId(OFPacketOut.BUFFER_ID_NONE)
+ .setCookie(0)
+ .setCommand(OFFlowMod.OFPFC_ADD)
+ .setPriority(ARP_PRIORITY)
+ .setLengthU(OFFlowMod.MINIMUM_LENGTH + OFActionOutput.MINIMUM_LENGTH);
- fm.setIdleTimeout((short)0)
- .setHardTimeout((short)0)
- .setBufferId(OFPacketOut.BUFFER_ID_NONE)
- .setCookie(0)
- .setCommand(OFFlowMod.OFPFC_ADD)
- .setPriority(ARP_PRIORITY)
- .setLengthU(OFFlowMod.MINIMUM_LENGTH + OFActionOutput.MINIMUM_LENGTH);
+ for (String strdpid : switches) {
+ flowCache.write(HexString.toLong(strdpid), fm);
+ }
+ }
- for (String strdpid : switches){
- flowCache.write(HexString.toLong(strdpid), fm);
- }
- }
- //TODO need update, waiting for the priority feature from flow Manager
- private void setupDefaultDropFlows() {
- OFFlowMod fm = new OFFlowMod();
- fm.setMatch(new OFMatch());
- fm.setActions(new ArrayList<OFAction>()); //No action means drop
+ //TODO need update, waiting for the priority feature from flow Manager
+ private void setupDefaultDropFlows() {
+ OFFlowMod fm = new OFFlowMod();
+ fm.setMatch(new OFMatch());
+ fm.setActions(new ArrayList<OFAction>()); //No action means drop
- fm.setIdleTimeout((short)0)
- .setHardTimeout((short)0)
- .setBufferId(OFPacketOut.BUFFER_ID_NONE)
- .setCookie(0)
- .setCommand(OFFlowMod.OFPFC_ADD)
- .setPriority((short)0)
- .setLengthU(OFFlowMod.MINIMUM_LENGTH);
+ fm.setIdleTimeout((short) 0)
+ .setHardTimeout((short) 0)
+ .setBufferId(OFPacketOut.BUFFER_ID_NONE)
+ .setCookie(0)
+ .setCommand(OFFlowMod.OFPFC_ADD)
+ .setPriority((short) 0)
+ .setLengthU(OFFlowMod.MINIMUM_LENGTH);
- OFFlowMod fmLLDP;
- OFFlowMod fmBDDP;
- try {
- fmLLDP = fm.clone();
- fmBDDP = fm.clone();
- } catch (CloneNotSupportedException e1) {
- log.error("Error cloning flow mod", e1);
- return;
- }
+ OFFlowMod fmLLDP;
+ OFFlowMod fmBDDP;
+ try {
+ fmLLDP = fm.clone();
+ fmBDDP = fm.clone();
+ } catch (CloneNotSupportedException e1) {
+ log.error("Error cloning flow mod", e1);
+ return;
+ }
- OFMatch matchLLDP = new OFMatch();
- matchLLDP.setDataLayerType((short)0x88cc);
- matchLLDP.setWildcards(matchLLDP.getWildcards() & ~ OFMatch.OFPFW_DL_TYPE);
- fmLLDP.setMatch(matchLLDP);
+ OFMatch matchLLDP = new OFMatch();
+ matchLLDP.setDataLayerType((short) 0x88cc);
+ matchLLDP.setWildcards(matchLLDP.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
+ fmLLDP.setMatch(matchLLDP);
- OFMatch matchBDDP = new OFMatch();
- matchBDDP.setDataLayerType((short)0x8942);
- matchBDDP.setWildcards(matchBDDP.getWildcards() & ~ OFMatch.OFPFW_DL_TYPE);
- fmBDDP.setMatch(matchBDDP);
+ OFMatch matchBDDP = new OFMatch();
+ matchBDDP.setDataLayerType((short) 0x8942);
+ matchBDDP.setWildcards(matchBDDP.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
+ fmBDDP.setMatch(matchBDDP);
- OFActionOutput action = new OFActionOutput();
- action.setPort(OFPort.OFPP_CONTROLLER.getValue());
- action.setMaxLength((short)0xffff);
- List<OFAction> actions = new ArrayList<OFAction>(1);
- actions.add(action);
+ OFActionOutput action = new OFActionOutput();
+ action.setPort(OFPort.OFPP_CONTROLLER.getValue());
+ action.setMaxLength((short) 0xffff);
+ List<OFAction> actions = new ArrayList<OFAction>(1);
+ actions.add(action);
- fmLLDP.setActions(actions);
- fmBDDP.setActions(actions);
+ fmLLDP.setActions(actions);
+ fmBDDP.setActions(actions);
- fmLLDP.setPriority(ARP_PRIORITY);
- fmLLDP.setLengthU(OFFlowMod.MINIMUM_LENGTH + OFActionOutput.MINIMUM_LENGTH);
- fmBDDP.setPriority(ARP_PRIORITY);
- fmBDDP.setLengthU(OFFlowMod.MINIMUM_LENGTH + OFActionOutput.MINIMUM_LENGTH);
+ fmLLDP.setPriority(ARP_PRIORITY);
+ fmLLDP.setLengthU(OFFlowMod.MINIMUM_LENGTH + OFActionOutput.MINIMUM_LENGTH);
+ fmBDDP.setPriority(ARP_PRIORITY);
+ fmBDDP.setLengthU(OFFlowMod.MINIMUM_LENGTH + OFActionOutput.MINIMUM_LENGTH);
- List<OFFlowMod> flowModList = new ArrayList<OFFlowMod>(3);
- flowModList.add(fm);
- flowModList.add(fmLLDP);
- flowModList.add(fmBDDP);
+ List<OFFlowMod> flowModList = new ArrayList<OFFlowMod>(3);
+ flowModList.add(fm);
+ flowModList.add(fmLLDP);
+ flowModList.add(fmBDDP);
- for (String strdpid : switches){
- flowCache.write(HexString.toLong(strdpid), flowModList);
- }
- }
+ for (String strdpid : switches) {
+ flowCache.write(HexString.toLong(strdpid), flowModList);
+ }
+ }
- private void beginRouting(){
- log.debug("Topology is now ready, beginning routing function");
- // TODO: Fix for the new Topology Network Graph
- // topology = topologyNetService.newDatabaseTopology();
+ private void beginRouting() {
+ log.debug("Topology is now ready, beginning routing function");
+ // TODO: Fix for the new Topology Network Graph
+ // topology = topologyNetService.newDatabaseTopology();
- // Wait Pavlin's API. We need the following functions.
- /*setupArpFlows();
- setupDefaultDropFlows();*/
+ // Wait Pavlin's API. We need the following functions.
+ /*setupArpFlows();
+ setupDefaultDropFlows();*/
- setupBgpPaths();
- setupFullMesh();
+ setupBgpPaths();
+ setupFullMesh();
- //Suppress link discovery on external-facing router ports
- for (Interface intf : interfaces.values()) {
- linkDiscoveryService.AddToSuppressLLDPs(intf.getDpid(), intf.getPort());
- }
+ //Suppress link discovery on external-facing router ports
+ for (Interface intf : interfaces.values()) {
+ linkDiscoveryService.AddToSuppressLLDPs(intf.getDpid(), intf.getPort());
+ }
- bgpUpdatesExecutor.execute(new Runnable() {
- @Override
- public void run() {
- doUpdatesThread();
- }
- });
- }
+ bgpUpdatesExecutor.execute(new Runnable() {
+ @Override
+ public void run() {
+ doUpdatesThread();
+ }
+ });
+ }
- // Before inserting the paths for BGP traffic, we should check
- // whether all the switches in the configure file are discovered by onos.
- private void checkSwitchesConnected(){
- for (String dpid : switches){
- // TODO: Fix the code below after topoSwitchSerice was removed
- /*
- Iterator<ISwitchObject> activeSwitches = topoSwitchService.
- getActiveSwitches().iterator();
- while(activeSwitches.hasNext())
- {
- ISwitchObject switchObject = activeSwitches.next();
- if (switchObject.getDPID().equals(dpid)) {
- break;
- }
- if(activeSwitches.hasNext() == false) {
- log.debug("Not all switches are here yet");
- return;
- }
- }
- */
- }
- switchesConnected = true;
- }
+ // Before inserting the paths for BGP traffic, we should check
+ // whether all the switches in the configure file are discovered by onos.
+ private void checkSwitchesConnected() {
+ for (String dpid : switches) {
+ // TODO: Fix the code below after topoSwitchSerice was removed
+ /*
+ Iterator<ISwitchObject> activeSwitches = topoSwitchService.
+ getActiveSwitches().iterator();
+ while(activeSwitches.hasNext())
+ {
+ ISwitchObject switchObject = activeSwitches.next();
+ if (switchObject.getDPID().equals(dpid)) {
+ break;
+ }
+ if(activeSwitches.hasNext() == false) {
+ log.debug("Not all switches are here yet");
+ return;
+ }
+ }
+ */
+ }
+ switchesConnected = true;
+ }
- //Actually we only need to go half way round to verify full mesh connectivity
- //(n^2)/2
- private void checkTopologyReady(){
- for (Interface dstInterface : interfaces.values()) {
- for (Interface srcInterface : interfaces.values()) {
- if (dstInterface.equals(srcInterface)) {
- continue;
- }
+ //Actually we only need to go half way round to verify full mesh connectivity
+ //(n^2)/2
+ private void checkTopologyReady() {
+ for (Interface dstInterface : interfaces.values()) {
+ for (Interface srcInterface : interfaces.values()) {
+ if (dstInterface.equals(srcInterface)) {
+ continue;
+ }
- // TODO: Fix for the new Topology Network Graph
- /*
- DataPath shortestPath = topologyNetService.getDatabaseShortestPath(
- srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
+ // TODO: Fix for the new Topology Network Graph
+ /*
+ DataPath shortestPath = topologyNetService.getDatabaseShortestPath(
+ srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
- if (shortestPath == null){
- log.debug("Shortest path between {} and {} not found",
- srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
- return;
- }
- */
- }
- }
- topologyReady = true;
- }
+ if (shortestPath == null){
+ log.debug("Shortest path between {} and {} not found",
+ srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
+ return;
+ }
+ */
+ }
+ }
+ topologyReady = true;
+ }
- private void checkStatus(){
- if (!switchesConnected){
- checkSwitchesConnected();
- }
- boolean oldTopologyReadyStatus = topologyReady;
- if (switchesConnected && !topologyReady){
- checkTopologyReady();
- }
- if (!oldTopologyReadyStatus && topologyReady){
- beginRouting();
- }
- }
+ private void checkStatus() {
+ if (!switchesConnected) {
+ checkSwitchesConnected();
+ }
+ boolean oldTopologyReadyStatus = topologyReady;
+ if (switchesConnected && !topologyReady) {
+ checkTopologyReady();
+ }
+ if (!oldTopologyReadyStatus && topologyReady) {
+ beginRouting();
+ }
+ }
- private void doUpdatesThread() {
- boolean interrupted = false;
- try {
- while (true) {
- try {
- RibUpdate update = ribUpdates.take();
- switch (update.getOperation()){
- case UPDATE:
- if (validateUpdate(update)) {
- processRibAdd(update);
- }
- else {
- log.debug("Rib UPDATE out of order: {} via {}",
- update.getPrefix(), update.getRibEntry().getNextHop());
- }
- break;
- case DELETE:
- if (validateUpdate(update)) {
- processRibDelete(update);
- }
- else {
- log.debug("Rib DELETE out of order: {} via {}",
- update.getPrefix(), update.getRibEntry().getNextHop());
- }
- break;
- }
- } catch (InterruptedException e) {
- log.debug("Interrupted while taking from updates queue", e);
- interrupted = true;
- } catch (Exception e) {
- log.debug("exception", e);
- }
- }
- } finally {
- if (interrupted) {
- Thread.currentThread().interrupt();
- }
- }
- }
+ private void doUpdatesThread() {
+ boolean interrupted = false;
+ try {
+ while (true) {
+ try {
+ RibUpdate update = ribUpdates.take();
+ switch (update.getOperation()) {
+ case UPDATE:
+ if (validateUpdate(update)) {
+ processRibAdd(update);
+ } else {
+ log.debug("Rib UPDATE out of order: {} via {}",
+ update.getPrefix(), update.getRibEntry().getNextHop());
+ }
+ break;
+ case DELETE:
+ if (validateUpdate(update)) {
+ processRibDelete(update);
+ } else {
+ log.debug("Rib DELETE out of order: {} via {}",
+ update.getPrefix(), update.getRibEntry().getNextHop());
+ }
+ break;
+ }
+ } catch (InterruptedException e) {
+ log.debug("Interrupted while taking from updates queue", e);
+ interrupted = true;
+ } catch (Exception e) {
+ log.debug("exception", e);
+ }
+ }
+ } finally {
+ if (interrupted) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
- private boolean validateUpdate(RibUpdate update) {
- RibEntry newEntry = update.getRibEntry();
- RibEntry oldEntry = ptree.lookup(update.getPrefix());
+ private boolean validateUpdate(RibUpdate update) {
+ RibEntry newEntry = update.getRibEntry();
+ RibEntry oldEntry = ptree.lookup(update.getPrefix());
- //If there is no existing entry we must assume this is the most recent
- //update. However this might not always be the case as we might have a
- //POST then DELETE reordering.
- //if (oldEntry == null || !newEntry.getNextHop().equals(oldEntry.getNextHop())) {
- if (oldEntry == null) {
- return true;
- }
+ //If there is no existing entry we must assume this is the most recent
+ //update. However this might not always be the case as we might have a
+ //POST then DELETE reordering.
+ //if (oldEntry == null || !newEntry.getNextHop().equals(oldEntry.getNextHop())) {
+ if (oldEntry == null) {
+ return true;
+ }
- // This handles the case where routes are gathered in the initial
- // request because they don't have sequence number info
- if (newEntry.getSysUpTime() == -1 && newEntry.getSequenceNum() == -1) {
- return true;
- }
+ // This handles the case where routes are gathered in the initial
+ // request because they don't have sequence number info
+ if (newEntry.getSysUpTime() == -1 && newEntry.getSequenceNum() == -1) {
+ return true;
+ }
- if (newEntry.getSysUpTime() > oldEntry.getSysUpTime()) {
- return true;
- }
- else if (newEntry.getSysUpTime() == oldEntry.getSysUpTime()) {
- if (newEntry.getSequenceNum() > oldEntry.getSequenceNum()) {
- return true;
- }
- else {
- return false;
- }
- }
- else {
- return false;
- }
- }
+ if (newEntry.getSysUpTime() > oldEntry.getSysUpTime()) {
+ return true;
+ } else if (newEntry.getSysUpTime() == oldEntry.getSysUpTime()) {
+ if (newEntry.getSequenceNum() > oldEntry.getSequenceNum()) {
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ return false;
+ }
+ }
- // The code below should be reimplemented after removal of Floodlight's
- // ITopologyService API. It should be implemented on top of network graph
- // notifications. (It was pretty hacky anyway...)
- /*
- @Override
- public void topologyChanged() {
- if (topologyReady) {
- return;
- }
+ // The code below should be reimplemented after removal of Floodlight's
+ // ITopologyService API. It should be implemented on top of network graph
+ // notifications. (It was pretty hacky anyway...)
+ /*
+ @Override
+ public void topologyChanged() {
+ if (topologyReady) {
+ return;
+ }
- boolean refreshNeeded = false;
- for (LDUpdate ldu : topologyService.getLastLinkUpdates()){
- if (!ldu.getOperation().equals(ILinkDiscovery.UpdateOperation.LINK_UPDATED)){
- //We don't need to recalculate anything for just link updates
- //They happen very frequently
- refreshNeeded = true;
- }
+ boolean refreshNeeded = false;
+ for (LDUpdate ldu : topologyService.getLastLinkUpdates()){
+ if (!ldu.getOperation().equals(ILinkDiscovery.UpdateOperation.LINK_UPDATED)){
+ //We don't need to recalculate anything for just link updates
+ //They happen very frequently
+ refreshNeeded = true;
+ }
- log.debug("Topo change {}", ldu.getOperation());
+ log.debug("Topo change {}", ldu.getOperation());
- if (ldu.getOperation().equals(ILinkDiscovery.UpdateOperation.LINK_ADDED)){
- synchronized (linkUpdates) {
- linkUpdates.add(ldu);
- }
- }
- }
+ if (ldu.getOperation().equals(ILinkDiscovery.UpdateOperation.LINK_ADDED)){
+ synchronized (linkUpdates) {
+ linkUpdates.add(ldu);
+ }
+ }
+ }
- if (refreshNeeded && !topologyReady){
- topologyChangeDetectorTask.reschedule(TOPO_DETECTION_WAIT, TimeUnit.SECONDS);
- }
- }
- */
+ if (refreshNeeded && !topologyReady){
+ topologyChangeDetectorTask.reschedule(TOPO_DETECTION_WAIT, TimeUnit.SECONDS);
+ }
+ }
+ */
- @Override
- public void addedSwitch(IOFSwitch sw) {
- if (!topologyReady) {
- sw.clearAllFlowMods();
- }
+ @Override
+ public void addedSwitch(IOFSwitch sw) {
+ if (!topologyReady) {
+ sw.clearAllFlowMods();
+ }
- flowCache.switchConnected(sw);
- }
+ flowCache.switchConnected(sw);
+ }
- @Override
- public void removedSwitch(IOFSwitch sw) {}
+ @Override
+ public void removedSwitch(IOFSwitch sw) {
+ }
- @Override
- public void switchPortChanged(Long switchId) {}
+ @Override
+ public void switchPortChanged(Long switchId) {
+ }
- @Override
- public String getName() {
- return "BgpRoute";
- }
+ @Override
+ public String getName() {
+ return "BgpRoute";
+ }
- /*
- * IConfigInfoService methods
- */
+ /*
+ * IConfigInfoService methods
+ */
- @Override
- public boolean isInterfaceAddress(InetAddress address) {
- Interface intf = interfacePtrie.match(new Prefix(address.getAddress(), 32));
- return (intf != null && intf.getIpAddress().equals(address));
- }
+ @Override
+ public boolean isInterfaceAddress(InetAddress address) {
+ Interface intf = interfacePtrie.match(new Prefix(address.getAddress(), 32));
+ return (intf != null && intf.getIpAddress().equals(address));
+ }
- @Override
- public boolean inConnectedNetwork(InetAddress address) {
- Interface intf = interfacePtrie.match(new Prefix(address.getAddress(), 32));
- return (intf != null && !intf.getIpAddress().equals(address));
- }
+ @Override
+ public boolean inConnectedNetwork(InetAddress address) {
+ Interface intf = interfacePtrie.match(new Prefix(address.getAddress(), 32));
+ return (intf != null && !intf.getIpAddress().equals(address));
+ }
- @Override
- public boolean fromExternalNetwork(long inDpid, short inPort) {
- for (Interface intf : interfaces.values()) {
- if (intf.getDpid() == inDpid && intf.getPort() == inPort) {
- return true;
- }
- }
- return false;
- }
+ @Override
+ public boolean fromExternalNetwork(long inDpid, short inPort) {
+ for (Interface intf : interfaces.values()) {
+ if (intf.getDpid() == inDpid && intf.getPort() == inPort) {
+ return true;
+ }
+ }
+ return false;
+ }
- @Override
- public Interface getOutgoingInterface(InetAddress dstIpAddress) {
- return interfacePtrie.match(new Prefix(dstIpAddress.getAddress(), 32));
- }
+ @Override
+ public Interface getOutgoingInterface(InetAddress dstIpAddress) {
+ return interfacePtrie.match(new Prefix(dstIpAddress.getAddress(), 32));
+ }
- @Override
- public boolean hasLayer3Configuration() {
- return !interfaces.isEmpty();
- }
+ @Override
+ public boolean hasLayer3Configuration() {
+ return !interfaces.isEmpty();
+ }
- @Override
- public MACAddress getRouterMacAddress() {
- return bgpdMacAddress;
- }
+ @Override
+ public MACAddress getRouterMacAddress() {
+ return bgpdMacAddress;
+ }
- @Override
- public short getVlan() {
- return vlan;
- }
+ @Override
+ public short getVlan() {
+ return vlan;
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/BgpRouteResource.java b/src/main/java/net/onrc/onos/apps/bgproute/BgpRouteResource.java
index cbb1634..2e14757 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/BgpRouteResource.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/BgpRouteResource.java
@@ -13,164 +13,160 @@
public class BgpRouteResource extends ServerResource {
- protected final static Logger log = LoggerFactory.getLogger(BgpRouteResource.class);
+ protected final static Logger log = LoggerFactory.getLogger(BgpRouteResource.class);
- @Get
- public String get(String fmJson) {
- String dest = (String) getRequestAttributes().get("dest");
- String output = "";
- IBgpRouteService bgpRoute = (IBgpRouteService)getContext().getAttributes().
- get(IBgpRouteService.class.getCanonicalName());
+ @Get
+ public String get(String fmJson) {
+ String dest = (String) getRequestAttributes().get("dest");
+ String output = "";
+ IBgpRouteService bgpRoute = (IBgpRouteService) getContext().getAttributes().
+ get(IBgpRouteService.class.getCanonicalName());
- if (dest != null) {
- //TODO Needs to be changed to use the new RestClient.get().
+ if (dest != null) {
+ //TODO Needs to be changed to use the new RestClient.get().
- // the dest here refers to router-id
- //bgpdRestIp includes port number, such as 1.1.1.1:8080
- String BGPdRestIp = bgpRoute.getBGPdRestIp();
- String url="http://"+BGPdRestIp+"/wm/bgp/"+dest;
+ // the dest here refers to router-id
+ //bgpdRestIp includes port number, such as 1.1.1.1:8080
+ String BGPdRestIp = bgpRoute.getBGPdRestIp();
+ String url = "http://" + BGPdRestIp + "/wm/bgp/" + dest;
- //Doesn't actually do anything with the response
- RestClient.get(url);
-
- output="Get rib from bgpd finished!\n";
- return output;
- }
- else {
- IPatriciaTrie<RibEntry> ptree = bgpRoute.getPtree();
- output += "{\n \"rib\": [\n";
- boolean printed = false;
-
- synchronized(ptree) {
- Iterator<IPatriciaTrie.Entry<RibEntry>> it = ptree.iterator();
- while (it.hasNext()) {
- IPatriciaTrie.Entry<RibEntry> entry = it.next();
-
- if (printed == true) {
- output += ",\n";
- }
-
- output += " {\"prefix\": \"" + entry.getPrefix() +"\", ";
- output += "\"nexthop\": \"" + entry.getValue().getNextHop().getHostAddress() +"\"}";
-
- printed = true;
- }
- }
-
- output += "\n ]\n}\n";
- }
-
- return output;
- }
+ //Doesn't actually do anything with the response
+ RestClient.get(url);
- @Post
- public String store(String fmJson) {
- IBgpRouteService bgpRoute = (IBgpRouteService) getContext().getAttributes().
- get(IBgpRouteService.class.getCanonicalName());
+ output = "Get rib from bgpd finished!\n";
+ return output;
+ } else {
+ IPatriciaTrie<RibEntry> ptree = bgpRoute.getPtree();
+ output += "{\n \"rib\": [\n";
+ boolean printed = false;
- String strSysuptime = (String) getRequestAttributes().get("sysuptime");
- String strSequence = (String) getRequestAttributes().get("sequence");
- String routerId = (String) getRequestAttributes().get("routerid");
- String prefix = (String) getRequestAttributes().get("prefix");
- String mask = (String) getRequestAttributes().get("mask");
- String nexthop = (String) getRequestAttributes().get("nexthop");
- String capability = (String) getRequestAttributes().get("capability");
-
- log.debug("sysuptime: {}", strSysuptime);
- log.debug("sequence: {}", strSequence);
+ synchronized (ptree) {
+ Iterator<IPatriciaTrie.Entry<RibEntry>> it = ptree.iterator();
+ while (it.hasNext()) {
+ IPatriciaTrie.Entry<RibEntry> entry = it.next();
- String reply = "";
+ if (printed == true) {
+ output += ",\n";
+ }
- if (capability == null) {
- // this is a prefix add
- Prefix p;
- long sysUpTime, sequenceNum;
- try {
- p = new Prefix(prefix, Integer.valueOf(mask));
- sysUpTime = Long.parseLong(strSysuptime);
- sequenceNum = Long.parseLong(strSequence);
- } catch (NumberFormatException e) {
- reply = "[POST: mask format is wrong]";
- log.info(reply);
- return reply + "\n";
- } catch (IllegalArgumentException e1) {
- reply = "[POST: prefix format is wrong]";
- log.info(reply);
- return reply + "\n";
- }
-
- RibEntry rib = new RibEntry(routerId, nexthop, sysUpTime, sequenceNum);
+ output += " {\"prefix\": \"" + entry.getPrefix() + "\", ";
+ output += "\"nexthop\": \"" + entry.getValue().getNextHop().getHostAddress() + "\"}";
- bgpRoute.newRibUpdate(new RibUpdate(Operation.UPDATE, p, rib));
-
- reply = "[POST: " + prefix + "/" + mask + ":" + nexthop + "]";
- log.info(reply);
- }
- else if(capability.equals("1")) {
- reply = "[POST-capability: " + capability + "]\n";
- log.info(reply);
- // to store the number in the top node of the Ptree
- }
- else {
- reply = "[POST-capability: " + capability + "]\n";
- log.info(reply);
- // to store the number in the top node of the Ptree
- }
+ printed = true;
+ }
+ }
- return reply + "\n";
- }
+ output += "\n ]\n}\n";
+ }
- @Delete
- public String delete(String fmJson) {
- IBgpRouteService bgpRoute = (IBgpRouteService)getContext().getAttributes().
- get(IBgpRouteService.class.getCanonicalName());
+ return output;
+ }
- String strSysuptime = (String) getRequestAttributes().get("sysuptime");
- String strSequence = (String) getRequestAttributes().get("sequence");
- String routerId = (String) getRequestAttributes().get("routerid");
- String prefix = (String) getRequestAttributes().get("prefix");
- String mask = (String) getRequestAttributes().get("mask");
- String nextHop = (String) getRequestAttributes().get("nexthop");
- String capability = (String) getRequestAttributes().get("capability");
+ @Post
+ public String store(String fmJson) {
+ IBgpRouteService bgpRoute = (IBgpRouteService) getContext().getAttributes().
+ get(IBgpRouteService.class.getCanonicalName());
- log.debug("sysuptime: {}", strSysuptime);
- log.debug("sequence: {}", strSequence);
-
- String reply = "";
+ String strSysuptime = (String) getRequestAttributes().get("sysuptime");
+ String strSequence = (String) getRequestAttributes().get("sequence");
+ String routerId = (String) getRequestAttributes().get("routerid");
+ String prefix = (String) getRequestAttributes().get("prefix");
+ String mask = (String) getRequestAttributes().get("mask");
+ String nexthop = (String) getRequestAttributes().get("nexthop");
+ String capability = (String) getRequestAttributes().get("capability");
- if (capability == null) {
- // this is a prefix delete
- Prefix p;
- long sysUpTime, sequenceNum;
- try {
- p = new Prefix(prefix, Integer.valueOf(mask));
- sysUpTime = Long.parseLong(strSysuptime);
- sequenceNum = Long.parseLong(strSequence);
- } catch (NumberFormatException e) {
- reply = "[DELE: mask format is wrong]";
- log.info(reply);
- return reply + "\n";
- } catch (IllegalArgumentException e1) {
- reply = "[DELE: prefix format is wrong]";
- log.info(reply);
- return reply + "\n";
- }
-
- RibEntry r = new RibEntry(routerId, nextHop, sysUpTime, sequenceNum);
-
- bgpRoute.newRibUpdate(new RibUpdate(Operation.DELETE, p, r));
-
- reply =reply + "[DELE: " + prefix + "/" + mask + ":" + nextHop + "]";
- }
- else {
- // clear the local rib: Ptree
- bgpRoute.clearPtree();
- reply = "[DELE-capability: " + capability + "; The local RibEntry is cleared!]\n";
+ log.debug("sysuptime: {}", strSysuptime);
+ log.debug("sequence: {}", strSequence);
- // to store the number in the top node of the Ptree
- }
-
- log.info(reply);
- return reply + "\n";
- }
+ String reply = "";
+
+ if (capability == null) {
+ // this is a prefix add
+ Prefix p;
+ long sysUpTime, sequenceNum;
+ try {
+ p = new Prefix(prefix, Integer.valueOf(mask));
+ sysUpTime = Long.parseLong(strSysuptime);
+ sequenceNum = Long.parseLong(strSequence);
+ } catch (NumberFormatException e) {
+ reply = "[POST: mask format is wrong]";
+ log.info(reply);
+ return reply + "\n";
+ } catch (IllegalArgumentException e1) {
+ reply = "[POST: prefix format is wrong]";
+ log.info(reply);
+ return reply + "\n";
+ }
+
+ RibEntry rib = new RibEntry(routerId, nexthop, sysUpTime, sequenceNum);
+
+ bgpRoute.newRibUpdate(new RibUpdate(Operation.UPDATE, p, rib));
+
+ reply = "[POST: " + prefix + "/" + mask + ":" + nexthop + "]";
+ log.info(reply);
+ } else if (capability.equals("1")) {
+ reply = "[POST-capability: " + capability + "]\n";
+ log.info(reply);
+ // to store the number in the top node of the Ptree
+ } else {
+ reply = "[POST-capability: " + capability + "]\n";
+ log.info(reply);
+ // to store the number in the top node of the Ptree
+ }
+
+ return reply + "\n";
+ }
+
+ @Delete
+ public String delete(String fmJson) {
+ IBgpRouteService bgpRoute = (IBgpRouteService) getContext().getAttributes().
+ get(IBgpRouteService.class.getCanonicalName());
+
+ String strSysuptime = (String) getRequestAttributes().get("sysuptime");
+ String strSequence = (String) getRequestAttributes().get("sequence");
+ String routerId = (String) getRequestAttributes().get("routerid");
+ String prefix = (String) getRequestAttributes().get("prefix");
+ String mask = (String) getRequestAttributes().get("mask");
+ String nextHop = (String) getRequestAttributes().get("nexthop");
+ String capability = (String) getRequestAttributes().get("capability");
+
+ log.debug("sysuptime: {}", strSysuptime);
+ log.debug("sequence: {}", strSequence);
+
+ String reply = "";
+
+ if (capability == null) {
+ // this is a prefix delete
+ Prefix p;
+ long sysUpTime, sequenceNum;
+ try {
+ p = new Prefix(prefix, Integer.valueOf(mask));
+ sysUpTime = Long.parseLong(strSysuptime);
+ sequenceNum = Long.parseLong(strSequence);
+ } catch (NumberFormatException e) {
+ reply = "[DELE: mask format is wrong]";
+ log.info(reply);
+ return reply + "\n";
+ } catch (IllegalArgumentException e1) {
+ reply = "[DELE: prefix format is wrong]";
+ log.info(reply);
+ return reply + "\n";
+ }
+
+ RibEntry r = new RibEntry(routerId, nextHop, sysUpTime, sequenceNum);
+
+ bgpRoute.newRibUpdate(new RibUpdate(Operation.DELETE, p, r));
+
+ reply = reply + "[DELE: " + prefix + "/" + mask + ":" + nextHop + "]";
+ } else {
+ // clear the local rib: Ptree
+ bgpRoute.clearPtree();
+ reply = "[DELE-capability: " + capability + "; The local RibEntry is cleared!]\n";
+
+ // to store the number in the top node of the Ptree
+ }
+
+ log.info(reply);
+ return reply + "\n";
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/BgpRouteResourceSynch.java b/src/main/java/net/onrc/onos/apps/bgproute/BgpRouteResourceSynch.java
index 5e33bc5..20fc71b 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/BgpRouteResourceSynch.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/BgpRouteResourceSynch.java
@@ -9,63 +9,65 @@
public class BgpRouteResourceSynch extends ServerResource {
-
- protected final static Logger log = LoggerFactory
+
+ protected final static Logger log = LoggerFactory
.getLogger(BgpRouteResource.class);
-
- @Post
- public String store(String fmJson) {
-
- IBgpRouteService bgpRoute = (IBgpRouteService)getContext().getAttributes().
+
+ @Post
+ public String store(String fmJson) {
+
+ IBgpRouteService bgpRoute = (IBgpRouteService) getContext().getAttributes().
get(IBgpRouteService.class.getCanonicalName());
-
- String router_id = (String) getRequestAttributes().get("routerid");
- String prefix = (String) getRequestAttributes().get("prefix");
- String mask = (String) getRequestAttributes().get("mask");
- String nexthop = (String) getRequestAttributes().get("nexthop");
-
- try{
-
- String BGPdRestIp = bgpRoute.getBGPdRestIp();
-
- //bgpdRestIp includes port number, such as 1.1.1.1:8080
- RestClient.post("http://"+BGPdRestIp+"/wm/bgp/"+router_id+"/"+prefix+"/"+mask+"/"+nexthop);
- }catch(Exception e)
- {e.printStackTrace();}
-
- String reply = "";
- reply = "[POST: " + prefix + "/" + mask + ":" + nexthop + "/synch]";
- log.info(reply);
-
- return reply + "\n";
-
-
- }
-
- @Delete
- public String delete(String fmJson) {
- IBgpRouteService bgpRoute = (IBgpRouteService)getContext().getAttributes().
- get(IBgpRouteService.class.getCanonicalName());
-
- String routerId = (String) getRequestAttributes().get("routerid");
- String prefix = (String) getRequestAttributes().get("prefix");
- String mask = (String) getRequestAttributes().get("mask");
- String nextHop = (String) getRequestAttributes().get("nexthop");
-
- String reply = "";
- try{
- String BGPdRestIp = bgpRoute.getBGPdRestIp();
-
- RestClient.delete("http://"+BGPdRestIp+"/wm/bgp/"+routerId+"/"+prefix+"/"+mask+"/"+nextHop);
-
- }catch(Exception e)
- {e.printStackTrace();}
-
- reply =reply + "[DELE: " + prefix + "/" + mask + ":" + nextHop + "/synch]";
-
- log.info(reply);
+
+ String router_id = (String) getRequestAttributes().get("routerid");
+ String prefix = (String) getRequestAttributes().get("prefix");
+ String mask = (String) getRequestAttributes().get("mask");
+ String nexthop = (String) getRequestAttributes().get("nexthop");
+
+ try {
+
+ String BGPdRestIp = bgpRoute.getBGPdRestIp();
+
+ //bgpdRestIp includes port number, such as 1.1.1.1:8080
+ RestClient.post("http://" + BGPdRestIp + "/wm/bgp/" + router_id + "/" + prefix + "/" + mask + "/" + nexthop);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ String reply = "";
+ reply = "[POST: " + prefix + "/" + mask + ":" + nexthop + "/synch]";
+ log.info(reply);
+
+ return reply + "\n";
- return reply + "\n";
- }
+ }
+
+ @Delete
+ public String delete(String fmJson) {
+ IBgpRouteService bgpRoute = (IBgpRouteService) getContext().getAttributes().
+ get(IBgpRouteService.class.getCanonicalName());
+
+ String routerId = (String) getRequestAttributes().get("routerid");
+ String prefix = (String) getRequestAttributes().get("prefix");
+ String mask = (String) getRequestAttributes().get("mask");
+ String nextHop = (String) getRequestAttributes().get("nexthop");
+
+ String reply = "";
+ try {
+ String BGPdRestIp = bgpRoute.getBGPdRestIp();
+
+ RestClient.delete("http://" + BGPdRestIp + "/wm/bgp/" + routerId + "/" + prefix + "/" + mask + "/" + nextHop);
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ reply = reply + "[DELE: " + prefix + "/" + mask + ":" + nextHop + "/synch]";
+
+ log.info(reply);
+
+
+ return reply + "\n";
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/BgpRouteWebRoutable.java b/src/main/java/net/onrc/onos/apps/bgproute/BgpRouteWebRoutable.java
index 7d304e8..a05015e 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/BgpRouteWebRoutable.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/BgpRouteWebRoutable.java
@@ -7,19 +7,19 @@
import org.restlet.routing.Router;
public class BgpRouteWebRoutable implements RestletRoutable {
- @Override
- public Restlet getRestlet(Context context) {
- Router router = new Router(context);
- router.attach("/json", BgpRouteResource.class);
- router.attach("/rib/{dest}", BgpRouteResource.class);
- router.attach("/{sysuptime}/{sequence}/{routerid}/{prefix}/{mask}/{nexthop}", BgpRouteResource.class);
- router.attach("/{routerid}/{prefix}/{mask}/{nexthop}/synch", BgpRouteResourceSynch.class);
- router.attach("/{routerid}/{capability}", BgpRouteResource.class);
- return router;
- }
-
- @Override
- public String basePath() {
- return "/wm/bgp";
- }
+ @Override
+ public Restlet getRestlet(Context context) {
+ Router router = new Router(context);
+ router.attach("/json", BgpRouteResource.class);
+ router.attach("/rib/{dest}", BgpRouteResource.class);
+ router.attach("/{sysuptime}/{sequence}/{routerid}/{prefix}/{mask}/{nexthop}", BgpRouteResource.class);
+ router.attach("/{routerid}/{prefix}/{mask}/{nexthop}/synch", BgpRouteResourceSynch.class);
+ router.attach("/{routerid}/{capability}", BgpRouteResource.class);
+ return router;
+ }
+
+ @Override
+ public String basePath() {
+ return "/wm/bgp";
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/Configuration.java b/src/main/java/net/onrc/onos/apps/bgproute/Configuration.java
index 6f02fe3..314324d 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/Configuration.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/Configuration.java
@@ -9,79 +9,79 @@
import org.openflow.util.HexString;
public class Configuration {
- private long bgpdAttachmentDpid;
- private short bgpdAttachmentPort;
- private MACAddress bgpdMacAddress;
- private short vlan;
- private List<String> switches;
- private List<Interface> interfaces;
- private List<BgpPeer> peers;
-
- public Configuration() {
- // TODO Auto-generated constructor stub
- }
+ private long bgpdAttachmentDpid;
+ private short bgpdAttachmentPort;
+ private MACAddress bgpdMacAddress;
+ private short vlan;
+ private List<String> switches;
+ private List<Interface> interfaces;
+ private List<BgpPeer> peers;
- public long getBgpdAttachmentDpid() {
- return bgpdAttachmentDpid;
- }
+ public Configuration() {
+ // TODO Auto-generated constructor stub
+ }
- @JsonProperty("bgpdAttachmentDpid")
- public void setBgpdAttachmentDpid(String bgpdAttachmentDpid) {
- this.bgpdAttachmentDpid = HexString.toLong(bgpdAttachmentDpid);
- }
+ public long getBgpdAttachmentDpid() {
+ return bgpdAttachmentDpid;
+ }
- public short getBgpdAttachmentPort() {
- return bgpdAttachmentPort;
- }
+ @JsonProperty("bgpdAttachmentDpid")
+ public void setBgpdAttachmentDpid(String bgpdAttachmentDpid) {
+ this.bgpdAttachmentDpid = HexString.toLong(bgpdAttachmentDpid);
+ }
- @JsonProperty("bgpdAttachmentPort")
- public void setBgpdAttachmentPort(short bgpdAttachmentPort) {
- this.bgpdAttachmentPort = bgpdAttachmentPort;
- }
-
- public MACAddress getBgpdMacAddress() {
- return bgpdMacAddress;
- }
+ public short getBgpdAttachmentPort() {
+ return bgpdAttachmentPort;
+ }
- @JsonProperty("bgpdMacAddress")
- public void setBgpdMacAddress(String strMacAddress) {
- this.bgpdMacAddress = MACAddress.valueOf(strMacAddress);
- }
-
- public List<String> getSwitches() {
- return Collections.unmodifiableList(switches);
- }
-
- @JsonProperty("vlan")
- public void setVlan(short vlan) {
- this.vlan = vlan;
- }
-
- public short getVlan() {
- return vlan;
- }
+ @JsonProperty("bgpdAttachmentPort")
+ public void setBgpdAttachmentPort(short bgpdAttachmentPort) {
+ this.bgpdAttachmentPort = bgpdAttachmentPort;
+ }
- @JsonProperty("switches")
- public void setSwitches(List<String> switches) {
- this.switches = switches;
- }
-
- public List<Interface> getInterfaces() {
- return Collections.unmodifiableList(interfaces);
- }
+ public MACAddress getBgpdMacAddress() {
+ return bgpdMacAddress;
+ }
- @JsonProperty("interfaces")
- public void setInterfaces(List<Interface> interfaces) {
- this.interfaces = interfaces;
- }
-
- public List<BgpPeer> getPeers() {
- return Collections.unmodifiableList(peers);
- }
+ @JsonProperty("bgpdMacAddress")
+ public void setBgpdMacAddress(String strMacAddress) {
+ this.bgpdMacAddress = MACAddress.valueOf(strMacAddress);
+ }
- @JsonProperty("bgpPeers")
- public void setPeers(List<BgpPeer> peers) {
- this.peers = peers;
- }
+ public List<String> getSwitches() {
+ return Collections.unmodifiableList(switches);
+ }
+
+ @JsonProperty("vlan")
+ public void setVlan(short vlan) {
+ this.vlan = vlan;
+ }
+
+ public short getVlan() {
+ return vlan;
+ }
+
+ @JsonProperty("switches")
+ public void setSwitches(List<String> switches) {
+ this.switches = switches;
+ }
+
+ public List<Interface> getInterfaces() {
+ return Collections.unmodifiableList(interfaces);
+ }
+
+ @JsonProperty("interfaces")
+ public void setInterfaces(List<Interface> interfaces) {
+ this.interfaces = interfaces;
+ }
+
+ public List<BgpPeer> getPeers() {
+ return Collections.unmodifiableList(peers);
+ }
+
+ @JsonProperty("bgpPeers")
+ public void setPeers(List<BgpPeer> peers) {
+ this.peers = peers;
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/FlowCache.java b/src/main/java/net/onrc/onos/apps/bgproute/FlowCache.java
index 31bbc95..145224b 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/FlowCache.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/FlowCache.java
@@ -19,140 +19,138 @@
import org.slf4j.LoggerFactory;
public class FlowCache {
- private final static Logger log = LoggerFactory.getLogger(FlowCache.class);
-
- private IFloodlightProviderService floodlightProvider;
-
- private Map<Long, List<OFFlowMod>> flowCache;
-
- private Comparator<OFFlowMod> cookieComparator = new Comparator<OFFlowMod>() {
- @Override
- public int compare(OFFlowMod fm1, OFFlowMod fm2) {
- long difference = fm2.getCookie() - fm1.getCookie();
-
- if (difference > 0) {
- return 1;
- }
- else if (difference < 0) {
- return -1;
- }
- else {
- return 0;
- }
- }
- };
-
- public FlowCache(IFloodlightProviderService floodlightProvider) {
- this.floodlightProvider = floodlightProvider;
-
- flowCache = new HashMap<Long, List<OFFlowMod>>();
- }
+ private final static Logger log = LoggerFactory.getLogger(FlowCache.class);
- public synchronized void write(long dpid, OFFlowMod flowMod) {
- List<OFFlowMod> flowModList = new ArrayList<OFFlowMod>(1);
- flowModList.add(flowMod);
- write(dpid, flowModList);
- }
-
- public synchronized void write(long dpid, List<OFFlowMod> flowMods) {
- ensureCacheForSwitch(dpid);
-
- List<OFFlowMod> clones = new ArrayList<OFFlowMod>(flowMods.size());
-
- //Somehow the OFFlowMods we get passed in will change later on.
- //No idea how this happens, but we can just clone to prevent problems
- try {
- for (OFFlowMod fm : flowMods) {
- clones.add(fm.clone());
- }
- } catch (CloneNotSupportedException e) {
- log.debug("Clone exception", e);
- }
-
- flowCache.get(dpid).addAll(clones);
-
- IOFSwitch sw = floodlightProvider.getSwitches().get(dpid);
-
- if (sw == null) {
- log.debug("Switch not found when writing flow mods");
- return;
- }
+ private IFloodlightProviderService floodlightProvider;
- List<OFMessage> msgList = new ArrayList<OFMessage>(clones.size());
- msgList.addAll(clones);
-
- try {
- sw.write(msgList, null);
- } catch (IOException e) {
- log.error("Error writing to switch", e);
- }
-
+ private Map<Long, List<OFFlowMod>> flowCache;
- }
-
- public synchronized void delete(long dpid, OFFlowMod flowMod) {
- List<OFFlowMod> flowModList = new ArrayList<OFFlowMod>(1);
- flowModList.add(flowMod);
- delete(dpid, flowModList);
- }
-
- public synchronized void delete(long dpid, List<OFFlowMod> flowMods) {
- ensureCacheForSwitch(dpid);
-
- //Remove the flow mods from the cache first before we alter them
- flowCache.get(dpid).removeAll(flowMods);
-
- //Alter the original flow mods to make them delete flow mods
- for (OFFlowMod fm : flowMods) {
- fm.setCommand(OFFlowMod.OFPFC_DELETE_STRICT)
- .setOutPort(OFPort.OFPP_NONE)
- .setLengthU(OFFlowMod.MINIMUM_LENGTH);
-
- fm.getActions().clear();
- }
-
- IOFSwitch sw = floodlightProvider.getSwitches().get(dpid);
- if (sw == null) {
- log.debug("Switch not found when writing flow mods");
- return;
- }
-
- List<OFMessage> msgList = new ArrayList<OFMessage>(flowMods.size());
- msgList.addAll(flowMods);
-
- try {
- sw.write(msgList, null);
- } catch (IOException e) {
- log.error("Error writing to switch", e);
- }
- }
-
- //TODO can the Prontos handle being sent all flow mods in one message?
- public synchronized void switchConnected(IOFSwitch sw) {
- log.debug("Switch connected: {}", sw);
-
- ensureCacheForSwitch(sw.getId());
-
- List<OFFlowMod> flowMods = flowCache.get(sw.getId());
+ private Comparator<OFFlowMod> cookieComparator = new Comparator<OFFlowMod>() {
+ @Override
+ public int compare(OFFlowMod fm1, OFFlowMod fm2) {
+ long difference = fm2.getCookie() - fm1.getCookie();
- Collections.sort(flowMods, cookieComparator);
-
- sw.clearAllFlowMods();
-
- List<OFMessage> messages = new ArrayList<OFMessage>(flowMods.size());
- messages.addAll(flowMods);
-
- try {
- sw.write(messages, null);
- } catch (IOException e) {
- log.error("Failure writing flow mods to switch {}",
- HexString.toHexString(sw.getId()));
- }
- }
-
- private void ensureCacheForSwitch(long dpid) {
- if (!flowCache.containsKey(dpid)) {
- flowCache.put(dpid, new ArrayList<OFFlowMod>());
- }
- }
+ if (difference > 0) {
+ return 1;
+ } else if (difference < 0) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ };
+
+ public FlowCache(IFloodlightProviderService floodlightProvider) {
+ this.floodlightProvider = floodlightProvider;
+
+ flowCache = new HashMap<Long, List<OFFlowMod>>();
+ }
+
+ public synchronized void write(long dpid, OFFlowMod flowMod) {
+ List<OFFlowMod> flowModList = new ArrayList<OFFlowMod>(1);
+ flowModList.add(flowMod);
+ write(dpid, flowModList);
+ }
+
+ public synchronized void write(long dpid, List<OFFlowMod> flowMods) {
+ ensureCacheForSwitch(dpid);
+
+ List<OFFlowMod> clones = new ArrayList<OFFlowMod>(flowMods.size());
+
+ //Somehow the OFFlowMods we get passed in will change later on.
+ //No idea how this happens, but we can just clone to prevent problems
+ try {
+ for (OFFlowMod fm : flowMods) {
+ clones.add(fm.clone());
+ }
+ } catch (CloneNotSupportedException e) {
+ log.debug("Clone exception", e);
+ }
+
+ flowCache.get(dpid).addAll(clones);
+
+ IOFSwitch sw = floodlightProvider.getSwitches().get(dpid);
+
+ if (sw == null) {
+ log.debug("Switch not found when writing flow mods");
+ return;
+ }
+
+ List<OFMessage> msgList = new ArrayList<OFMessage>(clones.size());
+ msgList.addAll(clones);
+
+ try {
+ sw.write(msgList, null);
+ } catch (IOException e) {
+ log.error("Error writing to switch", e);
+ }
+
+
+ }
+
+ public synchronized void delete(long dpid, OFFlowMod flowMod) {
+ List<OFFlowMod> flowModList = new ArrayList<OFFlowMod>(1);
+ flowModList.add(flowMod);
+ delete(dpid, flowModList);
+ }
+
+ public synchronized void delete(long dpid, List<OFFlowMod> flowMods) {
+ ensureCacheForSwitch(dpid);
+
+ //Remove the flow mods from the cache first before we alter them
+ flowCache.get(dpid).removeAll(flowMods);
+
+ //Alter the original flow mods to make them delete flow mods
+ for (OFFlowMod fm : flowMods) {
+ fm.setCommand(OFFlowMod.OFPFC_DELETE_STRICT)
+ .setOutPort(OFPort.OFPP_NONE)
+ .setLengthU(OFFlowMod.MINIMUM_LENGTH);
+
+ fm.getActions().clear();
+ }
+
+ IOFSwitch sw = floodlightProvider.getSwitches().get(dpid);
+ if (sw == null) {
+ log.debug("Switch not found when writing flow mods");
+ return;
+ }
+
+ List<OFMessage> msgList = new ArrayList<OFMessage>(flowMods.size());
+ msgList.addAll(flowMods);
+
+ try {
+ sw.write(msgList, null);
+ } catch (IOException e) {
+ log.error("Error writing to switch", e);
+ }
+ }
+
+ //TODO can the Prontos handle being sent all flow mods in one message?
+ public synchronized void switchConnected(IOFSwitch sw) {
+ log.debug("Switch connected: {}", sw);
+
+ ensureCacheForSwitch(sw.getId());
+
+ List<OFFlowMod> flowMods = flowCache.get(sw.getId());
+
+ Collections.sort(flowMods, cookieComparator);
+
+ sw.clearAllFlowMods();
+
+ List<OFMessage> messages = new ArrayList<OFMessage>(flowMods.size());
+ messages.addAll(flowMods);
+
+ try {
+ sw.write(messages, null);
+ } catch (IOException e) {
+ log.error("Failure writing flow mods to switch {}",
+ HexString.toHexString(sw.getId()));
+ }
+ }
+
+ private void ensureCacheForSwitch(long dpid) {
+ if (!flowCache.containsKey(dpid)) {
+ flowCache.put(dpid, new ArrayList<OFFlowMod>());
+ }
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/IBgpRouteService.java b/src/main/java/net/onrc/onos/apps/bgproute/IBgpRouteService.java
index 56d5393..95b81bf 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/IBgpRouteService.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/IBgpRouteService.java
@@ -4,24 +4,25 @@
public interface IBgpRouteService extends IFloodlightService {
- //public RibEntry lookupRib(byte[] dest);
+ //public RibEntry lookupRib(byte[] dest);
- //public Ptree getPtree();
- public IPatriciaTrie<RibEntry> getPtree();
+ //public Ptree getPtree();
+ public IPatriciaTrie<RibEntry> getPtree();
- public String getBGPdRestIp();
+ public String getBGPdRestIp();
- public String getRouterId();
+ public String getRouterId();
- public void clearPtree();
-
- /**
- * Pass a RIB update to the {@link IBgpRouteService}
- * @param update
- */
- public void newRibUpdate(RibUpdate update);
-
- //TODO This functionality should be provided by some sort of Ptree listener framework
- //public void prefixAdded(PtreeNode node);
- //public void prefixDeleted(PtreeNode node);
+ public void clearPtree();
+
+ /**
+ * Pass a RIB update to the {@link IBgpRouteService}
+ *
+ * @param update
+ */
+ public void newRibUpdate(RibUpdate update);
+
+ //TODO This functionality should be provided by some sort of Ptree listener framework
+ //public void prefixAdded(PtreeNode node);
+ //public void prefixDeleted(PtreeNode node);
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/IPatriciaTrie.java b/src/main/java/net/onrc/onos/apps/bgproute/IPatriciaTrie.java
index 854b340..bd4508a 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/IPatriciaTrie.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/IPatriciaTrie.java
@@ -3,18 +3,19 @@
import java.util.Iterator;
public interface IPatriciaTrie<V> {
- public V put(Prefix prefix, V value);
-
- public V lookup(Prefix prefix);
-
- public V match(Prefix prefix);
-
- public boolean remove(Prefix prefix, V value);
-
- public Iterator<Entry<V>> iterator();
-
- interface Entry<V> {
- public Prefix getPrefix();
- public V getValue();
- }
+ public V put(Prefix prefix, V value);
+
+ public V lookup(Prefix prefix);
+
+ public V match(Prefix prefix);
+
+ public boolean remove(Prefix prefix, V value);
+
+ public Iterator<Entry<V>> iterator();
+
+ interface Entry<V> {
+ public Prefix getPrefix();
+
+ public V getValue();
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/Interface.java b/src/main/java/net/onrc/onos/apps/bgproute/Interface.java
index b5c762d..52e9a32 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/Interface.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/Interface.java
@@ -13,75 +13,75 @@
import com.google.common.net.InetAddresses;
public class Interface {
- private final String name;
- private final long dpid;
- private final short port;
- private final InetAddress ipAddress;
- private final int prefixLength;
-
- @JsonCreator
- public Interface (@JsonProperty("name") String name,
- @JsonProperty("dpid") String dpid,
- @JsonProperty("port") short port,
- @JsonProperty("ipAddress") String ipAddress,
- @JsonProperty("prefixLength") int prefixLength) {
- this.name = name;
- this.dpid = HexString.toLong(dpid);
- this.port = port;
- this.ipAddress = InetAddresses.forString(ipAddress);
- this.prefixLength = prefixLength;
- }
-
- public String getName() {
- return name;
- }
+ private final String name;
+ private final long dpid;
+ private final short port;
+ private final InetAddress ipAddress;
+ private final int prefixLength;
- public SwitchPort getSwitchPort() {
- //TODO SwitchPort, Dpid and Port are mutable, but they could probably
- //be made immutable which would prevent the need to copy
- return new SwitchPort(new Dpid(dpid), new Port(port));
- }
-
- public long getDpid() {
- return dpid;
- }
+ @JsonCreator
+ public Interface(@JsonProperty("name") String name,
+ @JsonProperty("dpid") String dpid,
+ @JsonProperty("port") short port,
+ @JsonProperty("ipAddress") String ipAddress,
+ @JsonProperty("prefixLength") int prefixLength) {
+ this.name = name;
+ this.dpid = HexString.toLong(dpid);
+ this.port = port;
+ this.ipAddress = InetAddresses.forString(ipAddress);
+ this.prefixLength = prefixLength;
+ }
- public short getPort() {
- return port;
- }
+ public String getName() {
+ return name;
+ }
- public InetAddress getIpAddress() {
- return ipAddress;
- }
+ public SwitchPort getSwitchPort() {
+ //TODO SwitchPort, Dpid and Port are mutable, but they could probably
+ //be made immutable which would prevent the need to copy
+ return new SwitchPort(new Dpid(dpid), new Port(port));
+ }
- public int getPrefixLength() {
- return prefixLength;
- }
-
- @Override
- public boolean equals(Object other) {
- if (other == null || !(other instanceof Interface)) {
- return false;
- }
-
- Interface otherInterface = (Interface)other;
-
- //Don't check switchPort as it's comprised of dpid and port
- return (name.equals(otherInterface.name)) &&
- (dpid == otherInterface.dpid) &&
- (port == otherInterface.port) &&
- (ipAddress.equals(otherInterface.ipAddress)) &&
- (prefixLength == otherInterface.prefixLength);
- }
-
- @Override
- public int hashCode() {
- int hash = 17;
- hash = 31 * hash + name.hashCode();
- hash = 31 * hash + (int)(dpid ^ dpid >>> 32);
- hash = 31 * hash + (int)port;
- hash = 31 * hash + ipAddress.hashCode();
- hash = 31 * hash + prefixLength;
- return hash;
- }
+ public long getDpid() {
+ return dpid;
+ }
+
+ public short getPort() {
+ return port;
+ }
+
+ public InetAddress getIpAddress() {
+ return ipAddress;
+ }
+
+ public int getPrefixLength() {
+ return prefixLength;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (other == null || !(other instanceof Interface)) {
+ return false;
+ }
+
+ Interface otherInterface = (Interface) other;
+
+ //Don't check switchPort as it's comprised of dpid and port
+ return (name.equals(otherInterface.name)) &&
+ (dpid == otherInterface.dpid) &&
+ (port == otherInterface.port) &&
+ (ipAddress.equals(otherInterface.ipAddress)) &&
+ (prefixLength == otherInterface.prefixLength);
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 17;
+ hash = 31 * hash + name.hashCode();
+ hash = 31 * hash + (int) (dpid ^ dpid >>> 32);
+ hash = 31 * hash + (int) port;
+ hash = 31 * hash + ipAddress.hashCode();
+ hash = 31 * hash + prefixLength;
+ return hash;
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/Path.java b/src/main/java/net/onrc/onos/apps/bgproute/Path.java
index cd0b1b6..3ecf7c7 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/Path.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/Path.java
@@ -11,51 +11,51 @@
public class Path {
- private Interface dstInterface;
- private InetAddress dstIpAddress;
- private int numUsers = 0;
-
- private List<PushedFlowMod> flowMods = null;
- private boolean permanent = false;
-
- public Path(Interface dstInterface, InetAddress dstIpAddress) {
- this.dstInterface = dstInterface;
- this.dstIpAddress = dstIpAddress;
- }
+ private Interface dstInterface;
+ private InetAddress dstIpAddress;
+ private int numUsers = 0;
- public Interface getDstInterface() {
- return dstInterface;
- }
+ private List<PushedFlowMod> flowMods = null;
+ private boolean permanent = false;
- public InetAddress getDstIpAddress() {
- return dstIpAddress;
- }
-
- public void incrementUsers() {
- numUsers++;
- }
-
- public void decrementUsers() {
- numUsers--;
- }
-
- public int getUsers() {
- return numUsers;
- }
-
- public List<PushedFlowMod> getFlowMods() {
- return Collections.unmodifiableList(flowMods);
- }
-
- public void setFlowMods(List<PushedFlowMod> flowMods) {
- this.flowMods = flowMods;
- }
-
- public boolean isPermanent() {
- return permanent;
- }
-
- public void setPermanent() {
- permanent = true;
- }
+ public Path(Interface dstInterface, InetAddress dstIpAddress) {
+ this.dstInterface = dstInterface;
+ this.dstIpAddress = dstIpAddress;
+ }
+
+ public Interface getDstInterface() {
+ return dstInterface;
+ }
+
+ public InetAddress getDstIpAddress() {
+ return dstIpAddress;
+ }
+
+ public void incrementUsers() {
+ numUsers++;
+ }
+
+ public void decrementUsers() {
+ numUsers--;
+ }
+
+ public int getUsers() {
+ return numUsers;
+ }
+
+ public List<PushedFlowMod> getFlowMods() {
+ return Collections.unmodifiableList(flowMods);
+ }
+
+ public void setFlowMods(List<PushedFlowMod> flowMods) {
+ this.flowMods = flowMods;
+ }
+
+ public boolean isPermanent() {
+ return permanent;
+ }
+
+ public void setPermanent() {
+ permanent = true;
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/PatriciaTrie.java b/src/main/java/net/onrc/onos/apps/bgproute/PatriciaTrie.java
index 9badd11..8225d7d 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/PatriciaTrie.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/PatriciaTrie.java
@@ -4,503 +4,500 @@
import java.util.NoSuchElementException;
public class PatriciaTrie<V> implements IPatriciaTrie<V> {
- private final byte maskBits[] = {(byte)0x00, (byte)0x80, (byte)0xc0, (byte)0xe0, (byte)0xf0,
- (byte)0xf8, (byte)0xfc, (byte)0xfe, (byte)0xff};
-
- private int maxPrefixLength;
-
- private Node top;
+ private final byte maskBits[] = {(byte) 0x00, (byte) 0x80, (byte) 0xc0, (byte) 0xe0, (byte) 0xf0,
+ (byte) 0xf8, (byte) 0xfc, (byte) 0xfe, (byte) 0xff};
- public PatriciaTrie(int maxPrefixLength) {
- this.maxPrefixLength = maxPrefixLength;
- }
+ private int maxPrefixLength;
- @Override
- public synchronized V put(Prefix prefix, V value) {
- if (prefix == null || value == null) {
- throw new NullPointerException();
- }
-
- if (prefix.getPrefixLength() > maxPrefixLength) {
- throw new IllegalArgumentException(String.format(
- "Prefix length %d is greater than max prefix length %d",
- prefix.getPrefixLength(), maxPrefixLength));
- }
-
- Node node = top;
- Node match = null;
-
- while (node != null
- && node.prefix.getPrefixLength() <= prefix.getPrefixLength()
- && key_match(node.prefix.getAddress(), node.prefix.getPrefixLength(), prefix.getAddress(), prefix.getPrefixLength()) == true) {
- if (node.prefix.getPrefixLength() == prefix.getPrefixLength()) {
- /*
- * Prefix is already in tree. This may be an aggregate node, in which case
- * we are inserting a new prefix, or it could be an actual node, in which
- * case we are inserting a new nexthop for the prefix and should return
- * the old nexthop.
- */
- V oldValue = node.value;
- node.value = value;
- return oldValue;
- }
+ private Node top;
- match = node;
-
- if (bit_check(prefix.getAddress(), node.prefix.getPrefixLength()) == true) {
- node = node.right;
- } else {
- node = node.left;
- }
- }
+ public PatriciaTrie(int maxPrefixLength) {
+ this.maxPrefixLength = maxPrefixLength;
+ }
- Node add = null;
-
- if (node == null) {
- //add = new Node(p, r);
- add = new Node(prefix);
- add.value = value;
-
- if (match != null) {
- node_link(match, add);
- } else {
- top = add;
- }
- } else {
- add = node_common(node, prefix.getAddress(), prefix.getPrefixLength());
- if (add == null) {
- //I think this is -ENOMEM?
- //return null;
- }
-
- if (match != null) {
- node_link(match, add);
- } else {
- top = add;
- }
- node_link(add, node);
-
- if (add.prefix.getPrefixLength() != prefix.getPrefixLength()) {
- match = add;
-
- //add = new Node(p, r);
- add = new Node(prefix);
- add.value = value;
- node_link(match, add);
- }
- else {
- add.value = value;
- }
- }
-
- //If we added a new Node, there was no previous mapping
- return null;
- //return addReference(add);
- }
-
- /*exact match*/
- @Override
- public synchronized V lookup(Prefix prefix) {
- if (prefix.getPrefixLength() > maxPrefixLength) {
- return null;
- }
-
- /*
- Node node = top;
-
- while (node != null
- && node.prefix.getPrefixLength() <= p.getPrefixLength()
- && key_match(node.prefix.getAddress(), node.prefix.getPrefixLength(), p.getAddress(), p.getPrefixLength()) == true) {
- if (node.prefix.getPrefixLength() == p.getPrefixLength()) {
- //return addReference(node);
- return node.rib;
- }
-
- if (bit_check(p.getAddress(), node.prefix.getPrefixLength()) == true) {
- node = node.right;
- } else {
- node = node.left;
- }
- }
- */
-
- Node node = findNode(prefix);
-
- return node == null ? null : node.value;
- }
-
- /*closest containing prefix*/
- @Override
- public synchronized V match(Prefix prefix) {
- //TODO
- if (prefix.getPrefixLength() > maxPrefixLength) {
- return null;
- }
-
- Node closestNode = findClosestNode(prefix);
-
- return closestNode == null ? null : closestNode.value;
- }
-
- @Override
- public synchronized boolean remove(Prefix prefix, V value) {
- Node child;
- Node parent;
-
- if (prefix == null || value == null) {
- return false;
- }
-
- Node node = findNode(prefix);
-
- if (node == null || node.isAggregate() || !node.value.equals(value)) {
- //Given <prefix, nexthop> mapping is not in the tree
- return false;
- }
-
- if (node.left != null && node.right != null) {
- //Remove the RibEntry entry and leave this node as an aggregate node
- //In the future, maybe we should re-evaluate what the aggregate prefix should be?
- //It shouldn't necessarily stay the same.
- //More complicated if the above prefix is also aggregate.
- node.value = null;
- return true;
- }
-
- if (node.left != null) {
- child = node.left;
- } else {
- child = node.right;
- }
-
- parent = node.parent;
-
- if (child != null) {
- child.parent = parent;
- }
-
- if (parent != null) {
- if (parent.left == node) {
- parent.left = child;
- } else {
- parent.right = child;
- }
- } else {
- top = child;
- }
-
- /*
- * TODO not sure what to do here. I think this is lazily deleting aggregate nodes,
- * notice that it used to do nothing if it detected both children were not null earlier.
- * But here, what we really should do is reevaluate the aggregate prefix of the parent
- * node (if it is indeed an aggregate). Because at the moment, no aggregate node will ever
- * be removed. BUT, I don't actually think this presents a correctness problem, at
- * least from an external point of view.
- */
- //if (parent != null && parent.refCount == 0) {
- //node_remove(parent);
- //}
-
- return true;
- }
-
- @Override
- public Iterator<Entry<V>> iterator() {
- return new PatriciaTrieIterator(top);
- }
-
- private Node findNode(Prefix prefix) {
- Node node = top;
-
- while (node != null
- && node.prefix.getPrefixLength() <= prefix.getPrefixLength()
- && key_match(node.prefix.getAddress(), node.prefix.getPrefixLength(), prefix.getAddress(), prefix.getPrefixLength()) == true) {
- if (node.prefix.getPrefixLength() == prefix.getPrefixLength()) {
- //return addReference(node);
- return node;
- }
-
- if (bit_check(prefix.getAddress(), node.prefix.getPrefixLength()) == true) {
- node = node.right;
- } else {
- node = node.left;
- }
- }
-
- return null;
- }
-
- private Node findClosestNode(Prefix prefix) {
- Node node = top;
- Node match = null;
-
- while (node != null
- && node.prefix.getPrefixLength() <= prefix.getPrefixLength()
- && key_match(node.prefix.getAddress(), node.prefix.getPrefixLength(), prefix.getAddress(), prefix.getPrefixLength()) == true) {
- if (!node.isAggregate()) {
- match = node;
- }
-
- if (bit_check(prefix.getAddress(), node.prefix.getPrefixLength()) == true) {
- node = node.right;
- } else {
- node = node.left;
- }
- }
-
- return match;
- }
-
- /*
- * Receives a 1-based bit index
- * Returns a 1-based byte index
- * eg. (0 => 1), 1 => 1, 8 => 1, 9 => 2, 17 => 3
- */
- private int getByteContainingBit(int bitNumber) {
- return Math.max((bitNumber + 7) / 8, 1);
- }
-
- private boolean key_match(byte [] key1, int key1_len, byte [] key2, int key2_len) {
- //int offset;
- //int shift;
-
- if (key1_len > key2_len) {
- return false;
- }
-
- int offset = (Math.min(key1_len, key2_len)) / 8;
- int shift = (Math.min(key1_len, key2_len)) % 8;
-
- if (shift != 0) {
- if ((maskBits[shift] & (key1[offset] ^ key2[offset])) != 0) {
- return false;
- }
- }
-
- while (offset != 0) {
- offset--;
- if (key1[offset] != key2[offset]) {
- return false;
- }
- }
- return true;
- }
-
- private boolean bit_check(byte [] key, int key_bits) {
- int offset = key_bits / 8;
- int shift = 7 - (key_bits % 8);
- int bit = key[offset] & 0xff;
+ @Override
+ public synchronized V put(Prefix prefix, V value) {
+ if (prefix == null || value == null) {
+ throw new NullPointerException();
+ }
- bit >>= shift;
-
- if ((bit & 1) == 1) {
- return true;
- } else {
- return false;
- }
- }
-
- private void node_link(Node node, Node add) {
- boolean bit = bit_check(add.prefix.getAddress(), node.prefix.getPrefixLength());
-
- if (bit == true) {
- node.right = add;
- } else {
- node.left = add;
- }
- add.parent = node;
- }
-
- private Node node_common(Node node, byte [] key, int key_bits) {
- int i;
- int limit = Math.min(node.prefix.getPrefixLength(), key_bits) / 8;
+ if (prefix.getPrefixLength() > maxPrefixLength) {
+ throw new IllegalArgumentException(String.format(
+ "Prefix length %d is greater than max prefix length %d",
+ prefix.getPrefixLength(), maxPrefixLength));
+ }
- for (i = 0; i < limit; i++) {
- if (node.prefix.getAddress()[i] != key[i]) {
- break;
- }
- }
-
- int common_len = i * 8;
- int boundary = 0;
+ Node node = top;
+ Node match = null;
- if (common_len != key_bits) {
- byte diff = (byte)(node.prefix.getAddress()[i] ^ key[i]);
- byte mask = (byte)0x80;
- int shift_mask = 0;
-
- while (common_len < key_bits && ((mask & diff) == 0)) {
- boundary = 1;
+ while (node != null
+ && node.prefix.getPrefixLength() <= prefix.getPrefixLength()
+ && key_match(node.prefix.getAddress(), node.prefix.getPrefixLength(), prefix.getAddress(), prefix.getPrefixLength()) == true) {
+ if (node.prefix.getPrefixLength() == prefix.getPrefixLength()) {
+ /*
+ * Prefix is already in tree. This may be an aggregate node, in which case
+ * we are inserting a new prefix, or it could be an actual node, in which
+ * case we are inserting a new nexthop for the prefix and should return
+ * the old nexthop.
+ */
+ V oldValue = node.value;
+ node.value = value;
+ return oldValue;
+ }
- shift_mask = (mask & 0xff);
- shift_mask >>= 1;
- mask = (byte)shift_mask;
+ match = node;
- common_len++;
- }
- }
-
- //Node add = new Node(null, common_len, maxKeyOctets);
- //if (add == null)
- //Another -ENOMEM;
- //return null;
-
- //Creating a new Prefix with a prefix length of common_len
- //Bits are copied from node's up until the common_len'th bit
- //RibEntry is null, because this is an aggregate prefix - it's not
- //actually been added to the trie.
-
- byte[] newPrefix = new byte[getByteContainingBit(maxPrefixLength)];
-
- int j;
- for (j = 0; j < i; j++)
- newPrefix[j] = node.prefix.getAddress()[j];
+ if (bit_check(prefix.getAddress(), node.prefix.getPrefixLength()) == true) {
+ node = node.right;
+ } else {
+ node = node.left;
+ }
+ }
- if (boundary != 0)
- newPrefix[j] = (byte)(node.prefix.getAddress()[j] & maskBits[common_len % 8]);
-
- //return new Node(new Prefix(newPrefix, common_len), null);
- return new Node(new Prefix(newPrefix, common_len));
- //return add;
- }
-
- private class Node {
- public Node parent = null;
- public Node left = null;
- public Node right = null;
-
- public final Prefix prefix;
- public V value;
-
- //public Node(Prefix p, RibEntry r) {
- // this.prefix = p;
- // this.rib = r;
- //}
- public Node(Prefix p) {
- this.prefix = p;
- }
-
- public boolean isAggregate() {
- return value == null;
- }
-
- public Entry<V> getEntry() {
- return new PatriciaTrieEntry(prefix, value);
- }
- }
-
- private class PatriciaTrieEntry implements Entry<V> {
- private Prefix prefix;
- private V value;
-
- public PatriciaTrieEntry(Prefix prefix, V value) {
- this.prefix = prefix;
- this.value = value;
- }
-
- @Override
- public Prefix getPrefix() {
- return prefix;
- }
-
- @Override
- public V getValue() {
- return value;
- }
- }
-
- private class PatriciaTrieIterator implements Iterator<Entry<V>> {
-
- private Node current;
- private boolean started = false;
-
- public PatriciaTrieIterator(Node start) {
- current = start;
-
- //If the start is an aggregate node fast forward to find the next valid node
- if (current != null && current.isAggregate()) {
- current = findNext(current);
- }
- }
+ Node add = null;
- @Override
- public boolean hasNext() {
- if (current == null) {
- return false;
- }
-
- if (!started) {
- return true;
- }
-
- return findNext(current) != null;
- }
+ if (node == null) {
+ //add = new Node(p, r);
+ add = new Node(prefix);
+ add.value = value;
- @Override
- public Entry<V> next() {
- if (current == null) {
- throw new NoSuchElementException();
- }
-
- if (!started) {
- started = true;
- return current.getEntry();
- }
-
- current = findNext(current);
- if (current == null) {
- throw new NoSuchElementException();
- }
-
- return current.getEntry();
- }
+ if (match != null) {
+ node_link(match, add);
+ } else {
+ top = add;
+ }
+ } else {
+ add = node_common(node, prefix.getAddress(), prefix.getPrefixLength());
+ if (add == null) {
+ //I think this is -ENOMEM?
+ //return null;
+ }
- @Override
- public void remove() {
- // TODO This could be implemented, if it were needed
- throw new NoSuchElementException();
- }
-
- private Node findNext(Node node) {
- Node next = null;
-
- if (node.left != null) {
- next = node.left;
- //addReference(next);
- //delReference(node);
- //return next;
- }
- else if (node.right != null) {
- next = node.right;
- //addReference(next);
- //delReference(node);
- //return next;
- }
- else {
- //Node start = node;
- while (node.parent != null) {
- if (node.parent.left == node && node.parent.right != null) {
- next = node.parent.right;
- //addReference(next);
- //delReference(start);
- //return next;
- break;
- }
- node = node.parent;
- }
- }
-
- if (next == null) {
- return null;
- }
-
- //If the node doesn't have a value, it's not an actual node, it's an artifically
- //inserted aggregate node. We don't want to return these to the user.
- if (next.isAggregate()) {
- return findNext(next);
- }
-
- return next;
- }
- }
+ if (match != null) {
+ node_link(match, add);
+ } else {
+ top = add;
+ }
+ node_link(add, node);
+
+ if (add.prefix.getPrefixLength() != prefix.getPrefixLength()) {
+ match = add;
+
+ //add = new Node(p, r);
+ add = new Node(prefix);
+ add.value = value;
+ node_link(match, add);
+ } else {
+ add.value = value;
+ }
+ }
+
+ //If we added a new Node, there was no previous mapping
+ return null;
+ //return addReference(add);
+ }
+
+ /*exact match*/
+ @Override
+ public synchronized V lookup(Prefix prefix) {
+ if (prefix.getPrefixLength() > maxPrefixLength) {
+ return null;
+ }
+
+ /*
+ Node node = top;
+
+ while (node != null
+ && node.prefix.getPrefixLength() <= p.getPrefixLength()
+ && key_match(node.prefix.getAddress(), node.prefix.getPrefixLength(), p.getAddress(), p.getPrefixLength()) == true) {
+ if (node.prefix.getPrefixLength() == p.getPrefixLength()) {
+ //return addReference(node);
+ return node.rib;
+ }
+
+ if (bit_check(p.getAddress(), node.prefix.getPrefixLength()) == true) {
+ node = node.right;
+ } else {
+ node = node.left;
+ }
+ }
+ */
+
+ Node node = findNode(prefix);
+
+ return node == null ? null : node.value;
+ }
+
+ /*closest containing prefix*/
+ @Override
+ public synchronized V match(Prefix prefix) {
+ //TODO
+ if (prefix.getPrefixLength() > maxPrefixLength) {
+ return null;
+ }
+
+ Node closestNode = findClosestNode(prefix);
+
+ return closestNode == null ? null : closestNode.value;
+ }
+
+ @Override
+ public synchronized boolean remove(Prefix prefix, V value) {
+ Node child;
+ Node parent;
+
+ if (prefix == null || value == null) {
+ return false;
+ }
+
+ Node node = findNode(prefix);
+
+ if (node == null || node.isAggregate() || !node.value.equals(value)) {
+ //Given <prefix, nexthop> mapping is not in the tree
+ return false;
+ }
+
+ if (node.left != null && node.right != null) {
+ //Remove the RibEntry entry and leave this node as an aggregate node
+ //In the future, maybe we should re-evaluate what the aggregate prefix should be?
+ //It shouldn't necessarily stay the same.
+ //More complicated if the above prefix is also aggregate.
+ node.value = null;
+ return true;
+ }
+
+ if (node.left != null) {
+ child = node.left;
+ } else {
+ child = node.right;
+ }
+
+ parent = node.parent;
+
+ if (child != null) {
+ child.parent = parent;
+ }
+
+ if (parent != null) {
+ if (parent.left == node) {
+ parent.left = child;
+ } else {
+ parent.right = child;
+ }
+ } else {
+ top = child;
+ }
+
+ /*
+ * TODO not sure what to do here. I think this is lazily deleting aggregate nodes,
+ * notice that it used to do nothing if it detected both children were not null earlier.
+ * But here, what we really should do is reevaluate the aggregate prefix of the parent
+ * node (if it is indeed an aggregate). Because at the moment, no aggregate node will ever
+ * be removed. BUT, I don't actually think this presents a correctness problem, at
+ * least from an external point of view.
+ */
+ //if (parent != null && parent.refCount == 0) {
+ //node_remove(parent);
+ //}
+
+ return true;
+ }
+
+ @Override
+ public Iterator<Entry<V>> iterator() {
+ return new PatriciaTrieIterator(top);
+ }
+
+ private Node findNode(Prefix prefix) {
+ Node node = top;
+
+ while (node != null
+ && node.prefix.getPrefixLength() <= prefix.getPrefixLength()
+ && key_match(node.prefix.getAddress(), node.prefix.getPrefixLength(), prefix.getAddress(), prefix.getPrefixLength()) == true) {
+ if (node.prefix.getPrefixLength() == prefix.getPrefixLength()) {
+ //return addReference(node);
+ return node;
+ }
+
+ if (bit_check(prefix.getAddress(), node.prefix.getPrefixLength()) == true) {
+ node = node.right;
+ } else {
+ node = node.left;
+ }
+ }
+
+ return null;
+ }
+
+ private Node findClosestNode(Prefix prefix) {
+ Node node = top;
+ Node match = null;
+
+ while (node != null
+ && node.prefix.getPrefixLength() <= prefix.getPrefixLength()
+ && key_match(node.prefix.getAddress(), node.prefix.getPrefixLength(), prefix.getAddress(), prefix.getPrefixLength()) == true) {
+ if (!node.isAggregate()) {
+ match = node;
+ }
+
+ if (bit_check(prefix.getAddress(), node.prefix.getPrefixLength()) == true) {
+ node = node.right;
+ } else {
+ node = node.left;
+ }
+ }
+
+ return match;
+ }
+
+ /*
+ * Receives a 1-based bit index
+ * Returns a 1-based byte index
+ * eg. (0 => 1), 1 => 1, 8 => 1, 9 => 2, 17 => 3
+ */
+ private int getByteContainingBit(int bitNumber) {
+ return Math.max((bitNumber + 7) / 8, 1);
+ }
+
+ private boolean key_match(byte[] key1, int key1_len, byte[] key2, int key2_len) {
+ //int offset;
+ //int shift;
+
+ if (key1_len > key2_len) {
+ return false;
+ }
+
+ int offset = (Math.min(key1_len, key2_len)) / 8;
+ int shift = (Math.min(key1_len, key2_len)) % 8;
+
+ if (shift != 0) {
+ if ((maskBits[shift] & (key1[offset] ^ key2[offset])) != 0) {
+ return false;
+ }
+ }
+
+ while (offset != 0) {
+ offset--;
+ if (key1[offset] != key2[offset]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean bit_check(byte[] key, int key_bits) {
+ int offset = key_bits / 8;
+ int shift = 7 - (key_bits % 8);
+ int bit = key[offset] & 0xff;
+
+ bit >>= shift;
+
+ if ((bit & 1) == 1) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ private void node_link(Node node, Node add) {
+ boolean bit = bit_check(add.prefix.getAddress(), node.prefix.getPrefixLength());
+
+ if (bit == true) {
+ node.right = add;
+ } else {
+ node.left = add;
+ }
+ add.parent = node;
+ }
+
+ private Node node_common(Node node, byte[] key, int key_bits) {
+ int i;
+ int limit = Math.min(node.prefix.getPrefixLength(), key_bits) / 8;
+
+ for (i = 0; i < limit; i++) {
+ if (node.prefix.getAddress()[i] != key[i]) {
+ break;
+ }
+ }
+
+ int common_len = i * 8;
+ int boundary = 0;
+
+ if (common_len != key_bits) {
+ byte diff = (byte) (node.prefix.getAddress()[i] ^ key[i]);
+ byte mask = (byte) 0x80;
+ int shift_mask = 0;
+
+ while (common_len < key_bits && ((mask & diff) == 0)) {
+ boundary = 1;
+
+ shift_mask = (mask & 0xff);
+ shift_mask >>= 1;
+ mask = (byte) shift_mask;
+
+ common_len++;
+ }
+ }
+
+ //Node add = new Node(null, common_len, maxKeyOctets);
+ //if (add == null)
+ //Another -ENOMEM;
+ //return null;
+
+ //Creating a new Prefix with a prefix length of common_len
+ //Bits are copied from node's up until the common_len'th bit
+ //RibEntry is null, because this is an aggregate prefix - it's not
+ //actually been added to the trie.
+
+ byte[] newPrefix = new byte[getByteContainingBit(maxPrefixLength)];
+
+ int j;
+ for (j = 0; j < i; j++)
+ newPrefix[j] = node.prefix.getAddress()[j];
+
+ if (boundary != 0)
+ newPrefix[j] = (byte) (node.prefix.getAddress()[j] & maskBits[common_len % 8]);
+
+ //return new Node(new Prefix(newPrefix, common_len), null);
+ return new Node(new Prefix(newPrefix, common_len));
+ //return add;
+ }
+
+ private class Node {
+ public Node parent = null;
+ public Node left = null;
+ public Node right = null;
+
+ public final Prefix prefix;
+ public V value;
+
+ //public Node(Prefix p, RibEntry r) {
+ // this.prefix = p;
+ // this.rib = r;
+ //}
+ public Node(Prefix p) {
+ this.prefix = p;
+ }
+
+ public boolean isAggregate() {
+ return value == null;
+ }
+
+ public Entry<V> getEntry() {
+ return new PatriciaTrieEntry(prefix, value);
+ }
+ }
+
+ private class PatriciaTrieEntry implements Entry<V> {
+ private Prefix prefix;
+ private V value;
+
+ public PatriciaTrieEntry(Prefix prefix, V value) {
+ this.prefix = prefix;
+ this.value = value;
+ }
+
+ @Override
+ public Prefix getPrefix() {
+ return prefix;
+ }
+
+ @Override
+ public V getValue() {
+ return value;
+ }
+ }
+
+ private class PatriciaTrieIterator implements Iterator<Entry<V>> {
+
+ private Node current;
+ private boolean started = false;
+
+ public PatriciaTrieIterator(Node start) {
+ current = start;
+
+ //If the start is an aggregate node fast forward to find the next valid node
+ if (current != null && current.isAggregate()) {
+ current = findNext(current);
+ }
+ }
+
+ @Override
+ public boolean hasNext() {
+ if (current == null) {
+ return false;
+ }
+
+ if (!started) {
+ return true;
+ }
+
+ return findNext(current) != null;
+ }
+
+ @Override
+ public Entry<V> next() {
+ if (current == null) {
+ throw new NoSuchElementException();
+ }
+
+ if (!started) {
+ started = true;
+ return current.getEntry();
+ }
+
+ current = findNext(current);
+ if (current == null) {
+ throw new NoSuchElementException();
+ }
+
+ return current.getEntry();
+ }
+
+ @Override
+ public void remove() {
+ // TODO This could be implemented, if it were needed
+ throw new NoSuchElementException();
+ }
+
+ private Node findNext(Node node) {
+ Node next = null;
+
+ if (node.left != null) {
+ next = node.left;
+ //addReference(next);
+ //delReference(node);
+ //return next;
+ } else if (node.right != null) {
+ next = node.right;
+ //addReference(next);
+ //delReference(node);
+ //return next;
+ } else {
+ //Node start = node;
+ while (node.parent != null) {
+ if (node.parent.left == node && node.parent.right != null) {
+ next = node.parent.right;
+ //addReference(next);
+ //delReference(start);
+ //return next;
+ break;
+ }
+ node = node.parent;
+ }
+ }
+
+ if (next == null) {
+ return null;
+ }
+
+ //If the node doesn't have a value, it's not an actual node, it's an artifically
+ //inserted aggregate node. We don't want to return these to the user.
+ if (next.isAggregate()) {
+ return findNext(next);
+ }
+
+ return next;
+ }
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/Prefix.java b/src/main/java/net/onrc/onos/apps/bgproute/Prefix.java
index 8539759..5e5ba91 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/Prefix.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/Prefix.java
@@ -7,129 +7,129 @@
import com.google.common.net.InetAddresses;
public class Prefix {
- private final int MAX_BYTES = 4;
-
- private final int prefixLength;
- private final byte[] address;
-
- //For verifying the arguments and pretty printing
- private final InetAddress inetAddress;
-
- public Prefix(byte[] addr, int prefixLength) {
- if (addr == null || addr.length != MAX_BYTES ||
- prefixLength < 0 || prefixLength > MAX_BYTES * Byte.SIZE) {
- throw new IllegalArgumentException();
- }
+ private final int MAX_BYTES = 4;
- address = canonicalizeAddress(addr, prefixLength);
- this.prefixLength = prefixLength;
-
- try {
- inetAddress = InetAddress.getByAddress(address);
- } catch (UnknownHostException e) {
- throw new IllegalArgumentException();
- }
- }
+ private final int prefixLength;
+ private final byte[] address;
- public Prefix(String strAddress, int prefixLength) {
- byte[] addr = null;
- addr = InetAddresses.forString(strAddress).getAddress();
-
- if (addr == null || addr.length != MAX_BYTES ||
- prefixLength < 0 || prefixLength > MAX_BYTES * Byte.SIZE) {
- throw new IllegalArgumentException();
- }
-
- address = canonicalizeAddress(addr, prefixLength);
- this.prefixLength = prefixLength;
-
- try {
- inetAddress = InetAddress.getByAddress(address);
- } catch (UnknownHostException e) {
- throw new IllegalArgumentException();
- }
- }
-
- private byte[] canonicalizeAddress(byte[] address, int prefixLength) {
- byte[] result = new byte[address.length];
-
- if (prefixLength == 0) {
- for (int i = 0; i < MAX_BYTES; i++) {
- result[i] = 0;
- }
-
- return result;
- }
-
- result = Arrays.copyOf(address, address.length);
-
- //Set all bytes after the end of the prefix to 0
- int lastByteIndex = (prefixLength - 1) / Byte.SIZE;
- for (int i = lastByteIndex; i < MAX_BYTES; i++) {
- result[i] = 0;
- }
-
- byte lastByte = address[lastByteIndex];
- byte mask = 0;
- byte msb = (byte) 0x80;
- int lastBit = (prefixLength - 1) % Byte.SIZE;
- for (int i = 0; i < Byte.SIZE; i++) {
- if (i <= lastBit) {
- mask |= (msb >> i);
- }
- }
+ //For verifying the arguments and pretty printing
+ private final InetAddress inetAddress;
- result[lastByteIndex] = (byte) (lastByte & mask);
-
- return result;
- }
+ public Prefix(byte[] addr, int prefixLength) {
+ if (addr == null || addr.length != MAX_BYTES ||
+ prefixLength < 0 || prefixLength > MAX_BYTES * Byte.SIZE) {
+ throw new IllegalArgumentException();
+ }
- public int getPrefixLength() {
- return prefixLength;
- }
-
- public byte[] getAddress() {
- return address;
- }
-
- @Override
- public boolean equals(Object other) {
- if (other == null || !(other instanceof Prefix)) {
- return false;
- }
-
- Prefix otherPrefix = (Prefix) other;
-
- return (Arrays.equals(address, otherPrefix.address)) &&
- (prefixLength == otherPrefix.prefixLength);
- }
-
- @Override
- public int hashCode() {
- int hash = 17;
- hash = 31 * hash + prefixLength;
- hash = 31 * hash + Arrays.hashCode(address);
- return hash;
- }
-
- @Override
- public String toString() {
- return inetAddress.getHostAddress() + "/" + prefixLength;
- }
-
- public String printAsBits() {
- String result = "";
- for (int i = 0; i < address.length; i++) {
- byte b = address[i];
- for (int j = 0; j < Byte.SIZE; j++) {
- byte mask = (byte) (0x80 >>> j);
- result += ((b & mask) == 0)? "0" : "1";
- if (i*Byte.SIZE+j == prefixLength-1) {
- return result;
- }
- }
- result += " ";
- }
- return result.substring(0, result.length() - 1);
- }
+ address = canonicalizeAddress(addr, prefixLength);
+ this.prefixLength = prefixLength;
+
+ try {
+ inetAddress = InetAddress.getByAddress(address);
+ } catch (UnknownHostException e) {
+ throw new IllegalArgumentException();
+ }
+ }
+
+ public Prefix(String strAddress, int prefixLength) {
+ byte[] addr = null;
+ addr = InetAddresses.forString(strAddress).getAddress();
+
+ if (addr == null || addr.length != MAX_BYTES ||
+ prefixLength < 0 || prefixLength > MAX_BYTES * Byte.SIZE) {
+ throw new IllegalArgumentException();
+ }
+
+ address = canonicalizeAddress(addr, prefixLength);
+ this.prefixLength = prefixLength;
+
+ try {
+ inetAddress = InetAddress.getByAddress(address);
+ } catch (UnknownHostException e) {
+ throw new IllegalArgumentException();
+ }
+ }
+
+ private byte[] canonicalizeAddress(byte[] address, int prefixLength) {
+ byte[] result = new byte[address.length];
+
+ if (prefixLength == 0) {
+ for (int i = 0; i < MAX_BYTES; i++) {
+ result[i] = 0;
+ }
+
+ return result;
+ }
+
+ result = Arrays.copyOf(address, address.length);
+
+ //Set all bytes after the end of the prefix to 0
+ int lastByteIndex = (prefixLength - 1) / Byte.SIZE;
+ for (int i = lastByteIndex; i < MAX_BYTES; i++) {
+ result[i] = 0;
+ }
+
+ byte lastByte = address[lastByteIndex];
+ byte mask = 0;
+ byte msb = (byte) 0x80;
+ int lastBit = (prefixLength - 1) % Byte.SIZE;
+ for (int i = 0; i < Byte.SIZE; i++) {
+ if (i <= lastBit) {
+ mask |= (msb >> i);
+ }
+ }
+
+ result[lastByteIndex] = (byte) (lastByte & mask);
+
+ return result;
+ }
+
+ public int getPrefixLength() {
+ return prefixLength;
+ }
+
+ public byte[] getAddress() {
+ return address;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (other == null || !(other instanceof Prefix)) {
+ return false;
+ }
+
+ Prefix otherPrefix = (Prefix) other;
+
+ return (Arrays.equals(address, otherPrefix.address)) &&
+ (prefixLength == otherPrefix.prefixLength);
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 17;
+ hash = 31 * hash + prefixLength;
+ hash = 31 * hash + Arrays.hashCode(address);
+ return hash;
+ }
+
+ @Override
+ public String toString() {
+ return inetAddress.getHostAddress() + "/" + prefixLength;
+ }
+
+ public String printAsBits() {
+ String result = "";
+ for (int i = 0; i < address.length; i++) {
+ byte b = address[i];
+ for (int j = 0; j < Byte.SIZE; j++) {
+ byte mask = (byte) (0x80 >>> j);
+ result += ((b & mask) == 0) ? "0" : "1";
+ if (i * Byte.SIZE + j == prefixLength - 1) {
+ return result;
+ }
+ }
+ result += " ";
+ }
+ return result.substring(0, result.length() - 1);
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/Ptree.java b/src/main/java/net/onrc/onos/apps/bgproute/Ptree.java
index 682066a..9a0400f 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/Ptree.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/Ptree.java
@@ -11,312 +11,312 @@
* we don't leak them out the the Ptree.
*/
public class Ptree {
- private int maxKeyBits;
- private int maxKeyOctets;
- //private int refCount;
- private PtreeNode top;
- private byte maskBits[] = { (byte)0x00, (byte)0x80, (byte)0xc0, (byte)0xe0, (byte)0xf0, (byte)0xf8, (byte)0xfc, (byte)0xfe, (byte)0xff };
-
- public Ptree(int max_key_bits) {
- maxKeyBits = max_key_bits;
- maxKeyOctets = bit_to_octet(max_key_bits);
- //refCount = 0;
- }
-
- public synchronized PtreeNode acquire(byte [] key) {
- return acquire(key, maxKeyBits);
- }
-
- public synchronized PtreeNode acquire(byte [] key, int key_bits) {
- if (key_bits > maxKeyBits) {
- return null;
- }
-
- PtreeNode node = top;
- PtreeNode match = null;
-
- while (node != null
- && node.keyBits <= key_bits
- && key_match(node.key, node.keyBits, key, key_bits) == true) {
- if (node.keyBits == key_bits) {
- return addReference(node);
- }
+ private int maxKeyBits;
+ private int maxKeyOctets;
+ //private int refCount;
+ private PtreeNode top;
+ private byte maskBits[] = {(byte) 0x00, (byte) 0x80, (byte) 0xc0, (byte) 0xe0, (byte) 0xf0, (byte) 0xf8, (byte) 0xfc, (byte) 0xfe, (byte) 0xff};
- match = node;
-
- if (bit_check(key, node.keyBits) == true) {
- node = node.right;
- } else {
- node = node.left;
- }
- }
+ public Ptree(int max_key_bits) {
+ maxKeyBits = max_key_bits;
+ maxKeyOctets = bit_to_octet(max_key_bits);
+ //refCount = 0;
+ }
- PtreeNode add = null;
-
- if (node == null) {
- add = new PtreeNode(key, key_bits, maxKeyOctets);
-
- if (match != null) {
- node_link(match, add);
- } else {
- top = add;
- }
- } else {
- add = node_common(node, key, key_bits);
- if (add == null) {
- return null;
- }
-
- if (match != null) {
- node_link(match, add);
- } else {
- top = add;
- }
- node_link(add, node);
-
- if (add.keyBits != key_bits) {
- match = add;
-
- add = new PtreeNode(key, key_bits, maxKeyOctets);
- node_link(match, add);
- }
- }
-
- return addReference(add);
- }
+ public synchronized PtreeNode acquire(byte[] key) {
+ return acquire(key, maxKeyBits);
+ }
- public synchronized PtreeNode lookup(byte [] key, int key_bits) {
- if (key_bits > maxKeyBits) {
- return null;
- }
-
- PtreeNode node = top;
-
- while (node != null
- && node.keyBits <= key_bits
- && key_match(node.key, node.keyBits, key, key_bits) == true) {
- if (node.keyBits == key_bits) {
- return addReference(node);
- }
-
- if (bit_check(key, node.keyBits) == true) {
- node = node.right;
- } else {
- node = node.left;
- }
- }
- return null;
- }
-
- public synchronized PtreeNode match(byte [] key, int key_bits) {
- if (key_bits > maxKeyBits) {
- return null;
- }
- PtreeNode node = top;
- PtreeNode matched = null;
+ public synchronized PtreeNode acquire(byte[] key, int key_bits) {
+ if (key_bits > maxKeyBits) {
+ return null;
+ }
- if(node!=null)
-
- while (node != null
- && node.keyBits <= key_bits
- && key_match(node.key, node.keyBits, key, key_bits) == true) {
- matched = node;
-
- if (bit_check(key, node.keyBits) == true) {
- node = node.right;
- } else {
- node = node.left;
- }
- }
-
- if (matched != null) {
- return addReference(matched);
- }
-
- return null;
- }
-
- public synchronized PtreeNode begin() {
- if (top == null) {
- return null;
- }
- return addReference(top);
- }
-
- public synchronized PtreeNode next(PtreeNode node) {
- PtreeNode next;
-
- if (node.left != null) {
- next = node.left;
- addReference(next);
- delReference(node);
- return next;
- }
- if (node.right != null) {
- next = node.right;
- addReference(next);
- delReference(node);
- return next;
- }
-
- PtreeNode start = node;
- while (node.parent != null) {
- if (node.parent.left == node && node.parent.right != null) {
- next = node.parent.right;
- addReference(next);
- delReference(start);
- return next;
- }
- node = node.parent;
- }
-
- delReference(start);
-
- return null;
- }
+ PtreeNode node = top;
+ PtreeNode match = null;
- static public int bit_to_octet(int key_bits) {
- return Math.max((key_bits + 7) / 8, 1);
- }
+ while (node != null
+ && node.keyBits <= key_bits
+ && key_match(node.key, node.keyBits, key, key_bits) == true) {
+ if (node.keyBits == key_bits) {
+ return addReference(node);
+ }
- private PtreeNode addReference(PtreeNode node) {
- node.refCount++;
- return node;
- }
-
- public synchronized void delReference(PtreeNode node) {
- if (node.refCount > 0) {
- node.refCount--;
- }
- if (node.refCount == 0) {
- node_remove(node);
- }
- }
-
- private boolean key_match(byte [] key1, int key1_len, byte [] key2, int key2_len) {
- int offset;
- int shift;
-
- if (key1_len > key2_len) {
- return false;
- }
-
- offset = (Math.min(key1_len, key2_len)) / 8;
- shift = (Math.min(key1_len, key2_len)) % 8;
-
- if (shift != 0) {
- if ((maskBits[shift] & (key1[offset] ^ key2[offset])) != 0) {
- return false;
- }
- }
-
- while (offset != 0) {
- offset--;
- if (key1[offset] != key2[offset]) {
- return false;
- }
- }
- return true;
- }
-
- private boolean bit_check(byte [] key, int key_bits) {
- int offset = key_bits / 8;
- int shift = 7 - (key_bits % 8);
- int bit = key[offset] & 0xff;
+ match = node;
- bit >>= shift;
-
- if ((bit & 1) == 1) {
- return true;
- } else {
- return false;
- }
- }
-
- private void node_link(PtreeNode node, PtreeNode add) {
- boolean bit = bit_check(add.key, node.keyBits);
-
- if (bit == true) {
- node.right = add;
- } else {
- node.left = add;
- }
- add.parent = node;
- }
-
- private PtreeNode node_common(PtreeNode node, byte [] key, int key_bits) {
- int i;
- int limit = Math.min(node.keyBits, key_bits) / 8;
+ if (bit_check(key, node.keyBits) == true) {
+ node = node.right;
+ } else {
+ node = node.left;
+ }
+ }
- for (i = 0; i < limit; i++) {
- if (node.key[i] != key[i]) {
- break;
- }
- }
-
- int common_len = i * 8;
- int boundary = 0;
+ PtreeNode add = null;
- if (common_len != key_bits) {
- byte diff = (byte)(node.key[i] ^ key[i]);
- byte mask = (byte)0x80;
- int shift_mask = 0;
-
- while (common_len < key_bits && ((mask & diff) == 0)) {
- boundary = 1;
+ if (node == null) {
+ add = new PtreeNode(key, key_bits, maxKeyOctets);
- shift_mask = (mask & 0xff);
- shift_mask >>= 1;
- mask = (byte)shift_mask;
+ if (match != null) {
+ node_link(match, add);
+ } else {
+ top = add;
+ }
+ } else {
+ add = node_common(node, key, key_bits);
+ if (add == null) {
+ return null;
+ }
- common_len++;
- }
- }
-
- PtreeNode add = new PtreeNode(null, common_len, maxKeyOctets);
-
- int j;
- for (j = 0; j < i; j++)
- add.key[j] = node.key[j];
+ if (match != null) {
+ node_link(match, add);
+ } else {
+ top = add;
+ }
+ node_link(add, node);
- if (boundary != 0)
- add.key[j] = (byte)(node.key[j] & maskBits[add.keyBits % 8]);
-
- return add;
- }
-
- private void node_remove(PtreeNode node) {
- PtreeNode child;
- PtreeNode parent;
-
- if (node.left != null && node.right != null) {
- return;
- }
-
- if (node.left != null) {
- child = node.left;
- } else {
- child = node.right;
- }
-
- parent = node.parent;
-
- if (child != null) {
- child.parent = parent;
- }
-
- if (parent != null) {
- if (parent.left == node) {
- parent.left = child;
- } else {
- parent.right = child;
- }
- } else {
- top = child;
- }
-
- if (parent != null && parent.refCount == 0) {
- node_remove(parent);
- }
- }
+ if (add.keyBits != key_bits) {
+ match = add;
+
+ add = new PtreeNode(key, key_bits, maxKeyOctets);
+ node_link(match, add);
+ }
+ }
+
+ return addReference(add);
+ }
+
+ public synchronized PtreeNode lookup(byte[] key, int key_bits) {
+ if (key_bits > maxKeyBits) {
+ return null;
+ }
+
+ PtreeNode node = top;
+
+ while (node != null
+ && node.keyBits <= key_bits
+ && key_match(node.key, node.keyBits, key, key_bits) == true) {
+ if (node.keyBits == key_bits) {
+ return addReference(node);
+ }
+
+ if (bit_check(key, node.keyBits) == true) {
+ node = node.right;
+ } else {
+ node = node.left;
+ }
+ }
+ return null;
+ }
+
+ public synchronized PtreeNode match(byte[] key, int key_bits) {
+ if (key_bits > maxKeyBits) {
+ return null;
+ }
+ PtreeNode node = top;
+ PtreeNode matched = null;
+
+ if (node != null)
+
+ while (node != null
+ && node.keyBits <= key_bits
+ && key_match(node.key, node.keyBits, key, key_bits) == true) {
+ matched = node;
+
+ if (bit_check(key, node.keyBits) == true) {
+ node = node.right;
+ } else {
+ node = node.left;
+ }
+ }
+
+ if (matched != null) {
+ return addReference(matched);
+ }
+
+ return null;
+ }
+
+ public synchronized PtreeNode begin() {
+ if (top == null) {
+ return null;
+ }
+ return addReference(top);
+ }
+
+ public synchronized PtreeNode next(PtreeNode node) {
+ PtreeNode next;
+
+ if (node.left != null) {
+ next = node.left;
+ addReference(next);
+ delReference(node);
+ return next;
+ }
+ if (node.right != null) {
+ next = node.right;
+ addReference(next);
+ delReference(node);
+ return next;
+ }
+
+ PtreeNode start = node;
+ while (node.parent != null) {
+ if (node.parent.left == node && node.parent.right != null) {
+ next = node.parent.right;
+ addReference(next);
+ delReference(start);
+ return next;
+ }
+ node = node.parent;
+ }
+
+ delReference(start);
+
+ return null;
+ }
+
+ static public int bit_to_octet(int key_bits) {
+ return Math.max((key_bits + 7) / 8, 1);
+ }
+
+ private PtreeNode addReference(PtreeNode node) {
+ node.refCount++;
+ return node;
+ }
+
+ public synchronized void delReference(PtreeNode node) {
+ if (node.refCount > 0) {
+ node.refCount--;
+ }
+ if (node.refCount == 0) {
+ node_remove(node);
+ }
+ }
+
+ private boolean key_match(byte[] key1, int key1_len, byte[] key2, int key2_len) {
+ int offset;
+ int shift;
+
+ if (key1_len > key2_len) {
+ return false;
+ }
+
+ offset = (Math.min(key1_len, key2_len)) / 8;
+ shift = (Math.min(key1_len, key2_len)) % 8;
+
+ if (shift != 0) {
+ if ((maskBits[shift] & (key1[offset] ^ key2[offset])) != 0) {
+ return false;
+ }
+ }
+
+ while (offset != 0) {
+ offset--;
+ if (key1[offset] != key2[offset]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean bit_check(byte[] key, int key_bits) {
+ int offset = key_bits / 8;
+ int shift = 7 - (key_bits % 8);
+ int bit = key[offset] & 0xff;
+
+ bit >>= shift;
+
+ if ((bit & 1) == 1) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ private void node_link(PtreeNode node, PtreeNode add) {
+ boolean bit = bit_check(add.key, node.keyBits);
+
+ if (bit == true) {
+ node.right = add;
+ } else {
+ node.left = add;
+ }
+ add.parent = node;
+ }
+
+ private PtreeNode node_common(PtreeNode node, byte[] key, int key_bits) {
+ int i;
+ int limit = Math.min(node.keyBits, key_bits) / 8;
+
+ for (i = 0; i < limit; i++) {
+ if (node.key[i] != key[i]) {
+ break;
+ }
+ }
+
+ int common_len = i * 8;
+ int boundary = 0;
+
+ if (common_len != key_bits) {
+ byte diff = (byte) (node.key[i] ^ key[i]);
+ byte mask = (byte) 0x80;
+ int shift_mask = 0;
+
+ while (common_len < key_bits && ((mask & diff) == 0)) {
+ boundary = 1;
+
+ shift_mask = (mask & 0xff);
+ shift_mask >>= 1;
+ mask = (byte) shift_mask;
+
+ common_len++;
+ }
+ }
+
+ PtreeNode add = new PtreeNode(null, common_len, maxKeyOctets);
+
+ int j;
+ for (j = 0; j < i; j++)
+ add.key[j] = node.key[j];
+
+ if (boundary != 0)
+ add.key[j] = (byte) (node.key[j] & maskBits[add.keyBits % 8]);
+
+ return add;
+ }
+
+ private void node_remove(PtreeNode node) {
+ PtreeNode child;
+ PtreeNode parent;
+
+ if (node.left != null && node.right != null) {
+ return;
+ }
+
+ if (node.left != null) {
+ child = node.left;
+ } else {
+ child = node.right;
+ }
+
+ parent = node.parent;
+
+ if (child != null) {
+ child.parent = parent;
+ }
+
+ if (parent != null) {
+ if (parent.left == node) {
+ parent.left = child;
+ } else {
+ parent.right = child;
+ }
+ } else {
+ top = child;
+ }
+
+ if (parent != null && parent.refCount == 0) {
+ node_remove(parent);
+ }
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/PtreeNode.java b/src/main/java/net/onrc/onos/apps/bgproute/PtreeNode.java
index d20b7c4..e1b4c55 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/PtreeNode.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/PtreeNode.java
@@ -4,41 +4,41 @@
import org.slf4j.LoggerFactory;
public class PtreeNode {
- public PtreeNode parent;
- public PtreeNode left;
- public PtreeNode right;
-
- public byte key[];
- public int keyBits;
-
- public int refCount;
-
- public RibEntry rib;
- protected final static Logger log = LoggerFactory.getLogger(BgpRoute.class);
-
- PtreeNode(byte [] key, int key_bits, int max_key_octet) {
- parent = null;
- left = null;
- right = null;
- refCount = 0;
- rib = null;
- this.key = new byte[max_key_octet];
- this.keyBits = key_bits;
- log.debug("inside Ptreenode constructor key {} bits {}", key, key_bits);
-
- int octet = Ptree.bit_to_octet(key_bits);
- for (int i = 0; i < max_key_octet; i++) {
- if (i < octet) {
- if (key != null) {
- log.debug(octet + ": filling key[{}] {}", i, key[i]);
- this.key[i] = key[i];
- } else {
- log.debug("no filling, null key", i);
- }
- } else {
- log.debug("filling key {} as 0", i);
- this.key[i] = 0;
- }
- }
- }
+ public PtreeNode parent;
+ public PtreeNode left;
+ public PtreeNode right;
+
+ public byte key[];
+ public int keyBits;
+
+ public int refCount;
+
+ public RibEntry rib;
+ protected final static Logger log = LoggerFactory.getLogger(BgpRoute.class);
+
+ PtreeNode(byte[] key, int key_bits, int max_key_octet) {
+ parent = null;
+ left = null;
+ right = null;
+ refCount = 0;
+ rib = null;
+ this.key = new byte[max_key_octet];
+ this.keyBits = key_bits;
+ log.debug("inside Ptreenode constructor key {} bits {}", key, key_bits);
+
+ int octet = Ptree.bit_to_octet(key_bits);
+ for (int i = 0; i < max_key_octet; i++) {
+ if (i < octet) {
+ if (key != null) {
+ log.debug(octet + ": filling key[{}] {}", i, key[i]);
+ this.key[i] = key[i];
+ } else {
+ log.debug("no filling, null key", i);
+ }
+ } else {
+ log.debug("filling key {} as 0", i);
+ this.key[i] = 0;
+ }
+ }
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/PushedFlowMod.java b/src/main/java/net/onrc/onos/apps/bgproute/PushedFlowMod.java
index 1908050..612a704 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/PushedFlowMod.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/PushedFlowMod.java
@@ -5,28 +5,27 @@
/**
* Wraps up a DPID and a OFFlowMod so we know how to delete
* the flow if we have to.
- *
+ * <p/>
* TODO This functionality should be handled by ONOS's flow layer in future.
- *
*/
public class PushedFlowMod {
- private long dpid;
- private OFFlowMod flowMod;
-
- public PushedFlowMod(long dpid, OFFlowMod flowMod) {
- this.dpid = dpid;
- try {
- this.flowMod = flowMod.clone();
- } catch (CloneNotSupportedException e) {
- this.flowMod = flowMod;
- }
- }
-
- public long getDpid() {
- return dpid;
- }
-
- public OFFlowMod getFlowMod() {
- return flowMod;
- }
+ private long dpid;
+ private OFFlowMod flowMod;
+
+ public PushedFlowMod(long dpid, OFFlowMod flowMod) {
+ this.dpid = dpid;
+ try {
+ this.flowMod = flowMod.clone();
+ } catch (CloneNotSupportedException e) {
+ this.flowMod = flowMod;
+ }
+ }
+
+ public long getDpid() {
+ return dpid;
+ }
+
+ public OFFlowMod getFlowMod() {
+ return flowMod;
+ }
}
\ No newline at end of file
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/RestClient.java b/src/main/java/net/onrc/onos/apps/bgproute/RestClient.java
index d085e6c..5ea4699 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/RestClient.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/RestClient.java
@@ -13,92 +13,92 @@
public class RestClient {
- protected final static Logger log = LoggerFactory.getLogger(RestClient.class);
+ protected final static Logger log = LoggerFactory.getLogger(RestClient.class);
- public static String get(String str) {
- StringBuilder response = new StringBuilder();
+ public static String get(String str) {
+ StringBuilder response = new StringBuilder();
- try {
+ try {
- URL url = new URL(str);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setConnectTimeout(2 * 1000); //2 seconds
- conn.setRequestMethod("GET");
- conn.setRequestProperty("Accept", "application/json");
+ URL url = new URL(str);
+ HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+ conn.setConnectTimeout(2 * 1000); //2 seconds
+ conn.setRequestMethod("GET");
+ conn.setRequestProperty("Accept", "application/json");
- if (conn.getResponseCode() != 200) {
- throw new RuntimeException("Failed : HTTP error code : "
- + conn.getResponseCode());
- }
+ if (conn.getResponseCode() != 200) {
+ throw new RuntimeException("Failed : HTTP error code : "
+ + conn.getResponseCode());
+ }
- if (!conn.getContentType().equals("application/json")){
- log.warn("The content received from {} is not json", str);
- }
+ if (!conn.getContentType().equals("application/json")) {
+ log.warn("The content received from {} is not json", str);
+ }
- BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
- String line;
- while ((line = br.readLine()) != null) {
- response.append(line);
- }
-
- br.close();
- conn.disconnect();
-
- } catch (MalformedURLException e) {
- log.error("Malformed URL for GET request", e);
- } catch (ConnectTimeoutException e) {
- log.warn("Couldn't connect remote REST server");
- } catch (IOException e) {
- log.warn("Couldn't connect remote REST server");
- }
-
- return response.toString();
- }
+ BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
+ String line;
+ while ((line = br.readLine()) != null) {
+ response.append(line);
+ }
- public static void post (String str) {
+ br.close();
+ conn.disconnect();
- try {
- URL url = new URL(str);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setDoOutput(true);
- conn.setRequestMethod("POST");
- conn.setRequestProperty("Content-Type", "application/json");
+ } catch (MalformedURLException e) {
+ log.error("Malformed URL for GET request", e);
+ } catch (ConnectTimeoutException e) {
+ log.warn("Couldn't connect remote REST server");
+ } catch (IOException e) {
+ log.warn("Couldn't connect remote REST server");
+ }
- if (conn.getResponseCode() != 200) {
- throw new RuntimeException("Failed : HTTP error code : "
- + conn.getResponseCode());
- }
+ return response.toString();
+ }
- conn.disconnect();
+ public static void post(String str) {
- } catch (MalformedURLException e) {
- log.error("Malformed URL for GET request", e);
- } catch (IOException e) {
- log.warn("Couldn't connect remote REST server");
- }
- }
+ try {
+ URL url = new URL(str);
+ HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+ conn.setDoOutput(true);
+ conn.setRequestMethod("POST");
+ conn.setRequestProperty("Content-Type", "application/json");
+
+ if (conn.getResponseCode() != 200) {
+ throw new RuntimeException("Failed : HTTP error code : "
+ + conn.getResponseCode());
+ }
+
+ conn.disconnect();
+
+ } catch (MalformedURLException e) {
+ log.error("Malformed URL for GET request", e);
+ } catch (IOException e) {
+ log.warn("Couldn't connect remote REST server");
+ }
+ }
- public static void delete (String str) {
+ public static void delete(String str) {
- try {
- URL url = new URL(str);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("DELETE");
- conn.setRequestProperty("Accept", "application/json");
+ try {
+ URL url = new URL(str);
+ HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+ conn.setRequestMethod("DELETE");
+ conn.setRequestProperty("Accept", "application/json");
- if (conn.getResponseCode() != 200) {
- throw new RuntimeException("Failed : HTTP error code : "
- + conn.getResponseCode());
- }
+ if (conn.getResponseCode() != 200) {
+ throw new RuntimeException("Failed : HTTP error code : "
+ + conn.getResponseCode());
+ }
- conn.disconnect();
+ conn.disconnect();
- } catch (MalformedURLException e) {
- log.error("Malformed URL for GET request", e);
- } catch (IOException e) {
- log.warn("Couldn't connect remote REST server");
- }
- }
+ } catch (MalformedURLException e) {
+ log.error("Malformed URL for GET request", e);
+ } catch (IOException e) {
+ log.warn("Couldn't connect remote REST server");
+ }
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/RibEntry.java b/src/main/java/net/onrc/onos/apps/bgproute/RibEntry.java
index 16f5aff..4dccd5f 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/RibEntry.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/RibEntry.java
@@ -5,76 +5,76 @@
import com.google.common.net.InetAddresses;
public class RibEntry {
- private final InetAddress routerId;
- private final InetAddress nextHop;
+ private final InetAddress routerId;
+ private final InetAddress nextHop;
- /*
- * Store the sequence number information provided on the update here for
- * now. I think this *should* really be in the RibUpdate, and we should
- * store RibUpdates in the Ptrie. But, that's a bigger change to change
- * what the Ptrie stores.
- */
- private final long sysUpTime;
- private final long sequenceNum;
-
- /*
- * Marker for RibEntries where we don't have sequence number info.
- * The user of this class should make sure they don't check this data
- * if they don't provide it.
- */
- private final static long NULL_TIME = -1;
-
- public RibEntry(InetAddress routerId, InetAddress nextHop) {
- this.routerId = routerId;
- this.nextHop = nextHop;
- sequenceNum = NULL_TIME;
- sysUpTime = NULL_TIME;
- }
-
- public RibEntry(String routerId, String nextHop) {
- this.routerId = InetAddresses.forString(routerId);
- this.nextHop = InetAddresses.forString(nextHop);
- sequenceNum = NULL_TIME;
- sysUpTime = NULL_TIME;
- }
-
- public RibEntry(String routerId, String nextHop, long sysUpTime
- , long sequenceNum) {
- this.routerId = InetAddresses.forString(routerId);
- this.nextHop = InetAddresses.forString(nextHop);
- this.sequenceNum = sequenceNum;
- this.sysUpTime = sysUpTime;
- }
-
- public InetAddress getNextHop() {
- return nextHop;
- }
-
- public long getSysUpTime() {
- return sysUpTime;
- }
-
- public long getSequenceNum() {
- return sequenceNum;
- }
-
- @Override
- public boolean equals(Object other) {
- if (other == null || !(other instanceof RibEntry)) {
- return false;
- }
-
- RibEntry otherRibEntry = (RibEntry) other;
-
- return this.routerId.equals(otherRibEntry.routerId)
- && this.nextHop.equals(otherRibEntry.nextHop);
- }
-
- @Override
- public int hashCode() {
- int hash = 17;
- hash = 31 * hash + routerId.hashCode();
- hash = 31 * hash + nextHop.hashCode();
- return hash;
- }
+ /*
+ * Store the sequence number information provided on the update here for
+ * now. I think this *should* really be in the RibUpdate, and we should
+ * store RibUpdates in the Ptrie. But, that's a bigger change to change
+ * what the Ptrie stores.
+ */
+ private final long sysUpTime;
+ private final long sequenceNum;
+
+ /*
+ * Marker for RibEntries where we don't have sequence number info.
+ * The user of this class should make sure they don't check this data
+ * if they don't provide it.
+ */
+ private final static long NULL_TIME = -1;
+
+ public RibEntry(InetAddress routerId, InetAddress nextHop) {
+ this.routerId = routerId;
+ this.nextHop = nextHop;
+ sequenceNum = NULL_TIME;
+ sysUpTime = NULL_TIME;
+ }
+
+ public RibEntry(String routerId, String nextHop) {
+ this.routerId = InetAddresses.forString(routerId);
+ this.nextHop = InetAddresses.forString(nextHop);
+ sequenceNum = NULL_TIME;
+ sysUpTime = NULL_TIME;
+ }
+
+ public RibEntry(String routerId, String nextHop, long sysUpTime
+ , long sequenceNum) {
+ this.routerId = InetAddresses.forString(routerId);
+ this.nextHop = InetAddresses.forString(nextHop);
+ this.sequenceNum = sequenceNum;
+ this.sysUpTime = sysUpTime;
+ }
+
+ public InetAddress getNextHop() {
+ return nextHop;
+ }
+
+ public long getSysUpTime() {
+ return sysUpTime;
+ }
+
+ public long getSequenceNum() {
+ return sequenceNum;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (other == null || !(other instanceof RibEntry)) {
+ return false;
+ }
+
+ RibEntry otherRibEntry = (RibEntry) other;
+
+ return this.routerId.equals(otherRibEntry.routerId)
+ && this.nextHop.equals(otherRibEntry.nextHop);
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 17;
+ hash = 31 * hash + routerId.hashCode();
+ hash = 31 * hash + nextHop.hashCode();
+ return hash;
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/bgproute/RibUpdate.java b/src/main/java/net/onrc/onos/apps/bgproute/RibUpdate.java
index d69a538..0faa94f 100644
--- a/src/main/java/net/onrc/onos/apps/bgproute/RibUpdate.java
+++ b/src/main/java/net/onrc/onos/apps/bgproute/RibUpdate.java
@@ -1,27 +1,30 @@
package net.onrc.onos.apps.bgproute;
public class RibUpdate {
- public enum Operation {UPDATE, DELETE};
-
- private final Operation operation;
- private final Prefix prefix;
- private final RibEntry ribEntry;
-
- public RibUpdate(Operation operation, Prefix prefix, RibEntry ribEntry) {
- this.operation = operation;
- this.prefix = prefix;
- this.ribEntry = ribEntry;
- }
+ public enum Operation {
+ UPDATE,
+ DELETE
+ }
- public Operation getOperation() {
- return operation;
- }
+ private final Operation operation;
+ private final Prefix prefix;
+ private final RibEntry ribEntry;
- public Prefix getPrefix() {
- return prefix;
- }
+ public RibUpdate(Operation operation, Prefix prefix, RibEntry ribEntry) {
+ this.operation = operation;
+ this.prefix = prefix;
+ this.ribEntry = ribEntry;
+ }
- public RibEntry getRibEntry() {
- return ribEntry;
- }
+ public Operation getOperation() {
+ return operation;
+ }
+
+ public Prefix getPrefix() {
+ return prefix;
+ }
+
+ public RibEntry getRibEntry() {
+ return ribEntry;
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/forwarding/Forwarding.java b/src/main/java/net/onrc/onos/apps/forwarding/Forwarding.java
index bdafdcd..2ed8ba5 100644
--- a/src/main/java/net/onrc/onos/apps/forwarding/Forwarding.java
+++ b/src/main/java/net/onrc/onos/apps/forwarding/Forwarding.java
@@ -62,529 +62,526 @@
import com.google.common.collect.ListMultimap;
public class Forwarding implements IOFMessageListener, IFloodlightModule,
- IForwardingService, IEventChannelListener<Long, IntentStateList> {
- private final static Logger log = LoggerFactory.getLogger(Forwarding.class);
-
- private final int SLEEP_TIME_FOR_DB_DEVICE_INSTALLED = 100; // milliseconds
- private final static int NUMBER_OF_THREAD_FOR_EXECUTOR = 1;
-
- private final static ScheduledExecutorService executor = Executors.newScheduledThreadPool(NUMBER_OF_THREAD_FOR_EXECUTOR);
-
- private final String callerId = "Forwarding";
-
- private IFloodlightProviderService floodlightProvider;
- private IFlowPusherService flowPusher;
- private IDatagridService datagrid;
+ IForwardingService, IEventChannelListener<Long, IntentStateList> {
+ private final static Logger log = LoggerFactory.getLogger(Forwarding.class);
- private IEventChannel<Long, BroadcastPacketOutNotification> eventChannel;
- private static final String SINGLE_PACKET_OUT_CHANNEL_NAME = "onos.forwarding.packet_out";
+ private final int SLEEP_TIME_FOR_DB_DEVICE_INSTALLED = 100; // milliseconds
+ private final static int NUMBER_OF_THREAD_FOR_EXECUTOR = 1;
- private IControllerRegistryService controllerRegistryService;
-
- private INetworkGraphService networkGraphService;
- private NetworkGraph networkGraph;
- private IPathCalcRuntimeService pathRuntime;
- private IntentMap intentMap;
-
- // TODO it seems there is a Guava collection that will time out entries.
- // We should see if this will work here.
- private Map<Path, PushedFlow> pendingFlows;
- private ListMultimap<String, PacketToPush> waitingPackets;
-
- private final Object lock = new Object();
-
- private class PacketToPush {
- public final OFPacketOut packet;
- public final long dpid;
-
- public PacketToPush(OFPacketOut packet, long dpid) {
- this.packet = packet;
- this.dpid = dpid;
- }
- }
-
- private class PushedFlow {
- public final String intentId;
- public boolean installed = false;
- public short firstOutPort;
-
- public PushedFlow(String flowId) {
- this.intentId = flowId;
- }
- }
-
- private final class Path {
- public final MACAddress srcMac;
- public final MACAddress dstMac;
-
- public Path(MACAddress srcMac, MACAddress dstMac) {
- this.srcMac = srcMac;
- this.dstMac = dstMac;
- }
-
- @Override
- public boolean equals(Object other) {
- if (!(other instanceof Path)) {
- return false;
- }
-
- Path otherPath = (Path) other;
- return srcMac.equals(otherPath.srcMac) &&
- dstMac.equals(otherPath.dstMac);
- }
-
- @Override
- public int hashCode() {
- int hash = 17;
- hash = 31 * hash + srcMac.hashCode();
- hash = 31 * hash + dstMac.hashCode();
- return hash;
- }
-
- @Override
- public String toString() {
- return "(" + srcMac + ") => (" + dstMac + ")";
- }
- }
-
- @Override
- public Collection<Class<? extends IFloodlightService>> getModuleServices() {
- List<Class<? extends IFloodlightService>> services =
- new ArrayList<Class<? extends IFloodlightService>>(1);
- services.add(IForwardingService.class);
- return services;
- }
+ private final static ScheduledExecutorService executor = Executors.newScheduledThreadPool(NUMBER_OF_THREAD_FOR_EXECUTOR);
- @Override
- public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
- Map<Class<? extends IFloodlightService>, IFloodlightService> impls =
- new HashMap<Class<? extends IFloodlightService>, IFloodlightService>(1);
- impls.put(IForwardingService.class, this);
- return impls;
- }
+ private final String callerId = "Forwarding";
- @Override
- public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
- List<Class<? extends IFloodlightService>> dependencies =
- new ArrayList<Class<? extends IFloodlightService>>();
- dependencies.add(IFloodlightProviderService.class);
- dependencies.add(IFlowPusherService.class);
- dependencies.add(IControllerRegistryService.class);
- dependencies.add(IOnosDeviceService.class);
- dependencies.add(IDatagridService.class);
- dependencies.add(INetworkGraphService.class);
- dependencies.add(IPathCalcRuntimeService.class);
- // We don't use the IProxyArpService directly, but reactive forwarding
- // requires it to be loaded and answering ARP requests
- dependencies.add(IProxyArpService.class);
- return dependencies;
- }
-
- @Override
- public void init(FloodlightModuleContext context) {
- floodlightProvider =
- context.getServiceImpl(IFloodlightProviderService.class);
- flowPusher = context.getServiceImpl(IFlowPusherService.class);
- datagrid = context.getServiceImpl(IDatagridService.class);
- controllerRegistryService = context.getServiceImpl(IControllerRegistryService.class);
- networkGraphService = context.getServiceImpl(INetworkGraphService.class);
+ private IFloodlightProviderService floodlightProvider;
+ private IFlowPusherService flowPusher;
+ private IDatagridService datagrid;
+
+ private IEventChannel<Long, BroadcastPacketOutNotification> eventChannel;
+ private static final String SINGLE_PACKET_OUT_CHANNEL_NAME = "onos.forwarding.packet_out";
+
+ private IControllerRegistryService controllerRegistryService;
+
+ private INetworkGraphService networkGraphService;
+ private NetworkGraph networkGraph;
+ private IPathCalcRuntimeService pathRuntime;
+ private IntentMap intentMap;
+
+ // TODO it seems there is a Guava collection that will time out entries.
+ // We should see if this will work here.
+ private Map<Path, PushedFlow> pendingFlows;
+ private ListMultimap<String, PacketToPush> waitingPackets;
+
+ private final Object lock = new Object();
+
+ private class PacketToPush {
+ public final OFPacketOut packet;
+ public final long dpid;
+
+ public PacketToPush(OFPacketOut packet, long dpid) {
+ this.packet = packet;
+ this.dpid = dpid;
+ }
+ }
+
+ private class PushedFlow {
+ public final String intentId;
+ public boolean installed = false;
+ public short firstOutPort;
+
+ public PushedFlow(String flowId) {
+ this.intentId = flowId;
+ }
+ }
+
+ private final class Path {
+ public final MACAddress srcMac;
+ public final MACAddress dstMac;
+
+ public Path(MACAddress srcMac, MACAddress dstMac) {
+ this.srcMac = srcMac;
+ this.dstMac = dstMac;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (!(other instanceof Path)) {
+ return false;
+ }
+
+ Path otherPath = (Path) other;
+ return srcMac.equals(otherPath.srcMac) &&
+ dstMac.equals(otherPath.dstMac);
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 17;
+ hash = 31 * hash + srcMac.hashCode();
+ hash = 31 * hash + dstMac.hashCode();
+ return hash;
+ }
+
+ @Override
+ public String toString() {
+ return "(" + srcMac + ") => (" + dstMac + ")";
+ }
+ }
+
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleServices() {
+ List<Class<? extends IFloodlightService>> services =
+ new ArrayList<Class<? extends IFloodlightService>>(1);
+ services.add(IForwardingService.class);
+ return services;
+ }
+
+ @Override
+ public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
+ Map<Class<? extends IFloodlightService>, IFloodlightService> impls =
+ new HashMap<Class<? extends IFloodlightService>, IFloodlightService>(1);
+ impls.put(IForwardingService.class, this);
+ 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(IFlowPusherService.class);
+ dependencies.add(IControllerRegistryService.class);
+ dependencies.add(IOnosDeviceService.class);
+ dependencies.add(IDatagridService.class);
+ dependencies.add(INetworkGraphService.class);
+ dependencies.add(IPathCalcRuntimeService.class);
+ // We don't use the IProxyArpService directly, but reactive forwarding
+ // requires it to be loaded and answering ARP requests
+ dependencies.add(IProxyArpService.class);
+ return dependencies;
+ }
+
+ @Override
+ public void init(FloodlightModuleContext context) {
+ floodlightProvider =
+ context.getServiceImpl(IFloodlightProviderService.class);
+ flowPusher = context.getServiceImpl(IFlowPusherService.class);
+ datagrid = context.getServiceImpl(IDatagridService.class);
+ controllerRegistryService = context.getServiceImpl(IControllerRegistryService.class);
+ networkGraphService = context.getServiceImpl(INetworkGraphService.class);
pathRuntime = context.getServiceImpl(IPathCalcRuntimeService.class);
-
- floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
- pendingFlows = new HashMap<Path, PushedFlow>();
- waitingPackets = LinkedListMultimap.create();
- }
-
- @Override
- public void startUp(FloodlightModuleContext context) {
+ floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
- eventChannel = datagrid.createChannel(SINGLE_PACKET_OUT_CHANNEL_NAME,
- Long.class,
- BroadcastPacketOutNotification.class);
- networkGraph = networkGraphService.getNetworkGraph();
- intentMap = pathRuntime.getPathIntents();
- datagrid.addListener("onos.pathintent_state", this, Long.class, IntentStateList.class);
- }
+ pendingFlows = new HashMap<Path, PushedFlow>();
+ waitingPackets = LinkedListMultimap.create();
+ }
- @Override
- public String getName() {
- return "onosforwarding";
- }
+ @Override
+ public void startUp(FloodlightModuleContext context) {
- @Override
- public boolean isCallbackOrderingPrereq(OFType type, String name) {
- return (type == OFType.PACKET_IN) &&
- (name.equals("devicemanager") || name.equals("proxyarpmanager")
- || name.equals("onosdevicemanager"));
- }
+ eventChannel = datagrid.createChannel(SINGLE_PACKET_OUT_CHANNEL_NAME,
+ Long.class,
+ BroadcastPacketOutNotification.class);
+ networkGraph = networkGraphService.getNetworkGraph();
+ intentMap = pathRuntime.getPathIntents();
+ datagrid.addListener("onos.pathintent_state", this, Long.class, IntentStateList.class);
+ }
- @Override
- public boolean isCallbackOrderingPostreq(OFType type, String name) {
- return false;
- }
+ @Override
+ public String getName() {
+ return "onosforwarding";
+ }
- @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);
-
- log.debug("Receive PACKET_IN swId {}, portId {}", sw.getId(), pi.getInPort());
-
- if (eth.getEtherType() != Ethernet.TYPE_IPv4) {
- return Command.CONTINUE;
- }
-
- if (eth.isBroadcast() || eth.isMulticast()) {
- handleBroadcast(sw, pi, eth);
- }
- else {
- // Unicast
- handlePacketIn(sw, pi, eth);
- }
-
- return Command.STOP;
- }
-
- private void handleBroadcast(IOFSwitch sw, OFPacketIn pi, Ethernet eth) {
- if (log.isTraceEnabled()) {
- log.trace("Sending broadcast packet to other ONOS instances");
- }
+ @Override
+ public boolean isCallbackOrderingPrereq(OFType type, String name) {
+ return (type == OFType.PACKET_IN) &&
+ (name.equals("devicemanager") || name.equals("proxyarpmanager")
+ || name.equals("onosdevicemanager"));
+ }
- //We don't use address information, so 0 is put into the third argument.
- BroadcastPacketOutNotification key =
- new BroadcastPacketOutNotification(
- eth.serialize(),
- 0, sw.getId(),
- pi.getInPort());
- eventChannel.addTransientEntry(eth.getDestinationMAC().toLong(), key);
- }
-
- private void handlePacketIn(IOFSwitch sw, OFPacketIn pi, Ethernet eth){
- log.debug("Start handlePacketIn swId {}, portId {}", sw.getId(), pi.getInPort());
+ @Override
+ public boolean isCallbackOrderingPostreq(OFType type, String name) {
+ return false;
+ }
- String destinationMac =
- HexString.toHexString(eth.getDestinationMACAddress());
-
- //FIXME getDeviceByMac() is a blocking call, so it may be better way to handle it to avoid the condition.
- Device deviceObject = networkGraph.getDeviceByMac(MACAddress.valueOf(destinationMac));
+ @Override
+ public Command receive(
+ IOFSwitch sw, OFMessage msg, FloodlightContext cntx) {
- if (deviceObject == null) {
- log.debug("No device entry found for {}",
- destinationMac);
+ if (msg.getType() != OFType.PACKET_IN) {
+ return Command.CONTINUE;
+ }
- //Device is not in the DB, so wait it until the device is added.
- executor.schedule(new WaitDeviceArp(sw, pi, eth), SLEEP_TIME_FOR_DB_DEVICE_INSTALLED, TimeUnit.MILLISECONDS);
- return;
- }
+ OFPacketIn pi = (OFPacketIn) msg;
- continueHandlePacketIn(sw, pi, eth, deviceObject);
- }
-
- private class WaitDeviceArp implements Runnable {
- IOFSwitch sw;
- OFPacketIn pi;
- Ethernet eth;
+ Ethernet eth = IFloodlightProviderService.bcStore.
+ get(cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
- public WaitDeviceArp(IOFSwitch sw, OFPacketIn pi, Ethernet eth) {
- super();
- this.sw = sw;
- this.pi = pi;
- this.eth = eth;
- }
+ log.debug("Receive PACKET_IN swId {}, portId {}", sw.getId(), pi.getInPort());
- @Override
- public void run() {
- Device deviceObject = networkGraph.getDeviceByMac(MACAddress.valueOf(eth.getDestinationMACAddress()));
- if(deviceObject == null){
- log.debug("wait {}ms and device was not found. Send broadcast packet and the thread finish.", SLEEP_TIME_FOR_DB_DEVICE_INSTALLED);
- handleBroadcast(sw, pi, eth);
- return;
- }
- log.debug("wait {}ms and device {} was found, continue",SLEEP_TIME_FOR_DB_DEVICE_INSTALLED, deviceObject.getMacAddress());
- continueHandlePacketIn(sw, pi, eth, deviceObject);
- }
- }
+ if (eth.getEtherType() != Ethernet.TYPE_IPv4) {
+ return Command.CONTINUE;
+ }
- private void continueHandlePacketIn(IOFSwitch sw, OFPacketIn pi, Ethernet eth, Device deviceObject) {
+ if (eth.isBroadcast() || eth.isMulticast()) {
+ handleBroadcast(sw, pi, eth);
+ } else {
+ // Unicast
+ handlePacketIn(sw, pi, eth);
+ }
- log.debug("Start continuehandlePacketIn");
-
- //Iterator<IPortObject> ports = deviceObject.getAttachedPorts().iterator();
- Iterator<net.onrc.onos.core.topology.Port> ports = deviceObject.getAttachmentPoints().iterator();
- if (!ports.hasNext()) {
- log.debug("No attachment point found for device {} - broadcasting packet",
- deviceObject.getMacAddress());
- handleBroadcast(sw, pi, eth);
- return;
- }
+ return Command.STOP;
+ }
- //This code assumes the device has only one port. It should be problem.
- net.onrc.onos.core.topology.Port portObject = ports.next();
- short destinationPort = portObject.getNumber().shortValue();
- Switch switchObject = portObject.getSwitch();
- long destinationDpid = switchObject.getDpid();
-
- // TODO SwitchPort, Dpid and Port should probably be immutable
- SwitchPort srcSwitchPort = new SwitchPort(
- new Dpid(sw.getId()), new Port(pi.getInPort()));
- SwitchPort dstSwitchPort = new SwitchPort(
- new Dpid(destinationDpid), new Port(destinationPort));
-
- MACAddress srcMacAddress = MACAddress.valueOf(eth.getSourceMACAddress());
- MACAddress dstMacAddress = MACAddress.valueOf(eth.getDestinationMACAddress());
-
- synchronized (lock) {
- //TODO check concurrency
- Path pathspec = new Path(srcMacAddress, dstMacAddress);
- PushedFlow existingFlow = pendingFlows.get(pathspec);
+ private void handleBroadcast(IOFSwitch sw, OFPacketIn pi, Ethernet eth) {
+ if (log.isTraceEnabled()) {
+ log.trace("Sending broadcast packet to other ONOS instances");
+ }
- //A path is installed side by side to reduce a path timeout and a wrong state.
- if (existingFlow != null) {
- // We've already start to install a flow for this pair of MAC addresses
- if(log.isDebugEnabled()) {
- log.debug("Found existing the same pathspec {}, intent ID is {}",
- pathspec,
- existingFlow.intentId);
- }
-
- OFPacketOut po = constructPacketOut(pi, sw);
-
- // Find the correct port here. We just assume the PI is from
- // the first hop switch, but this is definitely not always
- // the case. We'll have to retrieve the flow from HZ every time
- // because it could change (be rerouted) sometimes.
- if (existingFlow.installed) {
- // Flow has been sent to the switches so it is safe to
- // send a packet out now
+ //We don't use address information, so 0 is put into the third argument.
+ BroadcastPacketOutNotification key =
+ new BroadcastPacketOutNotification(
+ eth.serialize(),
+ 0, sw.getId(),
+ pi.getInPort());
+ eventChannel.addTransientEntry(eth.getDestinationMAC().toLong(), key);
+ }
- Intent intent = intentMap.getIntent(existingFlow.intentId);
- PathIntent pathIntent = null;
- if(intent instanceof PathIntent) {
- pathIntent = (PathIntent)intent;
- } else {
- log.debug("Intent {} is not PathIntent. Return.", intent.getId());
- return;
- }
-
- Boolean isflowEntryForThisSwitch = false;
- net.onrc.onos.core.topology.Path path = pathIntent.getPath();
+ private void handlePacketIn(IOFSwitch sw, OFPacketIn pi, Ethernet eth) {
+ log.debug("Start handlePacketIn swId {}, portId {}", sw.getId(), pi.getInPort());
- for(Iterator<LinkEvent> i = path.iterator(); i.hasNext();) {
- LinkEvent le = (LinkEvent)i.next();
- if(le.getSrc().dpid == sw.getId()) {
- log.debug("src {} dst {}", le.getSrc(), le.getDst());
- isflowEntryForThisSwitch = true;
- break;
- }
- }
-
- if (isflowEntryForThisSwitch == false) {
- // If we don't find a flow entry for that switch, then we're
- // in the middle of a rerouting (or something's gone wrong).
- // This packet will be dropped as a victim of the rerouting.
- log.debug("Dropping packet on flow {} between {}-{}",
- existingFlow.intentId,
- srcMacAddress, dstMacAddress);
- } else {
- log.debug("Sending packet out from sw {}, outport{}", sw, existingFlow.firstOutPort);
- sendPacketOut(sw, po, existingFlow.firstOutPort);
- }
- }
- else {
- // Flow path has not yet been installed to switches so save the
- // packet out for later
- log.debug("Put a packet into the waitng list. flowId {}", existingFlow.intentId);
- waitingPackets.put(existingFlow.intentId, new PacketToPush(po, sw.getId()));
- }
- return;
- }
+ String destinationMac =
+ HexString.toHexString(eth.getDestinationMACAddress());
- log.debug("Adding new flow between {} at {} and {} at {}",
- new Object[]{srcMacAddress, srcSwitchPort, dstMacAddress, dstSwitchPort});
-
- String intentId = callerId + ":" + controllerRegistryService.getNextUniqueId();
- IntentOperationList operations = new IntentOperationList();
- ShortestPathIntent intent = new ShortestPathIntent(intentId,
- sw.getId(), pi.getInPort(), srcMacAddress.toLong(),
- destinationDpid, destinationPort, dstMacAddress.toLong());
- IntentOperation.Operator operator = IntentOperation.Operator.ADD;
- operations.add(operator, intent);
- pathRuntime.executeIntentOperations(operations);
+ //FIXME getDeviceByMac() is a blocking call, so it may be better way to handle it to avoid the condition.
+ Device deviceObject = networkGraph.getDeviceByMac(MACAddress.valueOf(destinationMac));
- OFPacketOut po = constructPacketOut(pi, sw);
-
- // Add to waiting lists
- pendingFlows.put(pathspec, new PushedFlow(intentId));
- log.debug("Put a Path {} in the pending flow, intent ID {}", pathspec, intentId);
- waitingPackets.put(intentId, new PacketToPush(po, sw.getId()));
- log.debug("Put a Packet in the wating list. related pathspec {}", pathspec);
-
- }
- }
+ if (deviceObject == null) {
+ log.debug("No device entry found for {}",
+ destinationMac);
- private OFPacketOut constructPacketOut(OFPacketIn pi, IOFSwitch sw) {
- OFPacketOut po = new OFPacketOut();
- po.setInPort(OFPort.OFPP_NONE)
- .setInPort(pi.getInPort())
- .setActions(new ArrayList<OFAction>())
- .setLengthU(OFPacketOut.MINIMUM_LENGTH);
-
- if (sw.getBuffers() == 0) {
- po.setBufferId(OFPacketOut.BUFFER_ID_NONE)
- .setPacketData(pi.getPacketData())
- .setLengthU(po.getLengthU() + po.getPacketData().length);
- }
- else {
- po.setBufferId(pi.getBufferId());
- }
-
- return po;
- }
+ //Device is not in the DB, so wait it until the device is added.
+ executor.schedule(new WaitDeviceArp(sw, pi, eth), SLEEP_TIME_FOR_DB_DEVICE_INSTALLED, TimeUnit.MILLISECONDS);
+ return;
+ }
- @Override
- public void flowsInstalled(Collection<FlowPath> installedFlowPaths) {
- }
-
- @Override
- public void flowRemoved(FlowPath removedFlowPath) {
- }
-
- public void flowRemoved(PathIntent removedIntent) {
- if(log.isTraceEnabled()){
- log.trace("Path {} was removed", removedIntent.getParentIntent().getId());
- }
+ continueHandlePacketIn(sw, pi, eth, deviceObject);
+ }
- ShortestPathIntent spfIntent = (ShortestPathIntent) removedIntent.getParentIntent();
- MACAddress srcMacAddress = MACAddress.valueOf(spfIntent.getSrcMac());
- MACAddress dstMacAddress = MACAddress.valueOf(spfIntent.getDstMac());
- Path removedPath = new Path(srcMacAddress, dstMacAddress);
-
- synchronized (lock) {
- // There *shouldn't* be any packets queued if the flow has
- // just been removed.
- List<PacketToPush> packets = waitingPackets.removeAll(spfIntent.getId());
- if (!packets.isEmpty()) {
- log.warn("Removed flow {} has packets queued.", spfIntent.getId());
- }
- pendingFlows.remove(removedPath);
- log.debug("Removed from the pendingFlow: Path {}, Flow ID {}", removedPath, spfIntent.getId());
- }
- }
-
- private void flowInstalled(PathIntent installedPath) {
- if(log.isTraceEnabled()){
- log.trace("Path {} was installed", installedPath.getParentIntent().getId());
- }
-
- ShortestPathIntent spfIntent = (ShortestPathIntent) installedPath.getParentIntent();
- MACAddress srcMacAddress = MACAddress.valueOf(spfIntent.getSrcMac());
- MACAddress dstMacAddress = MACAddress.valueOf(spfIntent.getDstMac());
- Path path = new Path(srcMacAddress, dstMacAddress);
- log.debug("Path spec {}", path);
-
- // TODO waiting packets should time out. We could request a path that
- // can't be installed right now because of a network partition. The path
- // may eventually be installed, but we may have received thousands of
- // packets in the meantime and probably don't want to send very old packets.
-
- List<PacketToPush> packets = null;
- net.onrc.onos.core.topology.Path graphPath = installedPath.getPath();
-
- log.debug("path{}", graphPath);
- Short outPort = graphPath.get(0).getSrc().getNumber().shortValue();
-
- PushedFlow existingFlow = null;
-
- synchronized (lock) {
- existingFlow = pendingFlows.get(path);
+ private class WaitDeviceArp implements Runnable {
+ IOFSwitch sw;
+ OFPacketIn pi;
+ Ethernet eth;
- if (existingFlow != null) {
- existingFlow.installed = true;
- existingFlow.firstOutPort = outPort;
- } else {
- log.debug("ExistingFlow {} is null", path);
- return;
- }
+ public WaitDeviceArp(IOFSwitch sw, OFPacketIn pi, Ethernet eth) {
+ super();
+ this.sw = sw;
+ this.pi = pi;
+ this.eth = eth;
+ }
- //Check both existing flow are installed status.
- if(existingFlow.installed){
- packets = waitingPackets.removeAll(existingFlow.intentId);
- if(log.isDebugEnabled()){
- log.debug("removed my packets {} to push from waitingPackets. outPort {} size {}",
- existingFlow.intentId, existingFlow.firstOutPort, packets.size());
- }
- }else{
- log.debug("Forward or reverse flows hasn't been pushed yet. return");
- return;
- }
- }
-
- for (PacketToPush packet : packets) {
- log.debug("Start packetToPush to sw {}, outPort {}, path {}", packet.dpid, existingFlow.firstOutPort, path);
- IOFSwitch sw = floodlightProvider.getSwitches().get(packet.dpid);
- sendPacketOut(sw, packet.packet, existingFlow.firstOutPort);
- }
- }
-
- private void sendPacketOut(IOFSwitch sw, OFPacketOut po, short outPort) {
- po.getActions().add(new OFActionOutput(outPort));
- po.setActionsLength((short)
- (po.getActionsLength() + OFActionOutput.MINIMUM_LENGTH));
- po.setLengthU(po.getLengthU() + OFActionOutput.MINIMUM_LENGTH);
-
- flowPusher.add(sw, po);
- }
+ @Override
+ public void run() {
+ Device deviceObject = networkGraph.getDeviceByMac(MACAddress.valueOf(eth.getDestinationMACAddress()));
+ if (deviceObject == null) {
+ log.debug("wait {}ms and device was not found. Send broadcast packet and the thread finish.", SLEEP_TIME_FOR_DB_DEVICE_INSTALLED);
+ handleBroadcast(sw, pi, eth);
+ return;
+ }
+ log.debug("wait {}ms and device {} was found, continue", SLEEP_TIME_FOR_DB_DEVICE_INSTALLED, deviceObject.getMacAddress());
+ continueHandlePacketIn(sw, pi, eth, deviceObject);
+ }
+ }
- @Override
- public void entryAdded(IntentStateList value) {
- entryUpdated(value);
-
- }
+ private void continueHandlePacketIn(IOFSwitch sw, OFPacketIn pi, Ethernet eth, Device deviceObject) {
- @Override
- public void entryRemoved(IntentStateList value) {
- //no-op
- }
+ log.debug("Start continuehandlePacketIn");
- @Override
- public void entryUpdated(IntentStateList value) {
- for (Entry<String, IntentState> entry: value.entrySet()) {
- log.debug("path intent key {}, value {}", entry.getKey(), entry.getValue());
- PathIntent pathIntent = (PathIntent) intentMap.getIntent(entry.getKey());
- if (pathIntent == null)
- continue;
-
- if (!(pathIntent.getParentIntent() instanceof ShortestPathIntent))
- continue;
+ //Iterator<IPortObject> ports = deviceObject.getAttachedPorts().iterator();
+ Iterator<net.onrc.onos.core.topology.Port> ports = deviceObject.getAttachmentPoints().iterator();
+ if (!ports.hasNext()) {
+ log.debug("No attachment point found for device {} - broadcasting packet",
+ deviceObject.getMacAddress());
+ handleBroadcast(sw, pi, eth);
+ return;
+ }
- IntentState state = entry.getValue();
- switch (state) {
- case INST_REQ:
- break;
- case INST_ACK:
- flowInstalled(pathIntent);
- break;
- case INST_NACK:
- break;
- case DEL_REQ:
- break;
- case DEL_ACK:
- flowRemoved(pathIntent);
- break;
- case DEL_PENDING:
- break;
- default:
- break;
- }
- }
- }
+ //This code assumes the device has only one port. It should be problem.
+ net.onrc.onos.core.topology.Port portObject = ports.next();
+ short destinationPort = portObject.getNumber().shortValue();
+ Switch switchObject = portObject.getSwitch();
+ long destinationDpid = switchObject.getDpid();
+
+ // TODO SwitchPort, Dpid and Port should probably be immutable
+ SwitchPort srcSwitchPort = new SwitchPort(
+ new Dpid(sw.getId()), new Port(pi.getInPort()));
+ SwitchPort dstSwitchPort = new SwitchPort(
+ new Dpid(destinationDpid), new Port(destinationPort));
+
+ MACAddress srcMacAddress = MACAddress.valueOf(eth.getSourceMACAddress());
+ MACAddress dstMacAddress = MACAddress.valueOf(eth.getDestinationMACAddress());
+
+ synchronized (lock) {
+ //TODO check concurrency
+ Path pathspec = new Path(srcMacAddress, dstMacAddress);
+ PushedFlow existingFlow = pendingFlows.get(pathspec);
+
+ //A path is installed side by side to reduce a path timeout and a wrong state.
+ if (existingFlow != null) {
+ // We've already start to install a flow for this pair of MAC addresses
+ if (log.isDebugEnabled()) {
+ log.debug("Found existing the same pathspec {}, intent ID is {}",
+ pathspec,
+ existingFlow.intentId);
+ }
+
+ OFPacketOut po = constructPacketOut(pi, sw);
+
+ // Find the correct port here. We just assume the PI is from
+ // the first hop switch, but this is definitely not always
+ // the case. We'll have to retrieve the flow from HZ every time
+ // because it could change (be rerouted) sometimes.
+ if (existingFlow.installed) {
+ // Flow has been sent to the switches so it is safe to
+ // send a packet out now
+
+ Intent intent = intentMap.getIntent(existingFlow.intentId);
+ PathIntent pathIntent = null;
+ if (intent instanceof PathIntent) {
+ pathIntent = (PathIntent) intent;
+ } else {
+ log.debug("Intent {} is not PathIntent. Return.", intent.getId());
+ return;
+ }
+
+ Boolean isflowEntryForThisSwitch = false;
+ net.onrc.onos.core.topology.Path path = pathIntent.getPath();
+
+ for (Iterator<LinkEvent> i = path.iterator(); i.hasNext(); ) {
+ LinkEvent le = (LinkEvent) i.next();
+ if (le.getSrc().dpid == sw.getId()) {
+ log.debug("src {} dst {}", le.getSrc(), le.getDst());
+ isflowEntryForThisSwitch = true;
+ break;
+ }
+ }
+
+ if (isflowEntryForThisSwitch == false) {
+ // If we don't find a flow entry for that switch, then we're
+ // in the middle of a rerouting (or something's gone wrong).
+ // This packet will be dropped as a victim of the rerouting.
+ log.debug("Dropping packet on flow {} between {}-{}",
+ existingFlow.intentId,
+ srcMacAddress, dstMacAddress);
+ } else {
+ log.debug("Sending packet out from sw {}, outport{}", sw, existingFlow.firstOutPort);
+ sendPacketOut(sw, po, existingFlow.firstOutPort);
+ }
+ } else {
+ // Flow path has not yet been installed to switches so save the
+ // packet out for later
+ log.debug("Put a packet into the waitng list. flowId {}", existingFlow.intentId);
+ waitingPackets.put(existingFlow.intentId, new PacketToPush(po, sw.getId()));
+ }
+ return;
+ }
+
+ log.debug("Adding new flow between {} at {} and {} at {}",
+ new Object[]{srcMacAddress, srcSwitchPort, dstMacAddress, dstSwitchPort});
+
+ String intentId = callerId + ":" + controllerRegistryService.getNextUniqueId();
+ IntentOperationList operations = new IntentOperationList();
+ ShortestPathIntent intent = new ShortestPathIntent(intentId,
+ sw.getId(), pi.getInPort(), srcMacAddress.toLong(),
+ destinationDpid, destinationPort, dstMacAddress.toLong());
+ IntentOperation.Operator operator = IntentOperation.Operator.ADD;
+ operations.add(operator, intent);
+ pathRuntime.executeIntentOperations(operations);
+
+ OFPacketOut po = constructPacketOut(pi, sw);
+
+ // Add to waiting lists
+ pendingFlows.put(pathspec, new PushedFlow(intentId));
+ log.debug("Put a Path {} in the pending flow, intent ID {}", pathspec, intentId);
+ waitingPackets.put(intentId, new PacketToPush(po, sw.getId()));
+ log.debug("Put a Packet in the wating list. related pathspec {}", pathspec);
+
+ }
+ }
+
+ private OFPacketOut constructPacketOut(OFPacketIn pi, IOFSwitch sw) {
+ OFPacketOut po = new OFPacketOut();
+ po.setInPort(OFPort.OFPP_NONE)
+ .setInPort(pi.getInPort())
+ .setActions(new ArrayList<OFAction>())
+ .setLengthU(OFPacketOut.MINIMUM_LENGTH);
+
+ if (sw.getBuffers() == 0) {
+ po.setBufferId(OFPacketOut.BUFFER_ID_NONE)
+ .setPacketData(pi.getPacketData())
+ .setLengthU(po.getLengthU() + po.getPacketData().length);
+ } else {
+ po.setBufferId(pi.getBufferId());
+ }
+
+ return po;
+ }
+
+ @Override
+ public void flowsInstalled(Collection<FlowPath> installedFlowPaths) {
+ }
+
+ @Override
+ public void flowRemoved(FlowPath removedFlowPath) {
+ }
+
+ public void flowRemoved(PathIntent removedIntent) {
+ if (log.isTraceEnabled()) {
+ log.trace("Path {} was removed", removedIntent.getParentIntent().getId());
+ }
+
+ ShortestPathIntent spfIntent = (ShortestPathIntent) removedIntent.getParentIntent();
+ MACAddress srcMacAddress = MACAddress.valueOf(spfIntent.getSrcMac());
+ MACAddress dstMacAddress = MACAddress.valueOf(spfIntent.getDstMac());
+ Path removedPath = new Path(srcMacAddress, dstMacAddress);
+
+ synchronized (lock) {
+ // There *shouldn't* be any packets queued if the flow has
+ // just been removed.
+ List<PacketToPush> packets = waitingPackets.removeAll(spfIntent.getId());
+ if (!packets.isEmpty()) {
+ log.warn("Removed flow {} has packets queued.", spfIntent.getId());
+ }
+ pendingFlows.remove(removedPath);
+ log.debug("Removed from the pendingFlow: Path {}, Flow ID {}", removedPath, spfIntent.getId());
+ }
+ }
+
+ private void flowInstalled(PathIntent installedPath) {
+ if (log.isTraceEnabled()) {
+ log.trace("Path {} was installed", installedPath.getParentIntent().getId());
+ }
+
+ ShortestPathIntent spfIntent = (ShortestPathIntent) installedPath.getParentIntent();
+ MACAddress srcMacAddress = MACAddress.valueOf(spfIntent.getSrcMac());
+ MACAddress dstMacAddress = MACAddress.valueOf(spfIntent.getDstMac());
+ Path path = new Path(srcMacAddress, dstMacAddress);
+ log.debug("Path spec {}", path);
+
+ // TODO waiting packets should time out. We could request a path that
+ // can't be installed right now because of a network partition. The path
+ // may eventually be installed, but we may have received thousands of
+ // packets in the meantime and probably don't want to send very old packets.
+
+ List<PacketToPush> packets = null;
+ net.onrc.onos.core.topology.Path graphPath = installedPath.getPath();
+
+ log.debug("path{}", graphPath);
+ Short outPort = graphPath.get(0).getSrc().getNumber().shortValue();
+
+ PushedFlow existingFlow = null;
+
+ synchronized (lock) {
+ existingFlow = pendingFlows.get(path);
+
+ if (existingFlow != null) {
+ existingFlow.installed = true;
+ existingFlow.firstOutPort = outPort;
+ } else {
+ log.debug("ExistingFlow {} is null", path);
+ return;
+ }
+
+ //Check both existing flow are installed status.
+ if (existingFlow.installed) {
+ packets = waitingPackets.removeAll(existingFlow.intentId);
+ if (log.isDebugEnabled()) {
+ log.debug("removed my packets {} to push from waitingPackets. outPort {} size {}",
+ existingFlow.intentId, existingFlow.firstOutPort, packets.size());
+ }
+ } else {
+ log.debug("Forward or reverse flows hasn't been pushed yet. return");
+ return;
+ }
+ }
+
+ for (PacketToPush packet : packets) {
+ log.debug("Start packetToPush to sw {}, outPort {}, path {}", packet.dpid, existingFlow.firstOutPort, path);
+ IOFSwitch sw = floodlightProvider.getSwitches().get(packet.dpid);
+ sendPacketOut(sw, packet.packet, existingFlow.firstOutPort);
+ }
+ }
+
+ private void sendPacketOut(IOFSwitch sw, OFPacketOut po, short outPort) {
+ po.getActions().add(new OFActionOutput(outPort));
+ po.setActionsLength((short)
+ (po.getActionsLength() + OFActionOutput.MINIMUM_LENGTH));
+ po.setLengthU(po.getLengthU() + OFActionOutput.MINIMUM_LENGTH);
+
+ flowPusher.add(sw, po);
+ }
+
+ @Override
+ public void entryAdded(IntentStateList value) {
+ entryUpdated(value);
+
+ }
+
+ @Override
+ public void entryRemoved(IntentStateList value) {
+ //no-op
+ }
+
+ @Override
+ public void entryUpdated(IntentStateList value) {
+ for (Entry<String, IntentState> entry : value.entrySet()) {
+ log.debug("path intent key {}, value {}", entry.getKey(), entry.getValue());
+ PathIntent pathIntent = (PathIntent) intentMap.getIntent(entry.getKey());
+ if (pathIntent == null)
+ continue;
+
+ if (!(pathIntent.getParentIntent() instanceof ShortestPathIntent))
+ continue;
+
+ IntentState state = entry.getValue();
+ switch (state) {
+ case INST_REQ:
+ break;
+ case INST_ACK:
+ flowInstalled(pathIntent);
+ break;
+ case INST_NACK:
+ break;
+ case DEL_REQ:
+ break;
+ case DEL_ACK:
+ flowRemoved(pathIntent);
+ break;
+ case DEL_PENDING:
+ break;
+ default:
+ break;
+ }
+ }
+ }
}
diff --git a/src/main/java/net/onrc/onos/apps/forwarding/IForwardingService.java b/src/main/java/net/onrc/onos/apps/forwarding/IForwardingService.java
index 375da88..6968999 100644
--- a/src/main/java/net/onrc/onos/apps/forwarding/IForwardingService.java
+++ b/src/main/java/net/onrc/onos/apps/forwarding/IForwardingService.java
@@ -8,26 +8,26 @@
/**
* Temporary interface that allows the Forwarding module to be
* notified when a flow has been installed.
- *
+ * <p/>
* This should be refactored to a listener framework in the future.
- * @author jono
*
+ * @author jono
*/
public interface IForwardingService extends IFloodlightService {
- /**
- * Notify the Forwarding module that a collection of flows has been
- * installed in the network.
- *
- * @param installedFlowPaths the collection of FlowPaths that have
- * been installed in the network.
- */
- public void flowsInstalled(Collection<FlowPath> installedFlowPaths);
-
- /**
- * Notify the Forwarding module that a flow has expired and been
- * removed from the network.
- *
- * @param removedFlowPath The FlowPath that was removed
- */
- public void flowRemoved(FlowPath removedFlowPath);
+ /**
+ * Notify the Forwarding module that a collection of flows has been
+ * installed in the network.
+ *
+ * @param installedFlowPaths the collection of FlowPaths that have
+ * been installed in the network.
+ */
+ public void flowsInstalled(Collection<FlowPath> installedFlowPaths);
+
+ /**
+ * Notify the Forwarding module that a flow has expired and been
+ * removed from the network.
+ *
+ * @param removedFlowPath The FlowPath that was removed
+ */
+ public void flowRemoved(FlowPath removedFlowPath);
}
diff --git a/src/main/java/net/onrc/onos/apps/proxyarp/ArpCache.java b/src/main/java/net/onrc/onos/apps/proxyarp/ArpCache.java
index f2e2891..f8c1589 100644
--- a/src/main/java/net/onrc/onos/apps/proxyarp/ArpCache.java
+++ b/src/main/java/net/onrc/onos/apps/proxyarp/ArpCache.java
@@ -43,6 +43,7 @@
/**
* Class constructor, specifying the MAC address for the entry.
+ *
* @param macAddress MAC address for the entry
*/
public ArpCacheEntry(MACAddress macAddress) {
@@ -52,6 +53,7 @@
/**
* Returns the MAC address this entry represents.
+ *
* @return this entry's MAC address
*/
public MACAddress getMacAddress() {
@@ -60,6 +62,7 @@
/**
* Update the timestamp for this entry.
+ *
* @param time the new timestamp to update the entry with
*/
public void setTimeLastSeen(long time) {
@@ -68,6 +71,7 @@
/**
* Returns whether the entry has timed out or not.
+ *
* @return true if the entry has timed out.
*/
public boolean isExpired() {
@@ -84,6 +88,7 @@
/**
* Get the MAC address that is mapped to an IP address in the ARP cache.
+ *
* @param ipAddress the IP address to look up
* @return the MAC address if found in the cache, null if not
*/
@@ -110,7 +115,8 @@
* Update an entry in the ARP cache. If the IP to MAC mapping is already
* in the cache, its timestamp will be updated. If not, the entry will
* be added with a new timestamp of the current time.
- * @param ipAddress the IP address that will be mapped in the cache
+ *
+ * @param ipAddress the IP address that will be mapped in the cache
* @param macAddress the MAC address that maps to {@code ipAddress}
*/
synchronized void update(InetAddress ipAddress, MACAddress macAddress) {
@@ -125,8 +131,8 @@
/**
* Retrieve a list of all mappings in the ARP cache.
- * @return list of all ARP mappings, formatted as a human-readable string
*
+ * @return list of all ARP mappings, formatted as a human-readable string
*/
synchronized List<String> getMappings() {
List<String> result = new ArrayList<String>(arpCache.size());
diff --git a/src/main/java/net/onrc/onos/apps/proxyarp/ArpCacheResource.java b/src/main/java/net/onrc/onos/apps/proxyarp/ArpCacheResource.java
index 7bf2a5a..70818c9 100644
--- a/src/main/java/net/onrc/onos/apps/proxyarp/ArpCacheResource.java
+++ b/src/main/java/net/onrc/onos/apps/proxyarp/ArpCacheResource.java
@@ -7,12 +7,12 @@
/**
* REST resource to view the IP to MAC mappings in the ARP cache.
- *
*/
public class ArpCacheResource extends ServerResource {
/**
* Handler for a REST call to retrieve the ARP cache.
+ *
* @return list of mappings formatted as a human-readable string.
*/
@Get("json")
diff --git a/src/main/java/net/onrc/onos/apps/proxyarp/ArpReplyNotification.java b/src/main/java/net/onrc/onos/apps/proxyarp/ArpReplyNotification.java
index bde2734..9866359 100644
--- a/src/main/java/net/onrc/onos/apps/proxyarp/ArpReplyNotification.java
+++ b/src/main/java/net/onrc/onos/apps/proxyarp/ArpReplyNotification.java
@@ -15,20 +15,24 @@
private int targetAddress;
private MACAddress targetMacAddress;
- protected ArpReplyNotification() {}
+ protected ArpReplyNotification() {
+ }
+
/**
* Class constructor.
- * @param targetAddress IP address received from the ARP reply
+ *
+ * @param targetAddress IP address received from the ARP reply
* @param targetMacAddress MAC address received from the ARP reply
*/
public ArpReplyNotification(int targetAddress,
- MACAddress targetMacAddress) {
+ MACAddress targetMacAddress) {
this.targetAddress = targetAddress;
this.targetMacAddress = targetMacAddress;
}
/**
* Returns the IP address of the ARP reply.
+ *
* @return the IP address
*/
public int getTargetAddress() {
@@ -37,6 +41,7 @@
/**
* Returns the MAC address of the ARP reply.
+ *
* @return the MAC address
*/
public MACAddress getTargetMacAddress() {
diff --git a/src/main/java/net/onrc/onos/apps/proxyarp/BroadcastPacketOutNotification.java b/src/main/java/net/onrc/onos/apps/proxyarp/BroadcastPacketOutNotification.java
index c2097f2..5f70cf1 100644
--- a/src/main/java/net/onrc/onos/apps/proxyarp/BroadcastPacketOutNotification.java
+++ b/src/main/java/net/onrc/onos/apps/proxyarp/BroadcastPacketOutNotification.java
@@ -1,16 +1,15 @@
package net.onrc.onos.apps.proxyarp;
-
// TODO This class is too generic to be handled by ProxyArpService.
// TODO The generic broadcast packet shouldn't contain an IP address which is
// only for ARP packets.
+
/**
* Notification to all ONOS instances to broadcast this packet out the edge of
* the network. The edge is defined as any port that doesn't have a link to
* another switch. The one exception is the port that the packet was received
* on.
- *
*/
public class BroadcastPacketOutNotification extends PacketOutNotification {
@@ -21,32 +20,29 @@
private final short inPort;
protected BroadcastPacketOutNotification() {
- super();
+ super();
this.address = -1;
this.inSwitch = -1;
this.inPort = -1;
}
+
/**
* Class constructor.
*
- * @param packet
- * packet data to send in the packet-out
- * @param address
- * target IP address if the packet is an ARP packet
- * @param inSwitch
- * dpid of the switch the packet was received on
- * @param inPort
- * port number of the receiving port
+ * @param packet packet data to send in the packet-out
+ * @param address target IP address if the packet is an ARP packet
+ * @param inSwitch dpid of the switch the packet was received on
+ * @param inPort port number of the receiving port
*/
public BroadcastPacketOutNotification(byte[] packet, int address,
- long inSwitch, short inPort) {
+ long inSwitch, short inPort) {
super(packet);
this.address = address;
this.inSwitch = inSwitch;
this.inPort = inPort;
}
-
+
/**
* Get the dpid of the switch the packet was received on.
*
@@ -69,7 +65,7 @@
* Get the target IP address if the packet is an ARP packet.
*
* @return the target IP address for ARP packets, or null if the packet is
- * not an ARP packet
+ * not an ARP packet
*/
public int getTargetAddress() {
return address;
diff --git a/src/main/java/net/onrc/onos/apps/proxyarp/IArpRequester.java b/src/main/java/net/onrc/onos/apps/proxyarp/IArpRequester.java
index ddc0ab4..ec83b28 100644
--- a/src/main/java/net/onrc/onos/apps/proxyarp/IArpRequester.java
+++ b/src/main/java/net/onrc/onos/apps/proxyarp/IArpRequester.java
@@ -7,7 +7,6 @@
/**
* Callback interface for modules using the {@link IProxyArpService} to send ARP
* requests.
- *
*/
public interface IArpRequester {
/**
@@ -15,10 +14,8 @@
* it receives a reply for a request previously submitted by this
* {@code IArpRequester}.
*
- * @param ipAddress
- * The IP address than an ARP request was sent for
- * @param macAddress
- * The MAC address mapped to the requested IP address
+ * @param ipAddress The IP address than an ARP request was sent for
+ * @param macAddress The MAC address mapped to the requested IP address
*/
public void arpResponse(InetAddress ipAddress, MACAddress macAddress);
}
diff --git a/src/main/java/net/onrc/onos/apps/proxyarp/IProxyArpService.java b/src/main/java/net/onrc/onos/apps/proxyarp/IProxyArpService.java
index 1cdf18c..7093d3b 100644
--- a/src/main/java/net/onrc/onos/apps/proxyarp/IProxyArpService.java
+++ b/src/main/java/net/onrc/onos/apps/proxyarp/IProxyArpService.java
@@ -7,6 +7,7 @@
import net.floodlightcontroller.util.MACAddress;
// Extends IFloodlightService so we can access it from REST API resources
+
/**
* Provides ARP services to other modules.
*/
@@ -17,7 +18,7 @@
*
* @param ipAddress the IP address to request the ARP mapping for
* @return the MACAddress that maps to the specified IP address, or null if
- * no mapping is found
+ * no mapping is found
*/
public MACAddress getMacAddress(InetAddress ipAddress);
@@ -28,10 +29,10 @@
* @param ipAddress the IP address to send an ARP request for
* @param requester the {@link IArpRequester} object that will be called if
* a reply is received
- * @param retry whether to keep sending requests until the MAC is learnt
+ * @param retry whether to keep sending requests until the MAC is learnt
*/
public void sendArpRequest(InetAddress ipAddress, IArpRequester requester,
- boolean retry);
+ boolean retry);
/**
* Returns a snapshot of the entire ARP cache.
diff --git a/src/main/java/net/onrc/onos/apps/proxyarp/PacketOutNotification.java b/src/main/java/net/onrc/onos/apps/proxyarp/PacketOutNotification.java
index bd64e59..c0b56a7 100644
--- a/src/main/java/net/onrc/onos/apps/proxyarp/PacketOutNotification.java
+++ b/src/main/java/net/onrc/onos/apps/proxyarp/PacketOutNotification.java
@@ -8,20 +8,21 @@
* abstract base class that will be subclassed by specific types of
* notifications.
*/
-public abstract class PacketOutNotification implements Serializable{
+public abstract class PacketOutNotification implements Serializable {
private static final long serialVersionUID = 1L;
protected final byte[] packet;
-
+
/**
* Class constructor.
+ *
* @param packet the packet data to send in the packet-out
*/
public PacketOutNotification() {
- packet = null;
+ packet = null;
}
-
+
public PacketOutNotification(byte[] packet) {
this.packet = packet;
}
diff --git a/src/main/java/net/onrc/onos/apps/proxyarp/ProxyArpManager.java b/src/main/java/net/onrc/onos/apps/proxyarp/ProxyArpManager.java
index f876310..805e657 100644
--- a/src/main/java/net/onrc/onos/apps/proxyarp/ProxyArpManager.java
+++ b/src/main/java/net/onrc/onos/apps/proxyarp/ProxyArpManager.java
@@ -55,7 +55,7 @@
import com.google.common.collect.SetMultimap;
public class ProxyArpManager implements IProxyArpService, IOFMessageListener,
- IFloodlightModule {
+ IFloodlightModule {
private static final Logger log = LoggerFactory
.getLogger(ProxyArpManager.class);
@@ -72,16 +72,16 @@
private static final String BROADCAST_PACKET_OUT_CHANNEL_NAME = "onos.broadcast_packet_out";
private static final String SINGLE_PACKET_OUT_CHANNEL_NAME = "onos.single_packet_out";
private ArpReplyEventHandler arpReplyEventHandler = new ArpReplyEventHandler();
- private BroadcastPacketOutEventHandler broadcastPacketOutEventHandler = new BroadcastPacketOutEventHandler();
+ private BroadcastPacketOutEventHandler broadcastPacketOutEventHandler = new BroadcastPacketOutEventHandler();
private SinglePacketOutEventHandler singlePacketOutEventHandler = new SinglePacketOutEventHandler();
private IConfigInfoService configService;
private IRestApiService restApi;
private IFlowPusherService flowPusher;
-
- private INetworkGraphService networkGraphService;
- private NetworkGraph networkGraph;
- private IOnosDeviceService onosDeviceService;
+
+ private INetworkGraphService networkGraphService;
+ private NetworkGraph networkGraph;
+ private IOnosDeviceService onosDeviceService;
private short vlan;
private static final short NO_VLAN = 0;
@@ -89,123 +89,123 @@
private SetMultimap<InetAddress, ArpRequest> arpRequests;
private class BroadcastPacketOutEventHandler implements
- IEventChannelListener<Long, BroadcastPacketOutNotification> {
+ IEventChannelListener<Long, BroadcastPacketOutNotification> {
- @Override
- public void entryAdded(BroadcastPacketOutNotification value) {
- if(log.isTraceEnabled()) {
- log.trace("entryAdded ip{}, sw {}, port {}, packet {}", value.getTargetAddress(), value.getInSwitch(), value.getInPort(), value.packet.length);
- }
- BroadcastPacketOutNotification notification = (BroadcastPacketOutNotification) value;
- broadcastArpRequestOutMyEdge(notification.packet,
- notification.getInSwitch(),
- notification.getInPort());
-
- // set timestamp
- ByteBuffer buffer = ByteBuffer.allocate(4);
- buffer.putInt(notification.getTargetAddress());
- InetAddress addr = null;
- try {
- addr = InetAddress.getByAddress(buffer.array());
- } catch (UnknownHostException e) {
- log.error("Exception:", e);
- }
-
- if (addr != null) {
- for (ArpRequest request : arpRequests.get(addr)) {
- request.setRequestTime();
- }
- }
- }
-
- @Override
- public void entryUpdated(BroadcastPacketOutNotification value) {
- log.debug("entryUpdated");
- // TODO: For now, entryUpdated() is processed as entryAdded()
- entryAdded(value);
- }
-
- @Override
- public void entryRemoved(BroadcastPacketOutNotification value) {
- log.debug("entryRemoved");
- // TODO: Not implemented. Revisit when this module is refactored
- }
+ @Override
+ public void entryAdded(BroadcastPacketOutNotification value) {
+ if (log.isTraceEnabled()) {
+ log.trace("entryAdded ip{}, sw {}, port {}, packet {}", value.getTargetAddress(), value.getInSwitch(), value.getInPort(), value.packet.length);
+ }
+ BroadcastPacketOutNotification notification = (BroadcastPacketOutNotification) value;
+ broadcastArpRequestOutMyEdge(notification.packet,
+ notification.getInSwitch(),
+ notification.getInPort());
+
+ // set timestamp
+ ByteBuffer buffer = ByteBuffer.allocate(4);
+ buffer.putInt(notification.getTargetAddress());
+ InetAddress addr = null;
+ try {
+ addr = InetAddress.getByAddress(buffer.array());
+ } catch (UnknownHostException e) {
+ log.error("Exception:", e);
+ }
+
+ if (addr != null) {
+ for (ArpRequest request : arpRequests.get(addr)) {
+ request.setRequestTime();
+ }
+ }
+ }
+
+ @Override
+ public void entryUpdated(BroadcastPacketOutNotification value) {
+ log.debug("entryUpdated");
+ // TODO: For now, entryUpdated() is processed as entryAdded()
+ entryAdded(value);
+ }
+
+ @Override
+ public void entryRemoved(BroadcastPacketOutNotification value) {
+ log.debug("entryRemoved");
+ // TODO: Not implemented. Revisit when this module is refactored
+ }
}
-
+
private class SinglePacketOutEventHandler implements
- IEventChannelListener<Long, SinglePacketOutNotification> {
- @Override
- public void entryAdded(SinglePacketOutNotification packetOutNotification) {
- log.debug("entryAdded");
- SinglePacketOutNotification notification =
- (SinglePacketOutNotification) packetOutNotification;
- sendArpRequestOutPort(notification.packet,
- notification.getOutSwitch(),
- notification.getOutPort());
-
- // set timestamp
- ByteBuffer buffer = ByteBuffer.allocate(4);
- buffer.putInt(notification.getTargetAddress());
- InetAddress addr = null;
- try {
- addr = InetAddress.getByAddress(buffer.array());
- } catch (UnknownHostException e) {
- log.error("Exception:", e);
- }
-
- if (addr != null) {
- for (ArpRequest request : arpRequests.get(addr)) {
- request.setRequestTime();
- }
- }
- }
-
- @Override
- public void entryUpdated(SinglePacketOutNotification packetOutNotification) {
- log.debug("entryUpdated");
- // TODO: For now, entryUpdated() is processed as entryAdded()
- entryAdded(packetOutNotification);
- }
-
- @Override
- public void entryRemoved(SinglePacketOutNotification packetOutNotification) {
- log.debug("entryRemoved");
- // TODO: Not implemented. Revisit when this module is refactored
- }
+ IEventChannelListener<Long, SinglePacketOutNotification> {
+ @Override
+ public void entryAdded(SinglePacketOutNotification packetOutNotification) {
+ log.debug("entryAdded");
+ SinglePacketOutNotification notification =
+ (SinglePacketOutNotification) packetOutNotification;
+ sendArpRequestOutPort(notification.packet,
+ notification.getOutSwitch(),
+ notification.getOutPort());
+
+ // set timestamp
+ ByteBuffer buffer = ByteBuffer.allocate(4);
+ buffer.putInt(notification.getTargetAddress());
+ InetAddress addr = null;
+ try {
+ addr = InetAddress.getByAddress(buffer.array());
+ } catch (UnknownHostException e) {
+ log.error("Exception:", e);
+ }
+
+ if (addr != null) {
+ for (ArpRequest request : arpRequests.get(addr)) {
+ request.setRequestTime();
+ }
+ }
+ }
+
+ @Override
+ public void entryUpdated(SinglePacketOutNotification packetOutNotification) {
+ log.debug("entryUpdated");
+ // TODO: For now, entryUpdated() is processed as entryAdded()
+ entryAdded(packetOutNotification);
+ }
+
+ @Override
+ public void entryRemoved(SinglePacketOutNotification packetOutNotification) {
+ log.debug("entryRemoved");
+ // TODO: Not implemented. Revisit when this module is refactored
+ }
}
private class ArpReplyEventHandler implements
- IEventChannelListener<Long, ArpReplyNotification> {
-
- @Override
- public void entryAdded(ArpReplyNotification arpReply) {
- log.debug("Received ARP reply notification for ip {}, mac {}",
- arpReply.getTargetAddress(), arpReply.getTargetMacAddress());
- ByteBuffer buffer = ByteBuffer.allocate(4);
- buffer.putInt(arpReply.getTargetAddress());
- InetAddress addr = null;
- try {
- addr = InetAddress.getByAddress(buffer.array());
- } catch (UnknownHostException e) {
- log.error("Exception:", e);
- }
-
- if(addr != null) {
- sendArpReplyToWaitingRequesters(addr,
- arpReply.getTargetMacAddress());
- }
- }
+ IEventChannelListener<Long, ArpReplyNotification> {
- @Override
- public void entryUpdated(ArpReplyNotification arpReply) {
- // TODO: For now, entryUpdated() is processed as entryAdded()
- entryAdded(arpReply);
- }
+ @Override
+ public void entryAdded(ArpReplyNotification arpReply) {
+ log.debug("Received ARP reply notification for ip {}, mac {}",
+ arpReply.getTargetAddress(), arpReply.getTargetMacAddress());
+ ByteBuffer buffer = ByteBuffer.allocate(4);
+ buffer.putInt(arpReply.getTargetAddress());
+ InetAddress addr = null;
+ try {
+ addr = InetAddress.getByAddress(buffer.array());
+ } catch (UnknownHostException e) {
+ log.error("Exception:", e);
+ }
- @Override
- public void entryRemoved(ArpReplyNotification arpReply) {
- // TODO: Not implemented. Revisit when this module is refactored
- }
+ if (addr != null) {
+ sendArpReplyToWaitingRequesters(addr,
+ arpReply.getTargetMacAddress());
+ }
+ }
+
+ @Override
+ public void entryUpdated(ArpReplyNotification arpReply) {
+ // TODO: For now, entryUpdated() is processed as entryAdded()
+ entryAdded(arpReply);
+ }
+
+ @Override
+ public void entryRemoved(ArpReplyNotification arpReply) {
+ // TODO: Not implemented. Revisit when this module is refactored
+ }
}
private static class ArpRequest {
@@ -234,7 +234,7 @@
}
public void dispatchReply(InetAddress ipAddress,
- MACAddress replyMacAddress) {
+ MACAddress replyMacAddress) {
requester.arpResponse(ipAddress, replyMacAddress);
}
@@ -260,10 +260,10 @@
ProxyArpManager.this.sendArpReply(arpRequest, dpid, port,
macAddress);
}
-
- public ARP getArpRequest() {
- return arpRequest;
- }
+
+ public ARP getArpRequest() {
+ return arpRequest;
+ }
}
@Override
@@ -298,7 +298,7 @@
@Override
public void init(FloodlightModuleContext context) {
- this.floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
+ this.floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
this.configService = context.getServiceImpl(IConfigInfoService.class);
this.restApi = context.getServiceImpl(IRestApiService.class);
this.datagrid = context.getServiceImpl(IDatagridService.class);
@@ -320,25 +320,25 @@
restApi.addRestletRoutable(new ArpWebRoutable());
floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
- networkGraph = networkGraphService.getNetworkGraph();
-
- //
- // Event notification setup: channels and event handlers
- //
- broadcastPacketOutEventChannel = datagrid.addListener(BROADCAST_PACKET_OUT_CHANNEL_NAME,
- broadcastPacketOutEventHandler,
- Long.class,
- BroadcastPacketOutNotification.class);
-
- singlePacketOutEventChannel = datagrid.addListener(SINGLE_PACKET_OUT_CHANNEL_NAME,
- singlePacketOutEventHandler,
- Long.class,
- SinglePacketOutNotification.class);
-
- arpReplyEventChannel = datagrid.addListener(ARP_REPLY_CHANNEL_NAME,
- arpReplyEventHandler,
- Long.class,
- ArpReplyNotification.class);
+ networkGraph = networkGraphService.getNetworkGraph();
+
+ //
+ // Event notification setup: channels and event handlers
+ //
+ broadcastPacketOutEventChannel = datagrid.addListener(BROADCAST_PACKET_OUT_CHANNEL_NAME,
+ broadcastPacketOutEventHandler,
+ Long.class,
+ BroadcastPacketOutNotification.class);
+
+ singlePacketOutEventChannel = datagrid.addListener(SINGLE_PACKET_OUT_CHANNEL_NAME,
+ singlePacketOutEventHandler,
+ Long.class,
+ SinglePacketOutNotification.class);
+
+ arpReplyEventChannel = datagrid.addListener(ARP_REPLY_CHANNEL_NAME,
+ arpReplyEventHandler,
+ Long.class,
+ ArpReplyNotification.class);
Timer arpTimer = new Timer("arp-processing");
arpTimer.scheduleAtFixedRate(new TimerTask() {
@@ -373,17 +373,17 @@
log.debug("Cleaning expired ARP request for {}", entry
.getKey().getHostAddress());
- // If the ARP request is expired and then delete the device
- // TODO check whether this is OK from this thread
- HostArpRequester requester = (HostArpRequester) request.requester;
- ARP req = requester.getArpRequest();
- Device targetDev = networkGraph.getDeviceByMac(MACAddress.valueOf(req.getTargetHardwareAddress()));
- if(targetDev != null) {
- onosDeviceService.deleteOnosDeviceByMac(MACAddress.valueOf(req.getTargetHardwareAddress()));
- if (log.isDebugEnabled()) {
- log.debug("RemoveDevice: {} due to no have not recieve the ARP reply", targetDev.getMacAddress());
- }
- }
+ // If the ARP request is expired and then delete the device
+ // TODO check whether this is OK from this thread
+ HostArpRequester requester = (HostArpRequester) request.requester;
+ ARP req = requester.getArpRequest();
+ Device targetDev = networkGraph.getDeviceByMac(MACAddress.valueOf(req.getTargetHardwareAddress()));
+ if (targetDev != null) {
+ onosDeviceService.deleteOnosDeviceByMac(MACAddress.valueOf(req.getTargetHardwareAddress()));
+ if (log.isDebugEnabled()) {
+ log.debug("RemoveDevice: {} due to no have not recieve the ARP reply", targetDev.getMacAddress());
+ }
+ }
it.remove();
@@ -460,7 +460,7 @@
}
private void handleArpRequest(IOFSwitch sw, OFPacketIn pi, ARP arp,
- Ethernet eth) {
+ Ethernet eth) {
if (log.isTraceEnabled()) {
log.trace("ARP request received for {}",
inetAddressToString(arp.getTargetProtocolAddress()));
@@ -492,86 +492,84 @@
// MACAddress macAddress = arpCache.lookup(target);
- arpRequests.put(target, new ArpRequest(
- new HostArpRequester(arp, sw.getId(), pi.getInPort()), false));
-
- Device targetDevice = networkGraph.getDeviceByMac(MACAddress.valueOf(arp.getTargetHardwareAddress()));
+ arpRequests.put(target, new ArpRequest(
+ new HostArpRequester(arp, sw.getId(), pi.getInPort()), false));
- if (targetDevice == null) {
- if (log.isTraceEnabled()) {
- log.trace("No device info found for {} - broadcasting",
- target.getHostAddress());
- }
-
- // We don't know the device so broadcast the request out
- BroadcastPacketOutNotification key =
- new BroadcastPacketOutNotification(eth.serialize(),
- ByteBuffer.wrap(arp.getTargetProtocolAddress()).getInt(), sw.getId(), pi.getInPort());
- log.debug("broadcastPacketOutEventChannel mac {}, ip {}, dpid {}, port {}, paket {}", eth.getSourceMAC().toLong(),
- ByteBuffer.wrap(arp.getTargetProtocolAddress()).getInt(), sw.getId(), pi.getInPort(), eth.serialize().length);
- broadcastPacketOutEventChannel.addTransientEntry(eth.getDestinationMAC().toLong(), key);
- }
- else {
- // Even if the device exists in our database, we do not reply to
- // the request directly, but check whether the device is still valid
- MACAddress macAddress = MACAddress.valueOf(arp.getTargetHardwareAddress());
+ Device targetDevice = networkGraph.getDeviceByMac(MACAddress.valueOf(arp.getTargetHardwareAddress()));
- if (log.isTraceEnabled()) {
- log.trace("The target Device Record in DB is: {} => {} from ARP request host at {}/{}",
- new Object [] {
- inetAddressToString(arp.getTargetProtocolAddress()),
- macAddress,
- HexString.toHexString(sw.getId()), pi.getInPort()});
- }
+ if (targetDevice == null) {
+ if (log.isTraceEnabled()) {
+ log.trace("No device info found for {} - broadcasting",
+ target.getHostAddress());
+ }
- // sendArpReply(arp, sw.getId(), pi.getInPort(), macAddress);
+ // We don't know the device so broadcast the request out
+ BroadcastPacketOutNotification key =
+ new BroadcastPacketOutNotification(eth.serialize(),
+ ByteBuffer.wrap(arp.getTargetProtocolAddress()).getInt(), sw.getId(), pi.getInPort());
+ log.debug("broadcastPacketOutEventChannel mac {}, ip {}, dpid {}, port {}, paket {}", eth.getSourceMAC().toLong(),
+ ByteBuffer.wrap(arp.getTargetProtocolAddress()).getInt(), sw.getId(), pi.getInPort(), eth.serialize().length);
+ broadcastPacketOutEventChannel.addTransientEntry(eth.getDestinationMAC().toLong(), key);
+ } else {
+ // Even if the device exists in our database, we do not reply to
+ // the request directly, but check whether the device is still valid
+ MACAddress macAddress = MACAddress.valueOf(arp.getTargetHardwareAddress());
- Iterable<net.onrc.onos.core.topology.Port> outPorts = targetDevice.getAttachmentPoints();
+ if (log.isTraceEnabled()) {
+ log.trace("The target Device Record in DB is: {} => {} from ARP request host at {}/{}",
+ new Object[]{
+ inetAddressToString(arp.getTargetProtocolAddress()),
+ macAddress,
+ HexString.toHexString(sw.getId()), pi.getInPort()});
+ }
- if (!outPorts.iterator().hasNext()){
- if (log.isTraceEnabled()) {
- log.trace("Device {} exists but is not connected to any ports" +
- " - broadcasting", macAddress);
- }
-
-// BroadcastPacketOutNotification key =
-// new BroadcastPacketOutNotification(eth.serialize(),
-// target, sw.getId(), pi.getInPort());
-// broadcastPacketOutEventChannel.addTransientEntry(eth.getDestinationMAC().toLong(), key);
- }
- else {
- for (net.onrc.onos.core.topology.Port portObject : outPorts) {
- //long outSwitch = 0;
- //short outPort = 0;
+ // sendArpReply(arp, sw.getId(), pi.getInPort(), macAddress);
- if(portObject.getOutgoingLink() != null || portObject.getIncomingLink() != null) {
- continue;
- }
-
- short outPort = portObject.getNumber().shortValue();
- Switch outSwitchObject = portObject.getSwitch();
- long outSwitch = outSwitchObject.getDpid();
-
- if (log.isTraceEnabled()) {
- log.trace("Probing device {} on port {}/{}",
- new Object[] {macAddress,
- HexString.toHexString(outSwitch), outPort});
- }
-
- SinglePacketOutNotification key =
- new SinglePacketOutNotification(eth.serialize(),
- ByteBuffer.wrap(target.getAddress()).getInt(), outSwitch, outPort);
- singlePacketOutEventChannel.addTransientEntry(eth.getDestinationMAC().toLong(), key);
- }
- }
- }
+ Iterable<net.onrc.onos.core.topology.Port> outPorts = targetDevice.getAttachmentPoints();
+
+ if (!outPorts.iterator().hasNext()) {
+ if (log.isTraceEnabled()) {
+ log.trace("Device {} exists but is not connected to any ports" +
+ " - broadcasting", macAddress);
+ }
+
+// BroadcastPacketOutNotification key =
+// new BroadcastPacketOutNotification(eth.serialize(),
+// target, sw.getId(), pi.getInPort());
+// broadcastPacketOutEventChannel.addTransientEntry(eth.getDestinationMAC().toLong(), key);
+ } else {
+ for (net.onrc.onos.core.topology.Port portObject : outPorts) {
+ //long outSwitch = 0;
+ //short outPort = 0;
+
+ if (portObject.getOutgoingLink() != null || portObject.getIncomingLink() != null) {
+ continue;
+ }
+
+ short outPort = portObject.getNumber().shortValue();
+ Switch outSwitchObject = portObject.getSwitch();
+ long outSwitch = outSwitchObject.getDpid();
+
+ if (log.isTraceEnabled()) {
+ log.trace("Probing device {} on port {}/{}",
+ new Object[]{macAddress,
+ HexString.toHexString(outSwitch), outPort});
+ }
+
+ SinglePacketOutNotification key =
+ new SinglePacketOutNotification(eth.serialize(),
+ ByteBuffer.wrap(target.getAddress()).getInt(), outSwitch, outPort);
+ singlePacketOutEventChannel.addTransientEntry(eth.getDestinationMAC().toLong(), key);
+ }
+ }
+ }
}
// Not used because device manager currently updates the database
// for ARP replies. May be useful in the future.
private void handleArpReply(IOFSwitch sw, OFPacketIn pi, ARP arp) {
if (log.isTraceEnabled()) {
- log.trace("ARP reply recieved: {} => {}, on {}/{}", new Object[] {
+ log.trace("ARP reply recieved: {} => {}, on {}/{}", new Object[]{
inetAddressToString(arp.getSenderProtocolAddress()),
HexString.toHexString(arp.getSenderHardwareAddress()),
HexString.toHexString(sw.getId()), pi.getInPort()});
@@ -660,19 +658,19 @@
}
// sendArpRequestToSwitches(ipAddress, eth.serialize());
- SinglePacketOutNotification key =
- new SinglePacketOutNotification(eth.serialize(), ByteBuffer.wrap(ipAddress.getAddress()).getInt(),
- intf.getDpid(), intf.getPort());
- singlePacketOutEventChannel.addTransientEntry(MACAddress.valueOf(senderMacAddress).toLong(), key);
+ SinglePacketOutNotification key =
+ new SinglePacketOutNotification(eth.serialize(), ByteBuffer.wrap(ipAddress.getAddress()).getInt(),
+ intf.getDpid(), intf.getPort());
+ singlePacketOutEventChannel.addTransientEntry(MACAddress.valueOf(senderMacAddress).toLong(), key);
}
-
+
private void sendArpRequestToSwitches(InetAddress dstAddress, byte[] arpRequest) {
- sendArpRequestToSwitches(dstAddress, arpRequest, 0,
- OFPort.OFPP_NONE.getValue());
+ sendArpRequestToSwitches(dstAddress, arpRequest, 0,
+ OFPort.OFPP_NONE.getValue());
}
private void sendArpRequestToSwitches(InetAddress dstAddress,
- byte[] arpRequest, long inSwitch, short inPort) {
+ byte[] arpRequest, long inSwitch, short inPort) {
if (configService.hasLayer3Configuration()) {
Interface intf = configService.getOutgoingInterface(dstAddress);
@@ -718,14 +716,14 @@
MACAddress mac = new MACAddress(arp.getSenderHardwareAddress());
- ArpReplyNotification key =
- new ArpReplyNotification(ByteBuffer.wrap(targetAddress.getAddress()).getInt(), mac);
- log.debug("ArpReplyNotification ip {}, mac{}", ByteBuffer.wrap(targetAddress.getAddress()).getInt(), mac);
- arpReplyEventChannel.addTransientEntry(mac.toLong(), key);
+ ArpReplyNotification key =
+ new ArpReplyNotification(ByteBuffer.wrap(targetAddress.getAddress()).getInt(), mac);
+ log.debug("ArpReplyNotification ip {}, mac{}", ByteBuffer.wrap(targetAddress.getAddress()).getInt(), mac);
+ arpReplyEventChannel.addTransientEntry(mac.toLong(), key);
}
private void broadcastArpRequestOutMyEdge(byte[] arpRequest, long inSwitch,
- short inPort) {
+ short inPort) {
List<SwitchPort> switchPorts = new ArrayList<SwitchPort>();
for (IOFSwitch sw : floodlightProvider.getSwitches().values()) {
@@ -736,27 +734,27 @@
List<OFAction> actions = new ArrayList<OFAction>();
- Switch graphSw = networkGraph.getSwitch(sw.getId());
- Collection<net.onrc.onos.core.topology.Port> ports = graphSw.getPorts();
-
- if (ports == null) {
- continue;
- }
-
- for (net.onrc.onos.core.topology.Port portObject : ports) {
- if (portObject.getOutgoingLink() == null && portObject.getNumber() > 0) {
- Long portNumber = portObject.getNumber();
-
- if (sw.getId() == inSwitch && portNumber.shortValue() == inPort) {
- // This is the port that the ARP message came in,
- // so don't broadcast out this port
- continue;
- }
- switchPorts.add(new SwitchPort(new Dpid(sw.getId()),
- new net.onrc.onos.core.util.Port(portNumber.shortValue())));
- actions.add(new OFActionOutput(portNumber.shortValue()));
- }
- }
+ Switch graphSw = networkGraph.getSwitch(sw.getId());
+ Collection<net.onrc.onos.core.topology.Port> ports = graphSw.getPorts();
+
+ if (ports == null) {
+ continue;
+ }
+
+ for (net.onrc.onos.core.topology.Port portObject : ports) {
+ if (portObject.getOutgoingLink() == null && portObject.getNumber() > 0) {
+ Long portNumber = portObject.getNumber();
+
+ if (sw.getId() == inSwitch && portNumber.shortValue() == inPort) {
+ // This is the port that the ARP message came in,
+ // so don't broadcast out this port
+ continue;
+ }
+ switchPorts.add(new SwitchPort(new Dpid(sw.getId()),
+ new net.onrc.onos.core.util.Port(portNumber.shortValue())));
+ actions.add(new OFActionOutput(portNumber.shortValue()));
+ }
+ }
po.setActions(actions);
short actionsLength = (short) (actions.size() * OFActionOutput.MINIMUM_LENGTH);
@@ -801,11 +799,11 @@
}
private void sendArpReply(ARP arpRequest, long dpid, short port,
- MACAddress targetMac) {
+ MACAddress targetMac) {
if (log.isTraceEnabled()) {
log.trace(
"Sending reply {} => {} to {}",
- new Object[] {
+ new Object[]{
inetAddressToString(arpRequest
.getTargetProtocolAddress()),
targetMac,
@@ -883,7 +881,7 @@
@Override
public void sendArpRequest(InetAddress ipAddress, IArpRequester requester,
- boolean retry) {
+ boolean retry) {
arpRequests.put(ipAddress, new ArpRequest(requester, retry));
// Sanity check to make sure we don't send a request for our own address
@@ -898,7 +896,7 @@
}
private void sendArpReplyToWaitingRequesters(InetAddress address,
- MACAddress mac) {
+ MACAddress mac) {
log.debug("Sending ARP reply for {} to requesters",
address.getHostAddress());
@@ -920,16 +918,16 @@
//TODO here, comment outed from long time ago. I will check if we need it later.
/*IDeviceObject deviceObject = deviceStorage.getDeviceByIP(
- InetAddresses.coerceToInteger(address));
+ InetAddresses.coerceToInteger(address));
MACAddress mac = MACAddress.valueOf(deviceObject.getMACAddress());
log.debug("Found {} at {} in network map",
- address.getHostAddress(), mac);*/
+ address.getHostAddress(), mac);*/
// Don't hold an ARP lock while dispatching requests
for (ArpRequest request : requestsToSend) {
request.dispatchReply(address, mac);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/net/onrc/onos/apps/proxyarp/SinglePacketOutNotification.java b/src/main/java/net/onrc/onos/apps/proxyarp/SinglePacketOutNotification.java
index 8ee255b..ff5ab87 100644
--- a/src/main/java/net/onrc/onos/apps/proxyarp/SinglePacketOutNotification.java
+++ b/src/main/java/net/onrc/onos/apps/proxyarp/SinglePacketOutNotification.java
@@ -1,8 +1,8 @@
package net.onrc.onos.apps.proxyarp;
-
// TODO This class is too generic to be handled by ProxyArpService.
+
/**
* Notification to another ONOS instance to send a packet out a single port.
*/
@@ -16,13 +16,14 @@
/**
* Class constructor.
- * @param packet the packet data to send in the packet-out
- * @param address target IP address if the packet is an ARP packet
+ *
+ * @param packet the packet data to send in the packet-out
+ * @param address target IP address if the packet is an ARP packet
* @param outSwitch the dpid of the switch to send the packet on
- * @param outPort the port number of the port to send the packet out
+ * @param outPort the port number of the port to send the packet out
*/
public SinglePacketOutNotification(byte[] packet, int address,
- long outSwitch, short outPort) {
+ long outSwitch, short outPort) {
super(packet);
this.address = address;
@@ -32,6 +33,7 @@
/**
* Get the dpid of the switch the packet will be sent out.
+ *
* @return the switch's dpid
*/
public long getOutSwitch() {
@@ -40,6 +42,7 @@
/**
* Get the port number of the port the packet will be sent out.
+ *
* @return the port number
*/
public short getOutPort() {
@@ -48,8 +51,9 @@
/**
* Get the target IP address if the packet is an ARP packet.
+ *
* @return the target IP address for ARP packets, or null if the packet is
- * not an ARP packet
+ * not an ARP packet
*/
public int getTargetAddress() {
return address;
diff --git a/src/main/java/net/onrc/onos/core/datagrid/web/GetNGFlowsSummaryResource.java b/src/main/java/net/onrc/onos/core/datagrid/web/GetNGFlowsSummaryResource.java
index 64edb24..fa7c6d1 100644
--- a/src/main/java/net/onrc/onos/core/datagrid/web/GetNGFlowsSummaryResource.java
+++ b/src/main/java/net/onrc/onos/core/datagrid/web/GetNGFlowsSummaryResource.java
@@ -29,9 +29,9 @@
/**
* REST API call to get a summary of Flow Paths.
- *
+ * <p/>
* NOTE: This REST API call is needed for the ONOS GUI.
- *
+ * <p/>
* GET /wm/onos/datagrid/get/ng-flows/summary/json
*/
public class GetNGFlowsSummaryResource extends ServerResource {
diff --git a/src/main/java/net/onrc/onos/core/datastore/DataStoreClient.java b/src/main/java/net/onrc/onos/core/datastore/DataStoreClient.java
index 7ec6251..be9fce5 100644
--- a/src/main/java/net/onrc/onos/core/datastore/DataStoreClient.java
+++ b/src/main/java/net/onrc/onos/core/datastore/DataStoreClient.java
@@ -8,17 +8,18 @@
private static final String BACKEND = System.getProperty("net.onrc.onos.core.datastore.backend", "hazelcast");
// Suppresses default constructor, ensuring non-instantiability.
- private DataStoreClient() {}
+ private DataStoreClient() {
+ }
public static IKVClient getClient() {
// TODO read config and return appropriate IKVClient
switch (BACKEND) {
- case "ramcloud":
- return RCClient.getClient();
- case "hazelcast":
- return HZClient.getClient();
- default:
- return HZClient.getClient();
+ case "ramcloud":
+ return RCClient.getClient();
+ case "hazelcast":
+ return HZClient.getClient();
+ default:
+ return HZClient.getClient();
}
}
diff --git a/src/main/java/net/onrc/onos/core/datastore/IKVClient.java b/src/main/java/net/onrc/onos/core/datastore/IKVClient.java
index e298548..50bdf92 100644
--- a/src/main/java/net/onrc/onos/core/datastore/IKVClient.java
+++ b/src/main/java/net/onrc/onos/core/datastore/IKVClient.java
@@ -14,7 +14,7 @@
/**
* Drop table.
- *
+ * <p/>
* Behavior of IKVTable instances accessing dropped table is undefined.
*
* @param table IKVTable to drop.
@@ -58,8 +58,7 @@
* @param tableId
* @param key
* @param value
- * @param version
- * expected version in the data store
+ * @param version expected version in the data store
* @return version after update
* @throws ObjectDoesntExistException
* @throws WrongVersionException
@@ -69,8 +68,9 @@
/**
* Update an existing Key-Value entry in table, without checking version.
- *
+ * <p/>
* FIXME remove this method and use forceCreate for this purpose?
+ *
* @param tableId
* @param key
* @param value
@@ -83,13 +83,13 @@
// TODO Adding serialized value as parameter to this interface may
// give an option to improve performance on some backends.
+
/**
* Remove an existing Key-Value entry in table
*
* @param tableId
* @param key
- * @param version
- * expected version in the data store
+ * @param version expected version in the data store
* @return version of removed object
* @throws ObjectDoesntExistException
* @throws WrongVersionException
@@ -108,35 +108,34 @@
/**
* Get all the entries in table.
+ *
* @param tableId
* @return entries in this table.
*/
public Iterable<IKVEntry> getAllEntries(IKVTableID tableId);
/**
- *
- * @see #create(IKVTableID, byte[], byte[])
- *
* @return IMultiOpEntry for this operation
- *
+ * @see #create(IKVTableID, byte[], byte[])
*/
public IMultiEntryOperation createOp(IKVTableID tableId, byte[] key, byte[] value);
public IMultiEntryOperation forceCreateOp(IKVTableID tableId, byte[] key,
- byte[] value);
+ byte[] value);
public IMultiEntryOperation readOp(IKVTableID tableId, byte[] key);
public IMultiEntryOperation updateOp(IKVTableID tableId, byte[] key, byte[] value,
- long version);
+ long version);
public IMultiEntryOperation deleteOp(IKVTableID tableId, byte[] key, byte[] value,
- long version);
+ long version);
public IMultiEntryOperation forceDeleteOp(IKVTableID tableId, byte[] key);
/**
* Batch delete operation
+ *
* @param ops delete operations
* @return true if failed operation exists
*/
@@ -144,6 +143,7 @@
/**
* Batch write operation
+ *
* @param ops write operations
* @return true if failed operation exists
*/
@@ -151,6 +151,7 @@
/**
* Batch read operation
+ *
* @param ops read operations
* @return true if failed operation exists
*/
diff --git a/src/main/java/net/onrc/onos/core/datastore/IKVTable.java b/src/main/java/net/onrc/onos/core/datastore/IKVTable.java
index 864b270..2260ad0 100644
--- a/src/main/java/net/onrc/onos/core/datastore/IKVTable.java
+++ b/src/main/java/net/onrc/onos/core/datastore/IKVTable.java
@@ -63,8 +63,7 @@
*
* @param key
* @param value
- * @param version
- * expected version in the data store
+ * @param version expected version in the data store
* @return version after update
* @throws ObjectDoesntExistException
* @throws WrongVersionException
@@ -87,8 +86,7 @@
* Remove an existing Key-Value entry in table
*
* @param key
- * @param version
- * expected version in the data store
+ * @param version expected version in the data store
* @return version of removed object
* @throws ObjectDoesntExistException
* @throws WrongVersionException
@@ -106,6 +104,7 @@
/**
* Get all the entries in table.
+ *
* @return entries in this table.
*/
public Iterable<IKVEntry> getAllEntries();
diff --git a/src/main/java/net/onrc/onos/core/datastore/ObjectDoesntExistException.java b/src/main/java/net/onrc/onos/core/datastore/ObjectDoesntExistException.java
index 06d21ca..354cd9c 100644
--- a/src/main/java/net/onrc/onos/core/datastore/ObjectDoesntExistException.java
+++ b/src/main/java/net/onrc/onos/core/datastore/ObjectDoesntExistException.java
@@ -13,7 +13,7 @@
}
public ObjectDoesntExistException(final IKVTableID tableID,
- final byte[] key, final Throwable cause) {
+ final byte[] key, final Throwable cause) {
super(ByteArrayUtil.toHexStringBuffer(key, ":")
+ " did not exist on table:" + tableID, cause);
}
diff --git a/src/main/java/net/onrc/onos/core/datastore/ObjectExistsException.java b/src/main/java/net/onrc/onos/core/datastore/ObjectExistsException.java
index 75c4e4d..08be74f 100644
--- a/src/main/java/net/onrc/onos/core/datastore/ObjectExistsException.java
+++ b/src/main/java/net/onrc/onos/core/datastore/ObjectExistsException.java
@@ -13,7 +13,7 @@
}
public ObjectExistsException(final IKVTableID tableID, final byte[] key,
- final Throwable cause) {
+ final Throwable cause) {
super(ByteArrayUtil.toHexStringBuffer(key, ":")
+ " already exist on table:" + tableID, cause);
}
diff --git a/src/main/java/net/onrc/onos/core/datastore/RCProtos.java b/src/main/java/net/onrc/onos/core/datastore/RCProtos.java
index 5e823ee..44b6934 100644
--- a/src/main/java/net/onrc/onos/core/datastore/RCProtos.java
+++ b/src/main/java/net/onrc/onos/core/datastore/RCProtos.java
@@ -4,2174 +4,2388 @@
package net.onrc.onos.core.datastore;
public final class RCProtos {
- private RCProtos() {}
- public static void registerAllExtensions(
- com.google.protobuf.ExtensionRegistry registry) {
- }
- public interface SwitchPropertyOrBuilder
- extends com.google.protobuf.MessageOrBuilder {
-
- // required int64 dpid = 1;
- /**
- * <code>required int64 dpid = 1;</code>
- */
- boolean hasDpid();
- /**
- * <code>required int64 dpid = 1;</code>
- */
- long getDpid();
-
- // required int32 status = 2;
- /**
- * <code>required int32 status = 2;</code>
- */
- boolean hasStatus();
- /**
- * <code>required int32 status = 2;</code>
- */
- int getStatus();
-
- // optional bytes value = 3;
- /**
- * <code>optional bytes value = 3;</code>
- */
- boolean hasValue();
- /**
- * <code>optional bytes value = 3;</code>
- */
- com.google.protobuf.ByteString getValue();
- }
- /**
- * Protobuf type {@code RCProtos.SwitchProperty}
- */
- public static final class SwitchProperty extends
- com.google.protobuf.GeneratedMessage
- implements SwitchPropertyOrBuilder {
- // Use SwitchProperty.newBuilder() to construct.
- private SwitchProperty(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
- super(builder);
- this.unknownFields = builder.getUnknownFields();
- }
- private SwitchProperty(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
-
- private static final SwitchProperty defaultInstance;
- public static SwitchProperty getDefaultInstance() {
- return defaultInstance;
+ private RCProtos() {
}
- public SwitchProperty getDefaultInstanceForType() {
- return defaultInstance;
+ public static void registerAllExtensions(
+ com.google.protobuf.ExtensionRegistry registry) {
}
- private final com.google.protobuf.UnknownFieldSet unknownFields;
- @java.lang.Override
- public final com.google.protobuf.UnknownFieldSet
- getUnknownFields() {
- return this.unknownFields;
- }
- private SwitchProperty(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- initFields();
- int mutable_bitField0_ = 0;
- com.google.protobuf.UnknownFieldSet.Builder unknownFields =
- com.google.protobuf.UnknownFieldSet.newBuilder();
- try {
- boolean done = false;
- while (!done) {
- int tag = input.readTag();
- switch (tag) {
- case 0:
- done = true;
- break;
- default: {
- if (!parseUnknownField(input, unknownFields,
- extensionRegistry, tag)) {
- done = true;
- }
- break;
- }
- case 8: {
- bitField0_ |= 0x00000001;
- dpid_ = input.readInt64();
- break;
- }
- case 16: {
- bitField0_ |= 0x00000002;
- status_ = input.readInt32();
- break;
- }
- case 26: {
- bitField0_ |= 0x00000004;
- value_ = input.readBytes();
- break;
- }
- }
- }
- } catch (com.google.protobuf.InvalidProtocolBufferException e) {
- throw e.setUnfinishedMessage(this);
- } catch (java.io.IOException e) {
- throw new com.google.protobuf.InvalidProtocolBufferException(
- e.getMessage()).setUnfinishedMessage(this);
- } finally {
- this.unknownFields = unknownFields.build();
- makeExtensionsImmutable();
- }
- }
- public static final com.google.protobuf.Descriptors.Descriptor
- getDescriptor() {
- return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_SwitchProperty_descriptor;
+ public interface SwitchPropertyOrBuilder
+ extends com.google.protobuf.MessageOrBuilder {
+
+ // required int64 dpid = 1;
+
+ /**
+ * <code>required int64 dpid = 1;</code>
+ */
+ boolean hasDpid();
+
+ /**
+ * <code>required int64 dpid = 1;</code>
+ */
+ long getDpid();
+
+ // required int32 status = 2;
+
+ /**
+ * <code>required int32 status = 2;</code>
+ */
+ boolean hasStatus();
+
+ /**
+ * <code>required int32 status = 2;</code>
+ */
+ int getStatus();
+
+ // optional bytes value = 3;
+
+ /**
+ * <code>optional bytes value = 3;</code>
+ */
+ boolean hasValue();
+
+ /**
+ * <code>optional bytes value = 3;</code>
+ */
+ com.google.protobuf.ByteString getValue();
}
- protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
- internalGetFieldAccessorTable() {
- return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_SwitchProperty_fieldAccessorTable
- .ensureFieldAccessorsInitialized(
- net.onrc.onos.core.datastore.RCProtos.SwitchProperty.class, net.onrc.onos.core.datastore.RCProtos.SwitchProperty.Builder.class);
- }
-
- public static com.google.protobuf.Parser<SwitchProperty> PARSER =
- new com.google.protobuf.AbstractParser<SwitchProperty>() {
- public SwitchProperty parsePartialFrom(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return new SwitchProperty(input, extensionRegistry);
- }
- };
-
- @java.lang.Override
- public com.google.protobuf.Parser<SwitchProperty> getParserForType() {
- return PARSER;
- }
-
- private int bitField0_;
- // required int64 dpid = 1;
- public static final int DPID_FIELD_NUMBER = 1;
- private long dpid_;
- /**
- * <code>required int64 dpid = 1;</code>
- */
- public boolean hasDpid() {
- return ((bitField0_ & 0x00000001) == 0x00000001);
- }
- /**
- * <code>required int64 dpid = 1;</code>
- */
- public long getDpid() {
- return dpid_;
- }
-
- // required int32 status = 2;
- public static final int STATUS_FIELD_NUMBER = 2;
- private int status_;
- /**
- * <code>required int32 status = 2;</code>
- */
- public boolean hasStatus() {
- return ((bitField0_ & 0x00000002) == 0x00000002);
- }
- /**
- * <code>required int32 status = 2;</code>
- */
- public int getStatus() {
- return status_;
- }
-
- // optional bytes value = 3;
- public static final int VALUE_FIELD_NUMBER = 3;
- private com.google.protobuf.ByteString value_;
- /**
- * <code>optional bytes value = 3;</code>
- */
- public boolean hasValue() {
- return ((bitField0_ & 0x00000004) == 0x00000004);
- }
- /**
- * <code>optional bytes value = 3;</code>
- */
- public com.google.protobuf.ByteString getValue() {
- return value_;
- }
-
- private void initFields() {
- dpid_ = 0L;
- status_ = 0;
- value_ = com.google.protobuf.ByteString.EMPTY;
- }
- private byte memoizedIsInitialized = -1;
- public final boolean isInitialized() {
- byte isInitialized = memoizedIsInitialized;
- if (isInitialized != -1) return isInitialized == 1;
-
- if (!hasDpid()) {
- memoizedIsInitialized = 0;
- return false;
- }
- if (!hasStatus()) {
- memoizedIsInitialized = 0;
- return false;
- }
- memoizedIsInitialized = 1;
- return true;
- }
-
- public void writeTo(com.google.protobuf.CodedOutputStream output)
- throws java.io.IOException {
- getSerializedSize();
- if (((bitField0_ & 0x00000001) == 0x00000001)) {
- output.writeInt64(1, dpid_);
- }
- if (((bitField0_ & 0x00000002) == 0x00000002)) {
- output.writeInt32(2, status_);
- }
- if (((bitField0_ & 0x00000004) == 0x00000004)) {
- output.writeBytes(3, value_);
- }
- getUnknownFields().writeTo(output);
- }
-
- private int memoizedSerializedSize = -1;
- public int getSerializedSize() {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (((bitField0_ & 0x00000001) == 0x00000001)) {
- size += com.google.protobuf.CodedOutputStream
- .computeInt64Size(1, dpid_);
- }
- if (((bitField0_ & 0x00000002) == 0x00000002)) {
- size += com.google.protobuf.CodedOutputStream
- .computeInt32Size(2, status_);
- }
- if (((bitField0_ & 0x00000004) == 0x00000004)) {
- size += com.google.protobuf.CodedOutputStream
- .computeBytesSize(3, value_);
- }
- size += getUnknownFields().getSerializedSize();
- memoizedSerializedSize = size;
- return size;
- }
-
- private static final long serialVersionUID = 0L;
- @java.lang.Override
- protected java.lang.Object writeReplace()
- throws java.io.ObjectStreamException {
- return super.writeReplace();
- }
-
- public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseFrom(
- com.google.protobuf.ByteString data)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return PARSER.parseFrom(data);
- }
- public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseFrom(
- com.google.protobuf.ByteString data,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return PARSER.parseFrom(data, extensionRegistry);
- }
- public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseFrom(byte[] data)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return PARSER.parseFrom(data);
- }
- public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseFrom(
- byte[] data,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return PARSER.parseFrom(data, extensionRegistry);
- }
- public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseFrom(java.io.InputStream input)
- throws java.io.IOException {
- return PARSER.parseFrom(input);
- }
- public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseFrom(
- java.io.InputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- return PARSER.parseFrom(input, extensionRegistry);
- }
- public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseDelimitedFrom(java.io.InputStream input)
- throws java.io.IOException {
- return PARSER.parseDelimitedFrom(input);
- }
- public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseDelimitedFrom(
- java.io.InputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- return PARSER.parseDelimitedFrom(input, extensionRegistry);
- }
- public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseFrom(
- com.google.protobuf.CodedInputStream input)
- throws java.io.IOException {
- return PARSER.parseFrom(input);
- }
- public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseFrom(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- return PARSER.parseFrom(input, extensionRegistry);
- }
-
- public static Builder newBuilder() { return Builder.create(); }
- public Builder newBuilderForType() { return newBuilder(); }
- public static Builder newBuilder(net.onrc.onos.core.datastore.RCProtos.SwitchProperty prototype) {
- return newBuilder().mergeFrom(prototype);
- }
- public Builder toBuilder() { return newBuilder(this); }
-
- @java.lang.Override
- protected Builder newBuilderForType(
- com.google.protobuf.GeneratedMessage.BuilderParent parent) {
- Builder builder = new Builder(parent);
- return builder;
- }
/**
* Protobuf type {@code RCProtos.SwitchProperty}
*/
- public static final class Builder extends
- com.google.protobuf.GeneratedMessage.Builder<Builder>
- implements net.onrc.onos.core.datastore.RCProtos.SwitchPropertyOrBuilder {
- public static final com.google.protobuf.Descriptors.Descriptor
- getDescriptor() {
- return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_SwitchProperty_descriptor;
- }
-
- protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
- internalGetFieldAccessorTable() {
- return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_SwitchProperty_fieldAccessorTable
- .ensureFieldAccessorsInitialized(
- net.onrc.onos.core.datastore.RCProtos.SwitchProperty.class, net.onrc.onos.core.datastore.RCProtos.SwitchProperty.Builder.class);
- }
-
- // Construct using net.onrc.onos.core.datastore.RCProtos.SwitchProperty.newBuilder()
- private Builder() {
- maybeForceBuilderInitialization();
- }
-
- private Builder(
- com.google.protobuf.GeneratedMessage.BuilderParent parent) {
- super(parent);
- maybeForceBuilderInitialization();
- }
- private void maybeForceBuilderInitialization() {
- if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+ public static final class SwitchProperty extends
+ com.google.protobuf.GeneratedMessage
+ implements SwitchPropertyOrBuilder {
+ // Use SwitchProperty.newBuilder() to construct.
+ private SwitchProperty(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+ super(builder);
+ this.unknownFields = builder.getUnknownFields();
}
- }
- private static Builder create() {
- return new Builder();
- }
- public Builder clear() {
- super.clear();
- dpid_ = 0L;
- bitField0_ = (bitField0_ & ~0x00000001);
- status_ = 0;
- bitField0_ = (bitField0_ & ~0x00000002);
- value_ = com.google.protobuf.ByteString.EMPTY;
- bitField0_ = (bitField0_ & ~0x00000004);
- return this;
- }
-
- public Builder clone() {
- return create().mergeFrom(buildPartial());
- }
-
- public com.google.protobuf.Descriptors.Descriptor
- getDescriptorForType() {
- return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_SwitchProperty_descriptor;
- }
-
- public net.onrc.onos.core.datastore.RCProtos.SwitchProperty getDefaultInstanceForType() {
- return net.onrc.onos.core.datastore.RCProtos.SwitchProperty.getDefaultInstance();
- }
-
- public net.onrc.onos.core.datastore.RCProtos.SwitchProperty build() {
- net.onrc.onos.core.datastore.RCProtos.SwitchProperty result = buildPartial();
- if (!result.isInitialized()) {
- throw newUninitializedMessageException(result);
+ private SwitchProperty(boolean noInit) {
+ this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
- return result;
- }
- public net.onrc.onos.core.datastore.RCProtos.SwitchProperty buildPartial() {
- net.onrc.onos.core.datastore.RCProtos.SwitchProperty result = new net.onrc.onos.core.datastore.RCProtos.SwitchProperty(this);
- int from_bitField0_ = bitField0_;
- int to_bitField0_ = 0;
- if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
- to_bitField0_ |= 0x00000001;
+ private static final SwitchProperty defaultInstance;
+
+ public static SwitchProperty getDefaultInstance() {
+ return defaultInstance;
}
- result.dpid_ = dpid_;
- if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
- to_bitField0_ |= 0x00000002;
+
+ public SwitchProperty getDefaultInstanceForType() {
+ return defaultInstance;
}
- result.status_ = status_;
- if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
- to_bitField0_ |= 0x00000004;
- }
- result.value_ = value_;
- result.bitField0_ = to_bitField0_;
- onBuilt();
- return result;
- }
- public Builder mergeFrom(com.google.protobuf.Message other) {
- if (other instanceof net.onrc.onos.core.datastore.RCProtos.SwitchProperty) {
- return mergeFrom((net.onrc.onos.core.datastore.RCProtos.SwitchProperty)other);
- } else {
- super.mergeFrom(other);
- return this;
- }
- }
+ private final com.google.protobuf.UnknownFieldSet unknownFields;
- public Builder mergeFrom(net.onrc.onos.core.datastore.RCProtos.SwitchProperty other) {
- if (other == net.onrc.onos.core.datastore.RCProtos.SwitchProperty.getDefaultInstance()) return this;
- if (other.hasDpid()) {
- setDpid(other.getDpid());
- }
- if (other.hasStatus()) {
- setStatus(other.getStatus());
- }
- if (other.hasValue()) {
- setValue(other.getValue());
- }
- this.mergeUnknownFields(other.getUnknownFields());
- return this;
- }
-
- public final boolean isInitialized() {
- if (!hasDpid()) {
-
- return false;
- }
- if (!hasStatus()) {
-
- return false;
- }
- return true;
- }
-
- public Builder mergeFrom(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- net.onrc.onos.core.datastore.RCProtos.SwitchProperty parsedMessage = null;
- try {
- parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
- } catch (com.google.protobuf.InvalidProtocolBufferException e) {
- parsedMessage = (net.onrc.onos.core.datastore.RCProtos.SwitchProperty) e.getUnfinishedMessage();
- throw e;
- } finally {
- if (parsedMessage != null) {
- mergeFrom(parsedMessage);
- }
- }
- return this;
- }
- private int bitField0_;
-
- // required int64 dpid = 1;
- private long dpid_ ;
- /**
- * <code>required int64 dpid = 1;</code>
- */
- public boolean hasDpid() {
- return ((bitField0_ & 0x00000001) == 0x00000001);
- }
- /**
- * <code>required int64 dpid = 1;</code>
- */
- public long getDpid() {
- return dpid_;
- }
- /**
- * <code>required int64 dpid = 1;</code>
- */
- public Builder setDpid(long value) {
- bitField0_ |= 0x00000001;
- dpid_ = value;
- onChanged();
- return this;
- }
- /**
- * <code>required int64 dpid = 1;</code>
- */
- public Builder clearDpid() {
- bitField0_ = (bitField0_ & ~0x00000001);
- dpid_ = 0L;
- onChanged();
- return this;
- }
-
- // required int32 status = 2;
- private int status_ ;
- /**
- * <code>required int32 status = 2;</code>
- */
- public boolean hasStatus() {
- return ((bitField0_ & 0x00000002) == 0x00000002);
- }
- /**
- * <code>required int32 status = 2;</code>
- */
- public int getStatus() {
- return status_;
- }
- /**
- * <code>required int32 status = 2;</code>
- */
- public Builder setStatus(int value) {
- bitField0_ |= 0x00000002;
- status_ = value;
- onChanged();
- return this;
- }
- /**
- * <code>required int32 status = 2;</code>
- */
- public Builder clearStatus() {
- bitField0_ = (bitField0_ & ~0x00000002);
- status_ = 0;
- onChanged();
- return this;
- }
-
- // optional bytes value = 3;
- private com.google.protobuf.ByteString value_ = com.google.protobuf.ByteString.EMPTY;
- /**
- * <code>optional bytes value = 3;</code>
- */
- public boolean hasValue() {
- return ((bitField0_ & 0x00000004) == 0x00000004);
- }
- /**
- * <code>optional bytes value = 3;</code>
- */
- public com.google.protobuf.ByteString getValue() {
- return value_;
- }
- /**
- * <code>optional bytes value = 3;</code>
- */
- public Builder setValue(com.google.protobuf.ByteString value) {
- if (value == null) {
- throw new NullPointerException();
- }
- bitField0_ |= 0x00000004;
- value_ = value;
- onChanged();
- return this;
- }
- /**
- * <code>optional bytes value = 3;</code>
- */
- public Builder clearValue() {
- bitField0_ = (bitField0_ & ~0x00000004);
- value_ = getDefaultInstance().getValue();
- onChanged();
- return this;
- }
-
- // @@protoc_insertion_point(builder_scope:RCProtos.SwitchProperty)
- }
-
- static {
- defaultInstance = new SwitchProperty(true);
- defaultInstance.initFields();
- }
-
- // @@protoc_insertion_point(class_scope:RCProtos.SwitchProperty)
- }
-
- public interface PortPropertyOrBuilder
- extends com.google.protobuf.MessageOrBuilder {
-
- // required int64 dpid = 1;
- /**
- * <code>required int64 dpid = 1;</code>
- */
- boolean hasDpid();
- /**
- * <code>required int64 dpid = 1;</code>
- */
- long getDpid();
-
- // required int64 number = 2;
- /**
- * <code>required int64 number = 2;</code>
- */
- boolean hasNumber();
- /**
- * <code>required int64 number = 2;</code>
- */
- long getNumber();
-
- // required int32 status = 3;
- /**
- * <code>required int32 status = 3;</code>
- */
- boolean hasStatus();
- /**
- * <code>required int32 status = 3;</code>
- */
- int getStatus();
-
- // optional bytes value = 4;
- /**
- * <code>optional bytes value = 4;</code>
- */
- boolean hasValue();
- /**
- * <code>optional bytes value = 4;</code>
- */
- com.google.protobuf.ByteString getValue();
- }
- /**
- * Protobuf type {@code RCProtos.PortProperty}
- */
- public static final class PortProperty extends
- com.google.protobuf.GeneratedMessage
- implements PortPropertyOrBuilder {
- // Use PortProperty.newBuilder() to construct.
- private PortProperty(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
- super(builder);
- this.unknownFields = builder.getUnknownFields();
- }
- private PortProperty(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
-
- private static final PortProperty defaultInstance;
- public static PortProperty getDefaultInstance() {
- return defaultInstance;
- }
-
- public PortProperty getDefaultInstanceForType() {
- return defaultInstance;
- }
-
- private final com.google.protobuf.UnknownFieldSet unknownFields;
- @java.lang.Override
- public final com.google.protobuf.UnknownFieldSet
+ @java.lang.Override
+ public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
- return this.unknownFields;
- }
- private PortProperty(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- initFields();
- int mutable_bitField0_ = 0;
- com.google.protobuf.UnknownFieldSet.Builder unknownFields =
- com.google.protobuf.UnknownFieldSet.newBuilder();
- try {
- boolean done = false;
- while (!done) {
- int tag = input.readTag();
- switch (tag) {
- case 0:
- done = true;
- break;
- default: {
- if (!parseUnknownField(input, unknownFields,
- extensionRegistry, tag)) {
- done = true;
- }
- break;
- }
- case 8: {
- bitField0_ |= 0x00000001;
- dpid_ = input.readInt64();
- break;
- }
- case 16: {
- bitField0_ |= 0x00000002;
- number_ = input.readInt64();
- break;
- }
- case 24: {
- bitField0_ |= 0x00000004;
- status_ = input.readInt32();
- break;
- }
- case 34: {
- bitField0_ |= 0x00000008;
- value_ = input.readBytes();
- break;
- }
- }
+ return this.unknownFields;
}
- } catch (com.google.protobuf.InvalidProtocolBufferException e) {
- throw e.setUnfinishedMessage(this);
- } catch (java.io.IOException e) {
- throw new com.google.protobuf.InvalidProtocolBufferException(
- e.getMessage()).setUnfinishedMessage(this);
- } finally {
- this.unknownFields = unknownFields.build();
- makeExtensionsImmutable();
- }
- }
- public static final com.google.protobuf.Descriptors.Descriptor
+
+ private SwitchProperty(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ initFields();
+ int mutable_bitField0_ = 0;
+ com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+ com.google.protobuf.UnknownFieldSet.newBuilder();
+ try {
+ boolean done = false;
+ while (!done) {
+ int tag = input.readTag();
+ switch (tag) {
+ case 0:
+ done = true;
+ break;
+ default: {
+ if (!parseUnknownField(input, unknownFields,
+ extensionRegistry, tag)) {
+ done = true;
+ }
+ break;
+ }
+ case 8: {
+ bitField0_ |= 0x00000001;
+ dpid_ = input.readInt64();
+ break;
+ }
+ case 16: {
+ bitField0_ |= 0x00000002;
+ status_ = input.readInt32();
+ break;
+ }
+ case 26: {
+ bitField0_ |= 0x00000004;
+ value_ = input.readBytes();
+ break;
+ }
+ }
+ }
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ throw e.setUnfinishedMessage(this);
+ } catch (java.io.IOException e) {
+ throw new com.google.protobuf.InvalidProtocolBufferException(
+ e.getMessage()).setUnfinishedMessage(this);
+ } finally {
+ this.unknownFields = unknownFields.build();
+ makeExtensionsImmutable();
+ }
+ }
+
+ public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
- return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_PortProperty_descriptor;
- }
+ return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_SwitchProperty_descriptor;
+ }
- protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
- return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_PortProperty_fieldAccessorTable
- .ensureFieldAccessorsInitialized(
- net.onrc.onos.core.datastore.RCProtos.PortProperty.class, net.onrc.onos.core.datastore.RCProtos.PortProperty.Builder.class);
+ return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_SwitchProperty_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ net.onrc.onos.core.datastore.RCProtos.SwitchProperty.class, net.onrc.onos.core.datastore.RCProtos.SwitchProperty.Builder.class);
+ }
+
+ public static com.google.protobuf.Parser<SwitchProperty> PARSER =
+ new com.google.protobuf.AbstractParser<SwitchProperty>() {
+ public SwitchProperty parsePartialFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return new SwitchProperty(input, extensionRegistry);
+ }
+ };
+
+ @java.lang.Override
+ public com.google.protobuf.Parser<SwitchProperty> getParserForType() {
+ return PARSER;
+ }
+
+ private int bitField0_;
+ // required int64 dpid = 1;
+ public static final int DPID_FIELD_NUMBER = 1;
+ private long dpid_;
+
+ /**
+ * <code>required int64 dpid = 1;</code>
+ */
+ public boolean hasDpid() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+
+ /**
+ * <code>required int64 dpid = 1;</code>
+ */
+ public long getDpid() {
+ return dpid_;
+ }
+
+ // required int32 status = 2;
+ public static final int STATUS_FIELD_NUMBER = 2;
+ private int status_;
+
+ /**
+ * <code>required int32 status = 2;</code>
+ */
+ public boolean hasStatus() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+
+ /**
+ * <code>required int32 status = 2;</code>
+ */
+ public int getStatus() {
+ return status_;
+ }
+
+ // optional bytes value = 3;
+ public static final int VALUE_FIELD_NUMBER = 3;
+ private com.google.protobuf.ByteString value_;
+
+ /**
+ * <code>optional bytes value = 3;</code>
+ */
+ public boolean hasValue() {
+ return ((bitField0_ & 0x00000004) == 0x00000004);
+ }
+
+ /**
+ * <code>optional bytes value = 3;</code>
+ */
+ public com.google.protobuf.ByteString getValue() {
+ return value_;
+ }
+
+ private void initFields() {
+ dpid_ = 0L;
+ status_ = 0;
+ value_ = com.google.protobuf.ByteString.EMPTY;
+ }
+
+ private byte memoizedIsInitialized = -1;
+
+ public final boolean isInitialized() {
+ byte isInitialized = memoizedIsInitialized;
+ if (isInitialized != -1) return isInitialized == 1;
+
+ if (!hasDpid()) {
+ memoizedIsInitialized = 0;
+ return false;
+ }
+ if (!hasStatus()) {
+ memoizedIsInitialized = 0;
+ return false;
+ }
+ memoizedIsInitialized = 1;
+ return true;
+ }
+
+ public void writeTo(com.google.protobuf.CodedOutputStream output)
+ throws java.io.IOException {
+ getSerializedSize();
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ output.writeInt64(1, dpid_);
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ output.writeInt32(2, status_);
+ }
+ if (((bitField0_ & 0x00000004) == 0x00000004)) {
+ output.writeBytes(3, value_);
+ }
+ getUnknownFields().writeTo(output);
+ }
+
+ private int memoizedSerializedSize = -1;
+
+ public int getSerializedSize() {
+ int size = memoizedSerializedSize;
+ if (size != -1) return size;
+
+ size = 0;
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeInt64Size(1, dpid_);
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeInt32Size(2, status_);
+ }
+ if (((bitField0_ & 0x00000004) == 0x00000004)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeBytesSize(3, value_);
+ }
+ size += getUnknownFields().getSerializedSize();
+ memoizedSerializedSize = size;
+ return size;
+ }
+
+ private static final long serialVersionUID = 0L;
+
+ @java.lang.Override
+ protected java.lang.Object writeReplace()
+ throws java.io.ObjectStreamException {
+ return super.writeReplace();
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseFrom(
+ com.google.protobuf.ByteString data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseFrom(
+ com.google.protobuf.ByteString data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseFrom(byte[] data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseFrom(
+ byte[] data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseDelimitedFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseDelimitedFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input, extensionRegistry);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseFrom(
+ com.google.protobuf.CodedInputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.SwitchProperty parseFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+
+ public static Builder newBuilder() {
+ return Builder.create();
+ }
+
+ public Builder newBuilderForType() {
+ return newBuilder();
+ }
+
+ public static Builder newBuilder(net.onrc.onos.core.datastore.RCProtos.SwitchProperty prototype) {
+ return newBuilder().mergeFrom(prototype);
+ }
+
+ public Builder toBuilder() {
+ return newBuilder(this);
+ }
+
+ @java.lang.Override
+ protected Builder newBuilderForType(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ Builder builder = new Builder(parent);
+ return builder;
+ }
+
+ /**
+ * Protobuf type {@code RCProtos.SwitchProperty}
+ */
+ public static final class Builder extends
+ com.google.protobuf.GeneratedMessage.Builder<Builder>
+ implements net.onrc.onos.core.datastore.RCProtos.SwitchPropertyOrBuilder {
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_SwitchProperty_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_SwitchProperty_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ net.onrc.onos.core.datastore.RCProtos.SwitchProperty.class, net.onrc.onos.core.datastore.RCProtos.SwitchProperty.Builder.class);
+ }
+
+ // Construct using net.onrc.onos.core.datastore.RCProtos.SwitchProperty.newBuilder()
+ private Builder() {
+ maybeForceBuilderInitialization();
+ }
+
+ private Builder(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ super(parent);
+ maybeForceBuilderInitialization();
+ }
+
+ private void maybeForceBuilderInitialization() {
+ if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+ }
+ }
+
+ private static Builder create() {
+ return new Builder();
+ }
+
+ public Builder clear() {
+ super.clear();
+ dpid_ = 0L;
+ bitField0_ = (bitField0_ & ~0x00000001);
+ status_ = 0;
+ bitField0_ = (bitField0_ & ~0x00000002);
+ value_ = com.google.protobuf.ByteString.EMPTY;
+ bitField0_ = (bitField0_ & ~0x00000004);
+ return this;
+ }
+
+ public Builder clone() {
+ return create().mergeFrom(buildPartial());
+ }
+
+ public com.google.protobuf.Descriptors.Descriptor
+ getDescriptorForType() {
+ return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_SwitchProperty_descriptor;
+ }
+
+ public net.onrc.onos.core.datastore.RCProtos.SwitchProperty getDefaultInstanceForType() {
+ return net.onrc.onos.core.datastore.RCProtos.SwitchProperty.getDefaultInstance();
+ }
+
+ public net.onrc.onos.core.datastore.RCProtos.SwitchProperty build() {
+ net.onrc.onos.core.datastore.RCProtos.SwitchProperty result = buildPartial();
+ if (!result.isInitialized()) {
+ throw newUninitializedMessageException(result);
+ }
+ return result;
+ }
+
+ public net.onrc.onos.core.datastore.RCProtos.SwitchProperty buildPartial() {
+ net.onrc.onos.core.datastore.RCProtos.SwitchProperty result = new net.onrc.onos.core.datastore.RCProtos.SwitchProperty(this);
+ int from_bitField0_ = bitField0_;
+ int to_bitField0_ = 0;
+ if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+ to_bitField0_ |= 0x00000001;
+ }
+ result.dpid_ = dpid_;
+ if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
+ to_bitField0_ |= 0x00000002;
+ }
+ result.status_ = status_;
+ if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
+ to_bitField0_ |= 0x00000004;
+ }
+ result.value_ = value_;
+ result.bitField0_ = to_bitField0_;
+ onBuilt();
+ return result;
+ }
+
+ public Builder mergeFrom(com.google.protobuf.Message other) {
+ if (other instanceof net.onrc.onos.core.datastore.RCProtos.SwitchProperty) {
+ return mergeFrom((net.onrc.onos.core.datastore.RCProtos.SwitchProperty) other);
+ } else {
+ super.mergeFrom(other);
+ return this;
+ }
+ }
+
+ public Builder mergeFrom(net.onrc.onos.core.datastore.RCProtos.SwitchProperty other) {
+ if (other == net.onrc.onos.core.datastore.RCProtos.SwitchProperty.getDefaultInstance())
+ return this;
+ if (other.hasDpid()) {
+ setDpid(other.getDpid());
+ }
+ if (other.hasStatus()) {
+ setStatus(other.getStatus());
+ }
+ if (other.hasValue()) {
+ setValue(other.getValue());
+ }
+ this.mergeUnknownFields(other.getUnknownFields());
+ return this;
+ }
+
+ public final boolean isInitialized() {
+ if (!hasDpid()) {
+
+ return false;
+ }
+ if (!hasStatus()) {
+
+ return false;
+ }
+ return true;
+ }
+
+ public Builder mergeFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ net.onrc.onos.core.datastore.RCProtos.SwitchProperty parsedMessage = null;
+ try {
+ parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ parsedMessage = (net.onrc.onos.core.datastore.RCProtos.SwitchProperty) e.getUnfinishedMessage();
+ throw e;
+ } finally {
+ if (parsedMessage != null) {
+ mergeFrom(parsedMessage);
+ }
+ }
+ return this;
+ }
+
+ private int bitField0_;
+
+ // required int64 dpid = 1;
+ private long dpid_;
+
+ /**
+ * <code>required int64 dpid = 1;</code>
+ */
+ public boolean hasDpid() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+
+ /**
+ * <code>required int64 dpid = 1;</code>
+ */
+ public long getDpid() {
+ return dpid_;
+ }
+
+ /**
+ * <code>required int64 dpid = 1;</code>
+ */
+ public Builder setDpid(long value) {
+ bitField0_ |= 0x00000001;
+ dpid_ = value;
+ onChanged();
+ return this;
+ }
+
+ /**
+ * <code>required int64 dpid = 1;</code>
+ */
+ public Builder clearDpid() {
+ bitField0_ = (bitField0_ & ~0x00000001);
+ dpid_ = 0L;
+ onChanged();
+ return this;
+ }
+
+ // required int32 status = 2;
+ private int status_;
+
+ /**
+ * <code>required int32 status = 2;</code>
+ */
+ public boolean hasStatus() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+
+ /**
+ * <code>required int32 status = 2;</code>
+ */
+ public int getStatus() {
+ return status_;
+ }
+
+ /**
+ * <code>required int32 status = 2;</code>
+ */
+ public Builder setStatus(int value) {
+ bitField0_ |= 0x00000002;
+ status_ = value;
+ onChanged();
+ return this;
+ }
+
+ /**
+ * <code>required int32 status = 2;</code>
+ */
+ public Builder clearStatus() {
+ bitField0_ = (bitField0_ & ~0x00000002);
+ status_ = 0;
+ onChanged();
+ return this;
+ }
+
+ // optional bytes value = 3;
+ private com.google.protobuf.ByteString value_ = com.google.protobuf.ByteString.EMPTY;
+
+ /**
+ * <code>optional bytes value = 3;</code>
+ */
+ public boolean hasValue() {
+ return ((bitField0_ & 0x00000004) == 0x00000004);
+ }
+
+ /**
+ * <code>optional bytes value = 3;</code>
+ */
+ public com.google.protobuf.ByteString getValue() {
+ return value_;
+ }
+
+ /**
+ * <code>optional bytes value = 3;</code>
+ */
+ public Builder setValue(com.google.protobuf.ByteString value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00000004;
+ value_ = value;
+ onChanged();
+ return this;
+ }
+
+ /**
+ * <code>optional bytes value = 3;</code>
+ */
+ public Builder clearValue() {
+ bitField0_ = (bitField0_ & ~0x00000004);
+ value_ = getDefaultInstance().getValue();
+ onChanged();
+ return this;
+ }
+
+ // @@protoc_insertion_point(builder_scope:RCProtos.SwitchProperty)
+ }
+
+ static {
+ defaultInstance = new SwitchProperty(true);
+ defaultInstance.initFields();
+ }
+
+ // @@protoc_insertion_point(class_scope:RCProtos.SwitchProperty)
}
- public static com.google.protobuf.Parser<PortProperty> PARSER =
- new com.google.protobuf.AbstractParser<PortProperty>() {
- public PortProperty parsePartialFrom(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return new PortProperty(input, extensionRegistry);
- }
- };
+ public interface PortPropertyOrBuilder
+ extends com.google.protobuf.MessageOrBuilder {
- @java.lang.Override
- public com.google.protobuf.Parser<PortProperty> getParserForType() {
- return PARSER;
+ // required int64 dpid = 1;
+
+ /**
+ * <code>required int64 dpid = 1;</code>
+ */
+ boolean hasDpid();
+
+ /**
+ * <code>required int64 dpid = 1;</code>
+ */
+ long getDpid();
+
+ // required int64 number = 2;
+
+ /**
+ * <code>required int64 number = 2;</code>
+ */
+ boolean hasNumber();
+
+ /**
+ * <code>required int64 number = 2;</code>
+ */
+ long getNumber();
+
+ // required int32 status = 3;
+
+ /**
+ * <code>required int32 status = 3;</code>
+ */
+ boolean hasStatus();
+
+ /**
+ * <code>required int32 status = 3;</code>
+ */
+ int getStatus();
+
+ // optional bytes value = 4;
+
+ /**
+ * <code>optional bytes value = 4;</code>
+ */
+ boolean hasValue();
+
+ /**
+ * <code>optional bytes value = 4;</code>
+ */
+ com.google.protobuf.ByteString getValue();
}
- private int bitField0_;
- // required int64 dpid = 1;
- public static final int DPID_FIELD_NUMBER = 1;
- private long dpid_;
- /**
- * <code>required int64 dpid = 1;</code>
- */
- public boolean hasDpid() {
- return ((bitField0_ & 0x00000001) == 0x00000001);
- }
- /**
- * <code>required int64 dpid = 1;</code>
- */
- public long getDpid() {
- return dpid_;
- }
-
- // required int64 number = 2;
- public static final int NUMBER_FIELD_NUMBER = 2;
- private long number_;
- /**
- * <code>required int64 number = 2;</code>
- */
- public boolean hasNumber() {
- return ((bitField0_ & 0x00000002) == 0x00000002);
- }
- /**
- * <code>required int64 number = 2;</code>
- */
- public long getNumber() {
- return number_;
- }
-
- // required int32 status = 3;
- public static final int STATUS_FIELD_NUMBER = 3;
- private int status_;
- /**
- * <code>required int32 status = 3;</code>
- */
- public boolean hasStatus() {
- return ((bitField0_ & 0x00000004) == 0x00000004);
- }
- /**
- * <code>required int32 status = 3;</code>
- */
- public int getStatus() {
- return status_;
- }
-
- // optional bytes value = 4;
- public static final int VALUE_FIELD_NUMBER = 4;
- private com.google.protobuf.ByteString value_;
- /**
- * <code>optional bytes value = 4;</code>
- */
- public boolean hasValue() {
- return ((bitField0_ & 0x00000008) == 0x00000008);
- }
- /**
- * <code>optional bytes value = 4;</code>
- */
- public com.google.protobuf.ByteString getValue() {
- return value_;
- }
-
- private void initFields() {
- dpid_ = 0L;
- number_ = 0L;
- status_ = 0;
- value_ = com.google.protobuf.ByteString.EMPTY;
- }
- private byte memoizedIsInitialized = -1;
- public final boolean isInitialized() {
- byte isInitialized = memoizedIsInitialized;
- if (isInitialized != -1) return isInitialized == 1;
-
- if (!hasDpid()) {
- memoizedIsInitialized = 0;
- return false;
- }
- if (!hasNumber()) {
- memoizedIsInitialized = 0;
- return false;
- }
- if (!hasStatus()) {
- memoizedIsInitialized = 0;
- return false;
- }
- memoizedIsInitialized = 1;
- return true;
- }
-
- public void writeTo(com.google.protobuf.CodedOutputStream output)
- throws java.io.IOException {
- getSerializedSize();
- if (((bitField0_ & 0x00000001) == 0x00000001)) {
- output.writeInt64(1, dpid_);
- }
- if (((bitField0_ & 0x00000002) == 0x00000002)) {
- output.writeInt64(2, number_);
- }
- if (((bitField0_ & 0x00000004) == 0x00000004)) {
- output.writeInt32(3, status_);
- }
- if (((bitField0_ & 0x00000008) == 0x00000008)) {
- output.writeBytes(4, value_);
- }
- getUnknownFields().writeTo(output);
- }
-
- private int memoizedSerializedSize = -1;
- public int getSerializedSize() {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (((bitField0_ & 0x00000001) == 0x00000001)) {
- size += com.google.protobuf.CodedOutputStream
- .computeInt64Size(1, dpid_);
- }
- if (((bitField0_ & 0x00000002) == 0x00000002)) {
- size += com.google.protobuf.CodedOutputStream
- .computeInt64Size(2, number_);
- }
- if (((bitField0_ & 0x00000004) == 0x00000004)) {
- size += com.google.protobuf.CodedOutputStream
- .computeInt32Size(3, status_);
- }
- if (((bitField0_ & 0x00000008) == 0x00000008)) {
- size += com.google.protobuf.CodedOutputStream
- .computeBytesSize(4, value_);
- }
- size += getUnknownFields().getSerializedSize();
- memoizedSerializedSize = size;
- return size;
- }
-
- private static final long serialVersionUID = 0L;
- @java.lang.Override
- protected java.lang.Object writeReplace()
- throws java.io.ObjectStreamException {
- return super.writeReplace();
- }
-
- public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseFrom(
- com.google.protobuf.ByteString data)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return PARSER.parseFrom(data);
- }
- public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseFrom(
- com.google.protobuf.ByteString data,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return PARSER.parseFrom(data, extensionRegistry);
- }
- public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseFrom(byte[] data)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return PARSER.parseFrom(data);
- }
- public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseFrom(
- byte[] data,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return PARSER.parseFrom(data, extensionRegistry);
- }
- public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseFrom(java.io.InputStream input)
- throws java.io.IOException {
- return PARSER.parseFrom(input);
- }
- public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseFrom(
- java.io.InputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- return PARSER.parseFrom(input, extensionRegistry);
- }
- public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseDelimitedFrom(java.io.InputStream input)
- throws java.io.IOException {
- return PARSER.parseDelimitedFrom(input);
- }
- public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseDelimitedFrom(
- java.io.InputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- return PARSER.parseDelimitedFrom(input, extensionRegistry);
- }
- public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseFrom(
- com.google.protobuf.CodedInputStream input)
- throws java.io.IOException {
- return PARSER.parseFrom(input);
- }
- public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseFrom(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- return PARSER.parseFrom(input, extensionRegistry);
- }
-
- public static Builder newBuilder() { return Builder.create(); }
- public Builder newBuilderForType() { return newBuilder(); }
- public static Builder newBuilder(net.onrc.onos.core.datastore.RCProtos.PortProperty prototype) {
- return newBuilder().mergeFrom(prototype);
- }
- public Builder toBuilder() { return newBuilder(this); }
-
- @java.lang.Override
- protected Builder newBuilderForType(
- com.google.protobuf.GeneratedMessage.BuilderParent parent) {
- Builder builder = new Builder(parent);
- return builder;
- }
/**
* Protobuf type {@code RCProtos.PortProperty}
*/
- public static final class Builder extends
- com.google.protobuf.GeneratedMessage.Builder<Builder>
- implements net.onrc.onos.core.datastore.RCProtos.PortPropertyOrBuilder {
- public static final com.google.protobuf.Descriptors.Descriptor
- getDescriptor() {
- return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_PortProperty_descriptor;
- }
-
- protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
- internalGetFieldAccessorTable() {
- return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_PortProperty_fieldAccessorTable
- .ensureFieldAccessorsInitialized(
- net.onrc.onos.core.datastore.RCProtos.PortProperty.class, net.onrc.onos.core.datastore.RCProtos.PortProperty.Builder.class);
- }
-
- // Construct using net.onrc.onos.core.datastore.RCProtos.PortProperty.newBuilder()
- private Builder() {
- maybeForceBuilderInitialization();
- }
-
- private Builder(
- com.google.protobuf.GeneratedMessage.BuilderParent parent) {
- super(parent);
- maybeForceBuilderInitialization();
- }
- private void maybeForceBuilderInitialization() {
- if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+ public static final class PortProperty extends
+ com.google.protobuf.GeneratedMessage
+ implements PortPropertyOrBuilder {
+ // Use PortProperty.newBuilder() to construct.
+ private PortProperty(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+ super(builder);
+ this.unknownFields = builder.getUnknownFields();
}
- }
- private static Builder create() {
- return new Builder();
- }
- public Builder clear() {
- super.clear();
- dpid_ = 0L;
- bitField0_ = (bitField0_ & ~0x00000001);
- number_ = 0L;
- bitField0_ = (bitField0_ & ~0x00000002);
- status_ = 0;
- bitField0_ = (bitField0_ & ~0x00000004);
- value_ = com.google.protobuf.ByteString.EMPTY;
- bitField0_ = (bitField0_ & ~0x00000008);
- return this;
- }
-
- public Builder clone() {
- return create().mergeFrom(buildPartial());
- }
-
- public com.google.protobuf.Descriptors.Descriptor
- getDescriptorForType() {
- return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_PortProperty_descriptor;
- }
-
- public net.onrc.onos.core.datastore.RCProtos.PortProperty getDefaultInstanceForType() {
- return net.onrc.onos.core.datastore.RCProtos.PortProperty.getDefaultInstance();
- }
-
- public net.onrc.onos.core.datastore.RCProtos.PortProperty build() {
- net.onrc.onos.core.datastore.RCProtos.PortProperty result = buildPartial();
- if (!result.isInitialized()) {
- throw newUninitializedMessageException(result);
+ private PortProperty(boolean noInit) {
+ this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
- return result;
- }
- public net.onrc.onos.core.datastore.RCProtos.PortProperty buildPartial() {
- net.onrc.onos.core.datastore.RCProtos.PortProperty result = new net.onrc.onos.core.datastore.RCProtos.PortProperty(this);
- int from_bitField0_ = bitField0_;
- int to_bitField0_ = 0;
- if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
- to_bitField0_ |= 0x00000001;
+ private static final PortProperty defaultInstance;
+
+ public static PortProperty getDefaultInstance() {
+ return defaultInstance;
}
- result.dpid_ = dpid_;
- if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
- to_bitField0_ |= 0x00000002;
+
+ public PortProperty getDefaultInstanceForType() {
+ return defaultInstance;
}
- result.number_ = number_;
- if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
- to_bitField0_ |= 0x00000004;
- }
- result.status_ = status_;
- if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
- to_bitField0_ |= 0x00000008;
- }
- result.value_ = value_;
- result.bitField0_ = to_bitField0_;
- onBuilt();
- return result;
- }
- public Builder mergeFrom(com.google.protobuf.Message other) {
- if (other instanceof net.onrc.onos.core.datastore.RCProtos.PortProperty) {
- return mergeFrom((net.onrc.onos.core.datastore.RCProtos.PortProperty)other);
- } else {
- super.mergeFrom(other);
- return this;
- }
- }
+ private final com.google.protobuf.UnknownFieldSet unknownFields;
- public Builder mergeFrom(net.onrc.onos.core.datastore.RCProtos.PortProperty other) {
- if (other == net.onrc.onos.core.datastore.RCProtos.PortProperty.getDefaultInstance()) return this;
- if (other.hasDpid()) {
- setDpid(other.getDpid());
- }
- if (other.hasNumber()) {
- setNumber(other.getNumber());
- }
- if (other.hasStatus()) {
- setStatus(other.getStatus());
- }
- if (other.hasValue()) {
- setValue(other.getValue());
- }
- this.mergeUnknownFields(other.getUnknownFields());
- return this;
- }
-
- public final boolean isInitialized() {
- if (!hasDpid()) {
-
- return false;
- }
- if (!hasNumber()) {
-
- return false;
- }
- if (!hasStatus()) {
-
- return false;
- }
- return true;
- }
-
- public Builder mergeFrom(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- net.onrc.onos.core.datastore.RCProtos.PortProperty parsedMessage = null;
- try {
- parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
- } catch (com.google.protobuf.InvalidProtocolBufferException e) {
- parsedMessage = (net.onrc.onos.core.datastore.RCProtos.PortProperty) e.getUnfinishedMessage();
- throw e;
- } finally {
- if (parsedMessage != null) {
- mergeFrom(parsedMessage);
- }
- }
- return this;
- }
- private int bitField0_;
-
- // required int64 dpid = 1;
- private long dpid_ ;
- /**
- * <code>required int64 dpid = 1;</code>
- */
- public boolean hasDpid() {
- return ((bitField0_ & 0x00000001) == 0x00000001);
- }
- /**
- * <code>required int64 dpid = 1;</code>
- */
- public long getDpid() {
- return dpid_;
- }
- /**
- * <code>required int64 dpid = 1;</code>
- */
- public Builder setDpid(long value) {
- bitField0_ |= 0x00000001;
- dpid_ = value;
- onChanged();
- return this;
- }
- /**
- * <code>required int64 dpid = 1;</code>
- */
- public Builder clearDpid() {
- bitField0_ = (bitField0_ & ~0x00000001);
- dpid_ = 0L;
- onChanged();
- return this;
- }
-
- // required int64 number = 2;
- private long number_ ;
- /**
- * <code>required int64 number = 2;</code>
- */
- public boolean hasNumber() {
- return ((bitField0_ & 0x00000002) == 0x00000002);
- }
- /**
- * <code>required int64 number = 2;</code>
- */
- public long getNumber() {
- return number_;
- }
- /**
- * <code>required int64 number = 2;</code>
- */
- public Builder setNumber(long value) {
- bitField0_ |= 0x00000002;
- number_ = value;
- onChanged();
- return this;
- }
- /**
- * <code>required int64 number = 2;</code>
- */
- public Builder clearNumber() {
- bitField0_ = (bitField0_ & ~0x00000002);
- number_ = 0L;
- onChanged();
- return this;
- }
-
- // required int32 status = 3;
- private int status_ ;
- /**
- * <code>required int32 status = 3;</code>
- */
- public boolean hasStatus() {
- return ((bitField0_ & 0x00000004) == 0x00000004);
- }
- /**
- * <code>required int32 status = 3;</code>
- */
- public int getStatus() {
- return status_;
- }
- /**
- * <code>required int32 status = 3;</code>
- */
- public Builder setStatus(int value) {
- bitField0_ |= 0x00000004;
- status_ = value;
- onChanged();
- return this;
- }
- /**
- * <code>required int32 status = 3;</code>
- */
- public Builder clearStatus() {
- bitField0_ = (bitField0_ & ~0x00000004);
- status_ = 0;
- onChanged();
- return this;
- }
-
- // optional bytes value = 4;
- private com.google.protobuf.ByteString value_ = com.google.protobuf.ByteString.EMPTY;
- /**
- * <code>optional bytes value = 4;</code>
- */
- public boolean hasValue() {
- return ((bitField0_ & 0x00000008) == 0x00000008);
- }
- /**
- * <code>optional bytes value = 4;</code>
- */
- public com.google.protobuf.ByteString getValue() {
- return value_;
- }
- /**
- * <code>optional bytes value = 4;</code>
- */
- public Builder setValue(com.google.protobuf.ByteString value) {
- if (value == null) {
- throw new NullPointerException();
- }
- bitField0_ |= 0x00000008;
- value_ = value;
- onChanged();
- return this;
- }
- /**
- * <code>optional bytes value = 4;</code>
- */
- public Builder clearValue() {
- bitField0_ = (bitField0_ & ~0x00000008);
- value_ = getDefaultInstance().getValue();
- onChanged();
- return this;
- }
-
- // @@protoc_insertion_point(builder_scope:RCProtos.PortProperty)
- }
-
- static {
- defaultInstance = new PortProperty(true);
- defaultInstance.initFields();
- }
-
- // @@protoc_insertion_point(class_scope:RCProtos.PortProperty)
- }
-
- public interface LinkPropertyOrBuilder
- extends com.google.protobuf.MessageOrBuilder {
-
- // required bytes srcSwId = 1;
- /**
- * <code>required bytes srcSwId = 1;</code>
- */
- boolean hasSrcSwId();
- /**
- * <code>required bytes srcSwId = 1;</code>
- */
- com.google.protobuf.ByteString getSrcSwId();
-
- // required bytes srcPortId = 2;
- /**
- * <code>required bytes srcPortId = 2;</code>
- */
- boolean hasSrcPortId();
- /**
- * <code>required bytes srcPortId = 2;</code>
- */
- com.google.protobuf.ByteString getSrcPortId();
-
- // required bytes dstSwId = 3;
- /**
- * <code>required bytes dstSwId = 3;</code>
- */
- boolean hasDstSwId();
- /**
- * <code>required bytes dstSwId = 3;</code>
- */
- com.google.protobuf.ByteString getDstSwId();
-
- // required bytes dstPortId = 4;
- /**
- * <code>required bytes dstPortId = 4;</code>
- */
- boolean hasDstPortId();
- /**
- * <code>required bytes dstPortId = 4;</code>
- */
- com.google.protobuf.ByteString getDstPortId();
-
- // required int32 status = 5;
- /**
- * <code>required int32 status = 5;</code>
- */
- boolean hasStatus();
- /**
- * <code>required int32 status = 5;</code>
- */
- int getStatus();
-
- // optional bytes value = 6;
- /**
- * <code>optional bytes value = 6;</code>
- */
- boolean hasValue();
- /**
- * <code>optional bytes value = 6;</code>
- */
- com.google.protobuf.ByteString getValue();
- }
- /**
- * Protobuf type {@code RCProtos.LinkProperty}
- */
- public static final class LinkProperty extends
- com.google.protobuf.GeneratedMessage
- implements LinkPropertyOrBuilder {
- // Use LinkProperty.newBuilder() to construct.
- private LinkProperty(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
- super(builder);
- this.unknownFields = builder.getUnknownFields();
- }
- private LinkProperty(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
-
- private static final LinkProperty defaultInstance;
- public static LinkProperty getDefaultInstance() {
- return defaultInstance;
- }
-
- public LinkProperty getDefaultInstanceForType() {
- return defaultInstance;
- }
-
- private final com.google.protobuf.UnknownFieldSet unknownFields;
- @java.lang.Override
- public final com.google.protobuf.UnknownFieldSet
+ @java.lang.Override
+ public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
- return this.unknownFields;
- }
- private LinkProperty(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- initFields();
- int mutable_bitField0_ = 0;
- com.google.protobuf.UnknownFieldSet.Builder unknownFields =
- com.google.protobuf.UnknownFieldSet.newBuilder();
- try {
- boolean done = false;
- while (!done) {
- int tag = input.readTag();
- switch (tag) {
- case 0:
- done = true;
- break;
- default: {
- if (!parseUnknownField(input, unknownFields,
- extensionRegistry, tag)) {
- done = true;
- }
- break;
- }
- case 10: {
- bitField0_ |= 0x00000001;
- srcSwId_ = input.readBytes();
- break;
- }
- case 18: {
- bitField0_ |= 0x00000002;
- srcPortId_ = input.readBytes();
- break;
- }
- case 26: {
- bitField0_ |= 0x00000004;
- dstSwId_ = input.readBytes();
- break;
- }
- case 34: {
- bitField0_ |= 0x00000008;
- dstPortId_ = input.readBytes();
- break;
- }
- case 40: {
- bitField0_ |= 0x00000010;
- status_ = input.readInt32();
- break;
- }
- case 50: {
- bitField0_ |= 0x00000020;
- value_ = input.readBytes();
- break;
- }
- }
+ return this.unknownFields;
}
- } catch (com.google.protobuf.InvalidProtocolBufferException e) {
- throw e.setUnfinishedMessage(this);
- } catch (java.io.IOException e) {
- throw new com.google.protobuf.InvalidProtocolBufferException(
- e.getMessage()).setUnfinishedMessage(this);
- } finally {
- this.unknownFields = unknownFields.build();
- makeExtensionsImmutable();
- }
- }
- public static final com.google.protobuf.Descriptors.Descriptor
+
+ private PortProperty(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ initFields();
+ int mutable_bitField0_ = 0;
+ com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+ com.google.protobuf.UnknownFieldSet.newBuilder();
+ try {
+ boolean done = false;
+ while (!done) {
+ int tag = input.readTag();
+ switch (tag) {
+ case 0:
+ done = true;
+ break;
+ default: {
+ if (!parseUnknownField(input, unknownFields,
+ extensionRegistry, tag)) {
+ done = true;
+ }
+ break;
+ }
+ case 8: {
+ bitField0_ |= 0x00000001;
+ dpid_ = input.readInt64();
+ break;
+ }
+ case 16: {
+ bitField0_ |= 0x00000002;
+ number_ = input.readInt64();
+ break;
+ }
+ case 24: {
+ bitField0_ |= 0x00000004;
+ status_ = input.readInt32();
+ break;
+ }
+ case 34: {
+ bitField0_ |= 0x00000008;
+ value_ = input.readBytes();
+ break;
+ }
+ }
+ }
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ throw e.setUnfinishedMessage(this);
+ } catch (java.io.IOException e) {
+ throw new com.google.protobuf.InvalidProtocolBufferException(
+ e.getMessage()).setUnfinishedMessage(this);
+ } finally {
+ this.unknownFields = unknownFields.build();
+ makeExtensionsImmutable();
+ }
+ }
+
+ public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
- return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_LinkProperty_descriptor;
- }
+ return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_PortProperty_descriptor;
+ }
- protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
- return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_LinkProperty_fieldAccessorTable
- .ensureFieldAccessorsInitialized(
- net.onrc.onos.core.datastore.RCProtos.LinkProperty.class, net.onrc.onos.core.datastore.RCProtos.LinkProperty.Builder.class);
+ return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_PortProperty_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ net.onrc.onos.core.datastore.RCProtos.PortProperty.class, net.onrc.onos.core.datastore.RCProtos.PortProperty.Builder.class);
+ }
+
+ public static com.google.protobuf.Parser<PortProperty> PARSER =
+ new com.google.protobuf.AbstractParser<PortProperty>() {
+ public PortProperty parsePartialFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return new PortProperty(input, extensionRegistry);
+ }
+ };
+
+ @java.lang.Override
+ public com.google.protobuf.Parser<PortProperty> getParserForType() {
+ return PARSER;
+ }
+
+ private int bitField0_;
+ // required int64 dpid = 1;
+ public static final int DPID_FIELD_NUMBER = 1;
+ private long dpid_;
+
+ /**
+ * <code>required int64 dpid = 1;</code>
+ */
+ public boolean hasDpid() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+
+ /**
+ * <code>required int64 dpid = 1;</code>
+ */
+ public long getDpid() {
+ return dpid_;
+ }
+
+ // required int64 number = 2;
+ public static final int NUMBER_FIELD_NUMBER = 2;
+ private long number_;
+
+ /**
+ * <code>required int64 number = 2;</code>
+ */
+ public boolean hasNumber() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+
+ /**
+ * <code>required int64 number = 2;</code>
+ */
+ public long getNumber() {
+ return number_;
+ }
+
+ // required int32 status = 3;
+ public static final int STATUS_FIELD_NUMBER = 3;
+ private int status_;
+
+ /**
+ * <code>required int32 status = 3;</code>
+ */
+ public boolean hasStatus() {
+ return ((bitField0_ & 0x00000004) == 0x00000004);
+ }
+
+ /**
+ * <code>required int32 status = 3;</code>
+ */
+ public int getStatus() {
+ return status_;
+ }
+
+ // optional bytes value = 4;
+ public static final int VALUE_FIELD_NUMBER = 4;
+ private com.google.protobuf.ByteString value_;
+
+ /**
+ * <code>optional bytes value = 4;</code>
+ */
+ public boolean hasValue() {
+ return ((bitField0_ & 0x00000008) == 0x00000008);
+ }
+
+ /**
+ * <code>optional bytes value = 4;</code>
+ */
+ public com.google.protobuf.ByteString getValue() {
+ return value_;
+ }
+
+ private void initFields() {
+ dpid_ = 0L;
+ number_ = 0L;
+ status_ = 0;
+ value_ = com.google.protobuf.ByteString.EMPTY;
+ }
+
+ private byte memoizedIsInitialized = -1;
+
+ public final boolean isInitialized() {
+ byte isInitialized = memoizedIsInitialized;
+ if (isInitialized != -1) return isInitialized == 1;
+
+ if (!hasDpid()) {
+ memoizedIsInitialized = 0;
+ return false;
+ }
+ if (!hasNumber()) {
+ memoizedIsInitialized = 0;
+ return false;
+ }
+ if (!hasStatus()) {
+ memoizedIsInitialized = 0;
+ return false;
+ }
+ memoizedIsInitialized = 1;
+ return true;
+ }
+
+ public void writeTo(com.google.protobuf.CodedOutputStream output)
+ throws java.io.IOException {
+ getSerializedSize();
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ output.writeInt64(1, dpid_);
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ output.writeInt64(2, number_);
+ }
+ if (((bitField0_ & 0x00000004) == 0x00000004)) {
+ output.writeInt32(3, status_);
+ }
+ if (((bitField0_ & 0x00000008) == 0x00000008)) {
+ output.writeBytes(4, value_);
+ }
+ getUnknownFields().writeTo(output);
+ }
+
+ private int memoizedSerializedSize = -1;
+
+ public int getSerializedSize() {
+ int size = memoizedSerializedSize;
+ if (size != -1) return size;
+
+ size = 0;
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeInt64Size(1, dpid_);
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeInt64Size(2, number_);
+ }
+ if (((bitField0_ & 0x00000004) == 0x00000004)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeInt32Size(3, status_);
+ }
+ if (((bitField0_ & 0x00000008) == 0x00000008)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeBytesSize(4, value_);
+ }
+ size += getUnknownFields().getSerializedSize();
+ memoizedSerializedSize = size;
+ return size;
+ }
+
+ private static final long serialVersionUID = 0L;
+
+ @java.lang.Override
+ protected java.lang.Object writeReplace()
+ throws java.io.ObjectStreamException {
+ return super.writeReplace();
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseFrom(
+ com.google.protobuf.ByteString data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseFrom(
+ com.google.protobuf.ByteString data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseFrom(byte[] data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseFrom(
+ byte[] data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseDelimitedFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseDelimitedFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input, extensionRegistry);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseFrom(
+ com.google.protobuf.CodedInputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.PortProperty parseFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+
+ public static Builder newBuilder() {
+ return Builder.create();
+ }
+
+ public Builder newBuilderForType() {
+ return newBuilder();
+ }
+
+ public static Builder newBuilder(net.onrc.onos.core.datastore.RCProtos.PortProperty prototype) {
+ return newBuilder().mergeFrom(prototype);
+ }
+
+ public Builder toBuilder() {
+ return newBuilder(this);
+ }
+
+ @java.lang.Override
+ protected Builder newBuilderForType(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ Builder builder = new Builder(parent);
+ return builder;
+ }
+
+ /**
+ * Protobuf type {@code RCProtos.PortProperty}
+ */
+ public static final class Builder extends
+ com.google.protobuf.GeneratedMessage.Builder<Builder>
+ implements net.onrc.onos.core.datastore.RCProtos.PortPropertyOrBuilder {
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_PortProperty_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_PortProperty_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ net.onrc.onos.core.datastore.RCProtos.PortProperty.class, net.onrc.onos.core.datastore.RCProtos.PortProperty.Builder.class);
+ }
+
+ // Construct using net.onrc.onos.core.datastore.RCProtos.PortProperty.newBuilder()
+ private Builder() {
+ maybeForceBuilderInitialization();
+ }
+
+ private Builder(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ super(parent);
+ maybeForceBuilderInitialization();
+ }
+
+ private void maybeForceBuilderInitialization() {
+ if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+ }
+ }
+
+ private static Builder create() {
+ return new Builder();
+ }
+
+ public Builder clear() {
+ super.clear();
+ dpid_ = 0L;
+ bitField0_ = (bitField0_ & ~0x00000001);
+ number_ = 0L;
+ bitField0_ = (bitField0_ & ~0x00000002);
+ status_ = 0;
+ bitField0_ = (bitField0_ & ~0x00000004);
+ value_ = com.google.protobuf.ByteString.EMPTY;
+ bitField0_ = (bitField0_ & ~0x00000008);
+ return this;
+ }
+
+ public Builder clone() {
+ return create().mergeFrom(buildPartial());
+ }
+
+ public com.google.protobuf.Descriptors.Descriptor
+ getDescriptorForType() {
+ return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_PortProperty_descriptor;
+ }
+
+ public net.onrc.onos.core.datastore.RCProtos.PortProperty getDefaultInstanceForType() {
+ return net.onrc.onos.core.datastore.RCProtos.PortProperty.getDefaultInstance();
+ }
+
+ public net.onrc.onos.core.datastore.RCProtos.PortProperty build() {
+ net.onrc.onos.core.datastore.RCProtos.PortProperty result = buildPartial();
+ if (!result.isInitialized()) {
+ throw newUninitializedMessageException(result);
+ }
+ return result;
+ }
+
+ public net.onrc.onos.core.datastore.RCProtos.PortProperty buildPartial() {
+ net.onrc.onos.core.datastore.RCProtos.PortProperty result = new net.onrc.onos.core.datastore.RCProtos.PortProperty(this);
+ int from_bitField0_ = bitField0_;
+ int to_bitField0_ = 0;
+ if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+ to_bitField0_ |= 0x00000001;
+ }
+ result.dpid_ = dpid_;
+ if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
+ to_bitField0_ |= 0x00000002;
+ }
+ result.number_ = number_;
+ if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
+ to_bitField0_ |= 0x00000004;
+ }
+ result.status_ = status_;
+ if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
+ to_bitField0_ |= 0x00000008;
+ }
+ result.value_ = value_;
+ result.bitField0_ = to_bitField0_;
+ onBuilt();
+ return result;
+ }
+
+ public Builder mergeFrom(com.google.protobuf.Message other) {
+ if (other instanceof net.onrc.onos.core.datastore.RCProtos.PortProperty) {
+ return mergeFrom((net.onrc.onos.core.datastore.RCProtos.PortProperty) other);
+ } else {
+ super.mergeFrom(other);
+ return this;
+ }
+ }
+
+ public Builder mergeFrom(net.onrc.onos.core.datastore.RCProtos.PortProperty other) {
+ if (other == net.onrc.onos.core.datastore.RCProtos.PortProperty.getDefaultInstance())
+ return this;
+ if (other.hasDpid()) {
+ setDpid(other.getDpid());
+ }
+ if (other.hasNumber()) {
+ setNumber(other.getNumber());
+ }
+ if (other.hasStatus()) {
+ setStatus(other.getStatus());
+ }
+ if (other.hasValue()) {
+ setValue(other.getValue());
+ }
+ this.mergeUnknownFields(other.getUnknownFields());
+ return this;
+ }
+
+ public final boolean isInitialized() {
+ if (!hasDpid()) {
+
+ return false;
+ }
+ if (!hasNumber()) {
+
+ return false;
+ }
+ if (!hasStatus()) {
+
+ return false;
+ }
+ return true;
+ }
+
+ public Builder mergeFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ net.onrc.onos.core.datastore.RCProtos.PortProperty parsedMessage = null;
+ try {
+ parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ parsedMessage = (net.onrc.onos.core.datastore.RCProtos.PortProperty) e.getUnfinishedMessage();
+ throw e;
+ } finally {
+ if (parsedMessage != null) {
+ mergeFrom(parsedMessage);
+ }
+ }
+ return this;
+ }
+
+ private int bitField0_;
+
+ // required int64 dpid = 1;
+ private long dpid_;
+
+ /**
+ * <code>required int64 dpid = 1;</code>
+ */
+ public boolean hasDpid() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+
+ /**
+ * <code>required int64 dpid = 1;</code>
+ */
+ public long getDpid() {
+ return dpid_;
+ }
+
+ /**
+ * <code>required int64 dpid = 1;</code>
+ */
+ public Builder setDpid(long value) {
+ bitField0_ |= 0x00000001;
+ dpid_ = value;
+ onChanged();
+ return this;
+ }
+
+ /**
+ * <code>required int64 dpid = 1;</code>
+ */
+ public Builder clearDpid() {
+ bitField0_ = (bitField0_ & ~0x00000001);
+ dpid_ = 0L;
+ onChanged();
+ return this;
+ }
+
+ // required int64 number = 2;
+ private long number_;
+
+ /**
+ * <code>required int64 number = 2;</code>
+ */
+ public boolean hasNumber() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+
+ /**
+ * <code>required int64 number = 2;</code>
+ */
+ public long getNumber() {
+ return number_;
+ }
+
+ /**
+ * <code>required int64 number = 2;</code>
+ */
+ public Builder setNumber(long value) {
+ bitField0_ |= 0x00000002;
+ number_ = value;
+ onChanged();
+ return this;
+ }
+
+ /**
+ * <code>required int64 number = 2;</code>
+ */
+ public Builder clearNumber() {
+ bitField0_ = (bitField0_ & ~0x00000002);
+ number_ = 0L;
+ onChanged();
+ return this;
+ }
+
+ // required int32 status = 3;
+ private int status_;
+
+ /**
+ * <code>required int32 status = 3;</code>
+ */
+ public boolean hasStatus() {
+ return ((bitField0_ & 0x00000004) == 0x00000004);
+ }
+
+ /**
+ * <code>required int32 status = 3;</code>
+ */
+ public int getStatus() {
+ return status_;
+ }
+
+ /**
+ * <code>required int32 status = 3;</code>
+ */
+ public Builder setStatus(int value) {
+ bitField0_ |= 0x00000004;
+ status_ = value;
+ onChanged();
+ return this;
+ }
+
+ /**
+ * <code>required int32 status = 3;</code>
+ */
+ public Builder clearStatus() {
+ bitField0_ = (bitField0_ & ~0x00000004);
+ status_ = 0;
+ onChanged();
+ return this;
+ }
+
+ // optional bytes value = 4;
+ private com.google.protobuf.ByteString value_ = com.google.protobuf.ByteString.EMPTY;
+
+ /**
+ * <code>optional bytes value = 4;</code>
+ */
+ public boolean hasValue() {
+ return ((bitField0_ & 0x00000008) == 0x00000008);
+ }
+
+ /**
+ * <code>optional bytes value = 4;</code>
+ */
+ public com.google.protobuf.ByteString getValue() {
+ return value_;
+ }
+
+ /**
+ * <code>optional bytes value = 4;</code>
+ */
+ public Builder setValue(com.google.protobuf.ByteString value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00000008;
+ value_ = value;
+ onChanged();
+ return this;
+ }
+
+ /**
+ * <code>optional bytes value = 4;</code>
+ */
+ public Builder clearValue() {
+ bitField0_ = (bitField0_ & ~0x00000008);
+ value_ = getDefaultInstance().getValue();
+ onChanged();
+ return this;
+ }
+
+ // @@protoc_insertion_point(builder_scope:RCProtos.PortProperty)
+ }
+
+ static {
+ defaultInstance = new PortProperty(true);
+ defaultInstance.initFields();
+ }
+
+ // @@protoc_insertion_point(class_scope:RCProtos.PortProperty)
}
- public static com.google.protobuf.Parser<LinkProperty> PARSER =
- new com.google.protobuf.AbstractParser<LinkProperty>() {
- public LinkProperty parsePartialFrom(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return new LinkProperty(input, extensionRegistry);
- }
- };
+ public interface LinkPropertyOrBuilder
+ extends com.google.protobuf.MessageOrBuilder {
- @java.lang.Override
- public com.google.protobuf.Parser<LinkProperty> getParserForType() {
- return PARSER;
+ // required bytes srcSwId = 1;
+
+ /**
+ * <code>required bytes srcSwId = 1;</code>
+ */
+ boolean hasSrcSwId();
+
+ /**
+ * <code>required bytes srcSwId = 1;</code>
+ */
+ com.google.protobuf.ByteString getSrcSwId();
+
+ // required bytes srcPortId = 2;
+
+ /**
+ * <code>required bytes srcPortId = 2;</code>
+ */
+ boolean hasSrcPortId();
+
+ /**
+ * <code>required bytes srcPortId = 2;</code>
+ */
+ com.google.protobuf.ByteString getSrcPortId();
+
+ // required bytes dstSwId = 3;
+
+ /**
+ * <code>required bytes dstSwId = 3;</code>
+ */
+ boolean hasDstSwId();
+
+ /**
+ * <code>required bytes dstSwId = 3;</code>
+ */
+ com.google.protobuf.ByteString getDstSwId();
+
+ // required bytes dstPortId = 4;
+
+ /**
+ * <code>required bytes dstPortId = 4;</code>
+ */
+ boolean hasDstPortId();
+
+ /**
+ * <code>required bytes dstPortId = 4;</code>
+ */
+ com.google.protobuf.ByteString getDstPortId();
+
+ // required int32 status = 5;
+
+ /**
+ * <code>required int32 status = 5;</code>
+ */
+ boolean hasStatus();
+
+ /**
+ * <code>required int32 status = 5;</code>
+ */
+ int getStatus();
+
+ // optional bytes value = 6;
+
+ /**
+ * <code>optional bytes value = 6;</code>
+ */
+ boolean hasValue();
+
+ /**
+ * <code>optional bytes value = 6;</code>
+ */
+ com.google.protobuf.ByteString getValue();
}
- private int bitField0_;
- // required bytes srcSwId = 1;
- public static final int SRCSWID_FIELD_NUMBER = 1;
- private com.google.protobuf.ByteString srcSwId_;
- /**
- * <code>required bytes srcSwId = 1;</code>
- */
- public boolean hasSrcSwId() {
- return ((bitField0_ & 0x00000001) == 0x00000001);
- }
- /**
- * <code>required bytes srcSwId = 1;</code>
- */
- public com.google.protobuf.ByteString getSrcSwId() {
- return srcSwId_;
- }
-
- // required bytes srcPortId = 2;
- public static final int SRCPORTID_FIELD_NUMBER = 2;
- private com.google.protobuf.ByteString srcPortId_;
- /**
- * <code>required bytes srcPortId = 2;</code>
- */
- public boolean hasSrcPortId() {
- return ((bitField0_ & 0x00000002) == 0x00000002);
- }
- /**
- * <code>required bytes srcPortId = 2;</code>
- */
- public com.google.protobuf.ByteString getSrcPortId() {
- return srcPortId_;
- }
-
- // required bytes dstSwId = 3;
- public static final int DSTSWID_FIELD_NUMBER = 3;
- private com.google.protobuf.ByteString dstSwId_;
- /**
- * <code>required bytes dstSwId = 3;</code>
- */
- public boolean hasDstSwId() {
- return ((bitField0_ & 0x00000004) == 0x00000004);
- }
- /**
- * <code>required bytes dstSwId = 3;</code>
- */
- public com.google.protobuf.ByteString getDstSwId() {
- return dstSwId_;
- }
-
- // required bytes dstPortId = 4;
- public static final int DSTPORTID_FIELD_NUMBER = 4;
- private com.google.protobuf.ByteString dstPortId_;
- /**
- * <code>required bytes dstPortId = 4;</code>
- */
- public boolean hasDstPortId() {
- return ((bitField0_ & 0x00000008) == 0x00000008);
- }
- /**
- * <code>required bytes dstPortId = 4;</code>
- */
- public com.google.protobuf.ByteString getDstPortId() {
- return dstPortId_;
- }
-
- // required int32 status = 5;
- public static final int STATUS_FIELD_NUMBER = 5;
- private int status_;
- /**
- * <code>required int32 status = 5;</code>
- */
- public boolean hasStatus() {
- return ((bitField0_ & 0x00000010) == 0x00000010);
- }
- /**
- * <code>required int32 status = 5;</code>
- */
- public int getStatus() {
- return status_;
- }
-
- // optional bytes value = 6;
- public static final int VALUE_FIELD_NUMBER = 6;
- private com.google.protobuf.ByteString value_;
- /**
- * <code>optional bytes value = 6;</code>
- */
- public boolean hasValue() {
- return ((bitField0_ & 0x00000020) == 0x00000020);
- }
- /**
- * <code>optional bytes value = 6;</code>
- */
- public com.google.protobuf.ByteString getValue() {
- return value_;
- }
-
- private void initFields() {
- srcSwId_ = com.google.protobuf.ByteString.EMPTY;
- srcPortId_ = com.google.protobuf.ByteString.EMPTY;
- dstSwId_ = com.google.protobuf.ByteString.EMPTY;
- dstPortId_ = com.google.protobuf.ByteString.EMPTY;
- status_ = 0;
- value_ = com.google.protobuf.ByteString.EMPTY;
- }
- private byte memoizedIsInitialized = -1;
- public final boolean isInitialized() {
- byte isInitialized = memoizedIsInitialized;
- if (isInitialized != -1) return isInitialized == 1;
-
- if (!hasSrcSwId()) {
- memoizedIsInitialized = 0;
- return false;
- }
- if (!hasSrcPortId()) {
- memoizedIsInitialized = 0;
- return false;
- }
- if (!hasDstSwId()) {
- memoizedIsInitialized = 0;
- return false;
- }
- if (!hasDstPortId()) {
- memoizedIsInitialized = 0;
- return false;
- }
- if (!hasStatus()) {
- memoizedIsInitialized = 0;
- return false;
- }
- memoizedIsInitialized = 1;
- return true;
- }
-
- public void writeTo(com.google.protobuf.CodedOutputStream output)
- throws java.io.IOException {
- getSerializedSize();
- if (((bitField0_ & 0x00000001) == 0x00000001)) {
- output.writeBytes(1, srcSwId_);
- }
- if (((bitField0_ & 0x00000002) == 0x00000002)) {
- output.writeBytes(2, srcPortId_);
- }
- if (((bitField0_ & 0x00000004) == 0x00000004)) {
- output.writeBytes(3, dstSwId_);
- }
- if (((bitField0_ & 0x00000008) == 0x00000008)) {
- output.writeBytes(4, dstPortId_);
- }
- if (((bitField0_ & 0x00000010) == 0x00000010)) {
- output.writeInt32(5, status_);
- }
- if (((bitField0_ & 0x00000020) == 0x00000020)) {
- output.writeBytes(6, value_);
- }
- getUnknownFields().writeTo(output);
- }
-
- private int memoizedSerializedSize = -1;
- public int getSerializedSize() {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (((bitField0_ & 0x00000001) == 0x00000001)) {
- size += com.google.protobuf.CodedOutputStream
- .computeBytesSize(1, srcSwId_);
- }
- if (((bitField0_ & 0x00000002) == 0x00000002)) {
- size += com.google.protobuf.CodedOutputStream
- .computeBytesSize(2, srcPortId_);
- }
- if (((bitField0_ & 0x00000004) == 0x00000004)) {
- size += com.google.protobuf.CodedOutputStream
- .computeBytesSize(3, dstSwId_);
- }
- if (((bitField0_ & 0x00000008) == 0x00000008)) {
- size += com.google.protobuf.CodedOutputStream
- .computeBytesSize(4, dstPortId_);
- }
- if (((bitField0_ & 0x00000010) == 0x00000010)) {
- size += com.google.protobuf.CodedOutputStream
- .computeInt32Size(5, status_);
- }
- if (((bitField0_ & 0x00000020) == 0x00000020)) {
- size += com.google.protobuf.CodedOutputStream
- .computeBytesSize(6, value_);
- }
- size += getUnknownFields().getSerializedSize();
- memoizedSerializedSize = size;
- return size;
- }
-
- private static final long serialVersionUID = 0L;
- @java.lang.Override
- protected java.lang.Object writeReplace()
- throws java.io.ObjectStreamException {
- return super.writeReplace();
- }
-
- public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseFrom(
- com.google.protobuf.ByteString data)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return PARSER.parseFrom(data);
- }
- public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseFrom(
- com.google.protobuf.ByteString data,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return PARSER.parseFrom(data, extensionRegistry);
- }
- public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseFrom(byte[] data)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return PARSER.parseFrom(data);
- }
- public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseFrom(
- byte[] data,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return PARSER.parseFrom(data, extensionRegistry);
- }
- public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseFrom(java.io.InputStream input)
- throws java.io.IOException {
- return PARSER.parseFrom(input);
- }
- public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseFrom(
- java.io.InputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- return PARSER.parseFrom(input, extensionRegistry);
- }
- public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseDelimitedFrom(java.io.InputStream input)
- throws java.io.IOException {
- return PARSER.parseDelimitedFrom(input);
- }
- public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseDelimitedFrom(
- java.io.InputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- return PARSER.parseDelimitedFrom(input, extensionRegistry);
- }
- public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseFrom(
- com.google.protobuf.CodedInputStream input)
- throws java.io.IOException {
- return PARSER.parseFrom(input);
- }
- public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseFrom(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- return PARSER.parseFrom(input, extensionRegistry);
- }
-
- public static Builder newBuilder() { return Builder.create(); }
- public Builder newBuilderForType() { return newBuilder(); }
- public static Builder newBuilder(net.onrc.onos.core.datastore.RCProtos.LinkProperty prototype) {
- return newBuilder().mergeFrom(prototype);
- }
- public Builder toBuilder() { return newBuilder(this); }
-
- @java.lang.Override
- protected Builder newBuilderForType(
- com.google.protobuf.GeneratedMessage.BuilderParent parent) {
- Builder builder = new Builder(parent);
- return builder;
- }
/**
* Protobuf type {@code RCProtos.LinkProperty}
*/
- public static final class Builder extends
- com.google.protobuf.GeneratedMessage.Builder<Builder>
- implements net.onrc.onos.core.datastore.RCProtos.LinkPropertyOrBuilder {
- public static final com.google.protobuf.Descriptors.Descriptor
- getDescriptor() {
- return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_LinkProperty_descriptor;
- }
+ public static final class LinkProperty extends
+ com.google.protobuf.GeneratedMessage
+ implements LinkPropertyOrBuilder {
+ // Use LinkProperty.newBuilder() to construct.
+ private LinkProperty(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+ super(builder);
+ this.unknownFields = builder.getUnknownFields();
+ }
- protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
- internalGetFieldAccessorTable() {
- return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_LinkProperty_fieldAccessorTable
- .ensureFieldAccessorsInitialized(
- net.onrc.onos.core.datastore.RCProtos.LinkProperty.class, net.onrc.onos.core.datastore.RCProtos.LinkProperty.Builder.class);
- }
+ private LinkProperty(boolean noInit) {
+ this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance();
+ }
- // Construct using net.onrc.onos.core.datastore.RCProtos.LinkProperty.newBuilder()
- private Builder() {
- maybeForceBuilderInitialization();
- }
+ private static final LinkProperty defaultInstance;
- private Builder(
- com.google.protobuf.GeneratedMessage.BuilderParent parent) {
- super(parent);
- maybeForceBuilderInitialization();
- }
- private void maybeForceBuilderInitialization() {
- if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+ public static LinkProperty getDefaultInstance() {
+ return defaultInstance;
}
- }
- private static Builder create() {
- return new Builder();
- }
- public Builder clear() {
- super.clear();
- srcSwId_ = com.google.protobuf.ByteString.EMPTY;
- bitField0_ = (bitField0_ & ~0x00000001);
- srcPortId_ = com.google.protobuf.ByteString.EMPTY;
- bitField0_ = (bitField0_ & ~0x00000002);
- dstSwId_ = com.google.protobuf.ByteString.EMPTY;
- bitField0_ = (bitField0_ & ~0x00000004);
- dstPortId_ = com.google.protobuf.ByteString.EMPTY;
- bitField0_ = (bitField0_ & ~0x00000008);
- status_ = 0;
- bitField0_ = (bitField0_ & ~0x00000010);
- value_ = com.google.protobuf.ByteString.EMPTY;
- bitField0_ = (bitField0_ & ~0x00000020);
- return this;
- }
+ public LinkProperty getDefaultInstanceForType() {
+ return defaultInstance;
+ }
- public Builder clone() {
- return create().mergeFrom(buildPartial());
- }
+ private final com.google.protobuf.UnknownFieldSet unknownFields;
- public com.google.protobuf.Descriptors.Descriptor
- getDescriptorForType() {
- return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_LinkProperty_descriptor;
- }
+ @java.lang.Override
+ public final com.google.protobuf.UnknownFieldSet
+ getUnknownFields() {
+ return this.unknownFields;
+ }
- public net.onrc.onos.core.datastore.RCProtos.LinkProperty getDefaultInstanceForType() {
- return net.onrc.onos.core.datastore.RCProtos.LinkProperty.getDefaultInstance();
- }
+ private LinkProperty(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ initFields();
+ int mutable_bitField0_ = 0;
+ com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+ com.google.protobuf.UnknownFieldSet.newBuilder();
+ try {
+ boolean done = false;
+ while (!done) {
+ int tag = input.readTag();
+ switch (tag) {
+ case 0:
+ done = true;
+ break;
+ default: {
+ if (!parseUnknownField(input, unknownFields,
+ extensionRegistry, tag)) {
+ done = true;
+ }
+ break;
+ }
+ case 10: {
+ bitField0_ |= 0x00000001;
+ srcSwId_ = input.readBytes();
+ break;
+ }
+ case 18: {
+ bitField0_ |= 0x00000002;
+ srcPortId_ = input.readBytes();
+ break;
+ }
+ case 26: {
+ bitField0_ |= 0x00000004;
+ dstSwId_ = input.readBytes();
+ break;
+ }
+ case 34: {
+ bitField0_ |= 0x00000008;
+ dstPortId_ = input.readBytes();
+ break;
+ }
+ case 40: {
+ bitField0_ |= 0x00000010;
+ status_ = input.readInt32();
+ break;
+ }
+ case 50: {
+ bitField0_ |= 0x00000020;
+ value_ = input.readBytes();
+ break;
+ }
+ }
+ }
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ throw e.setUnfinishedMessage(this);
+ } catch (java.io.IOException e) {
+ throw new com.google.protobuf.InvalidProtocolBufferException(
+ e.getMessage()).setUnfinishedMessage(this);
+ } finally {
+ this.unknownFields = unknownFields.build();
+ makeExtensionsImmutable();
+ }
+ }
- public net.onrc.onos.core.datastore.RCProtos.LinkProperty build() {
- net.onrc.onos.core.datastore.RCProtos.LinkProperty result = buildPartial();
- if (!result.isInitialized()) {
- throw newUninitializedMessageException(result);
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_LinkProperty_descriptor;
}
- return result;
- }
- public net.onrc.onos.core.datastore.RCProtos.LinkProperty buildPartial() {
- net.onrc.onos.core.datastore.RCProtos.LinkProperty result = new net.onrc.onos.core.datastore.RCProtos.LinkProperty(this);
- int from_bitField0_ = bitField0_;
- int to_bitField0_ = 0;
- if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
- to_bitField0_ |= 0x00000001;
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_LinkProperty_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ net.onrc.onos.core.datastore.RCProtos.LinkProperty.class, net.onrc.onos.core.datastore.RCProtos.LinkProperty.Builder.class);
}
- result.srcSwId_ = srcSwId_;
- if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
- to_bitField0_ |= 0x00000002;
- }
- result.srcPortId_ = srcPortId_;
- if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
- to_bitField0_ |= 0x00000004;
- }
- result.dstSwId_ = dstSwId_;
- if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
- to_bitField0_ |= 0x00000008;
- }
- result.dstPortId_ = dstPortId_;
- if (((from_bitField0_ & 0x00000010) == 0x00000010)) {
- to_bitField0_ |= 0x00000010;
- }
- result.status_ = status_;
- if (((from_bitField0_ & 0x00000020) == 0x00000020)) {
- to_bitField0_ |= 0x00000020;
- }
- result.value_ = value_;
- result.bitField0_ = to_bitField0_;
- onBuilt();
- return result;
- }
- public Builder mergeFrom(com.google.protobuf.Message other) {
- if (other instanceof net.onrc.onos.core.datastore.RCProtos.LinkProperty) {
- return mergeFrom((net.onrc.onos.core.datastore.RCProtos.LinkProperty)other);
- } else {
- super.mergeFrom(other);
- return this;
- }
- }
+ public static com.google.protobuf.Parser<LinkProperty> PARSER =
+ new com.google.protobuf.AbstractParser<LinkProperty>() {
+ public LinkProperty parsePartialFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return new LinkProperty(input, extensionRegistry);
+ }
+ };
- public Builder mergeFrom(net.onrc.onos.core.datastore.RCProtos.LinkProperty other) {
- if (other == net.onrc.onos.core.datastore.RCProtos.LinkProperty.getDefaultInstance()) return this;
- if (other.hasSrcSwId()) {
- setSrcSwId(other.getSrcSwId());
+ @java.lang.Override
+ public com.google.protobuf.Parser<LinkProperty> getParserForType() {
+ return PARSER;
}
- if (other.hasSrcPortId()) {
- setSrcPortId(other.getSrcPortId());
- }
- if (other.hasDstSwId()) {
- setDstSwId(other.getDstSwId());
- }
- if (other.hasDstPortId()) {
- setDstPortId(other.getDstPortId());
- }
- if (other.hasStatus()) {
- setStatus(other.getStatus());
- }
- if (other.hasValue()) {
- setValue(other.getValue());
- }
- this.mergeUnknownFields(other.getUnknownFields());
- return this;
- }
- public final boolean isInitialized() {
- if (!hasSrcSwId()) {
-
- return false;
+ private int bitField0_;
+ // required bytes srcSwId = 1;
+ public static final int SRCSWID_FIELD_NUMBER = 1;
+ private com.google.protobuf.ByteString srcSwId_;
+
+ /**
+ * <code>required bytes srcSwId = 1;</code>
+ */
+ public boolean hasSrcSwId() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
}
- if (!hasSrcPortId()) {
-
- return false;
+
+ /**
+ * <code>required bytes srcSwId = 1;</code>
+ */
+ public com.google.protobuf.ByteString getSrcSwId() {
+ return srcSwId_;
}
- if (!hasDstSwId()) {
-
- return false;
+
+ // required bytes srcPortId = 2;
+ public static final int SRCPORTID_FIELD_NUMBER = 2;
+ private com.google.protobuf.ByteString srcPortId_;
+
+ /**
+ * <code>required bytes srcPortId = 2;</code>
+ */
+ public boolean hasSrcPortId() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
}
- if (!hasDstPortId()) {
-
- return false;
+
+ /**
+ * <code>required bytes srcPortId = 2;</code>
+ */
+ public com.google.protobuf.ByteString getSrcPortId() {
+ return srcPortId_;
}
- if (!hasStatus()) {
-
- return false;
+
+ // required bytes dstSwId = 3;
+ public static final int DSTSWID_FIELD_NUMBER = 3;
+ private com.google.protobuf.ByteString dstSwId_;
+
+ /**
+ * <code>required bytes dstSwId = 3;</code>
+ */
+ public boolean hasDstSwId() {
+ return ((bitField0_ & 0x00000004) == 0x00000004);
}
- return true;
- }
- public Builder mergeFrom(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- net.onrc.onos.core.datastore.RCProtos.LinkProperty parsedMessage = null;
- try {
- parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
- } catch (com.google.protobuf.InvalidProtocolBufferException e) {
- parsedMessage = (net.onrc.onos.core.datastore.RCProtos.LinkProperty) e.getUnfinishedMessage();
- throw e;
- } finally {
- if (parsedMessage != null) {
- mergeFrom(parsedMessage);
- }
+ /**
+ * <code>required bytes dstSwId = 3;</code>
+ */
+ public com.google.protobuf.ByteString getDstSwId() {
+ return dstSwId_;
}
- return this;
- }
- private int bitField0_;
- // required bytes srcSwId = 1;
- private com.google.protobuf.ByteString srcSwId_ = com.google.protobuf.ByteString.EMPTY;
- /**
- * <code>required bytes srcSwId = 1;</code>
- */
- public boolean hasSrcSwId() {
- return ((bitField0_ & 0x00000001) == 0x00000001);
- }
- /**
- * <code>required bytes srcSwId = 1;</code>
- */
- public com.google.protobuf.ByteString getSrcSwId() {
- return srcSwId_;
- }
- /**
- * <code>required bytes srcSwId = 1;</code>
- */
- public Builder setSrcSwId(com.google.protobuf.ByteString value) {
- if (value == null) {
- throw new NullPointerException();
- }
- bitField0_ |= 0x00000001;
- srcSwId_ = value;
- onChanged();
- return this;
- }
- /**
- * <code>required bytes srcSwId = 1;</code>
- */
- public Builder clearSrcSwId() {
- bitField0_ = (bitField0_ & ~0x00000001);
- srcSwId_ = getDefaultInstance().getSrcSwId();
- onChanged();
- return this;
- }
+ // required bytes dstPortId = 4;
+ public static final int DSTPORTID_FIELD_NUMBER = 4;
+ private com.google.protobuf.ByteString dstPortId_;
- // required bytes srcPortId = 2;
- private com.google.protobuf.ByteString srcPortId_ = com.google.protobuf.ByteString.EMPTY;
- /**
- * <code>required bytes srcPortId = 2;</code>
- */
- public boolean hasSrcPortId() {
- return ((bitField0_ & 0x00000002) == 0x00000002);
- }
- /**
- * <code>required bytes srcPortId = 2;</code>
- */
- public com.google.protobuf.ByteString getSrcPortId() {
- return srcPortId_;
- }
- /**
- * <code>required bytes srcPortId = 2;</code>
- */
- public Builder setSrcPortId(com.google.protobuf.ByteString value) {
- if (value == null) {
- throw new NullPointerException();
- }
- bitField0_ |= 0x00000002;
- srcPortId_ = value;
- onChanged();
- return this;
- }
- /**
- * <code>required bytes srcPortId = 2;</code>
- */
- public Builder clearSrcPortId() {
- bitField0_ = (bitField0_ & ~0x00000002);
- srcPortId_ = getDefaultInstance().getSrcPortId();
- onChanged();
- return this;
- }
+ /**
+ * <code>required bytes dstPortId = 4;</code>
+ */
+ public boolean hasDstPortId() {
+ return ((bitField0_ & 0x00000008) == 0x00000008);
+ }
- // required bytes dstSwId = 3;
- private com.google.protobuf.ByteString dstSwId_ = com.google.protobuf.ByteString.EMPTY;
- /**
- * <code>required bytes dstSwId = 3;</code>
- */
- public boolean hasDstSwId() {
- return ((bitField0_ & 0x00000004) == 0x00000004);
- }
- /**
- * <code>required bytes dstSwId = 3;</code>
- */
- public com.google.protobuf.ByteString getDstSwId() {
- return dstSwId_;
- }
- /**
- * <code>required bytes dstSwId = 3;</code>
- */
- public Builder setDstSwId(com.google.protobuf.ByteString value) {
- if (value == null) {
- throw new NullPointerException();
- }
- bitField0_ |= 0x00000004;
- dstSwId_ = value;
- onChanged();
- return this;
- }
- /**
- * <code>required bytes dstSwId = 3;</code>
- */
- public Builder clearDstSwId() {
- bitField0_ = (bitField0_ & ~0x00000004);
- dstSwId_ = getDefaultInstance().getDstSwId();
- onChanged();
- return this;
- }
+ /**
+ * <code>required bytes dstPortId = 4;</code>
+ */
+ public com.google.protobuf.ByteString getDstPortId() {
+ return dstPortId_;
+ }
- // required bytes dstPortId = 4;
- private com.google.protobuf.ByteString dstPortId_ = com.google.protobuf.ByteString.EMPTY;
- /**
- * <code>required bytes dstPortId = 4;</code>
- */
- public boolean hasDstPortId() {
- return ((bitField0_ & 0x00000008) == 0x00000008);
- }
- /**
- * <code>required bytes dstPortId = 4;</code>
- */
- public com.google.protobuf.ByteString getDstPortId() {
- return dstPortId_;
- }
- /**
- * <code>required bytes dstPortId = 4;</code>
- */
- public Builder setDstPortId(com.google.protobuf.ByteString value) {
- if (value == null) {
- throw new NullPointerException();
- }
- bitField0_ |= 0x00000008;
- dstPortId_ = value;
- onChanged();
- return this;
- }
- /**
- * <code>required bytes dstPortId = 4;</code>
- */
- public Builder clearDstPortId() {
- bitField0_ = (bitField0_ & ~0x00000008);
- dstPortId_ = getDefaultInstance().getDstPortId();
- onChanged();
- return this;
- }
+ // required int32 status = 5;
+ public static final int STATUS_FIELD_NUMBER = 5;
+ private int status_;
- // required int32 status = 5;
- private int status_ ;
- /**
- * <code>required int32 status = 5;</code>
- */
- public boolean hasStatus() {
- return ((bitField0_ & 0x00000010) == 0x00000010);
- }
- /**
- * <code>required int32 status = 5;</code>
- */
- public int getStatus() {
- return status_;
- }
- /**
- * <code>required int32 status = 5;</code>
- */
- public Builder setStatus(int value) {
- bitField0_ |= 0x00000010;
- status_ = value;
- onChanged();
- return this;
- }
- /**
- * <code>required int32 status = 5;</code>
- */
- public Builder clearStatus() {
- bitField0_ = (bitField0_ & ~0x00000010);
- status_ = 0;
- onChanged();
- return this;
- }
+ /**
+ * <code>required int32 status = 5;</code>
+ */
+ public boolean hasStatus() {
+ return ((bitField0_ & 0x00000010) == 0x00000010);
+ }
- // optional bytes value = 6;
- private com.google.protobuf.ByteString value_ = com.google.protobuf.ByteString.EMPTY;
- /**
- * <code>optional bytes value = 6;</code>
- */
- public boolean hasValue() {
- return ((bitField0_ & 0x00000020) == 0x00000020);
- }
- /**
- * <code>optional bytes value = 6;</code>
- */
- public com.google.protobuf.ByteString getValue() {
- return value_;
- }
- /**
- * <code>optional bytes value = 6;</code>
- */
- public Builder setValue(com.google.protobuf.ByteString value) {
- if (value == null) {
- throw new NullPointerException();
- }
- bitField0_ |= 0x00000020;
- value_ = value;
- onChanged();
- return this;
- }
- /**
- * <code>optional bytes value = 6;</code>
- */
- public Builder clearValue() {
- bitField0_ = (bitField0_ & ~0x00000020);
- value_ = getDefaultInstance().getValue();
- onChanged();
- return this;
- }
+ /**
+ * <code>required int32 status = 5;</code>
+ */
+ public int getStatus() {
+ return status_;
+ }
- // @@protoc_insertion_point(builder_scope:RCProtos.LinkProperty)
+ // optional bytes value = 6;
+ public static final int VALUE_FIELD_NUMBER = 6;
+ private com.google.protobuf.ByteString value_;
+
+ /**
+ * <code>optional bytes value = 6;</code>
+ */
+ public boolean hasValue() {
+ return ((bitField0_ & 0x00000020) == 0x00000020);
+ }
+
+ /**
+ * <code>optional bytes value = 6;</code>
+ */
+ public com.google.protobuf.ByteString getValue() {
+ return value_;
+ }
+
+ private void initFields() {
+ srcSwId_ = com.google.protobuf.ByteString.EMPTY;
+ srcPortId_ = com.google.protobuf.ByteString.EMPTY;
+ dstSwId_ = com.google.protobuf.ByteString.EMPTY;
+ dstPortId_ = com.google.protobuf.ByteString.EMPTY;
+ status_ = 0;
+ value_ = com.google.protobuf.ByteString.EMPTY;
+ }
+
+ private byte memoizedIsInitialized = -1;
+
+ public final boolean isInitialized() {
+ byte isInitialized = memoizedIsInitialized;
+ if (isInitialized != -1) return isInitialized == 1;
+
+ if (!hasSrcSwId()) {
+ memoizedIsInitialized = 0;
+ return false;
+ }
+ if (!hasSrcPortId()) {
+ memoizedIsInitialized = 0;
+ return false;
+ }
+ if (!hasDstSwId()) {
+ memoizedIsInitialized = 0;
+ return false;
+ }
+ if (!hasDstPortId()) {
+ memoizedIsInitialized = 0;
+ return false;
+ }
+ if (!hasStatus()) {
+ memoizedIsInitialized = 0;
+ return false;
+ }
+ memoizedIsInitialized = 1;
+ return true;
+ }
+
+ public void writeTo(com.google.protobuf.CodedOutputStream output)
+ throws java.io.IOException {
+ getSerializedSize();
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ output.writeBytes(1, srcSwId_);
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ output.writeBytes(2, srcPortId_);
+ }
+ if (((bitField0_ & 0x00000004) == 0x00000004)) {
+ output.writeBytes(3, dstSwId_);
+ }
+ if (((bitField0_ & 0x00000008) == 0x00000008)) {
+ output.writeBytes(4, dstPortId_);
+ }
+ if (((bitField0_ & 0x00000010) == 0x00000010)) {
+ output.writeInt32(5, status_);
+ }
+ if (((bitField0_ & 0x00000020) == 0x00000020)) {
+ output.writeBytes(6, value_);
+ }
+ getUnknownFields().writeTo(output);
+ }
+
+ private int memoizedSerializedSize = -1;
+
+ public int getSerializedSize() {
+ int size = memoizedSerializedSize;
+ if (size != -1) return size;
+
+ size = 0;
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeBytesSize(1, srcSwId_);
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeBytesSize(2, srcPortId_);
+ }
+ if (((bitField0_ & 0x00000004) == 0x00000004)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeBytesSize(3, dstSwId_);
+ }
+ if (((bitField0_ & 0x00000008) == 0x00000008)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeBytesSize(4, dstPortId_);
+ }
+ if (((bitField0_ & 0x00000010) == 0x00000010)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeInt32Size(5, status_);
+ }
+ if (((bitField0_ & 0x00000020) == 0x00000020)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeBytesSize(6, value_);
+ }
+ size += getUnknownFields().getSerializedSize();
+ memoizedSerializedSize = size;
+ return size;
+ }
+
+ private static final long serialVersionUID = 0L;
+
+ @java.lang.Override
+ protected java.lang.Object writeReplace()
+ throws java.io.ObjectStreamException {
+ return super.writeReplace();
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseFrom(
+ com.google.protobuf.ByteString data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseFrom(
+ com.google.protobuf.ByteString data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseFrom(byte[] data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseFrom(
+ byte[] data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseDelimitedFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseDelimitedFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input, extensionRegistry);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseFrom(
+ com.google.protobuf.CodedInputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+
+ public static net.onrc.onos.core.datastore.RCProtos.LinkProperty parseFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+
+ public static Builder newBuilder() {
+ return Builder.create();
+ }
+
+ public Builder newBuilderForType() {
+ return newBuilder();
+ }
+
+ public static Builder newBuilder(net.onrc.onos.core.datastore.RCProtos.LinkProperty prototype) {
+ return newBuilder().mergeFrom(prototype);
+ }
+
+ public Builder toBuilder() {
+ return newBuilder(this);
+ }
+
+ @java.lang.Override
+ protected Builder newBuilderForType(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ Builder builder = new Builder(parent);
+ return builder;
+ }
+
+ /**
+ * Protobuf type {@code RCProtos.LinkProperty}
+ */
+ public static final class Builder extends
+ com.google.protobuf.GeneratedMessage.Builder<Builder>
+ implements net.onrc.onos.core.datastore.RCProtos.LinkPropertyOrBuilder {
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_LinkProperty_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_LinkProperty_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ net.onrc.onos.core.datastore.RCProtos.LinkProperty.class, net.onrc.onos.core.datastore.RCProtos.LinkProperty.Builder.class);
+ }
+
+ // Construct using net.onrc.onos.core.datastore.RCProtos.LinkProperty.newBuilder()
+ private Builder() {
+ maybeForceBuilderInitialization();
+ }
+
+ private Builder(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ super(parent);
+ maybeForceBuilderInitialization();
+ }
+
+ private void maybeForceBuilderInitialization() {
+ if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+ }
+ }
+
+ private static Builder create() {
+ return new Builder();
+ }
+
+ public Builder clear() {
+ super.clear();
+ srcSwId_ = com.google.protobuf.ByteString.EMPTY;
+ bitField0_ = (bitField0_ & ~0x00000001);
+ srcPortId_ = com.google.protobuf.ByteString.EMPTY;
+ bitField0_ = (bitField0_ & ~0x00000002);
+ dstSwId_ = com.google.protobuf.ByteString.EMPTY;
+ bitField0_ = (bitField0_ & ~0x00000004);
+ dstPortId_ = com.google.protobuf.ByteString.EMPTY;
+ bitField0_ = (bitField0_ & ~0x00000008);
+ status_ = 0;
+ bitField0_ = (bitField0_ & ~0x00000010);
+ value_ = com.google.protobuf.ByteString.EMPTY;
+ bitField0_ = (bitField0_ & ~0x00000020);
+ return this;
+ }
+
+ public Builder clone() {
+ return create().mergeFrom(buildPartial());
+ }
+
+ public com.google.protobuf.Descriptors.Descriptor
+ getDescriptorForType() {
+ return net.onrc.onos.core.datastore.RCProtos.internal_static_ProtoBuffer_LinkProperty_descriptor;
+ }
+
+ public net.onrc.onos.core.datastore.RCProtos.LinkProperty getDefaultInstanceForType() {
+ return net.onrc.onos.core.datastore.RCProtos.LinkProperty.getDefaultInstance();
+ }
+
+ public net.onrc.onos.core.datastore.RCProtos.LinkProperty build() {
+ net.onrc.onos.core.datastore.RCProtos.LinkProperty result = buildPartial();
+ if (!result.isInitialized()) {
+ throw newUninitializedMessageException(result);
+ }
+ return result;
+ }
+
+ public net.onrc.onos.core.datastore.RCProtos.LinkProperty buildPartial() {
+ net.onrc.onos.core.datastore.RCProtos.LinkProperty result = new net.onrc.onos.core.datastore.RCProtos.LinkProperty(this);
+ int from_bitField0_ = bitField0_;
+ int to_bitField0_ = 0;
+ if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+ to_bitField0_ |= 0x00000001;
+ }
+ result.srcSwId_ = srcSwId_;
+ if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
+ to_bitField0_ |= 0x00000002;
+ }
+ result.srcPortId_ = srcPortId_;
+ if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
+ to_bitField0_ |= 0x00000004;
+ }
+ result.dstSwId_ = dstSwId_;
+ if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
+ to_bitField0_ |= 0x00000008;
+ }
+ result.dstPortId_ = dstPortId_;
+ if (((from_bitField0_ & 0x00000010) == 0x00000010)) {
+ to_bitField0_ |= 0x00000010;
+ }
+ result.status_ = status_;
+ if (((from_bitField0_ & 0x00000020) == 0x00000020)) {
+ to_bitField0_ |= 0x00000020;
+ }
+ result.value_ = value_;
+ result.bitField0_ = to_bitField0_;
+ onBuilt();
+ return result;
+ }
+
+ public Builder mergeFrom(com.google.protobuf.Message other) {
+ if (other instanceof net.onrc.onos.core.datastore.RCProtos.LinkProperty) {
+ return mergeFrom((net.onrc.onos.core.datastore.RCProtos.LinkProperty) other);
+ } else {
+ super.mergeFrom(other);
+ return this;
+ }
+ }
+
+ public Builder mergeFrom(net.onrc.onos.core.datastore.RCProtos.LinkProperty other) {
+ if (other == net.onrc.onos.core.datastore.RCProtos.LinkProperty.getDefaultInstance())
+ return this;
+ if (other.hasSrcSwId()) {
+ setSrcSwId(other.getSrcSwId());
+ }
+ if (other.hasSrcPortId()) {
+ setSrcPortId(other.getSrcPortId());
+ }
+ if (other.hasDstSwId()) {
+ setDstSwId(other.getDstSwId());
+ }
+ if (other.hasDstPortId()) {
+ setDstPortId(other.getDstPortId());
+ }
+ if (other.hasStatus()) {
+ setStatus(other.getStatus());
+ }
+ if (other.hasValue()) {
+ setValue(other.getValue());
+ }
+ this.mergeUnknownFields(other.getUnknownFields());
+ return this;
+ }
+
+ public final boolean isInitialized() {
+ if (!hasSrcSwId()) {
+
+ return false;
+ }
+ if (!hasSrcPortId()) {
+
+ return false;
+ }
+ if (!hasDstSwId()) {
+
+ return false;
+ }
+ if (!hasDstPortId()) {
+
+ return false;
+ }
+ if (!hasStatus()) {
+
+ return false;
+ }
+ return true;
+ }
+
+ public Builder mergeFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ net.onrc.onos.core.datastore.RCProtos.LinkProperty parsedMessage = null;
+ try {
+ parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ parsedMessage = (net.onrc.onos.core.datastore.RCProtos.LinkProperty) e.getUnfinishedMessage();
+ throw e;
+ } finally {
+ if (parsedMessage != null) {
+ mergeFrom(parsedMessage);
+ }
+ }
+ return this;
+ }
+
+ private int bitField0_;
+
+ // required bytes srcSwId = 1;
+ private com.google.protobuf.ByteString srcSwId_ = com.google.protobuf.ByteString.EMPTY;
+
+ /**
+ * <code>required bytes srcSwId = 1;</code>
+ */
+ public boolean hasSrcSwId() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+
+ /**
+ * <code>required bytes srcSwId = 1;</code>
+ */
+ public com.google.protobuf.ByteString getSrcSwId() {
+ return srcSwId_;
+ }
+
+ /**
+ * <code>required bytes srcSwId = 1;</code>
+ */
+ public Builder setSrcSwId(com.google.protobuf.ByteString value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00000001;
+ srcSwId_ = value;
+ onChanged();
+ return this;
+ }
+
+ /**
+ * <code>required bytes srcSwId = 1;</code>
+ */
+ public Builder clearSrcSwId() {
+ bitField0_ = (bitField0_ & ~0x00000001);
+ srcSwId_ = getDefaultInstance().getSrcSwId();
+ onChanged();
+ return this;
+ }
+
+ // required bytes srcPortId = 2;
+ private com.google.protobuf.ByteString srcPortId_ = com.google.protobuf.ByteString.EMPTY;
+
+ /**
+ * <code>required bytes srcPortId = 2;</code>
+ */
+ public boolean hasSrcPortId() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+
+ /**
+ * <code>required bytes srcPortId = 2;</code>
+ */
+ public com.google.protobuf.ByteString getSrcPortId() {
+ return srcPortId_;
+ }
+
+ /**
+ * <code>required bytes srcPortId = 2;</code>
+ */
+ public Builder setSrcPortId(com.google.protobuf.ByteString value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00000002;
+ srcPortId_ = value;
+ onChanged();
+ return this;
+ }
+
+ /**
+ * <code>required bytes srcPortId = 2;</code>
+ */
+ public Builder clearSrcPortId() {
+ bitField0_ = (bitField0_ & ~0x00000002);
+ srcPortId_ = getDefaultInstance().getSrcPortId();
+ onChanged();
+ return this;
+ }
+
+ // required bytes dstSwId = 3;
+ private com.google.protobuf.ByteString dstSwId_ = com.google.protobuf.ByteString.EMPTY;
+
+ /**
+ * <code>required bytes dstSwId = 3;</code>
+ */
+ public boolean hasDstSwId() {
+ return ((bitField0_ & 0x00000004) == 0x00000004);
+ }
+
+ /**
+ * <code>required bytes dstSwId = 3;</code>
+ */
+ public com.google.protobuf.ByteString getDstSwId() {
+ return dstSwId_;
+ }
+
+ /**
+ * <code>required bytes dstSwId = 3;</code>
+ */
+ public Builder setDstSwId(com.google.protobuf.ByteString value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00000004;
+ dstSwId_ = value;
+ onChanged();
+ return this;
+ }
+
+ /**
+ * <code>required bytes dstSwId = 3;</code>
+ */
+ public Builder clearDstSwId() {
+ bitField0_ = (bitField0_ & ~0x00000004);
+ dstSwId_ = getDefaultInstance().getDstSwId();
+ onChanged();
+ return this;
+ }
+
+ // required bytes dstPortId = 4;
+ private com.google.protobuf.ByteString dstPortId_ = com.google.protobuf.ByteString.EMPTY;
+
+ /**
+ * <code>required bytes dstPortId = 4;</code>
+ */
+ public boolean hasDstPortId() {
+ return ((bitField0_ & 0x00000008) == 0x00000008);
+ }
+
+ /**
+ * <code>required bytes dstPortId = 4;</code>
+ */
+ public com.google.protobuf.ByteString getDstPortId() {
+ return dstPortId_;
+ }
+
+ /**
+ * <code>required bytes dstPortId = 4;</code>
+ */
+ public Builder setDstPortId(com.google.protobuf.ByteString value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00000008;
+ dstPortId_ = value;
+ onChanged();
+ return this;
+ }
+
+ /**
+ * <code>required bytes dstPortId = 4;</code>
+ */
+ public Builder clearDstPortId() {
+ bitField0_ = (bitField0_ & ~0x00000008);
+ dstPortId_ = getDefaultInstance().getDstPortId();
+ onChanged();
+ return this;
+ }
+
+ // required int32 status = 5;
+ private int status_;
+
+ /**
+ * <code>required int32 status = 5;</code>
+ */
+ public boolean hasStatus() {
+ return ((bitField0_ & 0x00000010) == 0x00000010);
+ }
+
+ /**
+ * <code>required int32 status = 5;</code>
+ */
+ public int getStatus() {
+ return status_;
+ }
+
+ /**
+ * <code>required int32 status = 5;</code>
+ */
+ public Builder setStatus(int value) {
+ bitField0_ |= 0x00000010;
+ status_ = value;
+ onChanged();
+ return this;
+ }
+
+ /**
+ * <code>required int32 status = 5;</code>
+ */
+ public Builder clearStatus() {
+ bitField0_ = (bitField0_ & ~0x00000010);
+ status_ = 0;
+ onChanged();
+ return this;
+ }
+
+ // optional bytes value = 6;
+ private com.google.protobuf.ByteString value_ = com.google.protobuf.ByteString.EMPTY;
+
+ /**
+ * <code>optional bytes value = 6;</code>
+ */
+ public boolean hasValue() {
+ return ((bitField0_ & 0x00000020) == 0x00000020);
+ }
+
+ /**
+ * <code>optional bytes value = 6;</code>
+ */
+ public com.google.protobuf.ByteString getValue() {
+ return value_;
+ }
+
+ /**
+ * <code>optional bytes value = 6;</code>
+ */
+ public Builder setValue(com.google.protobuf.ByteString value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00000020;
+ value_ = value;
+ onChanged();
+ return this;
+ }
+
+ /**
+ * <code>optional bytes value = 6;</code>
+ */
+ public Builder clearValue() {
+ bitField0_ = (bitField0_ & ~0x00000020);
+ value_ = getDefaultInstance().getValue();
+ onChanged();
+ return this;
+ }
+
+ // @@protoc_insertion_point(builder_scope:RCProtos.LinkProperty)
+ }
+
+ static {
+ defaultInstance = new LinkProperty(true);
+ defaultInstance.initFields();
+ }
+
+ // @@protoc_insertion_point(class_scope:RCProtos.LinkProperty)
}
+ private static com.google.protobuf.Descriptors.Descriptor
+ internal_static_ProtoBuffer_SwitchProperty_descriptor;
+ private static
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internal_static_ProtoBuffer_SwitchProperty_fieldAccessorTable;
+ private static com.google.protobuf.Descriptors.Descriptor
+ internal_static_ProtoBuffer_PortProperty_descriptor;
+ private static
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internal_static_ProtoBuffer_PortProperty_fieldAccessorTable;
+ private static com.google.protobuf.Descriptors.Descriptor
+ internal_static_ProtoBuffer_LinkProperty_descriptor;
+ private static
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internal_static_ProtoBuffer_LinkProperty_fieldAccessorTable;
+
+ public static com.google.protobuf.Descriptors.FileDescriptor
+ getDescriptor() {
+ return descriptor;
+ }
+
+ private static com.google.protobuf.Descriptors.FileDescriptor
+ descriptor;
+
static {
- defaultInstance = new LinkProperty(true);
- defaultInstance.initFields();
+ java.lang.String[] descriptorData = {
+ "\n\027protobuf/ramcloud.proto\022\013ProtoBuffer\"=" +
+ "\n\016SwitchProperty\022\014\n\004dpid\030\001 \002(\003\022\016\n\006status" +
+ "\030\002 \002(\005\022\r\n\005value\030\003 \001(\014\"K\n\014PortProperty\022\014\n" +
+ "\004dpid\030\001 \002(\003\022\016\n\006number\030\002 \002(\003\022\016\n\006status\030\003 " +
+ "\002(\005\022\r\n\005value\030\004 \001(\014\"u\n\014LinkProperty\022\017\n\007sr" +
+ "cSwId\030\001 \002(\014\022\021\n\tsrcPortId\030\002 \002(\014\022\017\n\007dstSwI" +
+ "d\030\003 \002(\014\022\021\n\tdstPortId\030\004 \002(\014\022\016\n\006status\030\005 \002" +
+ "(\005\022\r\n\005value\030\006 \001(\014B&\n\027net.onrc.onos.datas" +
+ "toreB\013ProtoBuffer"
+ };
+ com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
+ new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
+ public com.google.protobuf.ExtensionRegistry assignDescriptors(
+ com.google.protobuf.Descriptors.FileDescriptor root) {
+ descriptor = root;
+ internal_static_ProtoBuffer_SwitchProperty_descriptor =
+ getDescriptor().getMessageTypes().get(0);
+ internal_static_ProtoBuffer_SwitchProperty_fieldAccessorTable = new
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+ internal_static_ProtoBuffer_SwitchProperty_descriptor,
+ new java.lang.String[]{"Dpid", "Status", "Value",});
+ internal_static_ProtoBuffer_PortProperty_descriptor =
+ getDescriptor().getMessageTypes().get(1);
+ internal_static_ProtoBuffer_PortProperty_fieldAccessorTable = new
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+ internal_static_ProtoBuffer_PortProperty_descriptor,
+ new java.lang.String[]{"Dpid", "Number", "Status", "Value",});
+ internal_static_ProtoBuffer_LinkProperty_descriptor =
+ getDescriptor().getMessageTypes().get(2);
+ internal_static_ProtoBuffer_LinkProperty_fieldAccessorTable = new
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+ internal_static_ProtoBuffer_LinkProperty_descriptor,
+ new java.lang.String[]{"SrcSwId", "SrcPortId", "DstSwId", "DstPortId", "Status", "Value",});
+ return null;
+ }
+ };
+ com.google.protobuf.Descriptors.FileDescriptor
+ .internalBuildGeneratedFileFrom(descriptorData,
+ new com.google.protobuf.Descriptors.FileDescriptor[]{
+ }, assigner);
}
- // @@protoc_insertion_point(class_scope:RCProtos.LinkProperty)
- }
-
- private static com.google.protobuf.Descriptors.Descriptor
- internal_static_ProtoBuffer_SwitchProperty_descriptor;
- private static
- com.google.protobuf.GeneratedMessage.FieldAccessorTable
- internal_static_ProtoBuffer_SwitchProperty_fieldAccessorTable;
- private static com.google.protobuf.Descriptors.Descriptor
- internal_static_ProtoBuffer_PortProperty_descriptor;
- private static
- com.google.protobuf.GeneratedMessage.FieldAccessorTable
- internal_static_ProtoBuffer_PortProperty_fieldAccessorTable;
- private static com.google.protobuf.Descriptors.Descriptor
- internal_static_ProtoBuffer_LinkProperty_descriptor;
- private static
- com.google.protobuf.GeneratedMessage.FieldAccessorTable
- internal_static_ProtoBuffer_LinkProperty_fieldAccessorTable;
-
- public static com.google.protobuf.Descriptors.FileDescriptor
- getDescriptor() {
- return descriptor;
- }
- private static com.google.protobuf.Descriptors.FileDescriptor
- descriptor;
- static {
- java.lang.String[] descriptorData = {
- "\n\027protobuf/ramcloud.proto\022\013ProtoBuffer\"=" +
- "\n\016SwitchProperty\022\014\n\004dpid\030\001 \002(\003\022\016\n\006status" +
- "\030\002 \002(\005\022\r\n\005value\030\003 \001(\014\"K\n\014PortProperty\022\014\n" +
- "\004dpid\030\001 \002(\003\022\016\n\006number\030\002 \002(\003\022\016\n\006status\030\003 " +
- "\002(\005\022\r\n\005value\030\004 \001(\014\"u\n\014LinkProperty\022\017\n\007sr" +
- "cSwId\030\001 \002(\014\022\021\n\tsrcPortId\030\002 \002(\014\022\017\n\007dstSwI" +
- "d\030\003 \002(\014\022\021\n\tdstPortId\030\004 \002(\014\022\016\n\006status\030\005 \002" +
- "(\005\022\r\n\005value\030\006 \001(\014B&\n\027net.onrc.onos.datas" +
- "toreB\013ProtoBuffer"
- };
- com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
- new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
- public com.google.protobuf.ExtensionRegistry assignDescriptors(
- com.google.protobuf.Descriptors.FileDescriptor root) {
- descriptor = root;
- internal_static_ProtoBuffer_SwitchProperty_descriptor =
- getDescriptor().getMessageTypes().get(0);
- internal_static_ProtoBuffer_SwitchProperty_fieldAccessorTable = new
- com.google.protobuf.GeneratedMessage.FieldAccessorTable(
- internal_static_ProtoBuffer_SwitchProperty_descriptor,
- new java.lang.String[] { "Dpid", "Status", "Value", });
- internal_static_ProtoBuffer_PortProperty_descriptor =
- getDescriptor().getMessageTypes().get(1);
- internal_static_ProtoBuffer_PortProperty_fieldAccessorTable = new
- com.google.protobuf.GeneratedMessage.FieldAccessorTable(
- internal_static_ProtoBuffer_PortProperty_descriptor,
- new java.lang.String[] { "Dpid", "Number", "Status", "Value", });
- internal_static_ProtoBuffer_LinkProperty_descriptor =
- getDescriptor().getMessageTypes().get(2);
- internal_static_ProtoBuffer_LinkProperty_fieldAccessorTable = new
- com.google.protobuf.GeneratedMessage.FieldAccessorTable(
- internal_static_ProtoBuffer_LinkProperty_descriptor,
- new java.lang.String[] { "SrcSwId", "SrcPortId", "DstSwId", "DstPortId", "Status", "Value", });
- return null;
- }
- };
- com.google.protobuf.Descriptors.FileDescriptor
- .internalBuildGeneratedFileFrom(descriptorData,
- new com.google.protobuf.Descriptors.FileDescriptor[] {
- }, assigner);
- }
-
- // @@protoc_insertion_point(outer_class_scope)
+ // @@protoc_insertion_point(outer_class_scope)
}
diff --git a/src/main/java/net/onrc/onos/core/datastore/RejectRulesException.java b/src/main/java/net/onrc/onos/core/datastore/RejectRulesException.java
index 351d1a1..4ce1610 100644
--- a/src/main/java/net/onrc/onos/core/datastore/RejectRulesException.java
+++ b/src/main/java/net/onrc/onos/core/datastore/RejectRulesException.java
@@ -4,6 +4,7 @@
// Not sure if we really need this base class.
// Just copied hierarchy from RAMCloud.
//
+
/**
* Base exception class for conditional write, etc. failure.
*/
diff --git a/src/main/java/net/onrc/onos/core/datastore/WrongVersionException.java b/src/main/java/net/onrc/onos/core/datastore/WrongVersionException.java
index 568f5e1..4fd0529 100644
--- a/src/main/java/net/onrc/onos/core/datastore/WrongVersionException.java
+++ b/src/main/java/net/onrc/onos/core/datastore/WrongVersionException.java
@@ -13,7 +13,7 @@
}
public WrongVersionException(final IKVTableID tableID, final byte[] key,
- final long expectedVersion, final Throwable cause) {
+ final long expectedVersion, final Throwable cause) {
// It will be best if {@code cause} has actual version encountered, but
// doesn't currently.
super(ByteArrayUtil.toHexStringBuffer(key, ":") + " on table:"
@@ -22,7 +22,7 @@
}
public WrongVersionException(final IKVTableID tableID, final byte[] key,
- final long expectedVersion, final long encounteredVersion) {
+ final long expectedVersion, final long encounteredVersion) {
super(ByteArrayUtil.toHexStringBuffer(key, ":") + " on table:"
+ tableID + " was expected to be version:" + expectedVersion
+ " but found:" + encounteredVersion);
diff --git a/src/main/java/net/onrc/onos/core/datastore/hazelcast/HZClient.java b/src/main/java/net/onrc/onos/core/datastore/hazelcast/HZClient.java
index d5107da..cbe10be 100644
--- a/src/main/java/net/onrc/onos/core/datastore/hazelcast/HZClient.java
+++ b/src/main/java/net/onrc/onos/core/datastore/hazelcast/HZClient.java
@@ -62,7 +62,7 @@
baseHzConfig = new FileSystemXmlConfig(hazelcastConfigFileName);
} catch (FileNotFoundException e) {
log.error("Error opening Hazelcast XML configuration. File not found: " + hazelcastConfigFileName, e);
- throw new Error("Cannot find Hazelcast configuration: " + hazelcastConfigFileName , e);
+ throw new Error("Cannot find Hazelcast configuration: " + hazelcastConfigFileName, e);
}
// use xml config if present, if not use System.property
@@ -118,6 +118,7 @@
/**
* Register serializer for VersionedValue class used to imitate value version.
+ *
* @param config
*/
private static void registerSerializer(final SerializationConfig config) {
@@ -178,7 +179,7 @@
@Override
public long update(final IKVTableID tableId, final byte[] key, final byte[] value,
- final long version) throws ObjectDoesntExistException,
+ final long version) throws ObjectDoesntExistException,
WrongVersionException {
IKVTable table = (IKVTable) tableId;
return table.update(key, value, version);
@@ -212,13 +213,13 @@
@Override
public IMultiEntryOperation createOp(final IKVTableID tableId, final byte[] key,
- final byte[] value) {
+ final byte[] value) {
return new HZMultiEntryOperation((HZTable) tableId, key, value, HZClient.VERSION_NONEXISTENT, OPERATION.CREATE);
}
@Override
public IMultiEntryOperation forceCreateOp(final IKVTableID tableId, final byte[] key,
- final byte[] value) {
+ final byte[] value) {
return new HZMultiEntryOperation((HZTable) tableId, key, value, HZClient.VERSION_NONEXISTENT, OPERATION.FORCE_CREATE);
}
@@ -229,13 +230,13 @@
@Override
public IMultiEntryOperation updateOp(final IKVTableID tableId, final byte[] key,
- final byte[] value, final long version) {
+ final byte[] value, final long version) {
return new HZMultiEntryOperation((HZTable) tableId, key, value, version, OPERATION.UPDATE);
}
@Override
public IMultiEntryOperation deleteOp(final IKVTableID tableId, final byte[] key,
- final byte[] value, final long version) {
+ final byte[] value, final long version) {
return new HZMultiEntryOperation((HZTable) tableId, key, value, version, OPERATION.DELETE);
}
@@ -250,24 +251,24 @@
for (IMultiEntryOperation op : ops) {
HZMultiEntryOperation mop = (HZMultiEntryOperation) op;
switch (mop.getOperation()) {
- case DELETE:
- try {
- final long version = delete(mop.getTableId(), mop.getKey(), mop.getVersion());
+ case DELETE:
+ try {
+ final long version = delete(mop.getTableId(), mop.getKey(), mop.getVersion());
+ mop.setVersion(version);
+ mop.setStatus(STATUS.SUCCESS);
+ } catch (ObjectDoesntExistException | WrongVersionException e) {
+ log.error(mop + " failed.", e);
+ mop.setStatus(STATUS.FAILED);
+ failExists = true;
+ }
+ break;
+ case FORCE_DELETE:
+ final long version = forceDelete(mop.getTableId(), mop.getKey());
mop.setVersion(version);
mop.setStatus(STATUS.SUCCESS);
- } catch (ObjectDoesntExistException | WrongVersionException e) {
- log.error(mop + " failed.", e);
- mop.setStatus(STATUS.FAILED);
- failExists = true;
- }
- break;
- case FORCE_DELETE:
- final long version = forceDelete(mop.getTableId(), mop.getKey());
- mop.setVersion(version);
- mop.setStatus(STATUS.SUCCESS);
- break;
- default:
- throw new UnsupportedOperationException(mop.toString());
+ break;
+ default:
+ throw new UnsupportedOperationException(mop.toString());
}
}
return failExists;
@@ -280,37 +281,36 @@
for (IMultiEntryOperation op : ops) {
IModifiableMultiEntryOperation mop = (IModifiableMultiEntryOperation) op;
switch (mop.getOperation()) {
- case CREATE:
- try {
- long version = create(mop.getTableId(), mop.getKey(), mop.getValue());
+ case CREATE:
+ try {
+ long version = create(mop.getTableId(), mop.getKey(), mop.getValue());
+ mop.setVersion(version);
+ mop.setStatus(STATUS.SUCCESS);
+ } catch (ObjectExistsException e) {
+ log.error(mop + " failed.", e);
+ mop.setStatus(STATUS.FAILED);
+ failExists = true;
+ }
+ break;
+ case FORCE_CREATE: {
+ final long version = forceCreate(mop.getTableId(), mop.getKey(), mop.getValue());
mop.setVersion(version);
mop.setStatus(STATUS.SUCCESS);
- } catch (ObjectExistsException e) {
- log.error(mop + " failed.", e);
- mop.setStatus(STATUS.FAILED);
- failExists = true;
+ break;
}
- break;
- case FORCE_CREATE:
- {
- final long version = forceCreate(mop.getTableId(), mop.getKey(), mop.getValue());
- mop.setVersion(version);
- mop.setStatus(STATUS.SUCCESS);
- break;
- }
- case UPDATE:
- try {
- long version = update(mop.getTableId(), mop.getKey(), mop.getValue(), mop.getVersion());
- mop.setVersion(version);
- mop.setStatus(STATUS.SUCCESS);
- } catch (ObjectDoesntExistException | WrongVersionException e) {
- log.error(mop + " failed.", e);
- mop.setStatus(STATUS.FAILED);
- failExists = true;
- }
- break;
- default:
- throw new UnsupportedOperationException(mop.toString());
+ case UPDATE:
+ try {
+ long version = update(mop.getTableId(), mop.getKey(), mop.getValue(), mop.getVersion());
+ mop.setVersion(version);
+ mop.setStatus(STATUS.SUCCESS);
+ } catch (ObjectDoesntExistException | WrongVersionException e) {
+ log.error(mop + " failed.", e);
+ mop.setStatus(STATUS.FAILED);
+ failExists = true;
+ }
+ break;
+ default:
+ throw new UnsupportedOperationException(mop.toString());
}
}
return failExists;
diff --git a/src/main/java/net/onrc/onos/core/datastore/hazelcast/HZMultiEntryOperation.java b/src/main/java/net/onrc/onos/core/datastore/hazelcast/HZMultiEntryOperation.java
index 105fc16..88649e7 100644
--- a/src/main/java/net/onrc/onos/core/datastore/hazelcast/HZMultiEntryOperation.java
+++ b/src/main/java/net/onrc/onos/core/datastore/hazelcast/HZMultiEntryOperation.java
@@ -28,6 +28,7 @@
/**
* Constructor for Read/ForceDelete Operation.
+ *
* @param table
* @param key
* @param operation
@@ -44,6 +45,7 @@
/**
* Constructor for Other Operations.
+ *
* @param table
* @param key
* @param value
@@ -108,6 +110,7 @@
/**
* Evaluate Future object and set Status and Value+Version.
+ *
* @return the value read or null on failure.
*/
private VersionedValue get() {
diff --git a/src/main/java/net/onrc/onos/core/datastore/hazelcast/HZTable.java b/src/main/java/net/onrc/onos/core/datastore/hazelcast/HZTable.java
index f071ecc..6cba576 100644
--- a/src/main/java/net/onrc/onos/core/datastore/hazelcast/HZTable.java
+++ b/src/main/java/net/onrc/onos/core/datastore/hazelcast/HZTable.java
@@ -26,10 +26,11 @@
private static final Logger log = LoggerFactory.getLogger(HZTable.class);
// not sure how strict this should be managed
- private static final AtomicLong initialVersion = new AtomicLong(HZClient.VERSION_NONEXISTENT);
+ private static final AtomicLong initialVersion = new AtomicLong(HZClient.VERSION_NONEXISTENT);
/**
* generate a new initial version for an entry.
+ *
* @return initial value
*/
protected static long getInitialVersion() {
@@ -43,6 +44,7 @@
/**
* increment version, avoiding VERSION_NONEXISTENT.
+ *
* @param version
* @return
*/
@@ -185,7 +187,6 @@
}
-
private final String mapName;
private final IMap<byte[], VersionedValue> map;
diff --git a/src/main/java/net/onrc/onos/core/datastore/hazelcast/VersionedValueSerializableFactory.java b/src/main/java/net/onrc/onos/core/datastore/hazelcast/VersionedValueSerializableFactory.java
index 7e77be7..75bd568 100644
--- a/src/main/java/net/onrc/onos/core/datastore/hazelcast/VersionedValueSerializableFactory.java
+++ b/src/main/java/net/onrc/onos/core/datastore/hazelcast/VersionedValueSerializableFactory.java
@@ -13,11 +13,11 @@
@Override
public IdentifiedDataSerializable create(final int typeId) {
switch (typeId) {
- case VERSIONED_VALUE_ID:
- return new HZTable.VersionedValue();
+ case VERSIONED_VALUE_ID:
+ return new HZTable.VersionedValue();
- default:
- return null;
+ default:
+ return null;
}
}
diff --git a/src/main/java/net/onrc/onos/core/datastore/internal/IModifiableMultiEntryOperation.java b/src/main/java/net/onrc/onos/core/datastore/internal/IModifiableMultiEntryOperation.java
index a607add..631aaea 100644
--- a/src/main/java/net/onrc/onos/core/datastore/internal/IModifiableMultiEntryOperation.java
+++ b/src/main/java/net/onrc/onos/core/datastore/internal/IModifiableMultiEntryOperation.java
@@ -4,7 +4,7 @@
/**
* Interface for backend to realize IMultiEntryOperation.
- *
+ * <p/>
* Backend implementation must use these interfaces to update IMultiEntryOperation
* in order to support KVObject.
*/
@@ -12,8 +12,9 @@
/**
* Set value and version.
- *
+ * <p/>
* Expected to be called on multiRead implementations.
+ *
* @param value
* @param version
*/
@@ -21,23 +22,26 @@
/**
* Update version of the value.
- *
+ * <p/>
* Expected to be called on multiWrite, multiRead implementations.
+ *
* @param version
*/
public void setVersion(long version);
/**
* Update status.
- *
+ * <p/>
* Backend implementation is expected to update to SUCCESS or FAILED after
* datastore operation.
+ *
* @param status
*/
public void setStatus(STATUS status);
/**
* Return actual IModifiableMultiEntryOperation if is a wrapper, this otherwise.
+ *
* @return actual IModifiableMultiEntryOperation directly interact with data store
*/
public IModifiableMultiEntryOperation getActualOperation();
diff --git a/src/main/java/net/onrc/onos/core/datastore/ramcloud/RCClient.java b/src/main/java/net/onrc/onos/core/datastore/ramcloud/RCClient.java
index 7ff7e7f..41fda9e 100644
--- a/src/main/java/net/onrc/onos/core/datastore/ramcloud/RCClient.java
+++ b/src/main/java/net/onrc/onos/core/datastore/ramcloud/RCClient.java
@@ -61,16 +61,16 @@
/**
* @return JRamCloud instance intended to be used only within the
- * SameThread.
+ * SameThread.
* @note Do not store the returned instance in a member variable, etc. which
- * may be accessed later by another thread.
+ * may be accessed later by another thread.
*/
static JRamCloud getJRamCloudClient() {
return tlsRCClient.get();
}
// Currently RCClient is state-less
- private static final RCClient theInstance= new RCClient();
+ private static final RCClient theInstance = new RCClient();
public static RCClient getClient() {
return theInstance;
@@ -172,13 +172,13 @@
}
@Override
- public IMultiEntryOperation updateOp(IKVTableID tableId, byte[] key, byte[] value,long version) {
+ public IMultiEntryOperation updateOp(IKVTableID tableId, byte[] key, byte[] value, long version) {
return RCMultiEntryOperation.update(tableId, key, value, version);
}
@Override
public long update(IKVTableID tableId, byte[] key, byte[] value,
- long version) throws ObjectDoesntExistException,
+ long version) throws ObjectDoesntExistException,
WrongVersionException {
RCTableID rcTableId = (RCTableID) tableId;
@@ -222,7 +222,7 @@
}
@Override
- public IMultiEntryOperation deleteOp(IKVTableID tableId, byte[] key, byte[] value,long version) {
+ public IMultiEntryOperation deleteOp(IKVTableID tableId, byte[] key, byte[] value, long version) {
return RCMultiEntryOperation.delete(tableId, key, value, version);
}
@@ -323,9 +323,9 @@
@Override
public boolean multiRead(final Collection<IMultiEntryOperation> ops) {
- if ( ops.size() <= MAX_MULTI_READS && ops instanceof ArrayList) {
- @SuppressWarnings({ "unchecked", "rawtypes" })
- final ArrayList<RCMultiEntryOperation> arrays = (ArrayList)ops;
+ if (ops.size() <= MAX_MULTI_READS && ops instanceof ArrayList) {
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ final ArrayList<RCMultiEntryOperation> arrays = (ArrayList) ops;
return multiReadInternal(arrays);
}
@@ -356,9 +356,9 @@
@Override
public boolean multiWrite(final List<IMultiEntryOperation> ops) {
- if ( ops.size() <= MAX_MULTI_WRITES && ops instanceof ArrayList) {
- @SuppressWarnings({ "unchecked", "rawtypes" })
- final ArrayList<RCMultiEntryOperation> arrays = (ArrayList)ops;
+ if (ops.size() <= MAX_MULTI_WRITES && ops instanceof ArrayList) {
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ final ArrayList<RCMultiEntryOperation> arrays = (ArrayList) ops;
return multiWriteInternal(arrays);
}
@@ -395,45 +395,45 @@
JRamCloud rcClient = getJRamCloudClient();
for (IMultiEntryOperation iop : ops) {
- RCMultiEntryOperation op = (RCMultiEntryOperation)iop;
+ RCMultiEntryOperation op = (RCMultiEntryOperation) iop;
switch (op.getOperation()) {
- case DELETE:
- RejectRules rules = new RejectRules();
- rules.rejectIfDoesntExists();
- rules.rejectIfNeVersion(op.getVersion());
+ case DELETE:
+ RejectRules rules = new RejectRules();
+ rules.rejectIfDoesntExists();
+ rules.rejectIfNeVersion(op.getVersion());
- try {
- final long removedVersion = rcClient.remove(op.tableId.getTableID(), op.entry.getKey(), rules);
- op.entry.setVersion(removedVersion);
- op.status = STATUS.SUCCESS;
- } catch (JRamCloud.ObjectDoesntExistException|JRamCloud.WrongVersionException e) {
- log.error("Failed to remove key:" + ByteArrayUtil.toHexStringBuffer(op.entry.getKey(), "") + " from tableID:" + op.tableId, e );
+ try {
+ final long removedVersion = rcClient.remove(op.tableId.getTableID(), op.entry.getKey(), rules);
+ op.entry.setVersion(removedVersion);
+ op.status = STATUS.SUCCESS;
+ } catch (JRamCloud.ObjectDoesntExistException | JRamCloud.WrongVersionException e) {
+ log.error("Failed to remove key:" + ByteArrayUtil.toHexStringBuffer(op.entry.getKey(), "") + " from tableID:" + op.tableId, e);
+ failExists = true;
+ op.status = STATUS.FAILED;
+ } catch (JRamCloud.RejectRulesException e) {
+ log.error("Failed to remove key:" + ByteArrayUtil.toHexStringBuffer(op.entry.getKey(), "") + " from tableID:" + op.tableId, e);
+ failExists = true;
+ op.status = STATUS.FAILED;
+ }
+ break;
+
+ case FORCE_DELETE:
+ final long removedVersion = rcClient.remove(op.tableId.getTableID(), op.entry.getKey());
+ if (removedVersion != VERSION_NONEXISTENT) {
+ op.entry.setVersion(removedVersion);
+ op.status = STATUS.SUCCESS;
+ } else {
+ log.error("Failed to remove key:{} from tableID:{}", ByteArrayUtil.toHexStringBuffer(op.entry.getKey(), ""), op.tableId);
+ failExists = true;
+ op.status = STATUS.FAILED;
+ }
+ break;
+
+ default:
+ log.error("Invalid operation {} specified on multiDelete", op.getOperation());
failExists = true;
op.status = STATUS.FAILED;
- } catch (JRamCloud.RejectRulesException e) {
- log.error("Failed to remove key:" + ByteArrayUtil.toHexStringBuffer(op.entry.getKey(), "") + " from tableID:" + op.tableId, e );
- failExists = true;
- op.status = STATUS.FAILED;
- }
- break;
-
- case FORCE_DELETE:
- final long removedVersion = rcClient.remove(op.tableId.getTableID(), op.entry.getKey());
- if (removedVersion != VERSION_NONEXISTENT) {
- op.entry.setVersion(removedVersion);
- op.status = STATUS.SUCCESS;
- } else {
- log.error("Failed to remove key:{} from tableID:{}", ByteArrayUtil.toHexStringBuffer(op.entry.getKey(), ""), op.tableId );
- failExists = true;
- op.status = STATUS.FAILED;
- }
- break;
-
- default:
- log.error("Invalid operation {} specified on multiDelete", op.getOperation() );
- failExists = true;
- op.status = STATUS.FAILED;
- break;
+ break;
}
}
return failExists;
@@ -450,7 +450,7 @@
// setup multi-read operation objects
for (int i = 0; i < reqs; ++i) {
IMultiEntryOperation op = ops.get(i);
- multiReadObjects.setObject(i, ((RCTableID)op.getTableId()).getTableID(), op.getKey());
+ multiReadObjects.setObject(i, ((RCTableID) op.getTableId()).getTableID(), op.getKey());
}
// execute
@@ -496,24 +496,24 @@
RejectRules rules = new RejectRules();
switch (op.getOperation()) {
- case CREATE:
- rules.rejectIfExists();
- break;
- case FORCE_CREATE:
- // no reject rule
- break;
- case UPDATE:
- rules.rejectIfDoesntExists();
- rules.rejectIfNeVersion(op.getVersion());
- break;
+ case CREATE:
+ rules.rejectIfExists();
+ break;
+ case FORCE_CREATE:
+ // no reject rule
+ break;
+ case UPDATE:
+ rules.rejectIfDoesntExists();
+ rules.rejectIfNeVersion(op.getVersion());
+ break;
- default:
- log.error("Invalid operation {} specified on multiWriteInternal", op.getOperation() );
- failExists = true;
- op.setStatus(STATUS.FAILED);
- return failExists;
+ default:
+ log.error("Invalid operation {} specified on multiWriteInternal", op.getOperation());
+ failExists = true;
+ op.setStatus(STATUS.FAILED);
+ return failExists;
}
- multiWriteObjects.setObject(i, ((RCTableID)op.getTableId()).getTableID(), op.getKey(), op.getValue(), rules);
+ multiWriteObjects.setObject(i, ((RCTableID) op.getTableId()).getTableID(), op.getKey(), op.getValue(), rules);
}
MultiWriteRspObject[] results = rcClient.multiWrite(multiWriteObjects.tableId, multiWriteObjects.key, multiWriteObjects.keyLength, multiWriteObjects.value, multiWriteObjects.valueLength, ops.size(), multiWriteObjects.rules);
diff --git a/src/main/java/net/onrc/onos/core/datastore/ramcloud/RCMultiEntryOperation.java b/src/main/java/net/onrc/onos/core/datastore/ramcloud/RCMultiEntryOperation.java
index 9b8c8b6..9893838 100644
--- a/src/main/java/net/onrc/onos/core/datastore/ramcloud/RCMultiEntryOperation.java
+++ b/src/main/java/net/onrc/onos/core/datastore/ramcloud/RCMultiEntryOperation.java
@@ -73,33 +73,33 @@
}
public static IMultiEntryOperation create(final IKVTableID tableId, final byte[] key, final byte[] value) {
- return new RCMultiEntryOperation(tableId, new Entry(key,value, RCClient.VERSION_NONEXISTENT), OPERATION.CREATE);
+ return new RCMultiEntryOperation(tableId, new Entry(key, value, RCClient.VERSION_NONEXISTENT), OPERATION.CREATE);
}
public static IMultiEntryOperation forceCreate(final IKVTableID tableId, final byte[] key, final byte[] value) {
- return new RCMultiEntryOperation(tableId, new Entry(key,value, RCClient.VERSION_NONEXISTENT), OPERATION.FORCE_CREATE);
+ return new RCMultiEntryOperation(tableId, new Entry(key, value, RCClient.VERSION_NONEXISTENT), OPERATION.FORCE_CREATE);
}
/**
* Constructor for READ operation.
*
* @param tableId table to read from
- * @param key key of an Entry to read
+ * @param key key of an Entry to read
*/
public static IMultiEntryOperation read(final IKVTableID tableId, final byte[] key) {
return new RCMultiEntryOperation(tableId, new Entry(key), OPERATION.READ);
}
public static IMultiEntryOperation update(final IKVTableID tableId, final byte[] key, final byte[] value, final long version) {
- return new RCMultiEntryOperation(tableId, new Entry(key,value, version), OPERATION.UPDATE);
+ return new RCMultiEntryOperation(tableId, new Entry(key, value, version), OPERATION.UPDATE);
}
public static IMultiEntryOperation delete(final IKVTableID tableId, final byte[] key, final byte[] value, final long version) {
- return new RCMultiEntryOperation(tableId, new Entry(key,value, version), OPERATION.DELETE);
+ return new RCMultiEntryOperation(tableId, new Entry(key, value, version), OPERATION.DELETE);
}
public static IMultiEntryOperation forceDelete(final IKVTableID tableId, final byte[] key) {
- return new RCMultiEntryOperation(tableId, new Entry(key), OPERATION.FORCE_DELETE);
+ return new RCMultiEntryOperation(tableId, new Entry(key), OPERATION.FORCE_DELETE);
}
@Override
diff --git a/src/main/java/net/onrc/onos/core/datastore/ramcloud/RCTable.java b/src/main/java/net/onrc/onos/core/datastore/ramcloud/RCTable.java
index 098215e..e5a6675 100644
--- a/src/main/java/net/onrc/onos/core/datastore/ramcloud/RCTable.java
+++ b/src/main/java/net/onrc/onos/core/datastore/ramcloud/RCTable.java
@@ -58,8 +58,8 @@
private final RCTableID rcTableId;
/**
- *
* {@code rcTableName} must be unique cluster wide.
+ *
* @param rcTableName RAMCloud table name
*/
RCTable(final String rcTableName) {
diff --git a/src/main/java/net/onrc/onos/core/datastore/ramcloud/RCTableID.java b/src/main/java/net/onrc/onos/core/datastore/ramcloud/RCTableID.java
index f69addc..9882ce3 100644
--- a/src/main/java/net/onrc/onos/core/datastore/ramcloud/RCTableID.java
+++ b/src/main/java/net/onrc/onos/core/datastore/ramcloud/RCTableID.java
@@ -21,7 +21,7 @@
// following is RAMCloud specific
public long getTableID() {
- if ( tableID != 0) {
+ if (tableID != 0) {
return tableID;
}
tableID = RCClient.getJRamCloudClient().createTable(tableName);
@@ -34,7 +34,7 @@
@Override
public String toString() {
- return "["+tableName + "]@" + getTableID();
+ return "[" + tableName + "]@" + getTableID();
}
@Override
diff --git a/src/main/java/net/onrc/onos/core/datastore/topology/KVDevice.java b/src/main/java/net/onrc/onos/core/datastore/topology/KVDevice.java
index 14268b5..8b1d8af 100644
--- a/src/main/java/net/onrc/onos/core/datastore/topology/KVDevice.java
+++ b/src/main/java/net/onrc/onos/core/datastore/topology/KVDevice.java
@@ -25,7 +25,7 @@
/**
* Device object.
- *
+ * <p/>
* TODO switch to ProtoBuf, etc.
*/
public class KVDevice extends KVObject {
@@ -55,7 +55,7 @@
private final byte[] mac;
private TreeSet<byte[]> portIds;
private transient boolean isPortIdsModified;
-
+
// Assume there is only one ip on a device now.
private int ip;
private long lastSeenTime;
@@ -86,9 +86,9 @@
/**
* Get an instance from Key.
*
- * @note You need to call `read()` to get the DB content.
* @param key
* @return
+ * @note You need to call `read()` to get the DB content.
*/
public static KVDevice createFromKey(final byte[] key) {
return new KVDevice(getMacFromKey(key));
@@ -150,7 +150,6 @@
}
/**
- *
* @return Unmodifiable Set view of all the PortIds;
*/
public Set<byte[]> getAllPortIds() {
@@ -203,20 +202,20 @@
return "[" + this.getClass().getSimpleName()
+ " " + ByteArrayUtil.toHexStringBuffer(mac, ":") + "]";
}
-
- public int getIp() {
- return ip;
- }
- public void setIp(int ip) {
- this.ip = ip;
- }
+ public int getIp() {
+ return ip;
+ }
- public long getLastSeenTime() {
- return lastSeenTime;
- }
+ public void setIp(int ip) {
+ this.ip = ip;
+ }
- public void setLastSeenTime(long lastSeenTime) {
- this.lastSeenTime = lastSeenTime;
- }
+ public long getLastSeenTime() {
+ return lastSeenTime;
+ }
+
+ public void setLastSeenTime(long lastSeenTime) {
+ this.lastSeenTime = lastSeenTime;
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/datastore/topology/KVLink.java b/src/main/java/net/onrc/onos/core/datastore/topology/KVLink.java
index 23001ff..64eabc1 100644
--- a/src/main/java/net/onrc/onos/core/datastore/topology/KVLink.java
+++ b/src/main/java/net/onrc/onos/core/datastore/topology/KVLink.java
@@ -76,7 +76,7 @@
private STATUS status;
public static byte[] getLinkID(final Long src_dpid, final Long src_port_no,
- final Long dst_dpid, final Long dst_port_no) {
+ final Long dst_dpid, final Long dst_port_no) {
return LinkEvent.getLinkID(src_dpid, src_port_no, dst_dpid,
dst_port_no).array();
}
@@ -103,7 +103,7 @@
}
public KVLink(final Long src_dpid, final Long src_port_no,
- final Long dst_dpid, final Long dst_port_no) {
+ final Long dst_dpid, final Long dst_port_no) {
super(DataStoreClient.getClient().getTable(GLOBAL_LINK_TABLE_NAME), getLinkID(src_dpid,
src_port_no, dst_dpid, dst_port_no));
@@ -115,9 +115,9 @@
/**
* Get an instance from Key.
*
- * @note You need to call `read()` to get the DB content.
* @param key
* @return KVLink instance
+ * @note You need to call `read()` to get the DB content.
*/
public static KVLink createFromKey(final byte[] key) {
long[] linkTuple = getLinkTupleFromKey(key);
diff --git a/src/main/java/net/onrc/onos/core/datastore/topology/KVPort.java b/src/main/java/net/onrc/onos/core/datastore/topology/KVPort.java
index a5b41e6..db4e1ff 100644
--- a/src/main/java/net/onrc/onos/core/datastore/topology/KVPort.java
+++ b/src/main/java/net/onrc/onos/core/datastore/topology/KVPort.java
@@ -21,10 +21,10 @@
/**
* Port object in data store.
- *
+ * <p/>
* Note: This class will not maintain invariants.
- * e.g., It will NOT automatically remove Links or Devices on Port,
- * when deleting a Port.
+ * e.g., It will NOT automatically remove Links or Devices on Port,
+ * when deleting a Port.
*/
public class KVPort extends KVObject {
private static final Logger log = LoggerFactory.getLogger(KVPort.class);
@@ -105,9 +105,9 @@
/**
* Get an instance from Key.
*
- * @note You need to call `read()` to get the DB content.
* @param key
* @return KVPort instance
+ * @note You need to call `read()` to get the DB content.
*/
public static KVPort createFromKey(final byte[] key) {
long[] pair = getPortPairFromKey(key);
diff --git a/src/main/java/net/onrc/onos/core/datastore/topology/KVSwitch.java b/src/main/java/net/onrc/onos/core/datastore/topology/KVSwitch.java
index 474e99a..9f865e0 100644
--- a/src/main/java/net/onrc/onos/core/datastore/topology/KVSwitch.java
+++ b/src/main/java/net/onrc/onos/core/datastore/topology/KVSwitch.java
@@ -20,10 +20,10 @@
/**
* Switch object in data store.
- *
+ * <p/>
* Note: This class will not maintain invariants.
- * e.g., It will NOT automatically remove Ports on Switch,
- * when deleting a Switch.
+ * e.g., It will NOT automatically remove Ports on Switch,
+ * when deleting a Switch.
*/
public class KVSwitch extends KVObject {
private static final Logger log = LoggerFactory.getLogger(KVSwitch.class);
@@ -80,9 +80,9 @@
/**
* Get an instance from Key.
*
- * @note You need to call `read()` to get the DB content.
* @param key
* @return KVSwitch instance
+ * @note You need to call `read()` to get the DB content.
*/
public static KVSwitch createFromKey(final byte[] key) {
return new KVSwitch(getDpidFromKey(key));
diff --git a/src/main/java/net/onrc/onos/core/datastore/utils/ByteArrayComparator.java b/src/main/java/net/onrc/onos/core/datastore/utils/ByteArrayComparator.java
index f937e50..0c0cf18 100644
--- a/src/main/java/net/onrc/onos/core/datastore/utils/ByteArrayComparator.java
+++ b/src/main/java/net/onrc/onos/core/datastore/utils/ByteArrayComparator.java
@@ -5,7 +5,7 @@
/**
* Comparator which will compares the content of byte[].
- *
+ * <p/>
* Expected to be used with TreeMap, etc. when you want to use byte[] as a key.
*/
public final class ByteArrayComparator implements Comparator<byte[]> {
diff --git a/src/main/java/net/onrc/onos/core/datastore/utils/ByteArrayUtil.java b/src/main/java/net/onrc/onos/core/datastore/utils/ByteArrayUtil.java
index 14cd419..32abb59 100644
--- a/src/main/java/net/onrc/onos/core/datastore/utils/ByteArrayUtil.java
+++ b/src/main/java/net/onrc/onos/core/datastore/utils/ByteArrayUtil.java
@@ -5,7 +5,8 @@
public class ByteArrayUtil {
// Suppresses default constructor, ensuring non-instantiability.
- private ByteArrayUtil() {}
+ private ByteArrayUtil() {
+ }
/**
* Returns a StringBuffer with each byte in {@code bytes}
@@ -13,11 +14,11 @@
* separated by {@code sep}.
*
* @param bytes byte array to convert
- * @param sep separator between each bytes
+ * @param sep separator between each bytes
* @return {@code bytes} converted to a StringBuffer
*/
public static StringBuffer toHexStringBuffer(final byte[] bytes,
- final String sep) {
+ final String sep) {
return toHexStringBuffer(bytes, sep, new StringBuffer());
}
@@ -27,12 +28,12 @@
* separated by {@code sep}.
*
* @param bytes byte array to convert
- * @param sep separator between each bytes
- * @param buf StringBuffer to append to.
+ * @param sep separator between each bytes
+ * @param buf StringBuffer to append to.
* @return {@code buf}
*/
public static StringBuffer toHexStringBuffer(final byte[] bytes,
- final String sep, final StringBuffer buf) {
+ final String sep, final StringBuffer buf) {
if (bytes == null) {
return buf;
}
diff --git a/src/main/java/net/onrc/onos/core/datastore/utils/KVObject.java b/src/main/java/net/onrc/onos/core/datastore/utils/KVObject.java
index ce4f617..937129a 100644
--- a/src/main/java/net/onrc/onos/core/datastore/utils/KVObject.java
+++ b/src/main/java/net/onrc/onos/core/datastore/utils/KVObject.java
@@ -27,7 +27,6 @@
/**
* Class to represent an Object represented as a single K-V pair Value blob.
- *
*/
public class KVObject {
private static final Logger log = LoggerFactory.getLogger(KVObject.class);
@@ -55,7 +54,7 @@
private long version;
/**
- * Map to store user-defined properties
+ * Map to store user-defined properties
*/
private Map<Object, Object> propertyMap;
@@ -105,8 +104,8 @@
/**
* Return user-defined object properties.
*
- * @note Will not trigger deserialization
* @return Will return null, if never been set, or was not deserialized
+ * @note Will not trigger deserialization
*/
protected Map<Object, Object> getPropertyMap() {
return this.propertyMap;
@@ -120,7 +119,7 @@
/**
* Serialize object.
- *
+ * <p/>
* sub-classes should override this method to customize serialization.
*
* @return serialized byte array
@@ -130,7 +129,7 @@
}
protected byte[] serializePropertyMap(final Kryo kryo,
- final Map<Object, Object> propMap) {
+ final Map<Object, Object> propMap) {
// value
@@ -144,7 +143,7 @@
/**
* Deserialize using value and version stored in data store.
*
- * @param bytes serialized bytes
+ * @param bytes serialized bytes
* @param version version of this {@code bytes}
* @return true if success
*/
@@ -155,7 +154,7 @@
/**
* Deserialize object.
- *
+ * <p/>
* sub-classes should override this method to customize deserialization.
*
* @param bytes serialized byte array
@@ -168,7 +167,8 @@
/**
* Deserialize and set {@link propertyMap}.
- * @param kryo serializer to use
+ *
+ * @param kryo serializer to use
* @param bytes Kryo serialized Map object
* @return true if success
*/
@@ -183,7 +183,7 @@
}
protected <T extends Map<?, ?>> T deserializePropertyMap(final Kryo kryo,
- final byte[] bytes, final Class<T> type) {
+ final byte[] bytes, final Class<T> type) {
if (bytes == null || bytes.length == 0) {
return null;
@@ -198,7 +198,7 @@
/**
* Create an Object in DataStore.
- *
+ * <p/>
* Fails if the Object with same key already exists.
*
* @throws ObjectExistsException
@@ -225,11 +225,10 @@
/**
* Read an Object from DataStore.
- *
+ * <p/>
* Fails if the Object with the key does not exist.
*
* @throws ObjectDoesntExistException
- *
*/
public void read() throws ObjectDoesntExistException {
IKVEntry e = table.read(key);
@@ -238,14 +237,14 @@
/**
* Update an existing Object in DataStore checking versions.
- *
+ * <p/>
* Fails if the Object with key does not exists, or conditional failure.
*
* @throws WrongVersionException
* @throws ObjectDoesntExistException
*/
public void update() throws ObjectDoesntExistException,
- WrongVersionException {
+ WrongVersionException {
if (this.propertyMap == null) {
replacePropertyMap(new HashMap<Object, Object>());
}
@@ -255,14 +254,14 @@
/**
* Remove an existing Object in DataStore.
- *
+ * <p/>
* Fails if the Object with key does not exists.
*
* @throws ObjectDoesntExistException
* @throws WrongVersionException
*/
public void delete() throws ObjectDoesntExistException,
- WrongVersionException {
+ WrongVersionException {
this.version = table.delete(key, this.version);
}
@@ -297,11 +296,10 @@
/**
* Multi-read RCObjects.
- *
+ * <p/>
* If the blob value was read successfully, RCObject will deserialize them.
*
- * @param objects
- * RCObjects to read
+ * @param objects RCObjects to read
* @return true if there exist a failed read.
*/
public static boolean multiRead(final List<? extends KVObject> objects) {
@@ -318,8 +316,8 @@
for (int i = 0; i < readOps.size(); ++i) {
KVObject obj = objects.get(i);
IMultiEntryOperation entry = readOps.get(i);
- if ( entry.hasSucceeded() ) {
- if ( !obj.deserialize(entry.getValue(), entry.getVersion()) ) {
+ if (entry.hasSucceeded()) {
+ if (!obj.deserialize(entry.getValue(), entry.getVersion())) {
//deserialize return true on success
failExists = true;
log.error("MultiRead error, failed to deserialize {}, {}", obj.getTable(), obj);
@@ -346,14 +344,14 @@
this.base = (IModifiableMultiEntryOperation) base;
this.obj = obj;
- // switch (base.getOperation()) {
- // case CREATE:
- // case FORCE_CREATE:
- // case UPDATE:
- // break;
- // default:
- // throw new UnsupportedOperationException("Unexpected OPERATION:"+base.getOperation());
- // }
+ // switch (base.getOperation()) {
+ // case CREATE:
+ // case FORCE_CREATE:
+ // case UPDATE:
+ // break;
+ // default:
+ // throw new UnsupportedOperationException("Unexpected OPERATION:"+base.getOperation());
+ // }
}
@Override
@@ -436,7 +434,7 @@
}
public abstract static class AbstractObjectIterator<E extends KVObject> implements
- Iterator<E> {
+ Iterator<E> {
protected Iterator<IKVEntry> enumerator;
@@ -450,13 +448,13 @@
}
// Implement something similar to below to realize Iterator
- // @Override
- // public E next() {
- // IKVTable.IKVEntry o = enumerator.next();
- // E obj = E.createFromKey(o.getKey());
- // obj.deserialize(o.getValue(), o.getVersion());
- // return obj;
- // }
+ // @Override
+ // public E next() {
+ // IKVTable.IKVEntry o = enumerator.next();
+ // E obj = E.createFromKey(o.getKey());
+ // obj.deserialize(o.getValue(), o.getVersion());
+ // return obj;
+ // }
@Deprecated
@Override
diff --git a/src/main/java/net/onrc/onos/core/devicemanager/IOnosDeviceListener.java b/src/main/java/net/onrc/onos/core/devicemanager/IOnosDeviceListener.java
index 69b340b..405340f 100644
--- a/src/main/java/net/onrc/onos/core/devicemanager/IOnosDeviceListener.java
+++ b/src/main/java/net/onrc/onos/core/devicemanager/IOnosDeviceListener.java
@@ -3,5 +3,6 @@
public interface IOnosDeviceListener {
public void onosDeviceAdded(OnosDevice device);
+
public void onosDeviceRemoved(OnosDevice device);
}
diff --git a/src/main/java/net/onrc/onos/core/devicemanager/IOnosDeviceService.java b/src/main/java/net/onrc/onos/core/devicemanager/IOnosDeviceService.java
index f343308..9eb6e31 100644
--- a/src/main/java/net/onrc/onos/core/devicemanager/IOnosDeviceService.java
+++ b/src/main/java/net/onrc/onos/core/devicemanager/IOnosDeviceService.java
@@ -5,20 +5,20 @@
/**
* {@link OnosDeviceManager} doesn't yet provide any API to fellow modules,
- * however making it export a dummy service means we can specify it as
+ * however making it export a dummy service means we can specify it as
* a dependency of Forwarding
- * @author jono
*
+ * @author jono
*/
public interface IOnosDeviceService extends IFloodlightService {
- public void addOnosDeviceListener(IOnosDeviceListener listener);
-
- public void deleteOnosDeviceListener(IOnosDeviceListener listener);
-
- public void deleteOnosDevice(OnosDevice dev);
+ public void addOnosDeviceListener(IOnosDeviceListener listener);
- public void deleteOnosDeviceByMac(MACAddress mac);
-
- public void addOnosDevice(Long mac, OnosDevice dev);
+ public void deleteOnosDeviceListener(IOnosDeviceListener listener);
+
+ public void deleteOnosDevice(OnosDevice dev);
+
+ public void deleteOnosDeviceByMac(MACAddress mac);
+
+ public void addOnosDevice(Long mac, OnosDevice dev);
}
diff --git a/src/main/java/net/onrc/onos/core/devicemanager/OnosDevice.java b/src/main/java/net/onrc/onos/core/devicemanager/OnosDevice.java
index 4ff17a3..adac787 100644
--- a/src/main/java/net/onrc/onos/core/devicemanager/OnosDevice.java
+++ b/src/main/java/net/onrc/onos/core/devicemanager/OnosDevice.java
@@ -1,19 +1,19 @@
/**
-l* Copyright 2011,2012, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ l* Copyright 2011,2012, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.devicemanager;
@@ -29,63 +29,63 @@
* with a particular VLAN tag, and a particular MAC address, along with any
* other packet characteristics we might want to consider as helpful for
* disambiguating devices.
- *
+ * <p/>
* Entities are the most basic element of devices; devices consist of one or
* more entities. Entities are immutable once created, except for the last
* seen timestamp.
- *
- * @author readams
*
+ * @author readams
*/
public class OnosDevice implements Serializable { //implements Comparable<OnosDevice> {
private static int ACTIVITY_TIMEOUT = 30000;
-
+
/**
* The MAC address associated with this entity
*/
private MACAddress macAddress;
-
+
/**
* The IP address associated with this entity, or null if no IP learned
* from the network observation associated with this entity
*/
private Integer ipv4Address;
-
+
/**
* The VLAN tag on this entity, or null if untagged
*/
private Short vlan;
-
+
/**
* The DPID of the switch for the ingress point for this entity,
* or null if not present
*/
private long switchDPID;
-
+
/**
* The port number of the switch for the ingress point for this entity,
* or null if not present
*/
private short switchPort;
-
+
/**
* The last time we observed this entity on the network
*/
private Date lastSeenTimestamp;
private Date activeSince;
-
+
private int hashCode = 0;
// ************
// Constructors
// ************
- protected OnosDevice() {}
-
+ protected OnosDevice() {
+ }
+
/**
* Create a new entity
- *
+ *
* @param macAddress
* @param vlan
* @param ipv4Address
@@ -93,9 +93,9 @@
* @param switchPort
* @param lastSeenTimestamp
*/
- public OnosDevice(MACAddress macAddress, Short vlan,
- Integer ipv4Address, Long switchDPID, short switchPort,
- Date lastSeenTimestamp) {
+ public OnosDevice(MACAddress macAddress, Short vlan,
+ Integer ipv4Address, Long switchDPID, short switchPort,
+ Date lastSeenTimestamp) {
this.macAddress = macAddress;
this.ipv4Address = ipv4Address;
this.vlan = vlan;
@@ -116,9 +116,9 @@
public Integer getIpv4Address() {
return ipv4Address;
}
-
+
public void setIpv4Address(Integer ipv4Address) {
- this.ipv4Address = ipv4Address;
+ this.ipv4Address = ipv4Address;
}
public Short getVlan() {
@@ -128,28 +128,28 @@
public Long getSwitchDPID() {
return switchDPID;
}
-
+
public void setSwitchDPID(long dpid) {
- this.switchDPID = dpid;
+ this.switchDPID = dpid;
}
public short getSwitchPort() {
return switchPort;
}
-
+
public void setSwitchPort(short port) {
- this.switchPort = port;
+ this.switchPort = port;
}
public Date getLastSeenTimestamp() {
return lastSeenTimestamp;
}
-
+
public void setLastSeenTimestamp(Date lastSeenTimestamp) {
if (activeSince == null ||
- (activeSince.getTime() + ACTIVITY_TIMEOUT) <
- lastSeenTimestamp.getTime())
+ (activeSince.getTime() + ACTIVITY_TIMEOUT) <
+ lastSeenTimestamp.getTime())
this.activeSince = lastSeenTimestamp;
this.lastSeenTimestamp = lastSeenTimestamp;
}
@@ -161,17 +161,17 @@
public void setActiveSince(Date activeSince) {
this.activeSince = activeSince;
}
-
+
@Override
public int hashCode() {
if (hashCode != 0) return hashCode;
final int prime = 31;
hashCode = 1;
hashCode = prime * hashCode
- + ((ipv4Address == null) ? 0 : ipv4Address.hashCode());
+ + ((ipv4Address == null) ? 0 : ipv4Address.hashCode());
hashCode = prime * hashCode + (int) (macAddress.toLong() ^ (macAddress.toLong() >>> 32));
- hashCode = prime * hashCode + (int)switchDPID;
- hashCode = prime * hashCode + (int)switchPort;
+ hashCode = prime * hashCode + (int) switchDPID;
+ hashCode = prime * hashCode + (int) switchPort;
hashCode = prime * hashCode + ((vlan == null) ? 0 : vlan.hashCode());
return hashCode;
}
@@ -185,26 +185,26 @@
if (hashCode() != other.hashCode()) return false;
if (ipv4Address == null) {
if (other.ipv4Address != null) return false;
- } else if (!ipv4Address.equals(other.ipv4Address)) return false;
+ } else if (!ipv4Address.equals(other.ipv4Address)) return false;
if (macAddress == null) {
if (other.macAddress != null) return false;
} else if (!macAddress.equals(other.macAddress)) return false;
- if(switchDPID != other.switchDPID) return false;
+ if (switchDPID != other.switchDPID) return false;
if (switchPort != other.switchPort) return false;
if (vlan == null) {
if (other.vlan != null) return false;
} else if (!vlan.equals(other.vlan)) return false;
return true;
}
-
+
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Entity [macAddress=");
builder.append(macAddress.toString());
builder.append(", ipv4Address=");
- builder.append(IPv4.fromIPv4Address(ipv4Address==null ?
- 0 : ipv4Address.intValue()));
+ builder.append(IPv4.fromIPv4Address(ipv4Address == null ?
+ 0 : ipv4Address.intValue()));
builder.append(", vlan=");
builder.append(vlan);
builder.append(", switchDPID=");
@@ -212,9 +212,9 @@
builder.append(", switchPort=");
builder.append(switchPort);
builder.append(", lastSeenTimestamp=");
- builder.append(lastSeenTimestamp == null? "null" : lastSeenTimestamp.getTime());
+ builder.append(lastSeenTimestamp == null ? "null" : lastSeenTimestamp.getTime());
builder.append(", activeSince=");
- builder.append(activeSince == null? "null" : activeSince.getTime());
+ builder.append(activeSince == null ? "null" : activeSince.getTime());
builder.append("]");
return builder.toString();
}
@@ -260,5 +260,5 @@
return 0;
}*/
-
+
}
diff --git a/src/main/java/net/onrc/onos/core/devicemanager/OnosDeviceManager.java b/src/main/java/net/onrc/onos/core/devicemanager/OnosDeviceManager.java
index cd4fa0d..22a564b 100644
--- a/src/main/java/net/onrc/onos/core/devicemanager/OnosDeviceManager.java
+++ b/src/main/java/net/onrc/onos/core/devicemanager/OnosDeviceManager.java
@@ -42,173 +42,174 @@
import org.slf4j.LoggerFactory;
public class OnosDeviceManager implements IFloodlightModule,
- IOFMessageListener,
- IOnosDeviceService,
- IEventChannelListener<Long, OnosDevice> {
- protected final static Logger log = LoggerFactory.getLogger(OnosDeviceManager.class);
- private static final int CLEANUP_SECOND = 60*60;
- private static final int AGEING_MILLSEC = 60*60*1000;
+ IOFMessageListener,
+ IOnosDeviceService,
+ IEventChannelListener<Long, OnosDevice> {
+ protected final static Logger log = LoggerFactory.getLogger(OnosDeviceManager.class);
+ private static final int CLEANUP_SECOND = 60 * 60;
+ private static final int AGEING_MILLSEC = 60 * 60 * 1000;
- private CopyOnWriteArrayList<IOnosDeviceListener> deviceListeners;
- private IFloodlightProviderService floodlightProvider;
- private final static ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
+ private CopyOnWriteArrayList<IOnosDeviceListener> deviceListeners;
+ private IFloodlightProviderService floodlightProvider;
+ private final static ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
- private IDatagridService datagrid;
- private IEventChannel<Long, OnosDevice> eventChannel;
- private static final String DEVICE_CHANNEL_NAME = "onos.device";
- private Map<Long, OnosDevice> mapDevice = new ConcurrentHashMap<Long, OnosDevice>();
- private INetworkGraphService networkGraphService;
- private NetworkGraph networkGraph;
+ private IDatagridService datagrid;
+ private IEventChannel<Long, OnosDevice> eventChannel;
+ private static final String DEVICE_CHANNEL_NAME = "onos.device";
+ private Map<Long, OnosDevice> mapDevice = new ConcurrentHashMap<Long, OnosDevice>();
+ private INetworkGraphService networkGraphService;
+ private NetworkGraph networkGraph;
public enum OnosDeviceUpdateType {
ADD, DELETE, UPDATE;
}
- private class OnosDeviceUpdate implements IUpdate {
- private OnosDevice device;
- private OnosDeviceUpdateType type;
+ private class OnosDeviceUpdate implements IUpdate {
+ private OnosDevice device;
+ private OnosDeviceUpdateType type;
- public OnosDeviceUpdate(OnosDevice device, OnosDeviceUpdateType type) {
- this.device = device;
- this.type = type;
- }
+ public OnosDeviceUpdate(OnosDevice device, OnosDeviceUpdateType type) {
+ this.device = device;
+ this.type = type;
+ }
- @Override
- public void dispatch() {
- if(type == OnosDeviceUpdateType.ADD) {
- for(IOnosDeviceListener listener: deviceListeners) {
- listener.onosDeviceAdded(device);
- }
- } else if (type == OnosDeviceUpdateType.DELETE){
- for(IOnosDeviceListener listener: deviceListeners) {
- listener.onosDeviceRemoved(device);
- }
- }
- }
- }
+ @Override
+ public void dispatch() {
+ if (type == OnosDeviceUpdateType.ADD) {
+ for (IOnosDeviceListener listener : deviceListeners) {
+ listener.onosDeviceAdded(device);
+ }
+ } else if (type == OnosDeviceUpdateType.DELETE) {
+ for (IOnosDeviceListener listener : deviceListeners) {
+ listener.onosDeviceRemoved(device);
+ }
+ }
+ }
+ }
- @Override
- public String getName() {
- return "onosdevicemanager";
- }
+ @Override
+ public String getName() {
+ return "onosdevicemanager";
+ }
- @Override
- public boolean isCallbackOrderingPrereq(OFType type, String name) {
- // We want link discovery to consume LLDP first otherwise we'll
- // end up reading bad device info from LLDP packets
- return type == OFType.PACKET_IN && "linkdiscovery".equals(name);
- }
+ @Override
+ public boolean isCallbackOrderingPrereq(OFType type, String name) {
+ // We want link discovery to consume LLDP first otherwise we'll
+ // end up reading bad device info from LLDP packets
+ return type == OFType.PACKET_IN && "linkdiscovery".equals(name);
+ }
- @Override
- public boolean isCallbackOrderingPostreq(OFType type, String name) {
- return type == OFType.PACKET_IN &&
- ("proxyarpmanager".equals(name) || "onosforwarding".equals(name));
- }
+ @Override
+ public boolean isCallbackOrderingPostreq(OFType type, String name) {
+ return type == OFType.PACKET_IN &&
+ ("proxyarpmanager".equals(name) || "onosforwarding".equals(name));
+ }
- @Override
- public Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx) {
- if (msg.getType().equals(OFType.PACKET_IN)) {
- OFPacketIn pi = (OFPacketIn) msg;
+ @Override
+ public Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx) {
+ if (msg.getType().equals(OFType.PACKET_IN)) {
+ OFPacketIn pi = (OFPacketIn) msg;
- Ethernet eth = IFloodlightProviderService.bcStore.
- get(cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
+ Ethernet eth = IFloodlightProviderService.bcStore.
+ get(cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
- return processPacketIn(sw, pi, eth);
- }
+ return processPacketIn(sw, pi, eth);
+ }
- return Command.CONTINUE;
- }
+ return Command.CONTINUE;
+ }
- private Command processPacketIn(IOFSwitch sw, OFPacketIn pi, Ethernet eth) {
- long dpid =sw.getId();
+ private Command processPacketIn(IOFSwitch sw, OFPacketIn pi, Ethernet eth) {
+ long dpid = sw.getId();
short portId = pi.getInPort();
Long mac = eth.getSourceMAC().toLong();
OnosDevice srcDevice =
getSourceDeviceFromPacket(eth, dpid, portId);
- if (srcDevice == null){
- return Command.STOP;
+ if (srcDevice == null) {
+ return Command.STOP;
}
//We check if it is the same device in datagrid to suppress the device update
OnosDevice exDev = null;
- if((exDev = mapDevice.get(mac)) != null ){
- if(exDev.equals(srcDevice)) {
- //There is the same existing device. Update only ActiveSince time.
- exDev.setLastSeenTimestamp(new Date());
- if(log.isTraceEnabled()) {
- log.debug("In the datagrid, there is the same device."
- + "Only update last seen time. dpid {}, port {}, mac {}, ip {}, lastSeenTime {}",
- dpid, portId, srcDevice.getMacAddress(), srcDevice.getIpv4Address(), srcDevice.getLastSeenTimestamp().getTime());
- }
- return Command.CONTINUE;
- } else if (srcDevice.getIpv4Address() == null &&
- exDev.getSwitchDPID().equals(srcDevice.getSwitchDPID()) &&
- exDev.getSwitchPort() == srcDevice.getSwitchPort()) {
- //Vlan should be handled based on the Onos spec. Until then, don't handle it.
- //Device attachment point and mac address are the same
- //but the packet does not have an ip address.
- exDev.setLastSeenTimestamp(new Date());
- if(log.isTraceEnabled()) {
- log.debug("In the datagrid, there is the same device with no ip."
- + "Keep ip and update last seen time. dpid {}, port {}, mac {}, ip {} lastSeenTime {}",
- dpid, portId, srcDevice.getMacAddress(), exDev.getIpv4Address(), srcDevice.getLastSeenTimestamp().getTime());
- }
- return Command.CONTINUE;
- }
- }
+ if ((exDev = mapDevice.get(mac)) != null) {
+ if (exDev.equals(srcDevice)) {
+ //There is the same existing device. Update only ActiveSince time.
+ exDev.setLastSeenTimestamp(new Date());
+ if (log.isTraceEnabled()) {
+ log.debug("In the datagrid, there is the same device."
+ + "Only update last seen time. dpid {}, port {}, mac {}, ip {}, lastSeenTime {}",
+ dpid, portId, srcDevice.getMacAddress(), srcDevice.getIpv4Address(), srcDevice.getLastSeenTimestamp().getTime());
+ }
+ return Command.CONTINUE;
+ } else if (srcDevice.getIpv4Address() == null &&
+ exDev.getSwitchDPID().equals(srcDevice.getSwitchDPID()) &&
+ exDev.getSwitchPort() == srcDevice.getSwitchPort()) {
+ //Vlan should be handled based on the Onos spec. Until then, don't handle it.
+ //Device attachment point and mac address are the same
+ //but the packet does not have an ip address.
+ exDev.setLastSeenTimestamp(new Date());
+ if (log.isTraceEnabled()) {
+ log.debug("In the datagrid, there is the same device with no ip."
+ + "Keep ip and update last seen time. dpid {}, port {}, mac {}, ip {} lastSeenTime {}",
+ dpid, portId, srcDevice.getMacAddress(), exDev.getIpv4Address(), srcDevice.getLastSeenTimestamp().getTime());
+ }
+ return Command.CONTINUE;
+ }
+ }
//If the switch port we try to attach a new device already has a link, then stop adding device
- if(networkGraph.getLink(dpid, (long)portId) != null) {
- if(log.isTraceEnabled()) {
- log.debug("Stop adding OnosDevice {} due to there is a link to: dpid {} port {}",
- srcDevice.getMacAddress(), dpid, portId);
- }
- return Command.CONTINUE;
+ if (networkGraph.getLink(dpid, (long) portId) != null) {
+ if (log.isTraceEnabled()) {
+ log.debug("Stop adding OnosDevice {} due to there is a link to: dpid {} port {}",
+ srcDevice.getMacAddress(), dpid, portId);
+ }
+ return Command.CONTINUE;
}
addOnosDevice(mac, srcDevice);
- if(log.isTraceEnabled()) {
- log.debug("Add device info in the set. dpid {}, port {}, mac {}, ip {}, lastSeenTime {}",
- dpid, portId, srcDevice.getMacAddress(), srcDevice.getIpv4Address(), srcDevice.getLastSeenTimestamp().getTime());
+ if (log.isTraceEnabled()) {
+ log.debug("Add device info in the set. dpid {}, port {}, mac {}, ip {}, lastSeenTime {}",
+ dpid, portId, srcDevice.getMacAddress(), srcDevice.getIpv4Address(), srcDevice.getLastSeenTimestamp().getTime());
}
return Command.CONTINUE;
- }
+ }
- //Thread to delete devices periodically.
- //Remove all devices from the map first and then finally delete devices from the DB.
- private class CleanDevice implements Runnable {
- @Override
- public void run() {
- log.debug("called CleanDevice");
- try{
- Set<OnosDevice> deleteSet = new HashSet<OnosDevice>();
- for (OnosDevice dev : mapDevice.values() ) {
- long now = new Date().getTime();
- if((now - dev.getLastSeenTimestamp().getTime() > AGEING_MILLSEC)) {
- if(log.isTraceEnabled()) {
- log.debug("Remove device info in the datagrid. dpid {}, port {}, mac {}, ip {}, lastSeenTime {}, diff {}",
- dev.getSwitchDPID(), dev.getSwitchPort(), dev.getMacAddress(), dev.getIpv4Address(),
- dev.getLastSeenTimestamp().getTime(), now - dev.getLastSeenTimestamp().getTime());
- }
- deleteSet.add(dev);
- }
- }
+ //Thread to delete devices periodically.
+ //Remove all devices from the map first and then finally delete devices from the DB.
+ private class CleanDevice implements Runnable {
+ @Override
+ public void run() {
+ log.debug("called CleanDevice");
+ try {
+ Set<OnosDevice> deleteSet = new HashSet<OnosDevice>();
+ for (OnosDevice dev : mapDevice.values()) {
+ long now = new Date().getTime();
+ if ((now - dev.getLastSeenTimestamp().getTime() > AGEING_MILLSEC)) {
+ if (log.isTraceEnabled()) {
+ log.debug("Remove device info in the datagrid. dpid {}, port {}, mac {}, ip {}, lastSeenTime {}, diff {}",
+ dev.getSwitchDPID(), dev.getSwitchPort(), dev.getMacAddress(), dev.getIpv4Address(),
+ dev.getLastSeenTimestamp().getTime(), now - dev.getLastSeenTimestamp().getTime());
+ }
+ deleteSet.add(dev);
+ }
+ }
- for(OnosDevice dev : deleteSet) {
- deleteOnosDevice(dev);
- }
- } catch(Exception e) {
- log.error("Error:", e);
- }
- }
- }
+ for (OnosDevice dev : deleteSet) {
+ deleteOnosDevice(dev);
+ }
+ } catch (Exception e) {
+ log.error("Error:", e);
+ }
+ }
+ }
/**
* Get IP address from packet if the packet is either an ARP
* or a DHCP packet
+ *
* @param eth
* @param dlAddr
* @return
@@ -223,9 +224,9 @@
} else if (eth.getPayload() instanceof IPv4) {
IPv4 ipv4 = (IPv4) eth.getPayload();
if (ipv4.getPayload() instanceof UDP) {
- UDP udp = (UDP)ipv4.getPayload();
+ UDP udp = (UDP) ipv4.getPayload();
if (udp.getPayload() instanceof DHCP) {
- DHCP dhcp = (DHCP)udp.getPayload();
+ DHCP dhcp = (DHCP) udp.getPayload();
if (dhcp.getOpCode() == DHCP.OPCODE_REPLY) {
return ipv4.getSourceAddress();
}
@@ -237,14 +238,15 @@
/**
* Parse an entity from an {@link Ethernet} packet.
+ *
* @param eth the packet to parse
- * @param sw the switch on which the packet arrived
- * @param pi the original packetin
+ * @param sw the switch on which the packet arrived
+ * @param pi the original packetin
* @return the entity from the packet
*/
private OnosDevice getSourceDeviceFromPacket(Ethernet eth,
- long swdpid,
- short port) {
+ long swdpid,
+ short port) {
byte[] dlAddrArr = eth.getSourceMACAddress();
long dlAddr = Ethernet.toLong(dlAddrArr);
@@ -255,106 +257,106 @@
short vlan = eth.getVlanID();
int nwSrc = getSrcNwAddr(eth, dlAddr);
return new OnosDevice(MACAddress.valueOf(dlAddr),
- ((vlan >= 0) ? vlan : null),
- ((nwSrc != 0) ? nwSrc : null),
- swdpid,
- port,
- new Date());
+ ((vlan >= 0) ? vlan : null),
+ ((nwSrc != 0) ? nwSrc : null),
+ swdpid,
+ port,
+ new Date());
}
- @Override
- public Collection<Class<? extends IFloodlightService>> getModuleServices() {
- List<Class<? extends IFloodlightService>> services =
- new ArrayList<Class<? extends IFloodlightService>>();
- services.add(IOnosDeviceService.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(IOnosDeviceService.class, this);
- 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(INetworkGraphService.class);
- dependencies.add(IDatagridService.class);
- return dependencies;
- }
-
- @Override
- public void init(FloodlightModuleContext context)
- throws FloodlightModuleException {
- floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
- executor.scheduleAtFixedRate(new CleanDevice(), 30 ,CLEANUP_SECOND, TimeUnit.SECONDS);
-
- deviceListeners = new CopyOnWriteArrayList<IOnosDeviceListener>();
- datagrid = context.getServiceImpl(IDatagridService.class);
- networkGraphService = context.getServiceImpl(INetworkGraphService.class);
- networkGraph = networkGraphService.getNetworkGraph();
- }
-
- @Override
- public void startUp(FloodlightModuleContext context) {
- floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
- eventChannel = datagrid.addListener(DEVICE_CHANNEL_NAME, this,
- Long.class,
- OnosDevice.class);
- }
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleServices() {
+ List<Class<? extends IFloodlightService>> services =
+ new ArrayList<Class<? extends IFloodlightService>>();
+ services.add(IOnosDeviceService.class);
+ return services;
+ }
@Override
- public void deleteOnosDevice(OnosDevice dev) {
- Long mac = dev.getMacAddress().toLong();
- eventChannel.removeEntry(mac);
- floodlightProvider.publishUpdate(new OnosDeviceUpdate(dev, OnosDeviceUpdateType.DELETE));
- }
-
+ public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
+ Map<Class<? extends IFloodlightService>, IFloodlightService> impls =
+ new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
+ impls.put(IOnosDeviceService.class, this);
+ return impls;
+ }
+
@Override
- public void deleteOnosDeviceByMac(MACAddress mac) {
- OnosDevice deleteDevice = mapDevice.get(mac);
- deleteOnosDevice(deleteDevice);
- }
-
- @Override
- public void addOnosDevice(Long mac, OnosDevice dev) {
- eventChannel.addEntry(mac, dev);
- floodlightProvider.publishUpdate(new OnosDeviceUpdate(dev, OnosDeviceUpdateType.ADD));
- }
+ public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
+ List<Class<? extends IFloodlightService>> dependencies =
+ new ArrayList<Class<? extends IFloodlightService>>();
+ dependencies.add(IFloodlightProviderService.class);
+ dependencies.add(INetworkGraphService.class);
+ dependencies.add(IDatagridService.class);
+ return dependencies;
+ }
- @Override
- public void entryAdded(OnosDevice dev) {
- Long mac = dev.getMacAddress().toLong();
- mapDevice.put(mac, dev);
- log.debug("Device added: device mac {}", mac);
- }
+ @Override
+ public void init(FloodlightModuleContext context)
+ throws FloodlightModuleException {
+ floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
+ executor.scheduleAtFixedRate(new CleanDevice(), 30, CLEANUP_SECOND, TimeUnit.SECONDS);
- @Override
- public void entryRemoved(OnosDevice dev) {
- Long mac = dev.getMacAddress().toLong();
- mapDevice.remove(mac);
- log.debug("Device removed: device mac {}", mac);
- }
+ deviceListeners = new CopyOnWriteArrayList<IOnosDeviceListener>();
+ datagrid = context.getServiceImpl(IDatagridService.class);
+ networkGraphService = context.getServiceImpl(INetworkGraphService.class);
+ networkGraph = networkGraphService.getNetworkGraph();
+ }
- @Override
- public void entryUpdated(OnosDevice dev) {
- Long mac = dev.getMacAddress().toLong();
- mapDevice.put(mac, dev);
- log.debug("Device updated: device mac {}", mac);
- }
+ @Override
+ public void startUp(FloodlightModuleContext context) {
+ floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
+ eventChannel = datagrid.addListener(DEVICE_CHANNEL_NAME, this,
+ Long.class,
+ OnosDevice.class);
+ }
- @Override
- public void addOnosDeviceListener(IOnosDeviceListener listener) {
- deviceListeners.add(listener);
- }
+ @Override
+ public void deleteOnosDevice(OnosDevice dev) {
+ Long mac = dev.getMacAddress().toLong();
+ eventChannel.removeEntry(mac);
+ floodlightProvider.publishUpdate(new OnosDeviceUpdate(dev, OnosDeviceUpdateType.DELETE));
+ }
- @Override
- public void deleteOnosDeviceListener(IOnosDeviceListener listener) {
- deviceListeners.remove(listener);
- }
+ @Override
+ public void deleteOnosDeviceByMac(MACAddress mac) {
+ OnosDevice deleteDevice = mapDevice.get(mac);
+ deleteOnosDevice(deleteDevice);
+ }
+
+ @Override
+ public void addOnosDevice(Long mac, OnosDevice dev) {
+ eventChannel.addEntry(mac, dev);
+ floodlightProvider.publishUpdate(new OnosDeviceUpdate(dev, OnosDeviceUpdateType.ADD));
+ }
+
+ @Override
+ public void entryAdded(OnosDevice dev) {
+ Long mac = dev.getMacAddress().toLong();
+ mapDevice.put(mac, dev);
+ log.debug("Device added: device mac {}", mac);
+ }
+
+ @Override
+ public void entryRemoved(OnosDevice dev) {
+ Long mac = dev.getMacAddress().toLong();
+ mapDevice.remove(mac);
+ log.debug("Device removed: device mac {}", mac);
+ }
+
+ @Override
+ public void entryUpdated(OnosDevice dev) {
+ Long mac = dev.getMacAddress().toLong();
+ mapDevice.put(mac, dev);
+ log.debug("Device updated: device mac {}", mac);
+ }
+
+ @Override
+ public void addOnosDeviceListener(IOnosDeviceListener listener) {
+ deviceListeners.add(listener);
+ }
+
+ @Override
+ public void deleteOnosDeviceListener(IOnosDeviceListener listener) {
+ deviceListeners.remove(listener);
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/flowprogrammer/IFlowPusherService.java b/src/main/java/net/onrc/onos/core/flowprogrammer/IFlowPusherService.java
index 89c6599..25b8044 100644
--- a/src/main/java/net/onrc/onos/core/flowprogrammer/IFlowPusherService.java
+++ b/src/main/java/net/onrc/onos/core/flowprogrammer/IFlowPusherService.java
@@ -24,7 +24,7 @@
public static enum MsgPriority {
HIGH, // High priority: e.g. flow synchronization
NORMAL, // Normal priority
-// LOW, // Low priority, not needed for now
+// LOW, // Low priority, not needed for now
}
public static enum QueueState {
diff --git a/src/main/java/net/onrc/onos/core/intent/Action.java b/src/main/java/net/onrc/onos/core/intent/Action.java
index 71c7183..6490fe5 100644
--- a/src/main/java/net/onrc/onos/core/intent/Action.java
+++ b/src/main/java/net/onrc/onos/core/intent/Action.java
@@ -3,9 +3,7 @@
import net.onrc.onos.core.util.FlowEntryAction;
/**
- *
* @author Brian O'Connor <bocon@onlab.us>
- *
*/
public abstract class Action {
diff --git a/src/main/java/net/onrc/onos/core/intent/ConstrainedBFSTree.java b/src/main/java/net/onrc/onos/core/intent/ConstrainedBFSTree.java
index fece148..c72ef4e 100644
--- a/src/main/java/net/onrc/onos/core/intent/ConstrainedBFSTree.java
+++ b/src/main/java/net/onrc/onos/core/intent/ConstrainedBFSTree.java
@@ -15,58 +15,62 @@
* which satisfies the bandwidth condition.
* If bandwidth parameter is not specified, the normal breadth first tree will be calculated.
* The paths are snapshot paths at the point of the class instantiation.
+ *
* @author Toshio Koide (t-koide@onlab.us)
*/
public class ConstrainedBFSTree {
- LinkedList<Switch> switchQueue = new LinkedList<>();
- HashSet<Switch> switchSearched = new HashSet<>();
- HashMap<Long, LinkEvent> upstreamLinks = new HashMap<>();
- HashMap<Switch, Path> paths = new HashMap<>();
- Switch rootSwitch;
- PathIntentMap intents = null;
- double bandwidth = 0.0; // 0.0 means no limit for bandwidth (normal BFS tree)
+ LinkedList<Switch> switchQueue = new LinkedList<>();
+ HashSet<Switch> switchSearched = new HashSet<>();
+ HashMap<Long, LinkEvent> upstreamLinks = new HashMap<>();
+ HashMap<Switch, Path> paths = new HashMap<>();
+ Switch rootSwitch;
+ PathIntentMap intents = null;
+ double bandwidth = 0.0; // 0.0 means no limit for bandwidth (normal BFS tree)
- public ConstrainedBFSTree(Switch rootSwitch) {
- this.rootSwitch = rootSwitch;
- calcTree();
- }
+ public ConstrainedBFSTree(Switch rootSwitch) {
+ this.rootSwitch = rootSwitch;
+ calcTree();
+ }
- public ConstrainedBFSTree(Switch rootSwitch, PathIntentMap intents, double bandwidth) {
- this.rootSwitch = rootSwitch;
- this.intents = intents;
- this.bandwidth = bandwidth;
- calcTree();
- }
+ public ConstrainedBFSTree(Switch rootSwitch, PathIntentMap intents, double bandwidth) {
+ this.rootSwitch = rootSwitch;
+ this.intents = intents;
+ this.bandwidth = bandwidth;
+ calcTree();
+ }
- protected void calcTree() {
- switchQueue.add(rootSwitch);
- switchSearched.add(rootSwitch);
- while (!switchQueue.isEmpty()) {
- Switch sw = switchQueue.poll();
- for (Link link: sw.getOutgoingLinks()) {
- Switch reachedSwitch = link.getDstPort().getSwitch();
- if (switchSearched.contains(reachedSwitch)) continue;
- if (intents != null && intents.getAvailableBandwidth(link) < bandwidth) continue;
- switchQueue.add(reachedSwitch);
- switchSearched.add(reachedSwitch);
- upstreamLinks.put(reachedSwitch.getDpid(), new LinkEvent(link));
- }
- }
- }
+ protected void calcTree() {
+ switchQueue.add(rootSwitch);
+ switchSearched.add(rootSwitch);
+ while (!switchQueue.isEmpty()) {
+ Switch sw = switchQueue.poll();
+ for (Link link : sw.getOutgoingLinks()) {
+ Switch reachedSwitch = link.getDstPort().getSwitch();
+ if (switchSearched.contains(reachedSwitch)) continue;
+ if (intents != null &&
+ intents.getAvailableBandwidth(link) < bandwidth) {
+ continue;
+ }
+ switchQueue.add(reachedSwitch);
+ switchSearched.add(reachedSwitch);
+ upstreamLinks.put(reachedSwitch.getDpid(), new LinkEvent(link));
+ }
+ }
+ }
- public Path getPath(Switch leafSwitch) {
- Path path = paths.get(leafSwitch);
- Long rootSwitchDpid = rootSwitch.getDpid();
- if (path == null && switchSearched.contains(leafSwitch)) {
- path = new Path();
- Long sw = leafSwitch.getDpid();
- while (!sw.equals(rootSwitchDpid)) {
- LinkEvent upstreamLink = upstreamLinks.get(sw);
- path.add(0, upstreamLink);
- sw = upstreamLink.getSrc().getDpid();
- }
- paths.put(leafSwitch, path);
- }
- return path;
- }
+ public Path getPath(Switch leafSwitch) {
+ Path path = paths.get(leafSwitch);
+ Long rootSwitchDpid = rootSwitch.getDpid();
+ if (path == null && switchSearched.contains(leafSwitch)) {
+ path = new Path();
+ Long sw = leafSwitch.getDpid();
+ while (!sw.equals(rootSwitchDpid)) {
+ LinkEvent upstreamLink = upstreamLinks.get(sw);
+ path.add(0, upstreamLink);
+ sw = upstreamLink.getSrc().getDpid();
+ }
+ paths.put(leafSwitch, path);
+ }
+ return path;
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/intent/ConstrainedShortestPathIntent.java b/src/main/java/net/onrc/onos/core/intent/ConstrainedShortestPathIntent.java
index ca4f753..7f3de9b 100644
--- a/src/main/java/net/onrc/onos/core/intent/ConstrainedShortestPathIntent.java
+++ b/src/main/java/net/onrc/onos/core/intent/ConstrainedShortestPathIntent.java
@@ -4,23 +4,23 @@
* @author Toshio Koide (t-koide@onlab.us)
*/
public class ConstrainedShortestPathIntent extends ShortestPathIntent {
- protected double bandwidth;
+ protected double bandwidth;
- /**
- * Default constructor for Kryo deserialization
- */
- protected ConstrainedShortestPathIntent() {
- }
+ /**
+ * Default constructor for Kryo deserialization
+ */
+ protected ConstrainedShortestPathIntent() {
+ }
- public ConstrainedShortestPathIntent(String id,
- long srcSwitch, long srcPort, long srcMac,
- long dstSwitch, long dstPort, long dstMac,
- double bandwidth) {
- super(id, srcSwitch, srcPort, srcMac, dstSwitch, dstPort, dstMac);
- this.bandwidth = bandwidth;
- }
+ public ConstrainedShortestPathIntent(String id,
+ long srcSwitch, long srcPort, long srcMac,
+ long dstSwitch, long dstPort, long dstMac,
+ double bandwidth) {
+ super(id, srcSwitch, srcPort, srcMac, dstSwitch, dstPort, dstMac);
+ this.bandwidth = bandwidth;
+ }
- public double getBandwidth() {
- return bandwidth;
- }
+ public double getBandwidth() {
+ return bandwidth;
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/intent/ErrorIntent.java b/src/main/java/net/onrc/onos/core/intent/ErrorIntent.java
index a5046e8..31715a8 100644
--- a/src/main/java/net/onrc/onos/core/intent/ErrorIntent.java
+++ b/src/main/java/net/onrc/onos/core/intent/ErrorIntent.java
@@ -2,29 +2,30 @@
/**
* This class is instantiated by Run-times to express intent calculation error
+ *
* @author Toshio Koide (t-koide@onlab.us)
*/
public class ErrorIntent extends Intent {
- public enum ErrorType {
- UNSUPPORTED_INTENT,
- SWITCH_NOT_FOUND,
- PATH_NOT_FOUND,
- }
+ public enum ErrorType {
+ UNSUPPORTED_INTENT,
+ SWITCH_NOT_FOUND,
+ PATH_NOT_FOUND,
+ }
- public ErrorType errorType;
- public String message;
- public Intent parentIntent;
+ public ErrorType errorType;
+ public String message;
+ public Intent parentIntent;
- /**
- * Default constructor for Kryo deserialization
- */
- protected ErrorIntent() {
- }
+ /**
+ * Default constructor for Kryo deserialization
+ */
+ protected ErrorIntent() {
+ }
- public ErrorIntent(ErrorType errorType, String message, Intent parentIntent) {
- super(parentIntent.getId());
- this.errorType = errorType;
- this.message = message;
- this.parentIntent = parentIntent;
- }
+ public ErrorIntent(ErrorType errorType, String message, Intent parentIntent) {
+ super(parentIntent.getId());
+ this.errorType = errorType;
+ this.message = message;
+ this.parentIntent = parentIntent;
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/intent/FlowEntry.java b/src/main/java/net/onrc/onos/core/intent/FlowEntry.java
index 570f4ef..526fe5f 100644
--- a/src/main/java/net/onrc/onos/core/intent/FlowEntry.java
+++ b/src/main/java/net/onrc/onos/core/intent/FlowEntry.java
@@ -11,79 +11,77 @@
import net.onrc.onos.core.util.FlowEntryUserState;
/**
- *
* @author Brian O'Connor <bocon@onlab.us>
- *
*/
public class FlowEntry {
- protected long sw;
- protected Match match;
- protected Set<Action> actions;
- protected Operator operator;
-
- public FlowEntry(long sw, long srcPort, long dstPort,
- MACAddress srcMac, MACAddress dstMac,
- Operator operator) {
- this.sw = sw;
- this.match = new Match(sw, srcPort, srcMac, dstMac);
- this.actions = new HashSet<Action>();
- this.actions.add(new ForwardAction(dstPort));
- this.operator = operator;
- }
-
- public String toString() {
- return match + "->" + actions;
- }
-
- public long getSwitch() {
- return sw;
- }
-
- public Operator getOperator() {
- return operator;
- }
-
- public void setOperator(Operator op) {
- operator = op;
- }
-
- public net.onrc.onos.core.util.FlowEntry getFlowEntry() {
- net.onrc.onos.core.util.FlowEntry entry = new net.onrc.onos.core.util.FlowEntry();
- entry.setDpid(new Dpid(sw));
- entry.setFlowEntryId(new FlowEntryId(hashCode())); // naive, but useful for now
- entry.setFlowEntryMatch(match.getFlowEntryMatch());
- FlowEntryActions flowEntryActions = new FlowEntryActions();
- for(Action action : actions) {
- flowEntryActions.addAction(action.getFlowEntryAction());
- }
- entry.setFlowEntryActions(flowEntryActions);
- switch(operator) {
- case ADD:
- entry.setFlowEntryUserState(FlowEntryUserState.FE_USER_MODIFY);
- break;
- case REMOVE:
- entry.setFlowEntryUserState(FlowEntryUserState.FE_USER_DELETE);
- break;
- default:
- break;
- }
- return entry;
- }
-
-
- public int hashCode() {
- return match.hashCode();
- }
-
- public boolean equals(Object o) {
- if(!(o instanceof FlowEntry)) {
- return false;
- }
- FlowEntry other = (FlowEntry) o;
- // Note: we should not consider the operator for this comparison
- return this.match.equals(other.match)
- && this.actions.containsAll(other.actions)
- && other.actions.containsAll(this.actions);
- }
+ protected long sw;
+ protected Match match;
+ protected Set<Action> actions;
+ protected Operator operator;
+
+ public FlowEntry(long sw, long srcPort, long dstPort,
+ MACAddress srcMac, MACAddress dstMac,
+ Operator operator) {
+ this.sw = sw;
+ this.match = new Match(sw, srcPort, srcMac, dstMac);
+ this.actions = new HashSet<Action>();
+ this.actions.add(new ForwardAction(dstPort));
+ this.operator = operator;
+ }
+
+ public String toString() {
+ return match + "->" + actions;
+ }
+
+ public long getSwitch() {
+ return sw;
+ }
+
+ public Operator getOperator() {
+ return operator;
+ }
+
+ public void setOperator(Operator op) {
+ operator = op;
+ }
+
+ public net.onrc.onos.core.util.FlowEntry getFlowEntry() {
+ net.onrc.onos.core.util.FlowEntry entry = new net.onrc.onos.core.util.FlowEntry();
+ entry.setDpid(new Dpid(sw));
+ entry.setFlowEntryId(new FlowEntryId(hashCode())); // naive, but useful for now
+ entry.setFlowEntryMatch(match.getFlowEntryMatch());
+ FlowEntryActions flowEntryActions = new FlowEntryActions();
+ for (Action action : actions) {
+ flowEntryActions.addAction(action.getFlowEntryAction());
+ }
+ entry.setFlowEntryActions(flowEntryActions);
+ switch (operator) {
+ case ADD:
+ entry.setFlowEntryUserState(FlowEntryUserState.FE_USER_MODIFY);
+ break;
+ case REMOVE:
+ entry.setFlowEntryUserState(FlowEntryUserState.FE_USER_DELETE);
+ break;
+ default:
+ break;
+ }
+ return entry;
+ }
+
+
+ public int hashCode() {
+ return match.hashCode();
+ }
+
+ public boolean equals(Object o) {
+ if (!(o instanceof FlowEntry)) {
+ return false;
+ }
+ FlowEntry other = (FlowEntry) o;
+ // Note: we should not consider the operator for this comparison
+ return this.match.equals(other.match)
+ && this.actions.containsAll(other.actions)
+ && other.actions.containsAll(this.actions);
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/intent/ForwardAction.java b/src/main/java/net/onrc/onos/core/intent/ForwardAction.java
index 482d3f1..4e4088f 100644
--- a/src/main/java/net/onrc/onos/core/intent/ForwardAction.java
+++ b/src/main/java/net/onrc/onos/core/intent/ForwardAction.java
@@ -3,38 +3,36 @@
import net.onrc.onos.core.util.FlowEntryAction;
/**
- *
* @author Brian O'Connor <bocon@onlab.us>
- *
*/
class ForwardAction extends Action {
- protected long dstPort;
-
- public ForwardAction(long dstPort) {
- this.dstPort = dstPort;
- }
-
- public String toString() {
- return Long.toString(dstPort);
- }
+ protected long dstPort;
- @Override
- public FlowEntryAction getFlowEntryAction() {
- FlowEntryAction action = new FlowEntryAction();
- action.setActionOutput(new net.onrc.onos.core.util.Port((short) dstPort));
- return action;
- }
+ public ForwardAction(long dstPort) {
+ this.dstPort = dstPort;
+ }
- public int hashCode() {
- return (int) dstPort;
- }
-
- public boolean equals(Object o) {
- if(!(o instanceof ForwardAction)) {
- return false;
- }
- ForwardAction action = (ForwardAction) o;
- return this.dstPort == action.dstPort;
- }
+ public String toString() {
+ return Long.toString(dstPort);
+ }
+
+ @Override
+ public FlowEntryAction getFlowEntryAction() {
+ FlowEntryAction action = new FlowEntryAction();
+ action.setActionOutput(new net.onrc.onos.core.util.Port((short) dstPort));
+ return action;
+ }
+
+ public int hashCode() {
+ return (int) dstPort;
+ }
+
+ public boolean equals(Object o) {
+ if (!(o instanceof ForwardAction)) {
+ return false;
+ }
+ ForwardAction action = (ForwardAction) o;
+ return this.dstPort == action.dstPort;
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/intent/Intent.java b/src/main/java/net/onrc/onos/core/intent/Intent.java
index 3c4dbea..a8a06b0 100644
--- a/src/main/java/net/onrc/onos/core/intent/Intent.java
+++ b/src/main/java/net/onrc/onos/core/intent/Intent.java
@@ -8,95 +8,95 @@
* @author Toshio Koide (t-koide@onlab.us)
*/
public class Intent {
- public enum IntentState {
- CREATED,
- INST_REQ,
- INST_NACK,
- INST_ACK,
- DEL_REQ,
- DEL_PENDING,
- DEL_ACK,
- REROUTE_REQ,
- }
+ public enum IntentState {
+ CREATED,
+ INST_REQ,
+ INST_NACK,
+ INST_ACK,
+ DEL_REQ,
+ DEL_PENDING,
+ DEL_ACK,
+ REROUTE_REQ,
+ }
- private String id;
- private IntentState state = IntentState.CREATED;
- private boolean pathFrozen = false;
+ private String id;
+ private IntentState state = IntentState.CREATED;
+ private boolean pathFrozen = false;
- @Optional(value="logs")
- private LinkedList<String> logs = new LinkedList<>();
+ @Optional(value = "logs")
+ private LinkedList<String> logs = new LinkedList<>();
- /**
- * Default constructor for Kryo deserialization
- */
- protected Intent() {
- logs.add(String.format("created, time:%d", System.nanoTime())); // for measurement
- }
+ /**
+ * Default constructor for Kryo deserialization
+ */
+ protected Intent() {
+ logs.add(String.format("created, time:%d", System.nanoTime())); // for measurement
+ }
- public Intent(String id) {
- logs.add(String.format("created, time:%d", System.nanoTime())); // for measurement
- this.id = id;
- }
+ public Intent(String id) {
+ logs.add(String.format("created, time:%d", System.nanoTime())); // for measurement
+ this.id = id;
+ }
- public Intent(String id, IntentState state) {
- logs.add(String.format("created, time:%d", System.nanoTime())); // for measurement
- setState(state);
- this.id = id;
- }
+ public Intent(String id, IntentState state) {
+ logs.add(String.format("created, time:%d", System.nanoTime())); // for measurement
+ setState(state);
+ this.id = id;
+ }
- public String getId() {
- return id;
- }
+ public String getId() {
+ return id;
+ }
- public IntentState getState() {
- return state;
- }
+ public IntentState getState() {
+ return state;
+ }
- public IntentState setState(IntentState newState) {
- logs.add(String.format("setState, oldState:%s, newState:%s, time:%d",
- state, newState, System.nanoTime())); // for measurement
- if (logs.size() > 20) { // TODO this size should be configurable
- logs.removeFirst();
- }
- IntentState oldState = state;
- state = newState;
- return oldState;
- }
+ public IntentState setState(IntentState newState) {
+ logs.add(String.format("setState, oldState:%s, newState:%s, time:%d",
+ state, newState, System.nanoTime())); // for measurement
+ if (logs.size() > 20) { // TODO this size should be configurable
+ logs.removeFirst();
+ }
+ IntentState oldState = state;
+ state = newState;
+ return oldState;
+ }
- public boolean isPathFrozen() {
- return pathFrozen;
- }
+ public boolean isPathFrozen() {
+ return pathFrozen;
+ }
- public void setPathFrozen(boolean isFrozen) {
- pathFrozen = isFrozen;
- }
+ public void setPathFrozen(boolean isFrozen) {
+ pathFrozen = isFrozen;
+ }
- public LinkedList<String> getLogs() {
- return logs;
- }
+ public LinkedList<String> getLogs() {
+ return logs;
+ }
- @Override
- public int hashCode() {
- return (id == null) ? 0 : id.hashCode();
- }
+ @Override
+ public int hashCode() {
+ return (id == null) ? 0 : id.hashCode();
+ }
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if ((obj == null) || (getClass() != obj.getClass()))
- return false;
- Intent other = (Intent) obj;
- if (id == null) {
- if (other.id != null)
- return false;
- } else if (!id.equals(other.id))
- return false;
- return true;
- }
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if ((obj == null) || (getClass() != obj.getClass()))
+ return false;
+ Intent other = (Intent) obj;
+ if (id == null) {
+ if (other.id != null)
+ return false;
+ } else if (!id.equals(other.id))
+ return false;
+ return true;
+ }
- @Override
- public String toString() {
- return id.toString() + ", " + state.toString();
- }
+ @Override
+ public String toString() {
+ return id.toString() + ", " + state.toString();
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/intent/IntentMap.java b/src/main/java/net/onrc/onos/core/intent/IntentMap.java
index ae314a7..e5cae77 100644
--- a/src/main/java/net/onrc/onos/core/intent/IntentMap.java
+++ b/src/main/java/net/onrc/onos/core/intent/IntentMap.java
@@ -14,177 +14,177 @@
* @author Toshio Koide (t-koide@onlab.us)
*/
public class IntentMap {
- private HashSet<ChangedListener> listeners = new HashSet<>();
- private HashMap<String, Intent> intents = new HashMap<>();
- private LinkedList<ChangedEvent> events = new LinkedList<>();
+ private HashSet<ChangedListener> listeners = new HashSet<>();
+ private HashMap<String, Intent> intents = new HashMap<>();
+ private LinkedList<ChangedEvent> events = new LinkedList<>();
- public enum ChangedEventType {
- /**
- * Added new intent.
- */
- ADDED,
+ public enum ChangedEventType {
+ /**
+ * Added new intent.
+ */
+ ADDED,
- /**
- * Removed existing intent.
- * The specified intent is an instance of Intent class (not a child class)
- * Only id and state are valid.
- */
- REMOVED,
+ /**
+ * Removed existing intent.
+ * The specified intent is an instance of Intent class (not a child class)
+ * Only id and state are valid.
+ */
+ REMOVED,
- /**
- * Changed state of existing intent.
- * The specified intent is an instance of Intent class (not a child class)
- * Only id and state are valid.
- */
- STATE_CHANGED,
- }
+ /**
+ * Changed state of existing intent.
+ * The specified intent is an instance of Intent class (not a child class)
+ * Only id and state are valid.
+ */
+ STATE_CHANGED,
+ }
- public class ChangedEvent {
- public ChangedEvent(ChangedEventType eventType, Intent intent) {
- this.eventType = eventType;
- this.intent = intent;
- }
- public ChangedEventType eventType;
- public Intent intent;
- }
+ public class ChangedEvent {
+ public ChangedEvent(ChangedEventType eventType, Intent intent) {
+ this.eventType = eventType;
+ this.intent = intent;
+ }
- public interface ChangedListener extends EventListener {
- void intentsChange(LinkedList<ChangedEvent> events);
- }
+ public ChangedEventType eventType;
+ public Intent intent;
+ }
- //================================================================================
- // public methods
- //================================================================================
+ public interface ChangedListener extends EventListener {
+ void intentsChange(LinkedList<ChangedEvent> events);
+ }
- public void executeOperations(IntentOperationList operations) {
- for (IntentOperation operation: operations) {
- switch (operation.operator) {
- case ADD:
- handleAddOperation(operation);
- break;
- case REMOVE:
- handleRemoveOperation(operation);
- break;
- case ERROR:
- handleErrorOperation(operation);
- break;
- }
- }
- notifyEvents();
- }
+ //================================================================================
+ // public methods
+ //================================================================================
- public void purge() {
- LinkedList<String> removeIds = new LinkedList<>();
- for (Entry<String, Intent> entry: intents.entrySet()) {
- Intent intent = entry.getValue();
- if (intent.getState() == IntentState.DEL_ACK
- || intent.getState() == IntentState.INST_NACK) {
- removeIds.add(intent.getId());
- }
- }
- for (String intentId: removeIds) {
- removeIntent(intentId);
- }
- notifyEvents();
- }
+ public void executeOperations(IntentOperationList operations) {
+ for (IntentOperation operation : operations) {
+ switch (operation.operator) {
+ case ADD:
+ handleAddOperation(operation);
+ break;
+ case REMOVE:
+ handleRemoveOperation(operation);
+ break;
+ case ERROR:
+ handleErrorOperation(operation);
+ break;
+ }
+ }
+ notifyEvents();
+ }
- public void changeStates(IntentStateList states) {
- for (Entry<String, IntentState> state: states.entrySet()) {
- setState(state.getKey(), state.getValue());
- }
- notifyEvents();
- }
+ public void purge() {
+ LinkedList<String> removeIds = new LinkedList<>();
+ for (Entry<String, Intent> entry : intents.entrySet()) {
+ Intent intent = entry.getValue();
+ if (intent.getState() == IntentState.DEL_ACK
+ || intent.getState() == IntentState.INST_NACK) {
+ removeIds.add(intent.getId());
+ }
+ }
+ for (String intentId : removeIds) {
+ removeIntent(intentId);
+ }
+ notifyEvents();
+ }
- public Intent getIntent(String intentId) {
- return intents.get(intentId);
- }
+ public void changeStates(IntentStateList states) {
+ for (Entry<String, IntentState> state : states.entrySet()) {
+ setState(state.getKey(), state.getValue());
+ }
+ notifyEvents();
+ }
- public Collection<Intent> getAllIntents() {
- return intents.values();
- }
+ public Intent getIntent(String intentId) {
+ return intents.get(intentId);
+ }
- public void addChangeListener(ChangedListener listener) {
- listeners.add(listener);
- }
+ public Collection<Intent> getAllIntents() {
+ return intents.values();
+ }
- public void removeChangedListener(ChangedListener listener) {
- listeners.remove(listener);
- }
+ public void addChangeListener(ChangedListener listener) {
+ listeners.add(listener);
+ }
- //================================================================================
- // methods that affect intents map (protected)
- //================================================================================
+ public void removeChangedListener(ChangedListener listener) {
+ listeners.remove(listener);
+ }
- protected void putIntent(Intent intent) {
- if (intents.containsKey(intent.getId()))
- removeIntent(intent.getId());
- intents.put(intent.getId(), intent);
- events.add(new ChangedEvent(ChangedEventType.ADDED, intent));
- }
+ //================================================================================
+ // methods that affect intents map (protected)
+ //================================================================================
- protected void removeIntent(String intentId) {
- Intent intent = intents.remove(intentId);
- if (intent == null) return;
- events.add(new ChangedEvent(ChangedEventType.REMOVED, intent));
- }
+ protected void putIntent(Intent intent) {
+ if (intents.containsKey(intent.getId()))
+ removeIntent(intent.getId());
+ intents.put(intent.getId(), intent);
+ events.add(new ChangedEvent(ChangedEventType.ADDED, intent));
+ }
- protected void setState(String intentId, IntentState state) {
- Intent intent = intents.get(intentId);
- if (intent == null) return;
- intent.setState(state);
- events.add(new ChangedEvent(ChangedEventType.STATE_CHANGED, intent));
- }
+ protected void removeIntent(String intentId) {
+ Intent intent = intents.remove(intentId);
+ if (intent == null) return;
+ events.add(new ChangedEvent(ChangedEventType.REMOVED, intent));
+ }
- //================================================================================
- // helper methods (protected)
- //================================================================================
+ protected void setState(String intentId, IntentState state) {
+ Intent intent = intents.get(intentId);
+ if (intent == null) return;
+ intent.setState(state);
+ events.add(new ChangedEvent(ChangedEventType.STATE_CHANGED, intent));
+ }
- protected void handleAddOperation(IntentOperation operation) {
- putIntent(operation.intent);
- }
+ //================================================================================
+ // helper methods (protected)
+ //================================================================================
- protected void handleRemoveOperation(IntentOperation operation) {
- Intent intent = getIntent(operation.intent.getId());
- if (intent == null) {
- // TODO error handling
- }
- else {
- setState(intent.getId(), IntentState.DEL_REQ);
- }
- }
+ protected void handleAddOperation(IntentOperation operation) {
+ putIntent(operation.intent);
+ }
- protected void handleErrorOperation(IntentOperation operation) {
- //TODO put error message into the intent
+ protected void handleRemoveOperation(IntentOperation operation) {
+ Intent intent = getIntent(operation.intent.getId());
+ if (intent == null) {
+ // TODO error handling
+ } else {
+ setState(intent.getId(), IntentState.DEL_REQ);
+ }
+ }
- ErrorIntent errorIntent = (ErrorIntent) operation.intent;
- Intent targetIntent = intents.get(errorIntent.getId());
- if (targetIntent == null) {
- // TODO error handling
- return;
- }
+ protected void handleErrorOperation(IntentOperation operation) {
+ //TODO put error message into the intent
- switch (targetIntent.getState()) {
- case CREATED:
- case INST_REQ:
- case INST_ACK:
- case REROUTE_REQ:
- setState(targetIntent.getId(), IntentState.INST_NACK);
- break;
- case DEL_REQ:
- setState(targetIntent.getId(), IntentState.DEL_PENDING);
- break;
- case INST_NACK:
- case DEL_PENDING:
- case DEL_ACK:
- // do nothing
- break;
- }
- }
+ ErrorIntent errorIntent = (ErrorIntent) operation.intent;
+ Intent targetIntent = intents.get(errorIntent.getId());
+ if (targetIntent == null) {
+ // TODO error handling
+ return;
+ }
- protected void notifyEvents() {
- for (ChangedListener listener: listeners) {
- listener.intentsChange(events);
- }
- events.clear();
- }
+ switch (targetIntent.getState()) {
+ case CREATED:
+ case INST_REQ:
+ case INST_ACK:
+ case REROUTE_REQ:
+ setState(targetIntent.getId(), IntentState.INST_NACK);
+ break;
+ case DEL_REQ:
+ setState(targetIntent.getId(), IntentState.DEL_PENDING);
+ break;
+ case INST_NACK:
+ case DEL_PENDING:
+ case DEL_ACK:
+ // do nothing
+ break;
+ }
+ }
+
+ protected void notifyEvents() {
+ for (ChangedListener listener : listeners) {
+ listener.intentsChange(events);
+ }
+ events.clear();
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/intent/IntentOperation.java b/src/main/java/net/onrc/onos/core/intent/IntentOperation.java
index 006c159..0cb42ff 100644
--- a/src/main/java/net/onrc/onos/core/intent/IntentOperation.java
+++ b/src/main/java/net/onrc/onos/core/intent/IntentOperation.java
@@ -4,37 +4,38 @@
* @author Toshio Koide (t-koide@onlab.us)
*/
public class IntentOperation {
- public enum Operator {
- /**
- * Add new intent specified by intent field.
- */
- ADD,
+ public enum Operator {
+ /**
+ * Add new intent specified by intent field.
+ */
+ ADD,
- /**
- * Remove existing intent specified by intent field.
- * The instance of intent field should be an instance of Intent class (not a child class)
- */
- REMOVE,
+ /**
+ * Remove existing intent specified by intent field.
+ * The instance of intent field should be an instance of Intent class (not a child class)
+ */
+ REMOVE,
- /**
- * Do error handling.
- * The instance of intent field should be an instance of ErrorIntent
- */
- ERROR,
- }
+ /**
+ * Do error handling.
+ * The instance of intent field should be an instance of ErrorIntent
+ */
+ ERROR,
+ }
- public Operator operator;
- public Intent intent;
+ public Operator operator;
+ public Intent intent;
- protected IntentOperation() {}
+ protected IntentOperation() {
+ }
- public IntentOperation(Operator operator, Intent intent) {
- this.operator = operator;
- this.intent = intent;
- }
+ public IntentOperation(Operator operator, Intent intent) {
+ this.operator = operator;
+ this.intent = intent;
+ }
- @Override
- public String toString() {
- return operator.toString() + ", (" + intent.toString() + ")";
- }
+ @Override
+ public String toString() {
+ return operator.toString() + ", (" + intent.toString() + ")";
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/intent/IntentOperationList.java b/src/main/java/net/onrc/onos/core/intent/IntentOperationList.java
index a3981fa..7691c68 100644
--- a/src/main/java/net/onrc/onos/core/intent/IntentOperationList.java
+++ b/src/main/java/net/onrc/onos/core/intent/IntentOperationList.java
@@ -6,9 +6,9 @@
* @author Toshio Koide (t-koide@onlab.us)
*/
public class IntentOperationList extends LinkedList<IntentOperation> {
- private static final long serialVersionUID = -3894081461861052610L;
+ private static final long serialVersionUID = -3894081461861052610L;
- public boolean add(IntentOperation.Operator op, Intent intent) {
- return add(new IntentOperation(op, intent));
- }
+ public boolean add(IntentOperation.Operator op, Intent intent) {
+ return add(new IntentOperation(op, intent));
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/intent/Match.java b/src/main/java/net/onrc/onos/core/intent/Match.java
index 5f92254..f7a2167 100644
--- a/src/main/java/net/onrc/onos/core/intent/Match.java
+++ b/src/main/java/net/onrc/onos/core/intent/Match.java
@@ -8,59 +8,56 @@
import net.onrc.onos.core.util.FlowEntryMatch;
/**
- *
* @author Brian O'Connor <bocon@onlab.us>
- *
*/
public class Match {
- protected long sw;
- protected MACAddress srcMac;
- protected MACAddress dstMac;
- protected long srcPort;
-
- public Match(long sw, long srcPort,
- MACAddress srcMac, MACAddress dstMac) {
- this.sw = sw;
- this.srcPort = srcPort;
- this.srcMac = srcMac;
- this.dstMac = dstMac;
- }
+ protected long sw;
+ protected MACAddress srcMac;
+ protected MACAddress dstMac;
+ protected long srcPort;
- @Override
- public boolean equals(Object obj) {
- if(obj instanceof Match) {
- Match other = (Match) obj;
- return this.sw == other.sw &&
- this.srcMac.equals(other.srcMac) &&
- this.dstMac.equals(other.dstMac) &&
- this.srcPort == other.srcPort;
- }
- else {
- return false;
- }
- }
+ public Match(long sw, long srcPort,
+ MACAddress srcMac, MACAddress dstMac) {
+ this.sw = sw;
+ this.srcPort = srcPort;
+ this.srcMac = srcMac;
+ this.dstMac = dstMac;
+ }
- public FlowEntryMatch getFlowEntryMatch(){
- FlowEntryMatch match = new FlowEntryMatch();
- match.enableSrcMac(srcMac);
- match.enableDstMac(dstMac);
- match.enableInPort(new net.onrc.onos.core.util.Port((short) srcPort));
- return match;
- }
+ @Override
+ public boolean equals(Object obj) {
+ if (obj instanceof Match) {
+ Match other = (Match) obj;
+ return this.sw == other.sw &&
+ this.srcMac.equals(other.srcMac) &&
+ this.dstMac.equals(other.dstMac) &&
+ this.srcPort == other.srcPort;
+ } else {
+ return false;
+ }
+ }
- @Override
- public String toString() {
- return "Sw:" + sw + " (" + srcPort + "," + srcMac + "," + dstMac + ")";
- }
-
- @Override
- public int hashCode() {
- long[] nums = new long[4];
- nums[0] = sw;
- nums[1] = srcPort;
- nums[2] = srcMac.toLong();
- nums[3] = dstMac.toLong();
- return Arrays.hashCode(nums);
- }
+ public FlowEntryMatch getFlowEntryMatch() {
+ FlowEntryMatch match = new FlowEntryMatch();
+ match.enableSrcMac(srcMac);
+ match.enableDstMac(dstMac);
+ match.enableInPort(new net.onrc.onos.core.util.Port((short) srcPort));
+ return match;
+ }
+
+ @Override
+ public String toString() {
+ return "Sw:" + sw + " (" + srcPort + "," + srcMac + "," + dstMac + ")";
+ }
+
+ @Override
+ public int hashCode() {
+ long[] nums = new long[4];
+ nums[0] = sw;
+ nums[1] = srcPort;
+ nums[2] = srcMac.toLong();
+ nums[3] = dstMac.toLong();
+ return Arrays.hashCode(nums);
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/intent/PathIntent.java b/src/main/java/net/onrc/onos/core/intent/PathIntent.java
index b06fb81..e541454 100644
--- a/src/main/java/net/onrc/onos/core/intent/PathIntent.java
+++ b/src/main/java/net/onrc/onos/core/intent/PathIntent.java
@@ -6,55 +6,54 @@
* @author Toshio Koide (t-koide@onlab.us)
*/
public class PathIntent extends Intent {
- protected Path path;
- protected double bandwidth;
- protected Intent parentIntent;
+ protected Path path;
+ protected double bandwidth;
+ protected Intent parentIntent;
- public static String createFirstId(String parentId) {
- return String.format("%s___0", parentId);
- }
+ public static String createFirstId(String parentId) {
+ return String.format("%s___0", parentId);
+ }
- public static String createNextId(String currentId) {
- String parts[] = currentId.split("___");
- return String.format("%s___%d", parts[0], Long.valueOf(parts[1])+1);
- }
+ public static String createNextId(String currentId) {
+ String parts[] = currentId.split("___");
+ return String.format("%s___%d", parts[0], Long.valueOf(parts[1]) + 1);
+ }
- /**
- * Default constructor for Kryo deserialization
- */
- protected PathIntent() {
- }
+ /**
+ * Default constructor for Kryo deserialization
+ */
+ protected PathIntent() {
+ }
- /**
- *
- * @param graph
- * @param path
- * @param bandwidth bandwidth which should be allocated for the path.
- * If 0, no intent for bandwidth allocation (best effort).
- * @param parentIntent parent intent. If null, this is root intent.
- * @param id
- */
- public PathIntent(String id, Path path, double bandwidth, Intent parentIntent) {
- super(id);
- this.path = path;
- this.bandwidth = bandwidth;
- this.parentIntent = parentIntent;
- }
+ /**
+ * @param graph
+ * @param path
+ * @param bandwidth bandwidth which should be allocated for the path.
+ * If 0, no intent for bandwidth allocation (best effort).
+ * @param parentIntent parent intent. If null, this is root intent.
+ * @param id
+ */
+ public PathIntent(String id, Path path, double bandwidth, Intent parentIntent) {
+ super(id);
+ this.path = path;
+ this.bandwidth = bandwidth;
+ this.parentIntent = parentIntent;
+ }
- public double getBandwidth() {
- return bandwidth;
- }
+ public double getBandwidth() {
+ return bandwidth;
+ }
- public Path getPath() {
- return path;
- }
+ public Path getPath() {
+ return path;
+ }
- public Intent getParentIntent() {
- return parentIntent;
- }
+ public Intent getParentIntent() {
+ return parentIntent;
+ }
- @Override
- public String toString() {
- return String.format("%s, %s, %s", getId(), getState(), getPath());
- }
+ @Override
+ public String toString() {
+ return String.format("%s, %s, %s", getId(), getState(), getPath());
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/intent/PathIntentMap.java b/src/main/java/net/onrc/onos/core/intent/PathIntentMap.java
index 6f66cb7..ad6b1a5 100644
--- a/src/main/java/net/onrc/onos/core/intent/PathIntentMap.java
+++ b/src/main/java/net/onrc/onos/core/intent/PathIntentMap.java
@@ -13,99 +13,100 @@
* @author Toshio Koide (t-koide@onlab.us)
*/
public class PathIntentMap extends IntentMap {
- private HashMap<Long, HashMap<Long, HashSet<PathIntent>>> intents;
+ private HashMap<Long, HashMap<Long, HashSet<PathIntent>>> intents;
- public PathIntentMap() {
- intents = new HashMap<>();
- }
+ public PathIntentMap() {
+ intents = new HashMap<>();
+ }
- private HashSet<PathIntent> get(SwitchPort swPort) {
- Long dpid = swPort.getDpid();
- Long port = swPort.getNumber();
- HashMap<Long, HashSet<PathIntent>> portToIntents = intents.get(dpid);
- if (portToIntents == null) {
- portToIntents = new HashMap<>();
- intents.put(dpid, portToIntents);
- }
- HashSet<PathIntent> targetIntents = portToIntents.get(port);
- if (targetIntents == null) {
- targetIntents = new HashSet<>();
- portToIntents.put(port, targetIntents);
- }
- return targetIntents;
- }
+ private HashSet<PathIntent> get(SwitchPort swPort) {
+ Long dpid = swPort.getDpid();
+ Long port = swPort.getNumber();
+ HashMap<Long, HashSet<PathIntent>> portToIntents = intents.get(dpid);
+ if (portToIntents == null) {
+ portToIntents = new HashMap<>();
+ intents.put(dpid, portToIntents);
+ }
+ HashSet<PathIntent> targetIntents = portToIntents.get(port);
+ if (targetIntents == null) {
+ targetIntents = new HashSet<>();
+ portToIntents.put(port, targetIntents);
+ }
+ return targetIntents;
+ }
- private void put(SwitchPort swPort, PathIntent intent) {
- get(swPort).add(intent);
- }
+ private void put(SwitchPort swPort, PathIntent intent) {
+ get(swPort).add(intent);
+ }
- @Override
- protected void putIntent(Intent intent) {
- if (!(intent instanceof PathIntent)) return; // TODO throw exception
- super.putIntent(intent);
+ @Override
+ protected void putIntent(Intent intent) {
+ if (!(intent instanceof PathIntent)) return; // TODO throw exception
+ super.putIntent(intent);
- PathIntent pathIntent = (PathIntent) intent;
- for (LinkEvent linkEvent: pathIntent.getPath()) {
- put(linkEvent.getSrc(), (PathIntent) intent);
- put(linkEvent.getDst(), (PathIntent) intent);
- }
- }
+ PathIntent pathIntent = (PathIntent) intent;
+ for (LinkEvent linkEvent : pathIntent.getPath()) {
+ put(linkEvent.getSrc(), (PathIntent) intent);
+ put(linkEvent.getDst(), (PathIntent) intent);
+ }
+ }
- @Override
- protected void removeIntent(String intentId) {
- PathIntent intent = (PathIntent) getIntent(intentId);
- for (LinkEvent linkEvent: intent.getPath()) {
- get(linkEvent.getSrc()).remove(intent);
- get(linkEvent.getDst()).remove(intent);
- }
- super.removeIntent(intentId);
- }
+ @Override
+ protected void removeIntent(String intentId) {
+ PathIntent intent = (PathIntent) getIntent(intentId);
+ for (LinkEvent linkEvent : intent.getPath()) {
+ get(linkEvent.getSrc()).remove(intent);
+ get(linkEvent.getDst()).remove(intent);
+ }
+ super.removeIntent(intentId);
+ }
- public Collection<PathIntent> getIntentsByLink(LinkEvent linkEvent) {
- return getIntentsByPort(
- linkEvent.getSrc().getDpid(),
- linkEvent.getSrc().getNumber());
- }
+ public Collection<PathIntent> getIntentsByLink(LinkEvent linkEvent) {
+ return getIntentsByPort(
+ linkEvent.getSrc().getDpid(),
+ linkEvent.getSrc().getNumber());
+ }
- public Collection<PathIntent> getIntentsByPort(Long dpid, Long port) {
- HashMap<Long, HashSet<PathIntent>> portToIntents = intents.get(dpid);
- if (portToIntents != null) {
- HashSet<PathIntent> targetIntents = portToIntents.get(port);
- if (targetIntents != null) {
- return Collections.unmodifiableCollection(targetIntents);
- }
- }
- return new HashSet<>();
- }
+ public Collection<PathIntent> getIntentsByPort(Long dpid, Long port) {
+ HashMap<Long, HashSet<PathIntent>> portToIntents = intents.get(dpid);
+ if (portToIntents != null) {
+ HashSet<PathIntent> targetIntents = portToIntents.get(port);
+ if (targetIntents != null) {
+ return Collections.unmodifiableCollection(targetIntents);
+ }
+ }
+ return new HashSet<>();
+ }
- public Collection<PathIntent> getIntentsByDpid(Long dpid) {
- HashSet<PathIntent> result = new HashSet<>();
- HashMap<Long, HashSet<PathIntent>> portToIntents = intents.get(dpid);
- if (portToIntents != null) {
- for (HashSet<PathIntent> targetIntents: portToIntents.values()) {
- result.addAll(targetIntents);
- }
- }
- return result;
- }
+ public Collection<PathIntent> getIntentsByDpid(Long dpid) {
+ HashSet<PathIntent> result = new HashSet<>();
+ HashMap<Long, HashSet<PathIntent>> portToIntents = intents.get(dpid);
+ if (portToIntents != null) {
+ for (HashSet<PathIntent> targetIntents : portToIntents.values()) {
+ result.addAll(targetIntents);
+ }
+ }
+ return result;
+ }
- /**
- * calculate available bandwidth of specified link
- * @param link
- * @return
- */
- public Double getAvailableBandwidth(Link link) {
- if (link == null) return null;
- Double bandwidth = link.getCapacity();
- LinkEvent linkEvent = new LinkEvent(link);
- if (!bandwidth.isInfinite()) {
- for (PathIntent intent: getIntentsByLink(linkEvent)) {
- Double intentBandwidth = intent.getBandwidth();
- if (intentBandwidth == null || intentBandwidth.isInfinite() || intentBandwidth.isNaN())
- continue;
- bandwidth -= intentBandwidth;
- }
- }
- return bandwidth;
- }
+ /**
+ * calculate available bandwidth of specified link
+ *
+ * @param link
+ * @return
+ */
+ public Double getAvailableBandwidth(Link link) {
+ if (link == null) return null;
+ Double bandwidth = link.getCapacity();
+ LinkEvent linkEvent = new LinkEvent(link);
+ if (!bandwidth.isInfinite()) {
+ for (PathIntent intent : getIntentsByLink(linkEvent)) {
+ Double intentBandwidth = intent.getBandwidth();
+ if (intentBandwidth == null || intentBandwidth.isInfinite() || intentBandwidth.isNaN())
+ continue;
+ bandwidth -= intentBandwidth;
+ }
+ }
+ return bandwidth;
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/intent/ShortestPathIntent.java b/src/main/java/net/onrc/onos/core/intent/ShortestPathIntent.java
index f4bb18c..3adc756 100644
--- a/src/main/java/net/onrc/onos/core/intent/ShortestPathIntent.java
+++ b/src/main/java/net/onrc/onos/core/intent/ShortestPathIntent.java
@@ -7,69 +7,69 @@
* @author Toshio Koide (t-koide@onlab.us)
*/
public class ShortestPathIntent extends Intent {
- protected long srcSwitchDpid;
- protected long srcPortNumber;
- protected long srcMacAddress;
- protected long dstSwitchDpid;
- protected long dstPortNumber;
- protected long dstMacAddress;
- protected String pathIntentId = null;
+ protected long srcSwitchDpid;
+ protected long srcPortNumber;
+ protected long srcMacAddress;
+ protected long dstSwitchDpid;
+ protected long dstPortNumber;
+ protected long dstMacAddress;
+ protected String pathIntentId = null;
- /**
- * Default constructor for Kryo deserialization
- */
- protected ShortestPathIntent() {
- }
+ /**
+ * Default constructor for Kryo deserialization
+ */
+ protected ShortestPathIntent() {
+ }
- public ShortestPathIntent(String id,
- long srcSwitch, long srcPort, long srcMac,
- long dstSwitch, long dstPort, long dstMac) {
- super(id);
- srcSwitchDpid = srcSwitch;
- srcPortNumber = srcPort;
- srcMacAddress = srcMac;
- dstSwitchDpid = dstSwitch;
- dstPortNumber = dstPort;
- dstMacAddress = dstMac;
- }
+ public ShortestPathIntent(String id,
+ long srcSwitch, long srcPort, long srcMac,
+ long dstSwitch, long dstPort, long dstMac) {
+ super(id);
+ srcSwitchDpid = srcSwitch;
+ srcPortNumber = srcPort;
+ srcMacAddress = srcMac;
+ dstSwitchDpid = dstSwitch;
+ dstPortNumber = dstPort;
+ dstMacAddress = dstMac;
+ }
- public long getSrcSwitchDpid() {
- return srcSwitchDpid;
- }
+ public long getSrcSwitchDpid() {
+ return srcSwitchDpid;
+ }
- public long getSrcPortNumber() {
- return srcPortNumber;
- }
+ public long getSrcPortNumber() {
+ return srcPortNumber;
+ }
- public long getSrcMac() {
- return srcMacAddress;
- }
+ public long getSrcMac() {
+ return srcMacAddress;
+ }
- public long getDstSwitchDpid() {
- return dstSwitchDpid;
- }
+ public long getDstSwitchDpid() {
+ return dstSwitchDpid;
+ }
- public long getDstPortNumber() {
- return dstPortNumber;
- }
+ public long getDstPortNumber() {
+ return dstPortNumber;
+ }
- public long getDstMac() {
- return dstMacAddress;
- }
+ public long getDstMac() {
+ return dstMacAddress;
+ }
- public void setPathIntent(PathIntent pathIntent) {
- pathIntentId = pathIntent.getId();
- }
+ public void setPathIntent(PathIntent pathIntent) {
+ pathIntentId = pathIntent.getId();
+ }
- public String getPathIntentId() {
- return pathIntentId;
- }
+ public String getPathIntentId() {
+ return pathIntentId;
+ }
- @Override
- public String toString() {
- return String.format("id:%s, state:%s, srcDpid:%s, srcPort:%d, srcMac:%s, dstDpid:%s, dstPort:%d, dstMac:%s",
- getId(), getState(),
- new Dpid(srcSwitchDpid), srcPortNumber, MACAddress.valueOf(srcMacAddress),
- new Dpid(dstSwitchDpid), dstPortNumber, MACAddress.valueOf(dstMacAddress));
- }
+ @Override
+ public String toString() {
+ return String.format("id:%s, state:%s, srcDpid:%s, srcPort:%d, srcMac:%s, dstDpid:%s, dstPort:%d, dstMac:%s",
+ getId(), getState(),
+ new Dpid(srcSwitchDpid), srcPortNumber, MACAddress.valueOf(srcMacAddress),
+ new Dpid(dstSwitchDpid), dstPortNumber, MACAddress.valueOf(dstMacAddress));
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/intent/runtime/IPathCalcRuntimeService.java b/src/main/java/net/onrc/onos/core/intent/runtime/IPathCalcRuntimeService.java
index c6aad89..dd7bfd0 100644
--- a/src/main/java/net/onrc/onos/core/intent/runtime/IPathCalcRuntimeService.java
+++ b/src/main/java/net/onrc/onos/core/intent/runtime/IPathCalcRuntimeService.java
@@ -8,8 +8,11 @@
* @author Toshio Koide (t-koide@onlab.us)
*/
public interface IPathCalcRuntimeService extends IFloodlightService {
- public IntentOperationList executeIntentOperations(IntentOperationList list);
- public IntentMap getHighLevelIntents();
- public IntentMap getPathIntents();
- public void purgeIntents();
+ public IntentOperationList executeIntentOperations(IntentOperationList list);
+
+ public IntentMap getHighLevelIntents();
+
+ public IntentMap getPathIntents();
+
+ public void purgeIntents();
}
diff --git a/src/main/java/net/onrc/onos/core/intent/runtime/IntentStateList.java b/src/main/java/net/onrc/onos/core/intent/runtime/IntentStateList.java
index e6f1180..e354811 100644
--- a/src/main/java/net/onrc/onos/core/intent/runtime/IntentStateList.java
+++ b/src/main/java/net/onrc/onos/core/intent/runtime/IntentStateList.java
@@ -8,5 +8,5 @@
* @author Toshio Koide (t-koide@onlab.us)
*/
public class IntentStateList extends HashMap<String, IntentState> {
- private static final long serialVersionUID = -3674903999581438936L;
+ private static final long serialVersionUID = -3674903999581438936L;
}
diff --git a/src/main/java/net/onrc/onos/core/intent/runtime/PathCalcRuntime.java b/src/main/java/net/onrc/onos/core/intent/runtime/PathCalcRuntime.java
index 9314959..c582fe1 100644
--- a/src/main/java/net/onrc/onos/core/intent/runtime/PathCalcRuntime.java
+++ b/src/main/java/net/onrc/onos/core/intent/runtime/PathCalcRuntime.java
@@ -27,115 +27,116 @@
* @author Toshio Koide (t-koide@onlab.us)
*/
public class PathCalcRuntime implements IFloodlightService {
- private NetworkGraph graph;
- private final static Logger log = LoggerFactory.getLogger(PathCalcRuntime.class);
- public PathCalcRuntime(NetworkGraph g) {
- this.graph = g;
- }
+ private NetworkGraph graph;
+ private final static Logger log = LoggerFactory.getLogger(PathCalcRuntime.class);
- /**
- * calculate shortest-path and constrained-shortest-path intents into low-level path intents
- * @param intentOpList IntentOperationList having instances of ShortestPathIntent/ConstrainedShortestPathIntent
- * @param pathIntents a set of current low-level intents
- * @return IntentOperationList. PathIntent and/or ErrorIntent instances.
- */
- public IntentOperationList calcPathIntents(final IntentOperationList intentOpList, final IntentMap appIntents, final PathIntentMap pathIntents) {
- IntentOperationList pathIntentOpList = new IntentOperationList();
- HashMap<Switch, ConstrainedBFSTree> spfTrees = new HashMap<>();
+ public PathCalcRuntime(NetworkGraph g) {
+ this.graph = g;
+ }
- // TODO optimize locking of NetworkGraph
- graph.acquireReadLock();
- log.debug("NetworkGraph: {}", graph.getLinks());
+ /**
+ * calculate shortest-path and constrained-shortest-path intents into low-level path intents
+ *
+ * @param intentOpList IntentOperationList having instances of ShortestPathIntent/ConstrainedShortestPathIntent
+ * @param pathIntents a set of current low-level intents
+ * @return IntentOperationList. PathIntent and/or ErrorIntent instances.
+ */
+ public IntentOperationList calcPathIntents(final IntentOperationList intentOpList, final IntentMap appIntents, final PathIntentMap pathIntents) {
+ IntentOperationList pathIntentOpList = new IntentOperationList();
+ HashMap<Switch, ConstrainedBFSTree> spfTrees = new HashMap<>();
- for (IntentOperation intentOp: intentOpList) {
- switch (intentOp.operator) {
- case ADD:
- if (!(intentOp.intent instanceof ShortestPathIntent)) {
- log.error("Unsupported intent type: {}", intentOp.intent.getClass().getName());
- pathIntentOpList.add(Operator.ERROR, new ErrorIntent(
- ErrorType.UNSUPPORTED_INTENT,
- "Unsupported intent type.",
- intentOp.intent));
- continue;
- }
+ // TODO optimize locking of NetworkGraph
+ graph.acquireReadLock();
+ log.debug("NetworkGraph: {}", graph.getLinks());
- ShortestPathIntent spIntent = (ShortestPathIntent) intentOp.intent;
- Switch srcSwitch = graph.getSwitch(spIntent.getSrcSwitchDpid());
- Switch dstSwitch = graph.getSwitch(spIntent.getDstSwitchDpid());
- if (srcSwitch == null || dstSwitch == null) {
- log.error("Switch not found. src:{}, dst:{}, NetworkGraph:{}",
- spIntent.getSrcSwitchDpid(),
- spIntent.getDstSwitchDpid(),
- graph.getLinks());
- pathIntentOpList.add(Operator.ERROR, new ErrorIntent(
- ErrorType.SWITCH_NOT_FOUND,
- "Switch not found.",
- spIntent));
- continue;
- }
+ for (IntentOperation intentOp : intentOpList) {
+ switch (intentOp.operator) {
+ case ADD:
+ if (!(intentOp.intent instanceof ShortestPathIntent)) {
+ log.error("Unsupported intent type: {}", intentOp.intent.getClass().getName());
+ pathIntentOpList.add(Operator.ERROR, new ErrorIntent(
+ ErrorType.UNSUPPORTED_INTENT,
+ "Unsupported intent type.",
+ intentOp.intent));
+ continue;
+ }
- double bandwidth = 0.0;
- ConstrainedBFSTree tree = null;
- if (spIntent instanceof ConstrainedShortestPathIntent) {
- bandwidth = ((ConstrainedShortestPathIntent) intentOp.intent).getBandwidth();
- tree = new ConstrainedBFSTree(srcSwitch, pathIntents, bandwidth);
- }
- else {
- tree = spfTrees.get(srcSwitch);
- if (tree == null) {
- tree = new ConstrainedBFSTree(srcSwitch);
- spfTrees.put(srcSwitch, tree);
- }
- }
- Path path = tree.getPath(dstSwitch);
- if (path == null) {
- log.error("Path not found. Intent: {}, NetworkGraph:{}", spIntent.toString(), graph.getLinks());
- pathIntentOpList.add(Operator.ERROR, new ErrorIntent(
- ErrorType.PATH_NOT_FOUND,
- "Path not found.",
- spIntent));
- continue;
- }
+ ShortestPathIntent spIntent = (ShortestPathIntent) intentOp.intent;
+ Switch srcSwitch = graph.getSwitch(spIntent.getSrcSwitchDpid());
+ Switch dstSwitch = graph.getSwitch(spIntent.getDstSwitchDpid());
+ if (srcSwitch == null || dstSwitch == null) {
+ log.error("Switch not found. src:{}, dst:{}, NetworkGraph:{}",
+ spIntent.getSrcSwitchDpid(),
+ spIntent.getDstSwitchDpid(),
+ graph.getLinks());
+ pathIntentOpList.add(Operator.ERROR, new ErrorIntent(
+ ErrorType.SWITCH_NOT_FOUND,
+ "Switch not found.",
+ spIntent));
+ continue;
+ }
- // generate new path-intent ID
- String oldPathIntentId = spIntent.getPathIntentId();
- String newPathIntentId;
- if (oldPathIntentId == null)
- newPathIntentId = PathIntent.createFirstId(spIntent.getId());
- else {
- newPathIntentId = PathIntent.createNextId(oldPathIntentId);
+ double bandwidth = 0.0;
+ ConstrainedBFSTree tree = null;
+ if (spIntent instanceof ConstrainedShortestPathIntent) {
+ bandwidth = ((ConstrainedShortestPathIntent) intentOp.intent).getBandwidth();
+ tree = new ConstrainedBFSTree(srcSwitch, pathIntents, bandwidth);
+ } else {
+ tree = spfTrees.get(srcSwitch);
+ if (tree == null) {
+ tree = new ConstrainedBFSTree(srcSwitch);
+ spfTrees.put(srcSwitch, tree);
+ }
+ }
+ Path path = tree.getPath(dstSwitch);
+ if (path == null) {
+ log.error("Path not found. Intent: {}, NetworkGraph:{}", spIntent.toString(), graph.getLinks());
+ pathIntentOpList.add(Operator.ERROR, new ErrorIntent(
+ ErrorType.PATH_NOT_FOUND,
+ "Path not found.",
+ spIntent));
+ continue;
+ }
- // Request removal of low-level intent if it exists.
- pathIntentOpList.add(Operator.REMOVE, new Intent(oldPathIntentId));
- }
+ // generate new path-intent ID
+ String oldPathIntentId = spIntent.getPathIntentId();
+ String newPathIntentId;
+ if (oldPathIntentId == null)
+ newPathIntentId = PathIntent.createFirstId(spIntent.getId());
+ else {
+ newPathIntentId = PathIntent.createNextId(oldPathIntentId);
- // create new path-intent
- PathIntent pathIntent = new PathIntent(newPathIntentId, path, bandwidth, spIntent);
- pathIntent.setState(IntentState.INST_REQ);
- spIntent.setPathIntent(pathIntent);
- pathIntentOpList.add(Operator.ADD, pathIntent);
+ // Request removal of low-level intent if it exists.
+ pathIntentOpList.add(Operator.REMOVE, new Intent(oldPathIntentId));
+ }
- break;
- case REMOVE:
- ShortestPathIntent targetAppIntent = (ShortestPathIntent) appIntents.getIntent(intentOp.intent.getId());
- if (targetAppIntent != null) {
- String pathIntentId = targetAppIntent.getPathIntentId();
- if (pathIntentId != null) {
- Intent targetPathIntent = pathIntents.getIntent(pathIntentId);
- if (targetPathIntent != null) {
- pathIntentOpList.add(Operator.REMOVE, targetPathIntent);
- }
- }
- }
- break;
- case ERROR:
- // just ignore
- break;
- }
- }
- // TODO optimize locking of NetworkGraph
- graph.releaseReadLock();
+ // create new path-intent
+ PathIntent pathIntent = new PathIntent(newPathIntentId, path, bandwidth, spIntent);
+ pathIntent.setState(IntentState.INST_REQ);
+ spIntent.setPathIntent(pathIntent);
+ pathIntentOpList.add(Operator.ADD, pathIntent);
- return pathIntentOpList;
- }
+ break;
+ case REMOVE:
+ ShortestPathIntent targetAppIntent = (ShortestPathIntent) appIntents.getIntent(intentOp.intent.getId());
+ if (targetAppIntent != null) {
+ String pathIntentId = targetAppIntent.getPathIntentId();
+ if (pathIntentId != null) {
+ Intent targetPathIntent = pathIntents.getIntent(pathIntentId);
+ if (targetPathIntent != null) {
+ pathIntentOpList.add(Operator.REMOVE, targetPathIntent);
+ }
+ }
+ }
+ break;
+ case ERROR:
+ // just ignore
+ break;
+ }
+ }
+ // TODO optimize locking of NetworkGraph
+ graph.releaseReadLock();
+
+ return pathIntentOpList;
+ }
}
\ No newline at end of file
diff --git a/src/main/java/net/onrc/onos/core/intent/runtime/PathCalcRuntimeModule.java b/src/main/java/net/onrc/onos/core/intent/runtime/PathCalcRuntimeModule.java
index 8c219c2..bacb5a3 100755
--- a/src/main/java/net/onrc/onos/core/intent/runtime/PathCalcRuntimeModule.java
+++ b/src/main/java/net/onrc/onos/core/intent/runtime/PathCalcRuntimeModule.java
@@ -41,367 +41,365 @@
* @author Toshio Koide (t-koide@onlab.us)
*/
public class PathCalcRuntimeModule implements IFloodlightModule, IPathCalcRuntimeService, INetworkGraphListener, IEventChannelListener<Long, IntentStateList> {
- class PerfLog {
- private String step;
- private long time;
+ class PerfLog {
+ private String step;
+ private long time;
- public PerfLog(String step) {
- this.step = step;
- this.time = System.nanoTime();
- }
+ public PerfLog(String step) {
+ this.step = step;
+ this.time = System.nanoTime();
+ }
- public void logThis() {
- log.error("Time:{}, Step:{}", time, step);
- }
- }
- class PerfLogger {
- private LinkedList<PerfLog> logData = new LinkedList<>();
+ public void logThis() {
+ log.error("Time:{}, Step:{}", time, step);
+ }
+ }
- public PerfLogger(String logPhase) {
- log("start_" + logPhase);
- }
+ class PerfLogger {
+ private LinkedList<PerfLog> logData = new LinkedList<>();
- public void log(String step) {
- logData.add(new PerfLog(step));
- }
+ public PerfLogger(String logPhase) {
+ log("start_" + logPhase);
+ }
- public void flushLog() {
- log("finish");
- for (PerfLog log: logData) {
- log.logThis();
- }
- logData.clear();
- }
- }
- private PathCalcRuntime runtime;
- private IDatagridService datagridService;
- private INetworkGraphService networkGraphService;
- private IntentMap highLevelIntents;
- private PathIntentMap pathIntents;
- private IControllerRegistryService controllerRegistry;
- private PersistIntent persistIntent;
+ public void log(String step) {
+ logData.add(new PerfLog(step));
+ }
- private IEventChannel<Long, IntentOperationList> opEventChannel;
- private final ReentrantLock lock = new ReentrantLock();
- private HashSet<LinkEvent> unmatchedLinkEvents = new HashSet<>();
- private static final String INTENT_OP_EVENT_CHANNEL_NAME = "onos.pathintent";
- private static final String INTENT_STATE_EVENT_CHANNEL_NAME = "onos.pathintent_state";
- private static final Logger log = LoggerFactory.getLogger(PathCalcRuntimeModule.class);
+ public void flushLog() {
+ log("finish");
+ for (PerfLog log : logData) {
+ log.logThis();
+ }
+ logData.clear();
+ }
+ }
- // ================================================================================
- // private methods
- // ================================================================================
+ private PathCalcRuntime runtime;
+ private IDatagridService datagridService;
+ private INetworkGraphService networkGraphService;
+ private IntentMap highLevelIntents;
+ private PathIntentMap pathIntents;
+ private IControllerRegistryService controllerRegistry;
+ private PersistIntent persistIntent;
- private void reroutePaths(Collection<Intent> oldPaths) {
- if (oldPaths == null || oldPaths.isEmpty())
- return;
+ private IEventChannel<Long, IntentOperationList> opEventChannel;
+ private final ReentrantLock lock = new ReentrantLock();
+ private HashSet<LinkEvent> unmatchedLinkEvents = new HashSet<>();
+ private static final String INTENT_OP_EVENT_CHANNEL_NAME = "onos.pathintent";
+ private static final String INTENT_STATE_EVENT_CHANNEL_NAME = "onos.pathintent_state";
+ private static final Logger log = LoggerFactory.getLogger(PathCalcRuntimeModule.class);
- IntentOperationList reroutingOperation = new IntentOperationList();
- for (Intent intent : oldPaths) {
- PathIntent pathIntent = (PathIntent) intent;
- if (pathIntent.isPathFrozen())
- continue;
- if (pathIntent.getState().equals(IntentState.INST_ACK) && // XXX: path intents in flight
- !reroutingOperation.contains(pathIntent.getParentIntent())) {
- reroutingOperation.add(Operator.ADD, pathIntent.getParentIntent());
- }
- }
- executeIntentOperations(reroutingOperation);
- }
+ // ================================================================================
+ // private methods
+ // ================================================================================
+
+ private void reroutePaths(Collection<Intent> oldPaths) {
+ if (oldPaths == null || oldPaths.isEmpty())
+ return;
+
+ IntentOperationList reroutingOperation = new IntentOperationList();
+ for (Intent intent : oldPaths) {
+ PathIntent pathIntent = (PathIntent) intent;
+ if (pathIntent.isPathFrozen())
+ continue;
+ if (pathIntent.getState().equals(IntentState.INST_ACK) && // XXX: path intents in flight
+ !reroutingOperation.contains(pathIntent.getParentIntent())) {
+ reroutingOperation.add(Operator.ADD, pathIntent.getParentIntent());
+ }
+ }
+ executeIntentOperations(reroutingOperation);
+ }
- // ================================================================================
- // IFloodlightModule implementations
- // ================================================================================
+ // ================================================================================
+ // IFloodlightModule implementations
+ // ================================================================================
- @Override
- public Collection<Class<? extends IFloodlightService>> getModuleServices() {
- Collection<Class<? extends IFloodlightService>> l = new ArrayList<>(1);
- l.add(IPathCalcRuntimeService.class);
- return l;
- }
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleServices() {
+ Collection<Class<? extends IFloodlightService>> l = new ArrayList<>(1);
+ l.add(IPathCalcRuntimeService.class);
+ return l;
+ }
- @Override
- public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
- Map<Class<? extends IFloodlightService>, IFloodlightService> m = new HashMap<>();
- m.put(IPathCalcRuntimeService.class, this);
- return m;
- }
+ @Override
+ public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
+ Map<Class<? extends IFloodlightService>, IFloodlightService> m = new HashMap<>();
+ m.put(IPathCalcRuntimeService.class, this);
+ return m;
+ }
- @Override
- public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
- Collection<Class<? extends IFloodlightService>> l = new ArrayList<>(2);
- l.add(IDatagridService.class);
- l.add(INetworkGraphService.class);
- return l;
- }
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
+ Collection<Class<? extends IFloodlightService>> l = new ArrayList<>(2);
+ l.add(IDatagridService.class);
+ l.add(INetworkGraphService.class);
+ return l;
+ }
- @Override
- public void init(FloodlightModuleContext context) throws FloodlightModuleException {
- datagridService = context.getServiceImpl(IDatagridService.class);
- networkGraphService = context.getServiceImpl(INetworkGraphService.class);
- controllerRegistry = context.getServiceImpl(IControllerRegistryService.class);
- }
+ @Override
+ public void init(FloodlightModuleContext context) throws FloodlightModuleException {
+ datagridService = context.getServiceImpl(IDatagridService.class);
+ networkGraphService = context.getServiceImpl(INetworkGraphService.class);
+ controllerRegistry = context.getServiceImpl(IControllerRegistryService.class);
+ }
- @Override
- public void startUp(FloodlightModuleContext context) {
- highLevelIntents = new IntentMap();
- runtime = new PathCalcRuntime(networkGraphService.getNetworkGraph());
- pathIntents = new PathIntentMap();
- opEventChannel = datagridService.createChannel(INTENT_OP_EVENT_CHANNEL_NAME, Long.class, IntentOperationList.class);
- datagridService.addListener(INTENT_STATE_EVENT_CHANNEL_NAME, this, Long.class, IntentStateList.class);
- networkGraphService.registerNetworkGraphListener(this);
- persistIntent = new PersistIntent(controllerRegistry, networkGraphService);
- }
+ @Override
+ public void startUp(FloodlightModuleContext context) {
+ highLevelIntents = new IntentMap();
+ runtime = new PathCalcRuntime(networkGraphService.getNetworkGraph());
+ pathIntents = new PathIntentMap();
+ opEventChannel = datagridService.createChannel(INTENT_OP_EVENT_CHANNEL_NAME, Long.class, IntentOperationList.class);
+ datagridService.addListener(INTENT_STATE_EVENT_CHANNEL_NAME, this, Long.class, IntentStateList.class);
+ networkGraphService.registerNetworkGraphListener(this);
+ persistIntent = new PersistIntent(controllerRegistry, networkGraphService);
+ }
- // ================================================================================
- // IPathCalcRuntimeService implementations
- // ================================================================================
+ // ================================================================================
+ // IPathCalcRuntimeService implementations
+ // ================================================================================
- @Override
- public IntentOperationList executeIntentOperations(IntentOperationList list) {
- if (list == null || list.size() == 0)
- return null;
- PerfLogger p = new PerfLogger("executeIntentOperations_" + list.get(0).operator);
+ @Override
+ public IntentOperationList executeIntentOperations(IntentOperationList list) {
+ if (list == null || list.size() == 0)
+ return null;
+ PerfLogger p = new PerfLogger("executeIntentOperations_" + list.get(0).operator);
- lock.lock(); // TODO optimize locking using smaller steps
- try {
- // update the map of high-level intents
- p.log("begin_updateInMemoryIntents");
- highLevelIntents.executeOperations(list);
+ lock.lock(); // TODO optimize locking using smaller steps
+ try {
+ // update the map of high-level intents
+ p.log("begin_updateInMemoryIntents");
+ highLevelIntents.executeOperations(list);
- // change states of high-level intents
- IntentStateList states = new IntentStateList();
- for (IntentOperation op : list) {
- switch (op.operator) {
- case ADD:
- switch (op.intent.getState()) {
- case CREATED:
- states.put(op.intent.getId(), IntentState.INST_REQ);
- break;
- case INST_ACK:
- states.put(op.intent.getId(), IntentState.REROUTE_REQ);
- break;
- default:
- break;
- }
- break;
- case REMOVE:
- switch (op.intent.getState()) {
- case CREATED:
- states.put(op.intent.getId(), IntentState.DEL_REQ);
- break;
- default:
- break;
- }
- break;
- default:
- break;
- }
- }
- highLevelIntents.changeStates(states);
- p.log("end_updateInMemoryIntents");
+ // change states of high-level intents
+ IntentStateList states = new IntentStateList();
+ for (IntentOperation op : list) {
+ switch (op.operator) {
+ case ADD:
+ switch (op.intent.getState()) {
+ case CREATED:
+ states.put(op.intent.getId(), IntentState.INST_REQ);
+ break;
+ case INST_ACK:
+ states.put(op.intent.getId(), IntentState.REROUTE_REQ);
+ break;
+ default:
+ break;
+ }
+ break;
+ case REMOVE:
+ switch (op.intent.getState()) {
+ case CREATED:
+ states.put(op.intent.getId(), IntentState.DEL_REQ);
+ break;
+ default:
+ break;
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ highLevelIntents.changeStates(states);
+ p.log("end_updateInMemoryIntents");
- // calculate path-intents (low-level operations)
- p.log("begin_calcPathIntents");
- IntentOperationList pathIntentOperations = runtime.calcPathIntents(list, highLevelIntents, pathIntents);
- p.log("end_calcPathIntents");
+ // calculate path-intents (low-level operations)
+ p.log("begin_calcPathIntents");
+ IntentOperationList pathIntentOperations = runtime.calcPathIntents(list, highLevelIntents, pathIntents);
+ p.log("end_calcPathIntents");
- // persist calculated low-level operations into data store
- p.log("begin_persistPathIntents");
- long key = persistIntent.getKey();
- persistIntent.persistIfLeader(key, pathIntentOperations);
- p.log("end_persistPathIntents");
+ // persist calculated low-level operations into data store
+ p.log("begin_persistPathIntents");
+ long key = persistIntent.getKey();
+ persistIntent.persistIfLeader(key, pathIntentOperations);
+ p.log("end_persistPathIntents");
- // remove error-intents and reflect them to high-level intents
- p.log("begin_removeErrorIntents");
- states.clear();
- Iterator<IntentOperation> i = pathIntentOperations.iterator();
- while (i.hasNext()) {
- IntentOperation op = i.next();
- if (op.operator.equals(Operator.ERROR)) {
- states.put(op.intent.getId(), IntentState.INST_NACK);
- i.remove();
- }
- }
- highLevelIntents.changeStates(states);
- p.log("end_removeErrorIntents");
+ // remove error-intents and reflect them to high-level intents
+ p.log("begin_removeErrorIntents");
+ states.clear();
+ Iterator<IntentOperation> i = pathIntentOperations.iterator();
+ while (i.hasNext()) {
+ IntentOperation op = i.next();
+ if (op.operator.equals(Operator.ERROR)) {
+ states.put(op.intent.getId(), IntentState.INST_NACK);
+ i.remove();
+ }
+ }
+ highLevelIntents.changeStates(states);
+ p.log("end_removeErrorIntents");
- // update the map of path intents and publish the path operations
- p.log("begin_updateInMemoryPathIntents");
- pathIntents.executeOperations(pathIntentOperations);
- p.log("end_updateInMemoryPathIntents");
+ // update the map of path intents and publish the path operations
+ p.log("begin_updateInMemoryPathIntents");
+ pathIntents.executeOperations(pathIntentOperations);
+ p.log("end_updateInMemoryPathIntents");
- // XXX Demo special: add a complete path to remove operation
- p.log("begin_addPathToRemoveOperation");
- for (IntentOperation op: pathIntentOperations) {
- if(op.operator.equals(Operator.REMOVE)) {
- op.intent = pathIntents.getIntent(op.intent.getId());
- }
- if (op.intent instanceof PathIntent) {
- log.debug("operation: {}, intent:{}", op.operator, op.intent);
- }
- }
- p.log("end_addPathToRemoveOperation");
+ // XXX Demo special: add a complete path to remove operation
+ p.log("begin_addPathToRemoveOperation");
+ for (IntentOperation op : pathIntentOperations) {
+ if (op.operator.equals(Operator.REMOVE)) {
+ op.intent = pathIntents.getIntent(op.intent.getId());
+ }
+ if (op.intent instanceof PathIntent) {
+ log.debug("operation: {}, intent:{}", op.operator, op.intent);
+ }
+ }
+ p.log("end_addPathToRemoveOperation");
- // send notification
- p.log("begin_sendNotification");
- // XXX: Send notifications using the same key every time
- // and receive them by entryAdded() and entryUpdated()
- opEventChannel.addEntry(0L, pathIntentOperations);
- p.log("end_sendNotification");
- //opEventChannel.removeEntry(key);
- return pathIntentOperations;
- }
- finally {
- p.flushLog();
- lock.unlock();
- }
- }
+ // send notification
+ p.log("begin_sendNotification");
+ // XXX: Send notifications using the same key every time
+ // and receive them by entryAdded() and entryUpdated()
+ opEventChannel.addEntry(0L, pathIntentOperations);
+ p.log("end_sendNotification");
+ //opEventChannel.removeEntry(key);
+ return pathIntentOperations;
+ } finally {
+ p.flushLog();
+ lock.unlock();
+ }
+ }
- @Override
- public IntentMap getHighLevelIntents() {
- return highLevelIntents;
- }
+ @Override
+ public IntentMap getHighLevelIntents() {
+ return highLevelIntents;
+ }
- @Override
- public IntentMap getPathIntents() {
- return pathIntents;
- }
+ @Override
+ public IntentMap getPathIntents() {
+ return pathIntents;
+ }
- @Override
- public void purgeIntents() {
- highLevelIntents.purge();
- pathIntents.purge();
- }
+ @Override
+ public void purgeIntents() {
+ highLevelIntents.purge();
+ pathIntents.purge();
+ }
- // ================================================================================
- // INetworkGraphListener implementations
- // ================================================================================
+ // ================================================================================
+ // INetworkGraphListener implementations
+ // ================================================================================
- @Override
- public void networkGraphEvents(Collection<SwitchEvent> addedSwitchEvents,
- Collection<SwitchEvent> removedSwitchEvents,
- Collection<PortEvent> addedPortEvents,
- Collection<PortEvent> removedPortEvents,
- Collection<LinkEvent> addedLinkEvents,
- Collection<LinkEvent> removedLinkEvents,
- Collection<DeviceEvent> addedDeviceEvents,
- Collection<DeviceEvent> removedDeviceEvents) {
+ @Override
+ public void networkGraphEvents(Collection<SwitchEvent> addedSwitchEvents,
+ Collection<SwitchEvent> removedSwitchEvents,
+ Collection<PortEvent> addedPortEvents,
+ Collection<PortEvent> removedPortEvents,
+ Collection<LinkEvent> addedLinkEvents,
+ Collection<LinkEvent> removedLinkEvents,
+ Collection<DeviceEvent> addedDeviceEvents,
+ Collection<DeviceEvent> removedDeviceEvents) {
- PerfLogger p = new PerfLogger("networkGraphEvents");
- HashSet<Intent> affectedPaths = new HashSet<>();
+ PerfLogger p = new PerfLogger("networkGraphEvents");
+ HashSet<Intent> affectedPaths = new HashSet<>();
- boolean rerouteAll = false;
- for(LinkEvent le : addedLinkEvents) {
- LinkEvent rev = new LinkEvent(le.getDst().getDpid(), le.getDst().getNumber(), le.getSrc().getDpid(), le.getSrc().getNumber());
- if(unmatchedLinkEvents.contains(rev)) {
- rerouteAll = true;
- unmatchedLinkEvents.remove(rev);
- log.debug("Found matched LinkEvent: {} {}", rev, le);
- }
- else {
- unmatchedLinkEvents.add(le);
- log.debug("Adding unmatched LinkEvent: {}", le);
- }
- }
- for(LinkEvent le : removedLinkEvents) {
- if (unmatchedLinkEvents.contains(le)) {
- unmatchedLinkEvents.remove(le);
- log.debug("Removing LinkEvent: {}", le);
- }
- }
- if(unmatchedLinkEvents.size() > 0) {
- log.debug("Unmatched link events: {} events", unmatchedLinkEvents.size());
- }
+ boolean rerouteAll = false;
+ for (LinkEvent le : addedLinkEvents) {
+ LinkEvent rev = new LinkEvent(le.getDst().getDpid(), le.getDst().getNumber(), le.getSrc().getDpid(), le.getSrc().getNumber());
+ if (unmatchedLinkEvents.contains(rev)) {
+ rerouteAll = true;
+ unmatchedLinkEvents.remove(rev);
+ log.debug("Found matched LinkEvent: {} {}", rev, le);
+ } else {
+ unmatchedLinkEvents.add(le);
+ log.debug("Adding unmatched LinkEvent: {}", le);
+ }
+ }
+ for (LinkEvent le : removedLinkEvents) {
+ if (unmatchedLinkEvents.contains(le)) {
+ unmatchedLinkEvents.remove(le);
+ log.debug("Removing LinkEvent: {}", le);
+ }
+ }
+ if (unmatchedLinkEvents.size() > 0) {
+ log.debug("Unmatched link events: {} events", unmatchedLinkEvents.size());
+ }
- if ( rerouteAll ) {//addedLinkEvents.size() > 0) { // ||
-// addedPortEvents.size() > 0 ||
-// addedSwitchEvents.size() > 0) {
- p.log("begin_getAllIntents");
- affectedPaths.addAll(getPathIntents().getAllIntents());
- p.log("end_getAllIntents");
- }
- else if (removedSwitchEvents.size() > 0 ||
- removedLinkEvents.size() > 0 ||
- removedPortEvents.size() > 0) {
- p.log("begin_getIntentsByLink");
- for (LinkEvent linkEvent: removedLinkEvents)
- affectedPaths.addAll(pathIntents.getIntentsByLink(linkEvent));
- p.log("end_getIntentsByLink");
+ if (rerouteAll) {//addedLinkEvents.size() > 0) { // ||
+// addedPortEvents.size() > 0 ||
+// addedSwitchEvents.size() > 0) {
+ p.log("begin_getAllIntents");
+ affectedPaths.addAll(getPathIntents().getAllIntents());
+ p.log("end_getAllIntents");
+ } else if (removedSwitchEvents.size() > 0 ||
+ removedLinkEvents.size() > 0 ||
+ removedPortEvents.size() > 0) {
+ p.log("begin_getIntentsByLink");
+ for (LinkEvent linkEvent : removedLinkEvents)
+ affectedPaths.addAll(pathIntents.getIntentsByLink(linkEvent));
+ p.log("end_getIntentsByLink");
- p.log("begin_getIntentsByPort");
- for (PortEvent portEvent: removedPortEvents)
- affectedPaths.addAll(pathIntents.getIntentsByPort(portEvent.getDpid(), portEvent.getNumber()));
- p.log("end_getIntentsByPort");
+ p.log("begin_getIntentsByPort");
+ for (PortEvent portEvent : removedPortEvents)
+ affectedPaths.addAll(pathIntents.getIntentsByPort(portEvent.getDpid(), portEvent.getNumber()));
+ p.log("end_getIntentsByPort");
- p.log("begin_getIntentsByDpid");
- for (SwitchEvent switchEvent: removedSwitchEvents)
- affectedPaths.addAll(pathIntents.getIntentsByDpid(switchEvent.getDpid()));
- p.log("end_getIntentsByDpid");
- }
- p.log("begin_reroutePaths");
- reroutePaths(affectedPaths);
- p.log("end_reroutePaths");
- p.flushLog();
- }
+ p.log("begin_getIntentsByDpid");
+ for (SwitchEvent switchEvent : removedSwitchEvents)
+ affectedPaths.addAll(pathIntents.getIntentsByDpid(switchEvent.getDpid()));
+ p.log("end_getIntentsByDpid");
+ }
+ p.log("begin_reroutePaths");
+ reroutePaths(affectedPaths);
+ p.log("end_reroutePaths");
+ p.flushLog();
+ }
- // ================================================================================
- // IEventChannelListener implementations
- // ================================================================================
+ // ================================================================================
+ // IEventChannelListener implementations
+ // ================================================================================
- @Override
- public void entryAdded(IntentStateList value) {
- entryUpdated(value);
- }
+ @Override
+ public void entryAdded(IntentStateList value) {
+ entryUpdated(value);
+ }
- @Override
- public void entryRemoved(IntentStateList value) {
- // do nothing
- }
+ @Override
+ public void entryRemoved(IntentStateList value) {
+ // do nothing
+ }
- @Override
- public void entryUpdated(IntentStateList value) {
- // TODO draw state transition diagram in multiple ONOS instances and update this method
- PerfLogger p = new PerfLogger("entryUpdated");
- lock.lock(); // TODO optimize locking using smaller steps
- try {
- // reflect state changes of path-level intent into application-level intents
- p.log("begin_changeStateByNotification");
- IntentStateList highLevelIntentStates = new IntentStateList();
- IntentStateList pathIntentStates = new IntentStateList();
- for (Entry<String, IntentState> entry: value.entrySet()) {
- PathIntent pathIntent = (PathIntent) pathIntents.getIntent(entry.getKey());
- if (pathIntent == null) continue;
+ @Override
+ public void entryUpdated(IntentStateList value) {
+ // TODO draw state transition diagram in multiple ONOS instances and update this method
+ PerfLogger p = new PerfLogger("entryUpdated");
+ lock.lock(); // TODO optimize locking using smaller steps
+ try {
+ // reflect state changes of path-level intent into application-level intents
+ p.log("begin_changeStateByNotification");
+ IntentStateList highLevelIntentStates = new IntentStateList();
+ IntentStateList pathIntentStates = new IntentStateList();
+ for (Entry<String, IntentState> entry : value.entrySet()) {
+ PathIntent pathIntent = (PathIntent) pathIntents.getIntent(entry.getKey());
+ if (pathIntent == null) continue;
- Intent parentIntent = pathIntent.getParentIntent();
- if (parentIntent == null ||
- !(parentIntent instanceof ShortestPathIntent) ||
- !((ShortestPathIntent) parentIntent).getPathIntentId().equals(pathIntent.getId()))
- continue;
+ Intent parentIntent = pathIntent.getParentIntent();
+ if (parentIntent == null ||
+ !(parentIntent instanceof ShortestPathIntent) ||
+ !((ShortestPathIntent) parentIntent).getPathIntentId().equals(pathIntent.getId()))
+ continue;
- IntentState state = entry.getValue();
- switch (state) {
- //case INST_REQ:
- case INST_ACK:
- case INST_NACK:
- //case DEL_REQ:
- case DEL_ACK:
- case DEL_PENDING:
- highLevelIntentStates.put(parentIntent.getId(), state);
- pathIntentStates.put(entry.getKey(), entry.getValue());
- break;
- default:
- break;
- }
- }
- highLevelIntents.changeStates(highLevelIntentStates);
- pathIntents.changeStates(pathIntentStates);
- p.log("end_changeStateByNotification");
- }
- finally {
- p.flushLog();
- lock.unlock();
- }
- }
+ IntentState state = entry.getValue();
+ switch (state) {
+ //case INST_REQ:
+ case INST_ACK:
+ case INST_NACK:
+ //case DEL_REQ:
+ case DEL_ACK:
+ case DEL_PENDING:
+ highLevelIntentStates.put(parentIntent.getId(), state);
+ pathIntentStates.put(entry.getKey(), entry.getValue());
+ break;
+ default:
+ break;
+ }
+ }
+ highLevelIntents.changeStates(highLevelIntentStates);
+ pathIntents.changeStates(pathIntentStates);
+ p.log("end_changeStateByNotification");
+ } finally {
+ p.flushLog();
+ lock.unlock();
+ }
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/intent/runtime/PersistIntent.java b/src/main/java/net/onrc/onos/core/intent/runtime/PersistIntent.java
index 53be91c..e8c5dfc 100755
--- a/src/main/java/net/onrc/onos/core/intent/runtime/PersistIntent.java
+++ b/src/main/java/net/onrc/onos/core/intent/runtime/PersistIntent.java
@@ -28,7 +28,6 @@
import com.esotericsoftware.kryo.io.Output;
/**
- *
* @author nickkaranatsios
*/
public class PersistIntent {
@@ -90,7 +89,7 @@
ByteBuffer keyBytes = ByteBuffer.allocate(8).putLong(key);
byte[] buffer = stream.toByteArray();
int total = buffer.length;
- if ((total >= valueStoreLimit )) {
+ if ((total >= valueStoreLimit)) {
int writeCount = total / valueStoreLimit;
int remainder = total % valueStoreLimit;
int upperIndex = 0;
@@ -99,14 +98,14 @@
keyBytes.putLong(key);
keyBytes.flip();
upperIndex = (i * valueStoreLimit + valueStoreLimit) - 1;
- log.debug("writing using indexes {}:{}", (i*valueStoreLimit) ,upperIndex);
+ log.debug("writing using indexes {}:{}", (i * valueStoreLimit), upperIndex);
table.create(keyBytes.array(), Arrays.copyOfRange(buffer, i * valueStoreLimit, upperIndex));
}
if (remainder > 0) {
keyBytes.clear();
keyBytes.putLong(key);
keyBytes.flip();
- log.debug("writing using indexes {}:{}" ,upperIndex ,total);
+ log.debug("writing using indexes {}:{}", upperIndex, total);
table.create(keyBytes.array(), Arrays.copyOfRange(buffer, upperIndex + 1, total - 1));
}
} else {
diff --git a/src/main/java/net/onrc/onos/core/intent/runtime/PlanCalcRuntime.java b/src/main/java/net/onrc/onos/core/intent/runtime/PlanCalcRuntime.java
index 09e50f6..7ea3bab 100644
--- a/src/main/java/net/onrc/onos/core/intent/runtime/PlanCalcRuntime.java
+++ b/src/main/java/net/onrc/onos/core/intent/runtime/PlanCalcRuntime.java
@@ -25,130 +25,125 @@
import org.slf4j.LoggerFactory;
/**
- *
* @author Brian O'Connor <bocon@onlab.us>
- *
*/
public class PlanCalcRuntime {
-// NetworkGraph graph;
+ // NetworkGraph graph;
private final static Logger log = LoggerFactory.getLogger(PlanCalcRuntime.class);
public PlanCalcRuntime(/*NetworkGraph graph*/) {
-// this.graph = graph;
+// this.graph = graph;
}
public List<Set<FlowEntry>> computePlan(IntentOperationList intentOps) {
- long start = System.nanoTime();
- List<Collection<FlowEntry>> flowEntries = computeFlowEntries(intentOps);
- long step1 = System.nanoTime();
- List<Set<FlowEntry>> plan = buildPhases(flowEntries);
- long step2 = System.nanoTime();
- log.error("MEASUREMENT: Compute flow entries: {} ns, Build phases: {} ns",
- (step1 - start), (step2 - step1));
- return plan;
+ long start = System.nanoTime();
+ List<Collection<FlowEntry>> flowEntries = computeFlowEntries(intentOps);
+ long step1 = System.nanoTime();
+ List<Set<FlowEntry>> plan = buildPhases(flowEntries);
+ long step2 = System.nanoTime();
+ log.error("MEASUREMENT: Compute flow entries: {} ns, Build phases: {} ns",
+ (step1 - start), (step2 - step1));
+ return plan;
}
private List<Collection<FlowEntry>> computeFlowEntries(IntentOperationList intentOps) {
- List<Collection<FlowEntry>> flowEntries = new LinkedList<>();
- for(IntentOperation i : intentOps) {
- if(!(i.intent instanceof PathIntent)) {
- log.warn("Not a path intent: {}", i);
- continue;
- }
- PathIntent intent = (PathIntent) i.intent;
- Intent parent = intent.getParentIntent();
- long srcPort, dstPort;
- long lastDstSw = -1, lastDstPort = -1;
- MACAddress srcMac, dstMac;
- if(parent instanceof ShortestPathIntent) {
- ShortestPathIntent pathIntent = (ShortestPathIntent) parent;
-// Switch srcSwitch = graph.getSwitch(pathIntent.getSrcSwitchDpid());
-// srcPort = srcSwitch.getPort(pathIntent.getSrcPortNumber());
- srcPort = pathIntent.getSrcPortNumber();
- srcMac = MACAddress.valueOf(pathIntent.getSrcMac());
- dstMac = MACAddress.valueOf(pathIntent.getDstMac());
-// Switch dstSwitch = graph.getSwitch(pathIntent.getDstSwitchDpid());
- lastDstSw = pathIntent.getDstSwitchDpid();
-// lastDstPort = dstSwitch.getPort(pathIntent.getDstPortNumber());
- lastDstPort = pathIntent.getDstPortNumber();
- }
- else {
- log.warn("Unsupported Intent: {}", parent);
- continue;
- }
- List<FlowEntry> entries = new ArrayList<>();
- for(LinkEvent linkEvent : intent.getPath()) {
-// Link link = graph.getLink(linkEvent.getSrc().getDpid(),
-// linkEvent.getSrc().getNumber(),
-// linkEvent.getDst().getDpid(),
-// linkEvent.getDst().getNumber());
-// Switch sw = link.getSrcSwitch();
- long sw = linkEvent.getSrc().getDpid();
-// dstPort = link.getSrcPort();
- dstPort = linkEvent.getSrc().getNumber();
- FlowEntry fe = new FlowEntry(sw, srcPort, dstPort, srcMac, dstMac, i.operator);
- entries.add(fe);
-// srcPort = link.getDstPort();
- srcPort = linkEvent.getDst().getNumber();
- }
- if(lastDstSw >= 0 && lastDstPort >= 0) {
- //Switch sw = lastDstPort.getSwitch();
- long sw = lastDstSw;
- dstPort = lastDstPort;
- FlowEntry fe = new FlowEntry(sw, srcPort, dstPort, srcMac, dstMac, i.operator);
- entries.add(fe);
- }
- // install flow entries in reverse order
- Collections.reverse(entries);
- flowEntries.add(entries);
- }
- return flowEntries;
+ List<Collection<FlowEntry>> flowEntries = new LinkedList<>();
+ for (IntentOperation i : intentOps) {
+ if (!(i.intent instanceof PathIntent)) {
+ log.warn("Not a path intent: {}", i);
+ continue;
+ }
+ PathIntent intent = (PathIntent) i.intent;
+ Intent parent = intent.getParentIntent();
+ long srcPort, dstPort;
+ long lastDstSw = -1, lastDstPort = -1;
+ MACAddress srcMac, dstMac;
+ if (parent instanceof ShortestPathIntent) {
+ ShortestPathIntent pathIntent = (ShortestPathIntent) parent;
+// Switch srcSwitch = graph.getSwitch(pathIntent.getSrcSwitchDpid());
+// srcPort = srcSwitch.getPort(pathIntent.getSrcPortNumber());
+ srcPort = pathIntent.getSrcPortNumber();
+ srcMac = MACAddress.valueOf(pathIntent.getSrcMac());
+ dstMac = MACAddress.valueOf(pathIntent.getDstMac());
+// Switch dstSwitch = graph.getSwitch(pathIntent.getDstSwitchDpid());
+ lastDstSw = pathIntent.getDstSwitchDpid();
+// lastDstPort = dstSwitch.getPort(pathIntent.getDstPortNumber());
+ lastDstPort = pathIntent.getDstPortNumber();
+ } else {
+ log.warn("Unsupported Intent: {}", parent);
+ continue;
+ }
+ List<FlowEntry> entries = new ArrayList<>();
+ for (LinkEvent linkEvent : intent.getPath()) {
+// Link link = graph.getLink(linkEvent.getSrc().getDpid(),
+// linkEvent.getSrc().getNumber(),
+// linkEvent.getDst().getDpid(),
+// linkEvent.getDst().getNumber());
+// Switch sw = link.getSrcSwitch();
+ long sw = linkEvent.getSrc().getDpid();
+// dstPort = link.getSrcPort();
+ dstPort = linkEvent.getSrc().getNumber();
+ FlowEntry fe = new FlowEntry(sw, srcPort, dstPort, srcMac, dstMac, i.operator);
+ entries.add(fe);
+// srcPort = link.getDstPort();
+ srcPort = linkEvent.getDst().getNumber();
+ }
+ if (lastDstSw >= 0 && lastDstPort >= 0) {
+ //Switch sw = lastDstPort.getSwitch();
+ long sw = lastDstSw;
+ dstPort = lastDstPort;
+ FlowEntry fe = new FlowEntry(sw, srcPort, dstPort, srcMac, dstMac, i.operator);
+ entries.add(fe);
+ }
+ // install flow entries in reverse order
+ Collections.reverse(entries);
+ flowEntries.add(entries);
+ }
+ return flowEntries;
}
private List<Set<FlowEntry>> buildPhases(List<Collection<FlowEntry>> flowEntries) {
- Map<FlowEntry, Integer> map = new HashMap<>();
- List<Set<FlowEntry>> plan = new ArrayList<>();
- for(Collection<FlowEntry> c : flowEntries) {
- for(FlowEntry e : c) {
- Integer i = map.get(e);
- if(i == null) {
- i = Integer.valueOf(0);
- }
- switch(e.getOperator()) {
- case ADD:
- i += 1;
- break;
- case REMOVE:
- i -= 1;
- break;
- default:
- break;
- }
- map.put(e, i);
- // System.out.println(e + " " + e.getOperator());
- }
- }
+ Map<FlowEntry, Integer> map = new HashMap<>();
+ List<Set<FlowEntry>> plan = new ArrayList<>();
+ for (Collection<FlowEntry> c : flowEntries) {
+ for (FlowEntry e : c) {
+ Integer i = map.get(e);
+ if (i == null) {
+ i = Integer.valueOf(0);
+ }
+ switch (e.getOperator()) {
+ case ADD:
+ i += 1;
+ break;
+ case REMOVE:
+ i -= 1;
+ break;
+ default:
+ break;
+ }
+ map.put(e, i);
+ // System.out.println(e + " " + e.getOperator());
+ }
+ }
- // really simple first iteration of plan
- //TODO: optimize the map in phases
- Set<FlowEntry> phase = new HashSet<>();
- for(FlowEntry e : map.keySet()) {
- Integer i = map.get(e);
- if(i == 0) {
- continue;
- }
- else if(i > 0) {
- e.setOperator(Operator.ADD);
- }
- else if(i < 0) {
- e.setOperator(Operator.REMOVE);
- }
- phase.add(e);
- }
- plan.add(phase);
+ // really simple first iteration of plan
+ //TODO: optimize the map in phases
+ Set<FlowEntry> phase = new HashSet<>();
+ for (FlowEntry e : map.keySet()) {
+ Integer i = map.get(e);
+ if (i == 0) {
+ continue;
+ } else if (i > 0) {
+ e.setOperator(Operator.ADD);
+ } else if (i < 0) {
+ e.setOperator(Operator.REMOVE);
+ }
+ phase.add(e);
+ }
+ plan.add(phase);
- return plan;
+ return plan;
}
}
diff --git a/src/main/java/net/onrc/onos/core/intent/runtime/PlanInstallModule.java b/src/main/java/net/onrc/onos/core/intent/runtime/PlanInstallModule.java
index 102a754..b4904c1 100644
--- a/src/main/java/net/onrc/onos/core/intent/runtime/PlanInstallModule.java
+++ b/src/main/java/net/onrc/onos/core/intent/runtime/PlanInstallModule.java
@@ -45,154 +45,152 @@
@Override
public void init(FloodlightModuleContext context)
- throws FloodlightModuleException {
- floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
- networkGraph = context.getServiceImpl(INetworkGraphService.class);
- datagridService = context.getServiceImpl(IDatagridService.class);
- flowPusher = context.getServiceImpl(IFlowPusherService.class);
-// NetworkGraph graph = networkGraph.getNetworkGraph();
- planCalc = new PlanCalcRuntime();
- planInstall = new PlanInstallRuntime(floodlightProvider, flowPusher);
- eventListener = new EventListener();
+ throws FloodlightModuleException {
+ floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
+ networkGraph = context.getServiceImpl(INetworkGraphService.class);
+ datagridService = context.getServiceImpl(IDatagridService.class);
+ flowPusher = context.getServiceImpl(IFlowPusherService.class);
+// NetworkGraph graph = networkGraph.getNetworkGraph();
+ planCalc = new PlanCalcRuntime();
+ planInstall = new PlanInstallRuntime(floodlightProvider, flowPusher);
+ eventListener = new EventListener();
}
class EventListener extends Thread
- implements IEventChannelListener<Long, IntentOperationList> {
+ implements IEventChannelListener<Long, IntentOperationList> {
- private BlockingQueue<IntentOperationList> intentQueue = new LinkedBlockingQueue<>();
- private Long key = Long.valueOf(0);
+ private BlockingQueue<IntentOperationList> intentQueue = new LinkedBlockingQueue<>();
+ private Long key = Long.valueOf(0);
- @Override
- public void run() {
- while(true) {
- try {
- IntentOperationList intents = intentQueue.take();
- //TODO: consider draining the remaining intent lists
- // and processing in one big batch
-// List<IntentOperationList> remaining = new LinkedList<>();
-// intentQueue.drainTo(remaining);
+ @Override
+ public void run() {
+ while (true) {
+ try {
+ IntentOperationList intents = intentQueue.take();
+ //TODO: consider draining the remaining intent lists
+ // and processing in one big batch
+// List<IntentOperationList> remaining = new LinkedList<>();
+// intentQueue.drainTo(remaining);
- processIntents(intents);
- } catch (InterruptedException e) {
- log.warn("Error taking from intent queue: {}", e.getMessage());
- }
- }
- }
+ processIntents(intents);
+ } catch (InterruptedException e) {
+ log.warn("Error taking from intent queue: {}", e.getMessage());
+ }
+ }
+ }
- private void processIntents(IntentOperationList intents) {
- log("start_processIntents");
- log.debug("Processing OperationList {}", intents);
- log("begin_computePlan");
- List<Set<FlowEntry>> plan = planCalc.computePlan(intents);
- log("end_computePlan");
- log.debug("Plan: {}", plan);
- log("begin_installPlan");
- boolean success = planInstall.installPlan(plan);
- log("end_installPlan");
+ private void processIntents(IntentOperationList intents) {
+ log("start_processIntents");
+ log.debug("Processing OperationList {}", intents);
+ log("begin_computePlan");
+ List<Set<FlowEntry>> plan = planCalc.computePlan(intents);
+ log("end_computePlan");
+ log.debug("Plan: {}", plan);
+ log("begin_installPlan");
+ boolean success = planInstall.installPlan(plan);
+ log("end_installPlan");
- log("begin_sendInstallNotif");
- sendNotifications(intents, true, success);
- log("end_sendInstallNotif");
- log("finish");
- }
+ log("begin_sendInstallNotif");
+ sendNotifications(intents, true, success);
+ log("end_sendInstallNotif");
+ log("finish");
+ }
- private void sendNotifications(IntentOperationList intents, boolean installed, boolean success) {
- IntentStateList states = new IntentStateList();
- for(IntentOperation i : intents) {
- IntentState newState;
- switch(i.operator) {
- case REMOVE:
- if(installed) {
- newState = success ? IntentState.DEL_ACK : IntentState.DEL_PENDING;
- }
- else {
- newState = IntentState.DEL_REQ;
- }
- break;
- case ADD:
- default:
- if(installed) {
- newState = success ? IntentState.INST_ACK : IntentState.INST_NACK;
- }
- else {
- newState = IntentState.INST_REQ;
- }
- break;
- }
- states.put(i.intent.getId(), newState);
- }
- intentStateChannel.addEntry(key, states);
- // XXX: Send notifications using the same key every time
- // and receive them by entryAdded() and entryUpdated()
- // key += 1;
- }
+ private void sendNotifications(IntentOperationList intents, boolean installed, boolean success) {
+ IntentStateList states = new IntentStateList();
+ for (IntentOperation i : intents) {
+ IntentState newState;
+ switch (i.operator) {
+ case REMOVE:
+ if (installed) {
+ newState = success ? IntentState.DEL_ACK : IntentState.DEL_PENDING;
+ } else {
+ newState = IntentState.DEL_REQ;
+ }
+ break;
+ case ADD:
+ default:
+ if (installed) {
+ newState = success ? IntentState.INST_ACK : IntentState.INST_NACK;
+ } else {
+ newState = IntentState.INST_REQ;
+ }
+ break;
+ }
+ states.put(i.intent.getId(), newState);
+ }
+ intentStateChannel.addEntry(key, states);
+ // XXX: Send notifications using the same key every time
+ // and receive them by entryAdded() and entryUpdated()
+ // key += 1;
+ }
- @Override
- public void entryAdded(IntentOperationList value) {
- entryUpdated(value);
- }
+ @Override
+ public void entryAdded(IntentOperationList value) {
+ entryUpdated(value);
+ }
- @Override
- public void entryRemoved(IntentOperationList value) {
- // This channel is a queue, so this method is not needed
- }
+ @Override
+ public void entryRemoved(IntentOperationList value) {
+ // This channel is a queue, so this method is not needed
+ }
- @Override
- public void entryUpdated(IntentOperationList value) {
- log("start_intentNotifRecv");
- log("begin_sendReceivedNotif");
- sendNotifications(value, false, false);
- log("end_sendReceivedNotif");
- log("finish");
+ @Override
+ public void entryUpdated(IntentOperationList value) {
+ log("start_intentNotifRecv");
+ log("begin_sendReceivedNotif");
+ sendNotifications(value, false, false);
+ log("end_sendReceivedNotif");
+ log("finish");
- log.debug("Added OperationList {}", value);
- try {
- intentQueue.put(value);
- } catch (InterruptedException e) {
- log.warn("Error putting to intent queue: {}", e.getMessage());
- }
- }
+ log.debug("Added OperationList {}", value);
+ try {
+ intentQueue.put(value);
+ } catch (InterruptedException e) {
+ log.warn("Error putting to intent queue: {}", e.getMessage());
+ }
+ }
}
public static void log(String step) {
- log.error("Time:{}, Step:{}", System.nanoTime(), step);
+ log.error("Time:{}, Step:{}", System.nanoTime(), step);
}
@Override
public void startUp(FloodlightModuleContext context) {
- // start subscriber
- datagridService.addListener(PATH_INTENT_CHANNEL_NAME,
- eventListener,
- Long.class,
- IntentOperationList.class);
- eventListener.start();
- // start publisher
- intentStateChannel = datagridService.createChannel(INTENT_STATE_EVENT_CHANNEL_NAME,
- Long.class,
- IntentStateList.class);
+ // start subscriber
+ datagridService.addListener(PATH_INTENT_CHANNEL_NAME,
+ eventListener,
+ Long.class,
+ IntentOperationList.class);
+ eventListener.start();
+ // start publisher
+ intentStateChannel = datagridService.createChannel(INTENT_STATE_EVENT_CHANNEL_NAME,
+ Long.class,
+ IntentStateList.class);
}
@Override
public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
- Collection<Class<? extends IFloodlightService>> l =
- new ArrayList<Class<? extends IFloodlightService>>();
- l.add(IFloodlightProviderService.class);
- l.add(INetworkGraphService.class);
- l.add(IDatagridService.class);
- l.add(IFlowPusherService.class);
- return l;
+ Collection<Class<? extends IFloodlightService>> l =
+ new ArrayList<Class<? extends IFloodlightService>>();
+ l.add(IFloodlightProviderService.class);
+ l.add(INetworkGraphService.class);
+ l.add(IDatagridService.class);
+ l.add(IFlowPusherService.class);
+ return l;
}
@Override
public Collection<Class<? extends IFloodlightService>> getModuleServices() {
- // no services, for now
- return null;
+ // no services, for now
+ return null;
}
@Override
public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
- // no services, for now
- return null;
+ // no services, for now
+ return null;
}
}
diff --git a/src/main/java/net/onrc/onos/core/intent/runtime/PlanInstallRuntime.java b/src/main/java/net/onrc/onos/core/intent/runtime/PlanInstallRuntime.java
index 6d5c985..114e718 100644
--- a/src/main/java/net/onrc/onos/core/intent/runtime/PlanInstallRuntime.java
+++ b/src/main/java/net/onrc/onos/core/intent/runtime/PlanInstallRuntime.java
@@ -21,136 +21,137 @@
import org.slf4j.LoggerFactory;
/**
- *
* @author Brian O'Connor <bocon@onlab.us>
- *
*/
public class PlanInstallRuntime {
-// NetworkGraph graph;
+ // NetworkGraph graph;
IFlowPusherService pusher;
IFloodlightProviderService provider;
private final static Logger log = LoggerFactory.getLogger(PlanInstallRuntime.class);
public PlanInstallRuntime(//NetworkGraph graph,
- IFloodlightProviderService provider,
- IFlowPusherService pusher) {
-// this.graph = graph;
- this.provider = provider;
- this.pusher = pusher;
+ IFloodlightProviderService provider,
+ IFlowPusherService pusher) {
+// this.graph = graph;
+ this.provider = provider;
+ this.pusher = pusher;
}
-
+
private static class FlowModCount {
- IOFSwitch sw;
- long modFlows = 0;
- long delFlows = 0;
- long errors = 0;
-
- FlowModCount(IOFSwitch sw) {
- this.sw = sw;
- }
-
- void addFlowEntry(FlowEntry entry) {
- switch(entry.getOperator()){
- case ADD:
- modFlows++;
- break;
- case ERROR:
- errors++;
- break;
- case REMOVE:
- delFlows++;
- break;
- default:
- break;
- }
- }
-
- public String toString() {
- return "sw:" + sw.getStringId() + ": modify " + modFlows + " delete " + delFlows + " error " + errors;
- }
-
- static Map<IOFSwitch, FlowModCount> map = new HashMap<>();
- static void countFlowEntry(IOFSwitch sw, FlowEntry entry) {
- FlowModCount count = map.get(sw);
- if(count == null) {
- count = new FlowModCount(sw);
- map.put(sw, count);
- }
- count.addFlowEntry(entry);
- }
- static void startCount() {
- map.clear();
- }
- static void printCount() {
- String result = "FLOWMOD COUNT:\n";
- for(FlowModCount count : map.values()) {
- result += count.toString() + '\n';
- }
- if(map.values().isEmpty()) {
- result += "No flow mods installed\n";
- }
- log.error(result);
- }
+ IOFSwitch sw;
+ long modFlows = 0;
+ long delFlows = 0;
+ long errors = 0;
+
+ FlowModCount(IOFSwitch sw) {
+ this.sw = sw;
+ }
+
+ void addFlowEntry(FlowEntry entry) {
+ switch (entry.getOperator()) {
+ case ADD:
+ modFlows++;
+ break;
+ case ERROR:
+ errors++;
+ break;
+ case REMOVE:
+ delFlows++;
+ break;
+ default:
+ break;
+ }
+ }
+
+ public String toString() {
+ return "sw:" + sw.getStringId() + ": modify " + modFlows + " delete " + delFlows + " error " + errors;
+ }
+
+ static Map<IOFSwitch, FlowModCount> map = new HashMap<>();
+
+ static void countFlowEntry(IOFSwitch sw, FlowEntry entry) {
+ FlowModCount count = map.get(sw);
+ if (count == null) {
+ count = new FlowModCount(sw);
+ map.put(sw, count);
+ }
+ count.addFlowEntry(entry);
+ }
+
+ static void startCount() {
+ map.clear();
+ }
+
+ static void printCount() {
+ String result = "FLOWMOD COUNT:\n";
+ for (FlowModCount count : map.values()) {
+ result += count.toString() + '\n';
+ }
+ if (map.values().isEmpty()) {
+ result += "No flow mods installed\n";
+ }
+ log.error(result);
+ }
}
public boolean installPlan(List<Set<FlowEntry>> plan) {
- long start = System.nanoTime();
- Map<Long,IOFSwitch> switches = provider.getSwitches();
-
- log.debug("IOFSwitches: {}", switches);
-
- FlowModCount.startCount();
- for(Set<FlowEntry> phase : plan) {
- Set<Pair<IOFSwitch, net.onrc.onos.core.util.FlowEntry>> entries = new HashSet<>();
- Set<IOFSwitch> modifiedSwitches = new HashSet<>();
-
- long step1 = System.nanoTime();
- // convert flow entries and create pairs
- for(FlowEntry entry : phase) {
- IOFSwitch sw = switches.get(entry.getSwitch());
- if(sw == null) {
- // no active switch, skip this flow entry
- log.debug("Skipping flow entry: {}", entry);
- continue;
- }
- entries.add(new Pair<>(sw, entry.getFlowEntry()));
- modifiedSwitches.add(sw);
- FlowModCount.countFlowEntry(sw, entry);
- }
- long step2 = System.nanoTime();
-
- // push flow entries to switches
- log.debug("Pushing flow entries: {}", entries);
- pusher.pushFlowEntries(entries);
- long step3 = System.nanoTime();
-
- // TODO: insert a barrier after each phase on each modifiedSwitch
- // TODO: wait for confirmation messages before proceeding
- List<Pair<IOFSwitch,OFMessageFuture<OFBarrierReply>>> barriers = new ArrayList<>();
- for(IOFSwitch sw : modifiedSwitches) {
- barriers.add(new Pair<>(sw, pusher.barrierAsync(sw)));
- }
- for(Pair<IOFSwitch,OFMessageFuture<OFBarrierReply>> pair : barriers) {
- IOFSwitch sw = pair.first;
- OFMessageFuture<OFBarrierReply> future = pair.second;
- try {
- future.get();
- } catch (InterruptedException | ExecutionException e) {
- log.error("Barrier message not received for sw: {}", sw);
- }
- }
- long step4 = System.nanoTime();
- log.error("MEASUREMENT: convert: {} ns, push: {} ns, barrierWait: {} ns",
- step2 - step1, step3 - step2, step4 - step3);
+ long start = System.nanoTime();
+ Map<Long, IOFSwitch> switches = provider.getSwitches();
- }
- long end = System.nanoTime();
- log.error("MEASUREMENT: Install plan: {} ns", (end-start));
- FlowModCount.printCount();
-
- // TODO: we assume that the plan installation succeeds for now
- return true;
+ log.debug("IOFSwitches: {}", switches);
+
+ FlowModCount.startCount();
+ for (Set<FlowEntry> phase : plan) {
+ Set<Pair<IOFSwitch, net.onrc.onos.core.util.FlowEntry>> entries = new HashSet<>();
+ Set<IOFSwitch> modifiedSwitches = new HashSet<>();
+
+ long step1 = System.nanoTime();
+ // convert flow entries and create pairs
+ for (FlowEntry entry : phase) {
+ IOFSwitch sw = switches.get(entry.getSwitch());
+ if (sw == null) {
+ // no active switch, skip this flow entry
+ log.debug("Skipping flow entry: {}", entry);
+ continue;
+ }
+ entries.add(new Pair<>(sw, entry.getFlowEntry()));
+ modifiedSwitches.add(sw);
+ FlowModCount.countFlowEntry(sw, entry);
+ }
+ long step2 = System.nanoTime();
+
+ // push flow entries to switches
+ log.debug("Pushing flow entries: {}", entries);
+ pusher.pushFlowEntries(entries);
+ long step3 = System.nanoTime();
+
+ // TODO: insert a barrier after each phase on each modifiedSwitch
+ // TODO: wait for confirmation messages before proceeding
+ List<Pair<IOFSwitch, OFMessageFuture<OFBarrierReply>>> barriers = new ArrayList<>();
+ for (IOFSwitch sw : modifiedSwitches) {
+ barriers.add(new Pair<>(sw, pusher.barrierAsync(sw)));
+ }
+ for (Pair<IOFSwitch, OFMessageFuture<OFBarrierReply>> pair : barriers) {
+ IOFSwitch sw = pair.first;
+ OFMessageFuture<OFBarrierReply> future = pair.second;
+ try {
+ future.get();
+ } catch (InterruptedException | ExecutionException e) {
+ log.error("Barrier message not received for sw: {}", sw);
+ }
+ }
+ long step4 = System.nanoTime();
+ log.error("MEASUREMENT: convert: {} ns, push: {} ns, barrierWait: {} ns",
+ step2 - step1, step3 - step2, step4 - step3);
+
+ }
+ long end = System.nanoTime();
+ log.error("MEASUREMENT: Install plan: {} ns", (end - start));
+ FlowModCount.printCount();
+
+ // TODO: we assume that the plan installation succeeds for now
+ return true;
}
}
diff --git a/src/main/java/net/onrc/onos/core/linkdiscovery/ILinkDiscovery.java b/src/main/java/net/onrc/onos/core/linkdiscovery/ILinkDiscovery.java
index ba35850..bfc19d2 100644
--- a/src/main/java/net/onrc/onos/core/linkdiscovery/ILinkDiscovery.java
+++ b/src/main/java/net/onrc/onos/core/linkdiscovery/ILinkDiscovery.java
@@ -8,28 +8,29 @@
public interface ILinkDiscovery {
- @JsonSerialize(using=ToStringSerializer.class)
+ @JsonSerialize(using = ToStringSerializer.class)
public enum UpdateOperation {
- LINK_ADDED("Link Added"), // Operation Added by ONOS
+ LINK_ADDED("Link Added"), // Operation Added by ONOS
LINK_UPDATED("Link Updated"),
LINK_REMOVED("Link Removed"),
SWITCH_UPDATED("Switch Updated"),
SWITCH_REMOVED("Switch Removed"),
PORT_UP("Port Up"),
PORT_DOWN("Port Down");
-
+
private String value;
+
UpdateOperation(String v) {
value = v;
}
-
+
@Override
public String toString() {
return value;
}
}
- public class LDUpdate implements IUpdate{
+ public class LDUpdate implements IUpdate {
protected long src;
protected short srcPort;
protected long dst;
@@ -39,9 +40,9 @@
protected UpdateOperation operation;
public LDUpdate(long src, short srcPort,
- long dst, short dstPort,
- ILinkDiscovery.LinkType type,
- UpdateOperation operation) {
+ long dst, short dstPort,
+ ILinkDiscovery.LinkType type,
+ UpdateOperation operation) {
this.src = src;
this.srcPort = srcPort;
this.dst = dst;
@@ -61,7 +62,7 @@
}
// For updtedSwitch(sw)
- public LDUpdate(long switchId, SwitchType stype, UpdateOperation oper ){
+ public LDUpdate(long switchId, SwitchType stype, UpdateOperation oper) {
this.operation = oper;
this.src = switchId;
this.srcType = stype;
@@ -105,68 +106,69 @@
public void setOperation(UpdateOperation operation) {
this.operation = operation;
}
-
+
@Override
public String toString() {
switch (operation) {
- case LINK_ADDED:
- case LINK_REMOVED:
- case LINK_UPDATED:
- return "LDUpdate [operation=" + operation +
- ", src=" + HexString.toHexString(src)
- + ", srcPort=" + srcPort
- + ", dst=" + HexString.toHexString(dst)
- + ", dstPort=" + dstPort
- + ", type=" + type + "]";
- case PORT_DOWN:
- case PORT_UP:
- return "LDUpdate [operation=" + operation +
- ", src=" + HexString.toHexString(src)
- + ", srcPort=" + srcPort + "]";
- case SWITCH_REMOVED:
- case SWITCH_UPDATED:
- return "LDUpdate [operation=" + operation +
- ", src=" + HexString.toHexString(src) + "]";
- default:
- return "LDUpdate: Unknown update.";
+ case LINK_ADDED:
+ case LINK_REMOVED:
+ case LINK_UPDATED:
+ return "LDUpdate [operation=" + operation +
+ ", src=" + HexString.toHexString(src)
+ + ", srcPort=" + srcPort
+ + ", dst=" + HexString.toHexString(dst)
+ + ", dstPort=" + dstPort
+ + ", type=" + type + "]";
+ case PORT_DOWN:
+ case PORT_UP:
+ return "LDUpdate [operation=" + operation +
+ ", src=" + HexString.toHexString(src)
+ + ", srcPort=" + srcPort + "]";
+ case SWITCH_REMOVED:
+ case SWITCH_UPDATED:
+ return "LDUpdate [operation=" + operation +
+ ", src=" + HexString.toHexString(src) + "]";
+ default:
+ return "LDUpdate: Unknown update.";
}
}
- @Override
- public void dispatch() {
- // TODO Auto-generated method stub
-
- }
+ @Override
+ public void dispatch() {
+ // TODO Auto-generated method stub
+
+ }
}
public enum SwitchType {
- BASIC_SWITCH, CORE_SWITCH
- };
+ BASIC_SWITCH,
+ CORE_SWITCH
+ }
public enum LinkType {
INVALID_LINK {
- @Override
- public String toString() {
- return "invalid";
- }
- },
- DIRECT_LINK{
- @Override
- public String toString() {
- return "internal";
- }
- },
+ @Override
+ public String toString() {
+ return "invalid";
+ }
+ },
+ DIRECT_LINK {
+ @Override
+ public String toString() {
+ return "internal";
+ }
+ },
MULTIHOP_LINK {
- @Override
- public String toString() {
- return "external";
- }
- },
+ @Override
+ public String toString() {
+ return "external";
+ }
+ },
TUNNEL {
- @Override
- public String toString() {
- return "tunnel";
- }
+ @Override
+ public String toString() {
+ return "tunnel";
+ }
}
- };
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/linkdiscovery/ILinkDiscoveryListener.java b/src/main/java/net/onrc/onos/core/linkdiscovery/ILinkDiscoveryListener.java
index 53721d8..9b237c4 100644
--- a/src/main/java/net/onrc/onos/core/linkdiscovery/ILinkDiscoveryListener.java
+++ b/src/main/java/net/onrc/onos/core/linkdiscovery/ILinkDiscoveryListener.java
@@ -1,7 +1,7 @@
/**
* Copyright 2011, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
@@ -17,7 +17,7 @@
package net.onrc.onos.core.linkdiscovery;
-public interface ILinkDiscoveryListener extends ILinkDiscovery{
+public interface ILinkDiscoveryListener extends ILinkDiscovery {
public void linkDiscoveryUpdate(LDUpdate update);
}
diff --git a/src/main/java/net/onrc/onos/core/linkdiscovery/ILinkDiscoveryService.java b/src/main/java/net/onrc/onos/core/linkdiscovery/ILinkDiscoveryService.java
index 6d41532..dce8be0 100644
--- a/src/main/java/net/onrc/onos/core/linkdiscovery/ILinkDiscoveryService.java
+++ b/src/main/java/net/onrc/onos/core/linkdiscovery/ILinkDiscoveryService.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.linkdiscovery;
@@ -32,19 +32,21 @@
/**
* Returns link type of a given link
+ *
* @param info
* @return
*/
public ILinkDiscovery.LinkType getLinkType(Link lt, LinkInfo info);
/**
- * Returns an unmodifiable map from switch id to a set of all links with it
+ * Returns an unmodifiable map from switch id to a set of all links with it
* as an endpoint.
*/
public Map<Long, Set<Link>> getSwitchLinks();
/**
* Adds a listener to listen for ILinkDiscoveryService messages
+ *
* @param listener The listener that wants the notifications
*/
public void addListener(ILinkDiscoveryListener listener);
@@ -76,6 +78,7 @@
/**
* Set the state for auto port fast feature.
+ *
* @param autoPortFastFeature
*/
public void setAutoPortFastFeature(boolean autoPortFastFeature);
diff --git a/src/main/java/net/onrc/onos/core/linkdiscovery/Link.java b/src/main/java/net/onrc/onos/core/linkdiscovery/Link.java
index eb43304..254cc24 100755
--- a/src/main/java/net/onrc/onos/core/linkdiscovery/Link.java
+++ b/src/main/java/net/onrc/onos/core/linkdiscovery/Link.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.linkdiscovery;
@@ -47,24 +47,25 @@
}
@JsonProperty("src-switch")
- @JsonSerialize(using=DPIDSerializer.class)
+ @JsonSerialize(using = DPIDSerializer.class)
public long getSrc() {
return src;
}
@JsonProperty("src-port")
- @JsonSerialize(using=UShortSerializer.class)
+ @JsonSerialize(using = UShortSerializer.class)
public short getSrcPort() {
return srcPort;
}
@JsonProperty("dst-switch")
- @JsonSerialize(using=DPIDSerializer.class)
+ @JsonSerialize(using = DPIDSerializer.class)
public long getDst() {
return dst;
}
+
@JsonProperty("dst-port")
- @JsonSerialize(using=UShortSerializer.class)
+ @JsonSerialize(using = UShortSerializer.class)
public short getDstPort() {
return dstPort;
}
@@ -103,7 +104,7 @@
@Override
public String toString() {
- return "Link [src=" + HexString.toHexString(this.src)
+ return "Link [src=" + HexString.toHexString(this.src)
+ " outPort="
+ (srcPort & 0xffff)
+ ", dst=" + HexString.toHexString(this.dst)
@@ -111,12 +112,12 @@
+ (dstPort & 0xffff)
+ "]";
}
-
+
public String toKeyString() {
- return (HexString.toHexString(this.src) + "|" +
- (this.srcPort & 0xffff) + "|" +
- HexString.toHexString(this.dst) + "|" +
- (this.dstPort & 0xffff) );
+ return (HexString.toHexString(this.src) + "|" +
+ (this.srcPort & 0xffff) + "|" +
+ HexString.toHexString(this.dst) + "|" +
+ (this.dstPort & 0xffff));
}
}
diff --git a/src/main/java/net/onrc/onos/core/linkdiscovery/LinkInfo.java b/src/main/java/net/onrc/onos/core/linkdiscovery/LinkInfo.java
index 831c63b..89e9a19 100644
--- a/src/main/java/net/onrc/onos/core/linkdiscovery/LinkInfo.java
+++ b/src/main/java/net/onrc/onos/core/linkdiscovery/LinkInfo.java
@@ -1,17 +1,17 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.* Originally created by David Erickson, Stanford University
-** Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.* Originally created by David Erickson, Stanford University
+ ** Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.linkdiscovery;
@@ -40,7 +40,8 @@
protected Long lastLldpReceivedTime; /* Standard LLLDP received time */
protected Long lastBddpReceivedTime; /* Modified LLDP received time */
- /** The port states stored here are topology's last knowledge of
+ /**
+ * The port states stored here are topology's last knowledge of
* the state of the port. This mostly mirrors the state
* maintained in the port list in IOFSwitch (i.e. the one returned
* from getPort), except that during a port status message the
@@ -51,10 +52,9 @@
*/
-
public boolean linkStpBlocked() {
return ((srcPortState & OFPortState.OFPPS_STP_MASK.getValue()) == OFPortState.OFPPS_STP_BLOCK.getValue()) ||
- ((dstPortState & OFPortState.OFPPS_STP_MASK.getValue()) == OFPortState.OFPPS_STP_BLOCK.getValue());
+ ((dstPortState & OFPortState.OFPPS_STP_MASK.getValue()) == OFPortState.OFPPS_STP_BLOCK.getValue());
}
public Long getFirstSeenTime() {
diff --git a/src/main/java/net/onrc/onos/core/linkdiscovery/NodePortTuple.java b/src/main/java/net/onrc/onos/core/linkdiscovery/NodePortTuple.java
index 8d7ba19..6e5e0c3 100644
--- a/src/main/java/net/onrc/onos/core/linkdiscovery/NodePortTuple.java
+++ b/src/main/java/net/onrc/onos/core/linkdiscovery/NodePortTuple.java
@@ -11,6 +11,7 @@
* A NodePortTuple is similar to a SwitchPortTuple
* but it only stores IDs instead of references
* to the actual objects.
+ *
* @author srini
*/
public class NodePortTuple {
@@ -19,6 +20,7 @@
/**
* Creates a NodePortTuple
+ *
* @param nodeId The DPID of the switch
* @param portId The port of the switch
*/
@@ -33,22 +35,25 @@
}
@JsonProperty("switch")
- @JsonSerialize(using=DPIDSerializer.class)
+ @JsonSerialize(using = DPIDSerializer.class)
public long getNodeId() {
return nodeId;
}
+
public void setNodeId(long nodeId) {
this.nodeId = nodeId;
}
+
@JsonProperty("port")
- @JsonSerialize(using=UShortSerializer.class)
+ @JsonSerialize(using = UShortSerializer.class)
public short getPortId() {
return portId;
}
+
public void setPortId(short portId) {
this.portId = portId;
}
-
+
public String toString() {
return "[id=" + HexString.toHexString(nodeId) + ", port=" + new Short(portId) + "]";
}
@@ -77,14 +82,15 @@
return false;
return true;
}
-
+
/**
* API to return a String value formed wtih NodeID and PortID
* The portID is a 16-bit field, so mask it as an integer to get full
* positive value
+ *
* @return
*/
public String toKeyString() {
- return (HexString.toHexString(nodeId)+ "|" + (portId & 0xffff));
+ return (HexString.toHexString(nodeId) + "|" + (portId & 0xffff));
}
}
diff --git a/src/main/java/net/onrc/onos/core/linkdiscovery/internal/EventHistoryTopologyCluster.java b/src/main/java/net/onrc/onos/core/linkdiscovery/internal/EventHistoryTopologyCluster.java
index 172714c..c92e02e 100644
--- a/src/main/java/net/onrc/onos/core/linkdiscovery/internal/EventHistoryTopologyCluster.java
+++ b/src/main/java/net/onrc/onos/core/linkdiscovery/internal/EventHistoryTopologyCluster.java
@@ -5,39 +5,42 @@
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;
-/***
+/**
* Topology Cluster merge/split event history related classes and members
- * @author subrata
*
+ * @author subrata
*/
public class EventHistoryTopologyCluster {
// The following fields are not stored as String to save memory
// They should be converted to appropriate human-readable strings by
// the front end (e.g. in cli in Python)
- public long dpid;
- public long clusterIdOld; // Switch with dpid moved from cluster x to y
- public long clusterIdNew;
- public String reason;
-
+ public long dpid;
+ public long clusterIdOld; // Switch with dpid moved from cluster x to y
+ public long clusterIdNew;
+ public String reason;
+
@JsonProperty("Switch")
- @JsonSerialize(using=DPIDSerializer.class)
+ @JsonSerialize(using = DPIDSerializer.class)
public long getDpid() {
return dpid;
}
+
@JsonProperty("OldClusterId")
- @JsonSerialize(using=DPIDSerializer.class)
+ @JsonSerialize(using = DPIDSerializer.class)
public long getClusterIdOld() {
return clusterIdOld;
}
+
@JsonProperty("NewClusterId")
- @JsonSerialize(using=DPIDSerializer.class)
+ @JsonSerialize(using = DPIDSerializer.class)
public long getClusterIdNew() {
return clusterIdNew;
}
+
@JsonProperty("Reason")
public String getReason() {
return reason;
}
-
-
+
+
}
diff --git a/src/main/java/net/onrc/onos/core/linkdiscovery/internal/EventHistoryTopologyLink.java b/src/main/java/net/onrc/onos/core/linkdiscovery/internal/EventHistoryTopologyLink.java
index 378859f..9f9bed9 100644
--- a/src/main/java/net/onrc/onos/core/linkdiscovery/internal/EventHistoryTopologyLink.java
+++ b/src/main/java/net/onrc/onos/core/linkdiscovery/internal/EventHistoryTopologyLink.java
@@ -5,58 +5,65 @@
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;
-/***
+/**
* Topology link up/down event history related classes and members
- * @author subrata
*
+ * @author subrata
*/
public class EventHistoryTopologyLink {
// The following fields are not stored as String to save memory
// They should be converted to appropriate human-readable strings by
// the front end (e.g. in cli in Python)
- public long srcSwDpid;
- public long dstSwDpid;
- public int srcPortState;
- public int dstPortState;
- public int srcSwport;
- public int dstSwport;
- public String linkType;
- public String reason;
-
+ public long srcSwDpid;
+ public long dstSwDpid;
+ public int srcPortState;
+ public int dstPortState;
+ public int srcSwport;
+ public int dstSwport;
+ public String linkType;
+ public String reason;
+
@JsonProperty("Source-Switch")
- @JsonSerialize(using=DPIDSerializer.class)
+ @JsonSerialize(using = DPIDSerializer.class)
public long getSrcSwDpid() {
return srcSwDpid;
}
+
@JsonProperty("Dest-Switch")
- @JsonSerialize(using=DPIDSerializer.class)
+ @JsonSerialize(using = DPIDSerializer.class)
public long getDstSwDpid() {
return dstSwDpid;
}
+
@JsonProperty("SrcPortState")
public int getSrcPortState() {
return srcPortState;
}
+
@JsonProperty("DstPortState")
public int getDstPortState() {
return dstPortState;
}
+
@JsonProperty("SrcPort")
public int getSrcSwport() {
return srcSwport;
}
+
@JsonProperty("DstPort")
public int getDstSwport() {
return dstSwport;
}
+
@JsonProperty("LinkType")
public String getLinkType() {
return linkType;
}
+
@JsonProperty("Reason")
public String getReason() {
return reason;
}
-
-
+
+
}
diff --git a/src/main/java/net/onrc/onos/core/linkdiscovery/internal/EventHistoryTopologySwitch.java b/src/main/java/net/onrc/onos/core/linkdiscovery/internal/EventHistoryTopologySwitch.java
index b659be7..4d77f76 100644
--- a/src/main/java/net/onrc/onos/core/linkdiscovery/internal/EventHistoryTopologySwitch.java
+++ b/src/main/java/net/onrc/onos/core/linkdiscovery/internal/EventHistoryTopologySwitch.java
@@ -6,38 +6,41 @@
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;
-/***
+/**
* Topology Switch event history related classes and members
- * @author subrata
*
+ * @author subrata
*/
public class EventHistoryTopologySwitch {
// The following fields are not stored as String to save memory
// They should be converted to appropriate human-readable strings by
// the front end (e.g. in cli in Python)
- public long dpid;
- public int ipv4Addr;
- public int l4Port;
- public String reason;
-
+ public long dpid;
+ public int ipv4Addr;
+ public int l4Port;
+ public String reason;
+
@JsonProperty("Switch")
- @JsonSerialize(using=DPIDSerializer.class)
+ @JsonSerialize(using = DPIDSerializer.class)
public long getDpid() {
return dpid;
}
+
@JsonProperty("IpAddr")
- @JsonSerialize(using=IPv4Serializer.class)
+ @JsonSerialize(using = IPv4Serializer.class)
public int getIpv4Addr() {
return ipv4Addr;
}
+
@JsonProperty("Port")
public int getL4Port() {
return l4Port;
}
+
@JsonProperty("Reason")
public String getReason() {
return reason;
}
-
-
+
+
}
diff --git a/src/main/java/net/onrc/onos/core/linkdiscovery/internal/LinkDiscoveryManager.java b/src/main/java/net/onrc/onos/core/linkdiscovery/internal/LinkDiscoveryManager.java
index daed20b..a395ab6 100644
--- a/src/main/java/net/onrc/onos/core/linkdiscovery/internal/LinkDiscoveryManager.java
+++ b/src/main/java/net/onrc/onos/core/linkdiscovery/internal/LinkDiscoveryManager.java
@@ -95,26 +95,26 @@
* match a known switch cause a new LinkTuple to be created according to the
* invariant rules listed below. This new LinkTuple is also passed to routing
* if it exists to trigger updates.
- *
+ * <p/>
* This class also handles removing links that are associated to switch ports
* that go down, and switches that are disconnected.
- *
+ * <p/>
* Invariants:
- * -portLinks and switchLinks will not contain empty Sets outside of
- * critical sections
- * -portLinks contains LinkTuples where one of the src or dst
- * SwitchPortTuple matches the map key
- * -switchLinks contains LinkTuples where one of the src or dst
- * SwitchPortTuple's id matches the switch id
- * -Each LinkTuple will be indexed into switchLinks for both
- * src.id and dst.id, and portLinks for each src and dst
- * -The updates queue is only added to from within a held write lock
+ * -portLinks and switchLinks will not contain empty Sets outside of
+ * critical sections
+ * -portLinks contains LinkTuples where one of the src or dst
+ * SwitchPortTuple matches the map key
+ * -switchLinks contains LinkTuples where one of the src or dst
+ * SwitchPortTuple's id matches the switch id
+ * -Each LinkTuple will be indexed into switchLinks for both
+ * src.id and dst.id, and portLinks for each src and dst
+ * -The updates queue is only added to from within a held write lock
*/
@LogMessageCategory("Network Topology")
public class LinkDiscoveryManager
-implements IOFMessageListener, IOFSwitchListener,
-ILinkDiscoveryService, IFloodlightModule {
- protected IFloodlightProviderService controller;
+ implements IOFMessageListener, IOFSwitchListener,
+ ILinkDiscoveryService, IFloodlightModule {
+ protected IFloodlightProviderService controller;
protected final static Logger log = LoggerFactory.getLogger(LinkDiscoveryManager.class);
protected IFloodlightProviderService floodlightProvider;
@@ -127,7 +127,7 @@
// LLDP and BDDP fields
private static final byte[] LLDP_STANDARD_DST_MAC_STRING =
HexString.fromHexString("01:80:c2:00:00:0e");
- private static final long LINK_LOCAL_MASK = 0xfffffffffff0L;
+ private static final long LINK_LOCAL_MASK = 0xfffffffffff0L;
private static final long LINK_LOCAL_VALUE = 0x0180c2000000L;
// BigSwitch OUI is 5C:16:C7, so 5D:16:C7 is the multicast version
@@ -142,27 +142,27 @@
private static final byte TLV_DIRECTION_VALUE_FORWARD[] = {0x01};
private static final byte TLV_DIRECTION_VALUE_REVERSE[] = {0x02};
private static final LLDPTLV forwardTLV
- = new LLDPTLV().
- setType(TLV_DIRECTION_TYPE).
- setLength(TLV_DIRECTION_LENGTH).
- setValue(TLV_DIRECTION_VALUE_FORWARD);
+ = new LLDPTLV().
+ setType(TLV_DIRECTION_TYPE).
+ setLength(TLV_DIRECTION_LENGTH).
+ setValue(TLV_DIRECTION_VALUE_FORWARD);
private static final LLDPTLV reverseTLV
- = new LLDPTLV().
- setType(TLV_DIRECTION_TYPE).
- setLength(TLV_DIRECTION_LENGTH).
- setValue(TLV_DIRECTION_VALUE_REVERSE);
+ = new LLDPTLV().
+ setType(TLV_DIRECTION_TYPE).
+ setLength(TLV_DIRECTION_LENGTH).
+ setValue(TLV_DIRECTION_VALUE_REVERSE);
// Link discovery task details.
protected SingletonTask discoveryTask;
protected final int DISCOVERY_TASK_INTERVAL = 1;
protected final int LINK_TIMEOUT = 35; // original 35 secs, aggressive 5 secs
- protected final int LLDP_TO_ALL_INTERVAL = 15 ; //original 15 seconds, aggressive 2 secs.
+ protected final int LLDP_TO_ALL_INTERVAL = 15; //original 15 seconds, aggressive 2 secs.
protected long lldpClock = 0;
// This value is intentionally kept higher than LLDP_TO_ALL_INTERVAL.
// If we want to identify link failures faster, we could decrease this
// value to a small number, say 1 or 2 sec.
- protected final int LLDP_TO_KNOWN_INTERVAL= 20; // LLDP frequency for known links
+ protected final int LLDP_TO_KNOWN_INTERVAL = 20; // LLDP frequency for known links
protected LLDPTLV controllerTLV;
protected ReentrantReadWriteLock lock;
@@ -209,34 +209,34 @@
protected class LinkUpdate extends LDUpdate {
- public LinkUpdate(LDUpdate old) {
- super(old);
- }
- @LogMessageDoc(level="ERROR",
- message="Error in link discovery updates loop",
- explanation="An unknown error occured while dispatching " +
- "link update notifications",
- recommendation=LogMessageDoc.GENERIC_ACTION)
- @Override
- public void dispatch() {
- if (linkDiscoveryAware != null) {
+ public LinkUpdate(LDUpdate old) {
+ super(old);
+ }
+
+ @LogMessageDoc(level = "ERROR",
+ message = "Error in link discovery updates loop",
+ explanation = "An unknown error occured while dispatching " +
+ "link update notifications",
+ recommendation = LogMessageDoc.GENERIC_ACTION)
+ @Override
+ public void dispatch() {
+ if (linkDiscoveryAware != null) {
if (log.isTraceEnabled()) {
log.trace("Dispatching link discovery update {} {} {} {} {} for {}",
- new Object[]{this.getOperation(),
- HexString.toHexString(this.getSrc()), this.getSrcPort(),
- HexString.toHexString(this.getDst()), this.getDstPort(),
- linkDiscoveryAware});
+ new Object[]{this.getOperation(),
+ HexString.toHexString(this.getSrc()), this.getSrcPort(),
+ HexString.toHexString(this.getDst()), this.getDstPort(),
+ linkDiscoveryAware});
}
try {
for (ILinkDiscoveryListener lda : linkDiscoveryAware) { // order maintained
lda.linkDiscoveryUpdate(this);
}
- }
- catch (Exception e) {
+ } catch (Exception e) {
log.error("Error in link discovery updates loop", e);
}
}
- }
+ }
}
/**
@@ -244,7 +244,8 @@
*/
protected Set<NodePortTuple> suppressLinkDiscovery;
- /** A list of ports that are quarantined for discovering links through
+ /**
+ * A list of ports that are quarantined for discovering links through
* them. Data traffic from these ports are not allowed until the ports
* are released from quarantine.
*/
@@ -265,6 +266,7 @@
/**
* Get the LLDP sending period in seconds.
+ *
* @return LLDP sending period in seconds.
*/
public int getLldpFrequency() {
@@ -273,6 +275,7 @@
/**
* Get the LLDP timeout value in seconds
+ *
* @return LLDP timeout value in seconds
*/
public int getLldpTimeout() {
@@ -293,8 +296,7 @@
* Remove any known links on the switch port.
*/
@Override
- public void AddToSuppressLLDPs(long sw, short port)
- {
+ public void AddToSuppressLLDPs(long sw, short port) {
NodePortTuple npt = new NodePortTuple(sw, port);
this.suppressLinkDiscovery.add(npt);
deleteLinksOnPort(npt, "LLDP suppressed.");
@@ -305,8 +307,7 @@
* Discover links on that switchport.
*/
@Override
- public void RemoveFromSuppressLLDPs(long sw, short port)
- {
+ public void RemoveFromSuppressLLDPs(long sw, short port) {
NodePortTuple npt = new NodePortTuple(sw, port);
this.suppressLinkDiscovery.remove(npt);
discover(npt);
@@ -341,7 +342,7 @@
timeoutLinks();
//increment LLDP clock
- lldpClock = (lldpClock + 1)% LLDP_TO_ALL_INTERVAL;
+ lldpClock = (lldpClock + 1) % LLDP_TO_ALL_INTERVAL;
if (lldpClock == 0) {
log.debug("Sending LLDP out on all ports.");
@@ -351,19 +352,18 @@
/**
- * Quarantine Ports.
+ * Quarantine Ports.
*/
protected class QuarantineWorker implements Runnable {
@Override
public void run() {
try {
processBDDPLists();
- }
- catch (Exception e) {
+ } catch (Exception e) {
log.error("Error in quarantine worker thread", e);
} finally {
- bddpTask.reschedule(BDDP_TASK_INTERVAL,
- TimeUnit.MILLISECONDS);
+ bddpTask.reschedule(BDDP_TASK_INTERVAL,
+ TimeUnit.MILLISECONDS);
}
}
}
@@ -372,6 +372,7 @@
* Add a switch port to the quarantine queue. Schedule the
* quarantine task if the quarantine queue was empty before adding
* this switch port.
+ *
* @param npt
*/
protected void addToQuarantineQueue(NodePortTuple npt) {
@@ -384,11 +385,12 @@
*/
protected void removeFromQuarantineQueue(NodePortTuple npt) {
// Remove all occurrences of the node port tuple from the list.
- while (quarantineQueue.remove(npt));
+ while (quarantineQueue.remove(npt)) ;
}
/**
* Add a switch port to maintenance queue.
+ *
* @param npt
*/
protected void addToMaintenanceQueue(NodePortTuple npt) {
@@ -401,26 +403,27 @@
/**
* Remove a switch port from maintenance queue.
+ *
* @param npt
*/
protected void removeFromMaintenanceQueue(NodePortTuple npt) {
// Remove all occurrences of the node port tuple from the queue.
- while (maintenanceQueue.remove(npt));
+ while (maintenanceQueue.remove(npt)) ;
}
/**
- * This method processes the quarantine list in bursts. The task is
- * at most once per BDDP_TASK_INTERVAL.
- * One each call, BDDP_TASK_SIZE number of switch ports are processed.
- * Once the BDDP packets are sent out through the switch ports, the ports
- * are removed from the quarantine list.
- */
+ * This method processes the quarantine list in bursts. The task is
+ * at most once per BDDP_TASK_INTERVAL.
+ * One each call, BDDP_TASK_SIZE number of switch ports are processed.
+ * Once the BDDP packets are sent out through the switch ports, the ports
+ * are removed from the quarantine list.
+ */
protected void processBDDPLists() {
int count = 0;
Set<NodePortTuple> nptList = new HashSet<NodePortTuple>();
- while(count < BDDP_TASK_SIZE && quarantineQueue.peek() !=null) {
+ while (count < BDDP_TASK_SIZE && quarantineQueue.peek() != null) {
NodePortTuple npt;
npt = quarantineQueue.remove();
sendDiscoveryMessage(npt.getNodeId(), npt.getPortId(), false, false);
@@ -436,7 +439,7 @@
count++;
}
- for(NodePortTuple npt:nptList) {
+ for (NodePortTuple npt : nptList) {
generateSwitchPortStatusUpdate(npt.getNodeId(), npt.getPortId());
}
}
@@ -487,7 +490,7 @@
nptSet.addAll(portLinks.keySet());
// Send LLDP from each of them.
- for(NodePortTuple npt: nptSet) {
+ for (NodePortTuple npt : nptSet) {
discover(npt);
}
}
@@ -504,27 +507,27 @@
* Learn remote switches when running as a distributed controller ONOS
*/
protected IOFSwitch addRemoteSwitch(long sw, short port) {
- IOnosRemoteSwitch remotesw = null;
+ IOnosRemoteSwitch remotesw = null;
- // add a switch if we have not seen it before
- remotesw = remoteSwitches.get(sw);
+ // add a switch if we have not seen it before
+ remotesw = remoteSwitches.get(sw);
- if (remotesw == null) {
- remotesw = new OFSwitchImpl();
- remotesw.setupRemoteSwitch(sw);
- remoteSwitches.put(remotesw.getId(), remotesw);
- log.debug("addRemoteSwitch(): added fake remote sw {}", remotesw);
+ if (remotesw == null) {
+ remotesw = new OFSwitchImpl();
+ remotesw.setupRemoteSwitch(sw);
+ remoteSwitches.put(remotesw.getId(), remotesw);
+ log.debug("addRemoteSwitch(): added fake remote sw {}", remotesw);
}
// add the port if we have not seen it before
if (remotesw.getPort(port) == null) {
- OFPhysicalPort remoteport = new OFPhysicalPort();
- remoteport.setPortNumber(port);
- remoteport.setName("fake_" + port);
- remoteport.setConfig(0);
- remoteport.setState(0);
- remotesw.setPort(remoteport);
- log.debug("addRemoteSwitch(): added fake remote port {} to sw {}", remoteport, remotesw.getId());
+ OFPhysicalPort remoteport = new OFPhysicalPort();
+ remoteport.setPortNumber(port);
+ remoteport.setName("fake_" + port);
+ remoteport.setConfig(0);
+ remoteport.setState(0);
+ remotesw.setPort(remoteport);
+ log.debug("addRemoteSwitch(): added fake remote port {} to sw {}", remoteport, remotesw.getId());
}
return remotesw;
@@ -534,22 +537,23 @@
* Send link discovery message out of a given switch port.
* The discovery message may be a standard LLDP or a modified
* LLDP, where the dst mac address is set to :ff.
- *
+ * <p/>
* TODO: The modified LLDP will updated in the future and may
* use a different eth-type.
+ *
* @param sw
* @param port
- * @param isStandard indicates standard or modified LLDP
- * @param isReverse indicates whether the LLDP was sent as a response
+ * @param isStandard indicates standard or modified LLDP
+ * @param isReverse indicates whether the LLDP was sent as a response
*/
- @LogMessageDoc(level="ERROR",
- message="Failure sending LLDP out port {port} on switch {switch}",
- explanation="An I/O error occured while sending LLDP message " +
- "to the switch.",
- recommendation=LogMessageDoc.CHECK_SWITCH)
+ @LogMessageDoc(level = "ERROR",
+ message = "Failure sending LLDP out port {port} on switch {switch}",
+ explanation = "An I/O error occured while sending LLDP message " +
+ "to the switch.",
+ recommendation = LogMessageDoc.CHECK_SWITCH)
protected void sendDiscoveryMessage(long sw, short port,
- boolean isStandard,
- boolean isReverse) {
+ boolean isStandard,
+ boolean isReverse) {
IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
if (iofSwitch == null) {
@@ -581,17 +585,17 @@
if (log.isTraceEnabled()) {
log.trace("Sending LLDP packet out of swich: {}, port: {}",
- sw, port);
+ sw, port);
}
// using "nearest customer bridge" MAC address for broadest possible propagation
// through provider and TPMR bridges (see IEEE 802.1AB-2009 and 802.1Q-2011),
// in particular the Linux bridge which behaves mostly like a provider bridge
- byte[] chassisId = new byte[] {4, 0, 0, 0, 0, 0, 0}; // filled in later
- byte[] portId = new byte[] {2, 0, 0}; // filled in later
- byte[] ttlValue = new byte[] {0, 0x78};
+ byte[] chassisId = new byte[]{4, 0, 0, 0, 0, 0, 0}; // filled in later
+ byte[] portId = new byte[]{2, 0, 0}; // filled in later
+ byte[] ttlValue = new byte[]{0, 0x78};
// OpenFlow OUI - 00-26-E1
- byte[] dpidTLVValue = new byte[] {0x0, 0x26, (byte) 0xe1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+ byte[] dpidTLVValue = new byte[]{0x0, 0x26, (byte) 0xe1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
LLDPTLV dpidTLV = new LLDPTLV().setType((byte) 127).setLength((short) dpidTLVValue.length).setValue(dpidTLVValue);
byte[] dpidArray = new byte[8];
@@ -612,7 +616,7 @@
portBB.putShort(port);
if (log.isTraceEnabled()) {
log.trace("Sending LLDP out of interface: {}/{}",
- HexString.toHexString(sw), port);
+ HexString.toHexString(sw), port);
}
LLDP lldp = new LLDP();
@@ -625,25 +629,25 @@
lldp.getOptionalTLVList().add(controllerTLV);
if (isReverse) {
lldp.getOptionalTLVList().add(reverseTLV);
- }else {
+ } else {
lldp.getOptionalTLVList().add(forwardTLV);
}
Ethernet ethernet;
if (isStandard) {
ethernet = new Ethernet()
- .setSourceMACAddress(ofpPort.getHardwareAddress())
- .setDestinationMACAddress(LLDP_STANDARD_DST_MAC_STRING)
- .setEtherType(Ethernet.TYPE_LLDP);
+ .setSourceMACAddress(ofpPort.getHardwareAddress())
+ .setDestinationMACAddress(LLDP_STANDARD_DST_MAC_STRING)
+ .setEtherType(Ethernet.TYPE_LLDP);
ethernet.setPayload(lldp);
} else {
BSN bsn = new BSN(BSN.BSN_TYPE_BDDP);
bsn.setPayload(lldp);
ethernet = new Ethernet()
- .setSourceMACAddress(ofpPort.getHardwareAddress())
- .setDestinationMACAddress(LLDP_BSN_DST_MAC_STRING)
- .setEtherType(Ethernet.TYPE_BSN);
+ .setSourceMACAddress(ofpPort.getHardwareAddress())
+ .setDestinationMACAddress(LLDP_BSN_DST_MAC_STRING)
+ .setEtherType(Ethernet.TYPE_BSN);
ethernet.setPayload(bsn);
}
@@ -669,7 +673,7 @@
iofSwitch.write(po, null);
iofSwitch.flush();
} catch (IOException e) {
- log.error("Failure sending LLDP out port "+port+" on switch "+iofSwitch.getStringId(), e);
+ log.error("Failure sending LLDP out port " + port + " on switch " + iofSwitch.getStringId(), e);
}
}
@@ -683,11 +687,11 @@
}
Set<Long> switches = floodlightProvider.getSwitches().keySet();
// Send standard LLDPs
- for (long sw: switches) {
+ for (long sw : switches) {
IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
if (iofSwitch == null) continue;
if (iofSwitch.getEnabledPorts() != null) {
- for (OFPhysicalPort ofp: iofSwitch.getEnabledPorts()) {
+ for (OFPhysicalPort ofp : iofSwitch.getEnabledPorts()) {
if (isLinkDiscoverySuppressed(sw, ofp.getPortNumber()))
continue;
if (autoPortFastFeature && isFastPort(sw, ofp.getPortNumber()))
@@ -714,10 +718,10 @@
InetAddress localIPAddress = null;
NetworkInterface localInterface = null;
- byte[] controllerTLVValue = new byte[] {0, 0, 0, 0, 0, 0, 0, 0}; // 8 byte value.
+ byte[] controllerTLVValue = new byte[]{0, 0, 0, 0, 0, 0, 0, 0}; // 8 byte value.
ByteBuffer bb = ByteBuffer.allocate(10);
- try{
+ try {
localIPAddress = java.net.InetAddress.getLocalHost();
localInterface = NetworkInterface.getByInetAddress(localIPAddress);
} catch (Exception e) {
@@ -787,16 +791,16 @@
for (LLDPTLV lldptlv : lldp.getOptionalTLVList()) {
if (lldptlv.getType() == 127 && lldptlv.getLength() == 12 &&
lldptlv.getValue()[0] == 0x0 && lldptlv.getValue()[1] == 0x26 &&
- lldptlv.getValue()[2] == (byte)0xe1 && lldptlv.getValue()[3] == 0x0) {
+ lldptlv.getValue()[2] == (byte) 0xe1 && lldptlv.getValue()[3] == 0x0) {
ByteBuffer dpidBB = ByteBuffer.wrap(lldptlv.getValue());
remoteSwitch = floodlightProvider.getSwitches().get(dpidBB.getLong(4));
if (remoteSwitch == null) {
- // Added by ONOS
- // floodlight LLDP coming from a remote switch connected to a different controller
- // add it to our cache of unconnected remote switches
- remoteSwitch = addRemoteSwitch(dpidBB.getLong(4), remotePort);
+ // Added by ONOS
+ // floodlight LLDP coming from a remote switch connected to a different controller
+ // add it to our cache of unconnected remote switches
+ remoteSwitch = addRemoteSwitch(dpidBB.getLong(4), remotePort);
}
- } else if (lldptlv.getType() == 12 && lldptlv.getLength() == 8){
+ } else if (lldptlv.getType() == 12 && lldptlv.getLength() == 8) {
otherId = ByteBuffer.wrap(lldptlv.getValue()).getLong();
if (myId == otherId)
myLLDP = true;
@@ -818,15 +822,14 @@
log.trace("Getting standard LLDP from a different controller and quelching it.");
}
return Command.STOP;
- }
- else if(sw <= remoteSwitch.getId()){
+ } else if (sw <= remoteSwitch.getId()) {
if (log.isTraceEnabled()) {
log.trace("Getting BBDP from a different controller. myId {}: remoteId {}", myId, otherId);
log.trace("and my controller id is smaller than the other, so quelching it. myPort {}: rPort {}", pi.getInPort(), remotePort);
- }
- //XXX ONOS: Fix the BDDP broadcast issue
- //return Command.CONTINUE;
- return Command.STOP;
+ }
+ //XXX ONOS: Fix the BDDP broadcast issue
+ //return Command.CONTINUE;
+ return Command.STOP;
}
/*
else if (myId < otherId) {
@@ -858,10 +861,10 @@
return Command.STOP;
}
if (suppressLinkDiscovery.contains(new NodePortTuple(remoteSwitch.getId(),
- remotePort))) {
+ remotePort))) {
if (log.isTraceEnabled()) {
log.trace("Ignoring link with suppressed src port: switch {} port {}",
- remoteSwitch, remotePort);
+ remoteSwitch, remotePort);
}
return Command.STOP;
}
@@ -893,7 +896,7 @@
LinkInfo newLinkInfo =
new LinkInfo(firstSeenTime, lastLldpTime, lastBddpTime,
- srcPortState, dstPortState);
+ srcPortState, dstPortState);
addOrUpdateLink(lt, newLinkInfo);
@@ -905,7 +908,7 @@
newLinkInfo = links.get(lt);
if (newLinkInfo != null && isStandard && isReverse == false) {
Link reverseLink = new Link(lt.getDst(), lt.getDstPort(),
- lt.getSrc(), lt.getSrcPort());
+ lt.getSrc(), lt.getSrcPort());
LinkInfo reverseInfo = links.get(reverseLink);
if (reverseInfo == null) {
// the reverse link does not exist.
@@ -919,12 +922,12 @@
// link as well.
if (!isStandard) {
Link reverseLink = new Link(lt.getDst(), lt.getDstPort(),
- lt.getSrc(), lt.getSrcPort());
+ lt.getSrc(), lt.getSrcPort());
// srcPortState and dstPort state are reversed.
LinkInfo reverseInfo =
new LinkInfo(firstSeenTime, lastLldpTime, lastBddpTime,
- dstPortState, srcPortState);
+ dstPortState, srcPortState);
addOrUpdateLink(reverseLink, reverseInfo);
}
@@ -945,9 +948,9 @@
FloodlightContext cntx) {
Ethernet eth =
IFloodlightProviderService.bcStore.get(cntx,
- IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
+ IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
- if(eth.getEtherType() == Ethernet.TYPE_BSN) {
+ if (eth.getEtherType() == Ethernet.TYPE_BSN) {
BSN bsn = (BSN) eth.getPayload();
if (bsn == null) return Command.STOP;
if (bsn.getPayload() == null) return Command.STOP;
@@ -956,11 +959,11 @@
if (bsn.getPayload() instanceof LLDP == false)
return Command.CONTINUE;
return handleLldp((LLDP) bsn.getPayload(), sw, pi, false, cntx);
- } else if (eth.getEtherType() == Ethernet.TYPE_LLDP) {
+ } else if (eth.getEtherType() == Ethernet.TYPE_LLDP) {
return handleLldp((LLDP) eth.getPayload(), sw, pi, true, cntx);
} else if (eth.getEtherType() < 1500) {
long destMac = eth.getDestinationMAC().toLong();
- if ((destMac & LINK_LOCAL_MASK) == LINK_LOCAL_VALUE){
+ if ((destMac & LINK_LOCAL_MASK) == LINK_LOCAL_VALUE) {
if (log.isTraceEnabled()) {
log.trace("Ignoring packet addressed to 802.1D/Q " +
"reserved address.");
@@ -980,18 +983,17 @@
int dstPortState) {
boolean added =
(((srcPortState &
- OFPortState.OFPPS_STP_MASK.getValue()) !=
- OFPortState.OFPPS_STP_BLOCK.getValue()) &&
- ((dstPortState &
- OFPortState.OFPPS_STP_MASK.getValue()) !=
- OFPortState.OFPPS_STP_BLOCK.getValue()));
+ OFPortState.OFPPS_STP_MASK.getValue()) !=
+ OFPortState.OFPPS_STP_BLOCK.getValue()) &&
+ ((dstPortState &
+ OFPortState.OFPPS_STP_MASK.getValue()) !=
+ OFPortState.OFPPS_STP_BLOCK.getValue()));
if (added) return UpdateOperation.LINK_UPDATED;
return UpdateOperation.LINK_REMOVED;
}
-
protected UpdateOperation getUpdateOperation(int srcPortState) {
boolean portUp = ((srcPortState &
OFPortState.OFPPS_STP_MASK.getValue()) !=
@@ -1016,8 +1018,8 @@
if (log.isTraceEnabled()) {
log.trace("addOrUpdateLink: {} {}",
- lt,
- (newInfo.getMulticastValidTime()!=null) ? "multicast" : "unicast");
+ lt,
+ (newInfo.getMulticastValidTime() != null) ? "multicast" : "unicast");
}
UpdateOperation updateOperation = null;
@@ -1056,12 +1058,12 @@
// Add to event history
evHistTopoLink(lt.getSrc(),
- lt.getDst(),
- lt.getSrcPort(),
- lt.getDstPort(),
- newInfo.getSrcPortState(), newInfo.getDstPortState(),
- getLinkType(lt, newInfo),
- EvAction.LINK_ADDED, "LLDP Recvd");
+ lt.getDst(),
+ lt.getSrcPort(),
+ lt.getDstPort(),
+ newInfo.getSrcPortState(), newInfo.getDstPortState(),
+ getLinkType(lt, newInfo),
+ EvAction.LINK_ADDED, "LLDP Recvd");
} else {
// Since the link info is already there, we need to
// update the right fields.
@@ -1099,33 +1101,33 @@
if (newInfo.getSrcPortState().intValue() !=
oldInfo.getSrcPortState().intValue() ||
newInfo.getDstPortState().intValue() !=
- oldInfo.getDstPortState().intValue())
+ oldInfo.getDstPortState().intValue())
linkChanged = true;
if (linkChanged) {
updateOperation = getUpdateOperation(newInfo.getSrcPortState(),
- newInfo.getDstPortState());
+ newInfo.getDstPortState());
if (log.isTraceEnabled()) {
log.trace("Updated link {}", lt);
}
// Add to event history
evHistTopoLink(lt.getSrc(),
- lt.getDst(),
- lt.getSrcPort(),
- lt.getDstPort(),
- newInfo.getSrcPortState(), newInfo.getDstPortState(),
- getLinkType(lt, newInfo),
- EvAction.LINK_PORT_STATE_UPDATED,
- "LLDP Recvd");
+ lt.getDst(),
+ lt.getSrcPort(),
+ lt.getDstPort(),
+ newInfo.getSrcPortState(), newInfo.getDstPortState(),
+ getLinkType(lt, newInfo),
+ EvAction.LINK_PORT_STATE_UPDATED,
+ "LLDP Recvd");
}
}
if (linkChanged) {
// find out if the link was added or removed here.
LinkUpdate update = new LinkUpdate(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
- lt.getDst(), lt.getDstPort(),
- getLinkType(lt, newInfo),
- updateOperation));
+ lt.getDst(), lt.getDstPort(),
+ getLinkType(lt, newInfo),
+ updateOperation));
controller.publishUpdate(update);
}
} finally {
@@ -1142,6 +1144,7 @@
/**
* Removes links from memory and storage.
+ *
* @param links The List of @LinkTuple to delete.
*/
protected void deleteLinks(List<Link> links, String reason) {
@@ -1151,7 +1154,7 @@
try {
for (Link lt : links) {
srcNpt = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
- dstNpt =new NodePortTuple(lt.getDst(), lt.getDstPort());
+ dstNpt = new NodePortTuple(lt.getDst(), lt.getDstPort());
switchLinks.get(lt.getSrc()).remove(lt);
switchLinks.get(lt.getDst()).remove(lt);
@@ -1175,19 +1178,19 @@
LinkInfo info = this.links.remove(lt);
LinkUpdate update = new LinkUpdate(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
- lt.getDst(), lt.getDstPort(),
- getLinkType(lt, info),
- UpdateOperation.LINK_REMOVED));
+ lt.getDst(), lt.getDstPort(),
+ getLinkType(lt, info),
+ UpdateOperation.LINK_REMOVED));
controller.publishUpdate(update);
// Update Event History
evHistTopoLink(lt.getSrc(),
- lt.getDst(),
- lt.getSrcPort(),
- lt.getDstPort(),
- 0, 0, // Port states
- ILinkDiscovery.LinkType.INVALID_LINK,
- EvAction.LINK_DELETED, reason);
+ lt.getDst(),
+ lt.getSrcPort(),
+ lt.getDstPort(),
+ 0, 0, // Port states
+ ILinkDiscovery.LinkType.INVALID_LINK,
+ EvAction.LINK_DELETED, reason);
// TODO Whenever link is removed, it has to checked if
// the switchports must be added to quarantine.
@@ -1204,6 +1207,7 @@
/**
* Handles an OFPortStatus message from a switch. We will add or
* delete LinkTupes as well re-compute the topology if needed.
+ *
* @param sw The IOFSwitch that sent the port status message
* @param ps The OFPortStatus message
* @return The Command to continue or stop after we process this message
@@ -1214,57 +1218,57 @@
if (iofSwitch == null) return Command.CONTINUE;
// ONOS: If we do not control this switch, then we should not process its port status messages
- if (!registryService.hasControl(iofSwitch.getId())) return Command.CONTINUE;
+ if (!registryService.hasControl(iofSwitch.getId()))
+ return Command.CONTINUE;
if (log.isTraceEnabled()) {
log.trace("handlePortStatus: Switch {} port #{} reason {}; " +
"config is {} state is {}",
- new Object[] {iofSwitch.getStringId(),
- ps.getDesc().getPortNumber(),
- ps.getReason(),
- ps.getDesc().getConfig(),
- ps.getDesc().getState()});
+ new Object[]{iofSwitch.getStringId(),
+ ps.getDesc().getPortNumber(),
+ ps.getReason(),
+ ps.getDesc().getConfig(),
+ ps.getDesc().getState()});
}
short port = ps.getDesc().getPortNumber();
NodePortTuple npt = new NodePortTuple(sw, port);
- boolean linkDeleted = false;
+ boolean linkDeleted = false;
boolean linkInfoChanged = false;
lock.writeLock().lock();
try {
// if ps is a delete, or a modify where the port is down or
// configured down
- if ((byte)OFPortReason.OFPPR_DELETE.ordinal() == ps.getReason() ||
- ((byte)OFPortReason.OFPPR_MODIFY.ordinal() ==
- ps.getReason() && !portEnabled(ps.getDesc()))) {
+ if ((byte) OFPortReason.OFPPR_DELETE.ordinal() == ps.getReason() ||
+ ((byte) OFPortReason.OFPPR_MODIFY.ordinal() ==
+ ps.getReason() && !portEnabled(ps.getDesc()))) {
deleteLinksOnPort(npt, "Port Status Changed");
LinkUpdate update = new LinkUpdate(new LDUpdate(sw, port, UpdateOperation.PORT_DOWN));
controller.publishUpdate(update);
linkDeleted = true;
- }
- else if (ps.getReason() ==
- (byte)OFPortReason.OFPPR_MODIFY.ordinal()) {
+ } else if (ps.getReason() ==
+ (byte) OFPortReason.OFPPR_MODIFY.ordinal()) {
// If ps is a port modification and the port state has changed
// that affects links in the topology
if (this.portLinks.containsKey(npt)) {
- for (Link lt: this.portLinks.get(npt)) {
+ for (Link lt : this.portLinks.get(npt)) {
LinkInfo linkInfo = links.get(lt);
- assert(linkInfo != null);
+ assert (linkInfo != null);
Integer updatedSrcPortState = null;
Integer updatedDstPortState = null;
if (lt.getSrc() == npt.getNodeId() &&
lt.getSrcPort() == npt.getPortId() &&
(linkInfo.getSrcPortState() !=
- ps.getDesc().getState())) {
+ ps.getDesc().getState())) {
updatedSrcPortState = ps.getDesc().getState();
linkInfo.setSrcPortState(updatedSrcPortState);
}
if (lt.getDst() == npt.getNodeId() &&
lt.getDstPort() == npt.getPortId() &&
(linkInfo.getDstPortState() !=
- ps.getDesc().getState())) {
+ ps.getDesc().getState())) {
updatedDstPortState = ps.getDesc().getState();
linkInfo.setDstPortState(updatedDstPortState);
}
@@ -1275,11 +1279,11 @@
// send an LinkUpdate.
UpdateOperation operation =
getUpdateOperation(linkInfo.getSrcPortState(),
- linkInfo.getDstPortState());
+ linkInfo.getDstPortState());
LinkUpdate update = new LinkUpdate(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
- lt.getDst(), lt.getDstPort(),
- getLinkType(lt, linkInfo),
- operation));
+ lt.getDst(), lt.getDstPort(),
+ getLinkType(lt, linkInfo),
+ operation));
controller.publishUpdate(update);
linkInfoChanged = true;
@@ -1293,13 +1297,13 @@
controller.publishUpdate(update);
}
- if (!linkDeleted && !linkInfoChanged){
+ if (!linkDeleted && !linkInfoChanged) {
if (log.isTraceEnabled()) {
- log.trace("handlePortStatus: Switch {} port #{} reason {};"+
+ log.trace("handlePortStatus: Switch {} port #{} reason {};" +
" no links to update/remove",
- new Object[] {HexString.toHexString(sw),
- ps.getDesc().getPortNumber(),
- ps.getReason()});
+ new Object[]{HexString.toHexString(sw),
+ ps.getDesc().getPortNumber(),
+ ps.getReason()});
}
}
} finally {
@@ -1324,17 +1328,16 @@
* If autoportfast feature is enabled and the port is a fast port, then
* do nothing.
* Otherwise, send LLDP message. Add the port to quarantine.
+ *
* @param sw
* @param p
*/
private void processNewPort(long sw, short p) {
if (isLinkDiscoverySuppressed(sw, p)) {
// Do nothing as link discovery is suppressed.
- }
- else if (autoPortFastFeature && isFastPort(sw, p)) {
+ } else if (autoPortFastFeature && isFastPort(sw, p)) {
// Do nothing as the port is a fast port.
- }
- else {
+ } else {
NodePortTuple npt = new NodePortTuple(sw, p);
discover(sw, p);
// if it is not a fast port, add it to quarantine.
@@ -1350,6 +1353,7 @@
/**
* We send out LLDP messages when a switch is added to discover the topology
+ *
* @param sw The IOFSwitch that connected to the controller
*/
@Override
@@ -1363,7 +1367,7 @@
// Update event history
evHistTopoSwitch(sw, EvAction.SWITCH_CONNECTED, "None");
LinkUpdate update = new LinkUpdate(new LDUpdate(sw.getId(), null,
- UpdateOperation.SWITCH_UPDATED));
+ UpdateOperation.SWITCH_UPDATED));
controller.publishUpdate(update);
}
@@ -1381,7 +1385,7 @@
if (switchLinks.containsKey(sw)) {
if (log.isTraceEnabled()) {
log.trace("Handle switchRemoved. Switch {}; removing links {}",
- HexString.toHexString(sw), switchLinks.get(sw));
+ HexString.toHexString(sw), switchLinks.get(sw));
}
// add all tuples with an endpoint on this switch to erase list
eraseList.addAll(switchLinks.get(sw));
@@ -1408,6 +1412,7 @@
/**
* Delete links incident on a given switch port.
+ *
* @param npt
* @param reason
*/
@@ -1417,9 +1422,9 @@
if (log.isTraceEnabled()) {
log.trace("handlePortStatus: Switch {} port #{} " +
"removing links {}",
- new Object[] {HexString.toHexString(npt.getNodeId()),
- npt.getPortId(),
- this.portLinks.get(npt)});
+ new Object[]{HexString.toHexString(npt.getNodeId()),
+ npt.getPortId(),
+ this.portLinks.get(npt)});
}
eraseList.addAll(this.portLinks.get(npt));
deleteLinks(eraseList, reason);
@@ -1448,7 +1453,7 @@
// Timeout the unicast and multicast LLDP valid times
// independently.
if ((info.getUnicastValidTime() != null) &&
- (info.getUnicastValidTime() + (this.LINK_TIMEOUT * 1000) < curTime)){
+ (info.getUnicastValidTime() + (this.LINK_TIMEOUT * 1000) < curTime)) {
info.setUnicastValidTime(null);
if (info.getMulticastValidTime() != null)
@@ -1457,8 +1462,8 @@
// the link would be deleted, which would trigger updateClusters().
linkChanged = true;
}
- if ((info.getMulticastValidTime()!= null) &&
- (info.getMulticastValidTime()+ (this.LINK_TIMEOUT * 1000) < curTime)) {
+ if ((info.getMulticastValidTime() != null) &&
+ (info.getMulticastValidTime() + (this.LINK_TIMEOUT * 1000) < curTime)) {
info.setMulticastValidTime(null);
// if uTime is not null, then link will remain as openflow
// link. If uTime is null, it will be deleted. So, we
@@ -1469,16 +1474,16 @@
// Add to the erase list only if the unicast
// time is null.
if (info.getUnicastValidTime() == null &&
- info.getMulticastValidTime() == null){
+ info.getMulticastValidTime() == null) {
eraseList.add(entry.getKey());
} else if (linkChanged) {
UpdateOperation operation;
operation = getUpdateOperation(info.getSrcPortState(),
- info.getDstPortState());
+ info.getDstPortState());
LinkUpdate update = new LinkUpdate(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
- lt.getDst(), lt.getDstPort(),
- getLinkType(lt, info),
- operation));
+ lt.getDst(), lt.getDstPort(),
+ getLinkType(lt, info),
+ operation));
controller.publishUpdate(update);
}
}
@@ -1562,6 +1567,7 @@
/**
* Register a link discovery aware component
+ *
* @param linkDiscoveryAwareComponent
*/
public void addLinkDiscoveryAware(ILinkDiscoveryListener linkDiscoveryAwareComponent) {
@@ -1571,6 +1577,7 @@
/**
* Deregister a link discovery aware component
+ *
* @param linkDiscoveryAwareComponent
*/
public void removeLinkDiscoveryAware(ILinkDiscoveryListener linkDiscoveryAwareComponent) {
@@ -1603,9 +1610,9 @@
public Map<Class<? extends IFloodlightService>, IFloodlightService>
getServiceImpls() {
Map<Class<? extends IFloodlightService>,
- IFloodlightService> m =
- new HashMap<Class<? extends IFloodlightService>,
- IFloodlightService>();
+ IFloodlightService> m =
+ new HashMap<Class<? extends IFloodlightService>,
+ IFloodlightService>();
// We are the class that implements the service
m.put(ILinkDiscoveryService.class, this);
return m;
@@ -1659,27 +1666,27 @@
@Override
@LogMessageDocs({
- @LogMessageDoc(level="ERROR",
- message="No storage source found.",
- explanation="Storage source was not initialized; cannot initialize " +
- "link discovery.",
- recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG),
- @LogMessageDoc(level="ERROR",
- message="Error in installing listener for " +
- "switch config table {table}",
- explanation="Failed to install storage notification for the " +
- "switch config table",
- recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG),
- @LogMessageDoc(level="ERROR",
- message="No storage source found.",
- explanation="Storage source was not initialized; cannot initialize " +
- "link discovery.",
- recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG),
- @LogMessageDoc(level="ERROR",
- message="Exception in LLDP send timer.",
- explanation="An unknown error occured while sending LLDP " +
- "messages to switches.",
- recommendation=LogMessageDoc.CHECK_SWITCH)
+ @LogMessageDoc(level = "ERROR",
+ message = "No storage source found.",
+ explanation = "Storage source was not initialized; cannot initialize " +
+ "link discovery.",
+ recommendation = LogMessageDoc.REPORT_CONTROLLER_BUG),
+ @LogMessageDoc(level = "ERROR",
+ message = "Error in installing listener for " +
+ "switch config table {table}",
+ explanation = "Failed to install storage notification for the " +
+ "switch config table",
+ recommendation = LogMessageDoc.REPORT_CONTROLLER_BUG),
+ @LogMessageDoc(level = "ERROR",
+ message = "No storage source found.",
+ explanation = "Storage source was not initialized; cannot initialize " +
+ "link discovery.",
+ recommendation = LogMessageDoc.REPORT_CONTROLLER_BUG),
+ @LogMessageDoc(level = "ERROR",
+ message = "Exception in LLDP send timer.",
+ explanation = "An unknown error occured while sending LLDP " +
+ "messages to switches.",
+ recommendation = LogMessageDoc.CHECK_SWITCH)
})
public void startUp(FloodlightModuleContext context) {
ScheduledExecutorService ses = threadPool.getScheduledExecutor();
@@ -1696,11 +1703,11 @@
log.error("Exception in LLDP send timer.", e);
} finally {
if (!shuttingDown) {
- // Always reschedule link discovery if we're not
- // shutting down (no chance of SLAVE role now)
+ // Always reschedule link discovery if we're not
+ // shutting down (no chance of SLAVE role now)
log.trace("Rescheduling discovery task");
discoveryTask.reschedule(DISCOVERY_TASK_INTERVAL,
- TimeUnit.SECONDS);
+ TimeUnit.SECONDS);
}
}
}
@@ -1730,11 +1737,11 @@
// ****************************************************
// Topology Manager event history
- public EventHistory<EventHistoryTopologySwitch> evHistTopologySwitch;
- public EventHistory<EventHistoryTopologyLink> evHistTopologyLink;
+ public EventHistory<EventHistoryTopologySwitch> evHistTopologySwitch;
+ public EventHistory<EventHistoryTopologyLink> evHistTopologyLink;
public EventHistory<EventHistoryTopologyCluster> evHistTopologyCluster;
- public EventHistoryTopologySwitch evTopoSwitch;
- public EventHistoryTopologyLink evTopoLink;
+ public EventHistoryTopologySwitch evTopoSwitch;
+ public EventHistoryTopologyLink evTopoLink;
public EventHistoryTopologyCluster evTopoCluster;
// Switch Added/Deleted
@@ -1742,21 +1749,21 @@
if (evTopoSwitch == null) {
evTopoSwitch = new EventHistoryTopologySwitch();
}
- evTopoSwitch.dpid = sw.getId();
+ evTopoSwitch.dpid = sw.getId();
if ((sw.getChannel() != null) &&
(SocketAddress.class.isInstance(
- sw.getChannel().getRemoteAddress()))) {
+ sw.getChannel().getRemoteAddress()))) {
evTopoSwitch.ipv4Addr =
- IPv4.toIPv4Address(((InetSocketAddress)(sw.getChannel().
+ IPv4.toIPv4Address(((InetSocketAddress) (sw.getChannel().
getRemoteAddress())).getAddress().getAddress());
- evTopoSwitch.l4Port =
- ((InetSocketAddress)(sw.getChannel().
+ evTopoSwitch.l4Port =
+ ((InetSocketAddress) (sw.getChannel().
getRemoteAddress())).getPort();
} else {
evTopoSwitch.ipv4Addr = 0;
evTopoSwitch.l4Port = 0;
}
- evTopoSwitch.reason = reason;
+ evTopoSwitch.reason = reason;
evTopoSwitch = evHistTopologySwitch.put(evTopoSwitch, actn);
}
@@ -1773,7 +1780,7 @@
evTopoLink.dstSwport = dstPort & 0xffff;
evTopoLink.srcPortState = srcPortState;
evTopoLink.dstPortState = dstPortState;
- evTopoLink.reason = reason;
+ evTopoLink.reason = reason;
switch (linkType) {
case DIRECT_LINK:
evTopoLink.linkType = "DIRECT_LINK";
@@ -1797,10 +1804,10 @@
if (evTopoCluster == null) {
evTopoCluster = new EventHistoryTopologyCluster();
}
- evTopoCluster.dpid = dpid;
+ evTopoCluster.dpid = dpid;
evTopoCluster.clusterIdOld = clusterIdOld;
evTopoCluster.clusterIdNew = clusterIdNew;
- evTopoCluster.reason = reason;
+ evTopoCluster.reason = reason;
evTopoCluster = evHistTopologyCluster.put(evTopoCluster, action);
}
diff --git a/src/main/java/net/onrc/onos/core/linkdiscovery/web/AutoPortFast.java b/src/main/java/net/onrc/onos/core/linkdiscovery/web/AutoPortFast.java
index 028776b..4b7eeca 100644
--- a/src/main/java/net/onrc/onos/core/linkdiscovery/web/AutoPortFast.java
+++ b/src/main/java/net/onrc/onos/core/linkdiscovery/web/AutoPortFast.java
@@ -14,10 +14,10 @@
@Get("json")
public String retrieve() {
ILinkDiscoveryService linkDiscovery;
- linkDiscovery = (ILinkDiscoveryService)getContext().getAttributes().
+ linkDiscovery = (ILinkDiscoveryService) getContext().getAttributes().
get(ILinkDiscoveryService.class.getCanonicalName());
- String param = ((String)getRequestAttributes().get("state")).toLowerCase();
+ String param = ((String) getRequestAttributes().get("state")).toLowerCase();
if (param.equals("enable") || param.equals("true")) {
linkDiscovery.setAutoPortFastFeature(true);
} else if (param.equals("disable") || param.equals("false")) {
diff --git a/src/main/java/net/onrc/onos/core/linkdiscovery/web/LinkWithType.java b/src/main/java/net/onrc/onos/core/linkdiscovery/web/LinkWithType.java
index c956cb1..733f28c 100644
--- a/src/main/java/net/onrc/onos/core/linkdiscovery/web/LinkWithType.java
+++ b/src/main/java/net/onrc/onos/core/linkdiscovery/web/LinkWithType.java
@@ -15,9 +15,10 @@
/**
* This class is both the datastructure and the serializer
* for a link with the corresponding type of link.
+ *
* @author alexreimers
*/
-@JsonSerialize(using=LinkWithType.class)
+@JsonSerialize(using = LinkWithType.class)
public class LinkWithType extends JsonSerializer<LinkWithType> {
public long srcSwDpid;
public short srcPort;
@@ -28,8 +29,9 @@
public LinkType type;
// Do NOT delete this, it's required for the serializer
- public LinkWithType() {}
-
+ public LinkWithType() {
+ }
+
public LinkWithType(Link link,
int srcPortState,
int dstPortState,
@@ -43,23 +45,23 @@
this.type = type;
}
- @Override
- public void serialize(LinkWithType lwt, JsonGenerator jgen, SerializerProvider arg2)
- throws IOException, JsonProcessingException {
- // You ****MUST*** use lwt for the fields as it's actually a different object.
- jgen.writeStartObject();
- jgen.writeStringField("src-switch", HexString.toHexString(lwt.srcSwDpid));
- jgen.writeNumberField("src-port", lwt.srcPort);
- jgen.writeNumberField("src-port-state", lwt.srcPortState);
- jgen.writeStringField("dst-switch", HexString.toHexString(lwt.dstSwDpid));
- jgen.writeNumberField("dst-port", lwt.dstPort);
- jgen.writeNumberField("dst-port-state", lwt.dstPortState);
- jgen.writeStringField("type", lwt.type.toString());
- jgen.writeEndObject();
- }
-
- @Override
- public Class<LinkWithType> handledType() {
- return LinkWithType.class;
- }
+ @Override
+ public void serialize(LinkWithType lwt, JsonGenerator jgen, SerializerProvider arg2)
+ throws IOException, JsonProcessingException {
+ // You ****MUST*** use lwt for the fields as it's actually a different object.
+ jgen.writeStartObject();
+ jgen.writeStringField("src-switch", HexString.toHexString(lwt.srcSwDpid));
+ jgen.writeNumberField("src-port", lwt.srcPort);
+ jgen.writeNumberField("src-port-state", lwt.srcPortState);
+ jgen.writeStringField("dst-switch", HexString.toHexString(lwt.dstSwDpid));
+ jgen.writeNumberField("dst-port", lwt.dstPort);
+ jgen.writeNumberField("dst-port-state", lwt.dstPortState);
+ jgen.writeStringField("type", lwt.type.toString());
+ jgen.writeEndObject();
+ }
+
+ @Override
+ public Class<LinkWithType> handledType() {
+ return LinkWithType.class;
+ }
}
\ No newline at end of file
diff --git a/src/main/java/net/onrc/onos/core/linkdiscovery/web/LinksResource.java b/src/main/java/net/onrc/onos/core/linkdiscovery/web/LinksResource.java
index 2714f66..81c0b9e 100644
--- a/src/main/java/net/onrc/onos/core/linkdiscovery/web/LinksResource.java
+++ b/src/main/java/net/onrc/onos/core/linkdiscovery/web/LinksResource.java
@@ -17,20 +17,20 @@
@Get("json")
public Set<LinkWithType> retrieve() {
- ILinkDiscoveryService ld = (ILinkDiscoveryService)getContext().getAttributes().
+ ILinkDiscoveryService ld = (ILinkDiscoveryService) getContext().getAttributes().
get(ILinkDiscoveryService.class.getCanonicalName());
Map<Link, LinkInfo> links = new HashMap<Link, LinkInfo>();
Set<LinkWithType> returnLinkSet = new HashSet<LinkWithType>();
if (ld != null) {
links.putAll(ld.getLinks());
- for(Entry<Link, LinkInfo> e : links.entrySet()) {
+ for (Entry<Link, LinkInfo> e : links.entrySet()) {
Link link = e.getKey();
LinkInfo info = e.getValue();
LinkWithType lwt = new LinkWithType(link,
- info.getSrcPortState(),
- info.getDstPortState(),
- ld.getLinkType(link, info));
+ info.getSrcPortState(),
+ info.getDstPortState(),
+ ld.getLinkType(link, info));
returnLinkSet.add(lwt);
}
}
diff --git a/src/main/java/net/onrc/onos/core/main/IOFSwitchPortListener.java b/src/main/java/net/onrc/onos/core/main/IOFSwitchPortListener.java
index 7f4e139..6498844 100644
--- a/src/main/java/net/onrc/onos/core/main/IOFSwitchPortListener.java
+++ b/src/main/java/net/onrc/onos/core/main/IOFSwitchPortListener.java
@@ -1,5 +1,5 @@
/**
- *
+ *
*/
package net.onrc.onos.core.main;
@@ -9,18 +9,17 @@
/**
* @author y-higuchi
- *
*/
public interface IOFSwitchPortListener extends IOFSwitchListener {
- /**
- * Fired when ports on a switch area added
- */
- public void switchPortAdded(Long switchId, OFPhysicalPort port);
+ /**
+ * Fired when ports on a switch area added
+ */
+ public void switchPortAdded(Long switchId, OFPhysicalPort port);
- /**
- * Fired when ports on a switch area removed
- */
- public void switchPortRemoved(Long switchId, OFPhysicalPort port);
+ /**
+ * Fired when ports on a switch area removed
+ */
+ public void switchPortRemoved(Long switchId, OFPhysicalPort port);
}
diff --git a/src/main/java/net/onrc/onos/core/main/IOnosRemoteSwitch.java b/src/main/java/net/onrc/onos/core/main/IOnosRemoteSwitch.java
index 0b95f42..1218555 100644
--- a/src/main/java/net/onrc/onos/core/main/IOnosRemoteSwitch.java
+++ b/src/main/java/net/onrc/onos/core/main/IOnosRemoteSwitch.java
@@ -1,5 +1,5 @@
/**
- *
+ *
*/
package net.onrc.onos.core.main;
@@ -7,14 +7,14 @@
/**
* @author y-higuchi
- *
*/
public interface IOnosRemoteSwitch extends IOFSwitch {
- /**
- * Setup an unconnected switch with the info required.
- * @param dpid of the switch
- */
- public void setupRemoteSwitch(Long dpid);
+ /**
+ * Setup an unconnected switch with the info required.
+ *
+ * @param dpid of the switch
+ */
+ public void setupRemoteSwitch(Long dpid);
}
diff --git a/src/main/java/net/onrc/onos/core/main/Main.java b/src/main/java/net/onrc/onos/core/main/Main.java
index 4e3dd44..d8e5581 100644
--- a/src/main/java/net/onrc/onos/core/main/Main.java
+++ b/src/main/java/net/onrc/onos/core/main/Main.java
@@ -12,20 +12,22 @@
/**
* Host for the ONOS main method
+ *
* @author alexreimers
*/
public class Main {
/**
* Main method to load configuration and modules
+ *
* @param args
- * @throws FloodlightModuleException
+ * @throws FloodlightModuleException
*/
public static void main(String[] args) throws FloodlightModuleException {
// Setup logger
- System.setProperty("org.restlet.engine.loggerFacadeClass",
+ System.setProperty("org.restlet.engine.loggerFacadeClass",
"org.restlet.ext.slf4j.Slf4jLoggerFacade");
-
+
CmdLineSettings settings = new CmdLineSettings();
CmdLineParser parser = new CmdLineParser(settings);
try {
@@ -34,7 +36,7 @@
parser.printUsage(System.out);
System.exit(1);
}
-
+
// Load modules
FloodlightModuleLoader fml = new FloodlightModuleLoader();
IFloodlightModuleContext moduleContext = fml.loadModulesFromConfig(settings.getModuleFile());
diff --git a/src/main/java/net/onrc/onos/core/main/config/DefaultConfiguration.java b/src/main/java/net/onrc/onos/core/main/config/DefaultConfiguration.java
index 2feb69d..7f09e31 100644
--- a/src/main/java/net/onrc/onos/core/main/config/DefaultConfiguration.java
+++ b/src/main/java/net/onrc/onos/core/main/config/DefaultConfiguration.java
@@ -17,71 +17,71 @@
public class DefaultConfiguration implements IConfigInfoService, IFloodlightModule {
- @Override
- public boolean isInterfaceAddress(InetAddress address) {
- return false;
- }
+ @Override
+ public boolean isInterfaceAddress(InetAddress address) {
+ return false;
+ }
- @Override
- public boolean inConnectedNetwork(InetAddress address) {
- return false;
- }
+ @Override
+ public boolean inConnectedNetwork(InetAddress address) {
+ return false;
+ }
- @Override
- public boolean fromExternalNetwork(long inDpid, short inPort) {
- return false;
- }
+ @Override
+ public boolean fromExternalNetwork(long inDpid, short inPort) {
+ return false;
+ }
- @Override
- public Interface getOutgoingInterface(InetAddress dstIpAddress) {
- return null;
- }
+ @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 boolean hasLayer3Configuration() {
+ return false;
+ }
- @Override
- public short getVlan() {
- return 0;
- }
+ @Override
+ public MACAddress getRouterMacAddress() {
+ return MACAddress.valueOf(HexString.fromHexString("000000000001"));
+ }
- @Override
- public Collection<Class<? extends IFloodlightService>> getModuleServices() {
- Collection<Class<? extends IFloodlightService>> l
- = new ArrayList<Class<? extends IFloodlightService>>();
- l.add(IConfigInfoService.class);
- return l;
- }
+ @Override
+ public short getVlan() {
+ return 0;
+ }
- @Override
- public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
- Map<Class<? extends IFloodlightService>, IFloodlightService> m
- = new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
- m.put(IConfigInfoService.class, this);
- return m;
- }
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleServices() {
+ Collection<Class<? extends IFloodlightService>> l
+ = new ArrayList<Class<? extends IFloodlightService>>();
+ l.add(IConfigInfoService.class);
+ return l;
+ }
- @Override
- public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
- return null;
- }
+ @Override
+ public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
+ Map<Class<? extends IFloodlightService>, IFloodlightService> m
+ = new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
+ m.put(IConfigInfoService.class, this);
+ return m;
+ }
- @Override
- public void init(FloodlightModuleContext context)
- throws FloodlightModuleException {
- // no-op
- }
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
+ return null;
+ }
- @Override
- public void startUp(FloodlightModuleContext context) {
- // no-op
- }
+ @Override
+ public void init(FloodlightModuleContext context)
+ throws FloodlightModuleException {
+ // no-op
+ }
+
+ @Override
+ public void startUp(FloodlightModuleContext context) {
+ // no-op
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/main/config/IConfigInfoService.java b/src/main/java/net/onrc/onos/core/main/config/IConfigInfoService.java
index 4ca8535..5c94626 100644
--- a/src/main/java/net/onrc/onos/core/main/config/IConfigInfoService.java
+++ b/src/main/java/net/onrc/onos/core/main/config/IConfigInfoService.java
@@ -9,40 +9,44 @@
/**
* Provides information about the layer 3 properties of the network.
* This is based on IP addresses configured on ports in the network.
- *
*/
public interface IConfigInfoService extends IFloodlightService {
- public boolean isInterfaceAddress(InetAddress address);
- public boolean inConnectedNetwork(InetAddress address);
- public boolean fromExternalNetwork(long inDpid, short inPort);
-
- /**
- * Retrieves the {@link Interface} object for the interface that packets
- * to dstIpAddress will be sent out of. Returns null if dstIpAddress is not
- * in a directly connected network, or if no interfaces are configured.
- * @param dstIpAddress Destination IP address that we want to match to
- * an outgoing interface
- * @return The {@link Interface} object if found, null if not
- */
- public Interface getOutgoingInterface(InetAddress dstIpAddress);
-
- /**
- * Returns whether this controller has a layer 3 configuration
- * (i.e. interfaces and IP addresses)
- * @return True if IP addresses are configured, false if not
- */
- 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();
+ public boolean isInterfaceAddress(InetAddress address);
+
+ public boolean inConnectedNetwork(InetAddress address);
+
+ public boolean fromExternalNetwork(long inDpid, short inPort);
+
+ /**
+ * Retrieves the {@link Interface} object for the interface that packets
+ * to dstIpAddress will be sent out of. Returns null if dstIpAddress is not
+ * in a directly connected network, or if no interfaces are configured.
+ *
+ * @param dstIpAddress Destination IP address that we want to match to
+ * an outgoing interface
+ * @return The {@link Interface} object if found, null if not
+ */
+ public Interface getOutgoingInterface(InetAddress dstIpAddress);
+
+ /**
+ * Returns whether this controller has a layer 3 configuration
+ * (i.e. interfaces and IP addresses)
+ *
+ * @return True if IP addresses are configured, false if not
+ */
+ 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/core/packet/ARP.java b/src/main/java/net/onrc/onos/core/packet/ARP.java
index a2e25c3..bc61c91 100644
--- a/src/main/java/net/onrc/onos/core/packet/ARP.java
+++ b/src/main/java/net/onrc/onos/core/packet/ARP.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.packet;
@@ -21,7 +21,6 @@
import java.util.Arrays;
/**
- *
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public class ARP extends BasePacket {
@@ -148,7 +147,7 @@
this.senderProtocolAddress = senderProtocolAddress;
return this;
}
-
+
public ARP setSenderProtocolAddress(int address) {
this.senderProtocolAddress = ByteBuffer.allocate(4).putInt(address).array();
return this;
@@ -179,9 +178,9 @@
/**
* @return True if gratuitous ARP (SPA = TPA), false otherwise
*/
- public boolean isGratuitous() {
- assert(senderProtocolAddress.length == targetProtocolAddress.length);
-
+ public boolean isGratuitous() {
+ assert (senderProtocolAddress.length == targetProtocolAddress.length);
+
int indx = 0;
while (indx < senderProtocolAddress.length) {
if (senderProtocolAddress[indx] != targetProtocolAddress[indx]) {
@@ -189,10 +188,10 @@
}
indx++;
}
-
+
return true;
}
-
+
/**
* @param targetProtocolAddress the targetProtocolAddress to set
*/
@@ -200,7 +199,7 @@
this.targetProtocolAddress = targetProtocolAddress;
return this;
}
-
+
public ARP setTargetProtocolAddress(int address) {
this.targetProtocolAddress = ByteBuffer.allocate(4).putInt(address).array();
return this;
diff --git a/src/main/java/net/onrc/onos/core/packet/BPDU.java b/src/main/java/net/onrc/onos/core/packet/BPDU.java
index 1dc7296..583eeff 100644
--- a/src/main/java/net/onrc/onos/core/packet/BPDU.java
+++ b/src/main/java/net/onrc/onos/core/packet/BPDU.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.packet;
@@ -22,6 +22,7 @@
/**
* This class is a Rapid Spanning Tree Protocol
* Bridge Protocol Data Unit
+ *
* @author alexreimers
*/
public class BPDU extends BasePacket {
@@ -29,9 +30,9 @@
CONFIG,
TOPOLOGY_CHANGE;
}
-
+
private final long destMac = 0x0180c2000000L; // 01-80-c2-00-00-00
-
+
// TODO - check this for RSTP
private LLC llcHeader;
private short protocolId = 0;
@@ -46,17 +47,17 @@
private short maxAge; // 256ths of a second
private short helloTime; // 256ths of a second
private short forwardDelay; // 256ths of a second
-
+
public BPDU(BPDUType type) {
rootBridgeId = new byte[8];
senderBridgeId = new byte[8];
-
+
llcHeader = new LLC();
llcHeader.setDsap((byte) 0x42);
llcHeader.setSsap((byte) 0x42);
llcHeader.setCtrl((byte) 0x03);
-
- switch(type) {
+
+ switch (type) {
case CONFIG:
this.type = 0x0;
break;
@@ -68,19 +69,19 @@
break;
}
}
-
+
@Override
public byte[] serialize() {
byte[] data;
// TODO check these
- if (type == 0x0) {
+ if (type == 0x0) {
// config
data = new byte[38];
} else {
// topology change
data = new byte[7]; // LLC + TC notification
}
-
+
ByteBuffer bb = ByteBuffer.wrap(data);
// Serialize the LLC header
byte[] llc = llcHeader.serialize();
@@ -88,7 +89,7 @@
bb.putShort(protocolId);
bb.put(version);
bb.put(type);
-
+
if (type == 0x0) {
bb.put(flags);
bb.put(rootBridgeId, 0, rootBridgeId.length);
@@ -100,21 +101,21 @@
bb.putShort(helloTime);
bb.putShort(forwardDelay);
}
-
+
return data;
}
@Override
public IPacket deserialize(byte[] data, int offset, int length) {
ByteBuffer bb = ByteBuffer.wrap(data, offset, length);
-
+
// LLC header
llcHeader.deserialize(data, offset, 3);
-
+
this.protocolId = bb.getShort();
this.version = bb.get();
this.type = bb.get();
-
+
// These fields only exist if it's a configuration BPDU
if (this.type == 0x0) {
this.flags = bb.get();
@@ -128,7 +129,7 @@
this.forwardDelay = bb.getShort();
}
// TODO should we set other fields to 0?
-
+
return this;
}
diff --git a/src/main/java/net/onrc/onos/core/packet/BSN.java b/src/main/java/net/onrc/onos/core/packet/BSN.java
index fead254..dedabd5 100644
--- a/src/main/java/net/onrc/onos/core/packet/BSN.java
+++ b/src/main/java/net/onrc/onos/core/packet/BSN.java
@@ -1,21 +1,21 @@
/**
-* Copyright 2012, Big Switch Networks, Inc.
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2012, Big Switch Networks, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
/**
- *
+ *
*/
package net.onrc.onos.core.packet;
@@ -25,72 +25,71 @@
/**
* @author Shudong Zhou (shudong.zhou@bigswitch.com)
- *
*/
public class BSN extends BasePacket {
- public static final int BSN_MAGIC = 0x20000604;
- public static final short BSN_VERSION_CURRENT = 0x0;
- public static final short BSN_TYPE_PROBE = 0x1;
- public static final short BSN_TYPE_BDDP = 0x2;
- public static Map<Short, Class<? extends IPacket>> typeClassMap;
-
+ public static final int BSN_MAGIC = 0x20000604;
+ public static final short BSN_VERSION_CURRENT = 0x0;
+ public static final short BSN_TYPE_PROBE = 0x1;
+ public static final short BSN_TYPE_BDDP = 0x2;
+ public static Map<Short, Class<? extends IPacket>> typeClassMap;
+
static {
typeClassMap = new HashMap<Short, Class<? extends IPacket>>();
typeClassMap.put(BSN_TYPE_PROBE, BSNPROBE.class);
typeClassMap.put(BSN_TYPE_BDDP, LLDP.class);
}
- protected short type;
- protected short version;
+ protected short type;
+ protected short version;
- public BSN() {
- version = BSN_VERSION_CURRENT;
- }
-
+ public BSN() {
+ version = BSN_VERSION_CURRENT;
+ }
+
public BSN(short type) {
- this.type = type;
- version = BSN_VERSION_CURRENT;
+ this.type = type;
+ version = BSN_VERSION_CURRENT;
}
public short getType() {
- return type;
- }
+ return type;
+ }
- public BSN setType(short type) {
- this.type = type;
- return this;
- }
-
+ public BSN setType(short type) {
+ this.type = type;
+ return this;
+ }
+
public short getVersion() {
- return version;
- }
+ return version;
+ }
- public BSN setVersion(short version) {
- this.version = version;
- return this;
- }
+ public BSN setVersion(short version) {
+ this.version = version;
+ return this;
+ }
@Override
public byte[] serialize() {
- short length = 4 /* magic */ + 2 /* type */ + 2 /* version */;
-
- byte[] payloadData = null;
- if (this.payload != null) {
+ short length = 4 /* magic */ + 2 /* type */ + 2 /* version */;
+
+ byte[] payloadData = null;
+ if (this.payload != null) {
payload.setParent(this);
payloadData = payload.serialize();
length += payloadData.length;
}
-
+
byte[] data = new byte[length];
ByteBuffer bb = ByteBuffer.wrap(data);
bb.putInt(BSN_MAGIC);
bb.putShort(this.type);
bb.putShort(this.version);
if (payloadData != null)
- bb.put(payloadData);
+ bb.put(payloadData);
if (this.parent != null && this.parent instanceof Ethernet)
- ((Ethernet)this.parent).setEtherType(Ethernet.TYPE_BSN);
+ ((Ethernet) this.parent).setEtherType(Ethernet.TYPE_BSN);
return data;
}
@@ -98,20 +97,20 @@
@Override
public IPacket deserialize(byte[] data, int offset, int length) {
ByteBuffer bb = ByteBuffer.wrap(data, offset, length);
-
+
int magic = bb.getInt();
if (magic != BSN_MAGIC) {
- throw new RuntimeException("Invalid BSN magic " + magic);
+ throw new RuntimeException("Invalid BSN magic " + magic);
}
-
+
this.type = bb.getShort();
this.version = bb.getShort();
if (this.version != BSN_VERSION_CURRENT) {
- throw new RuntimeException(
- "Invalid BSN packet version " + this.version + ", should be "
- + BSN_VERSION_CURRENT);
+ throw new RuntimeException(
+ "Invalid BSN packet version " + this.version + ", should be "
+ + BSN_VERSION_CURRENT);
}
-
+
IPacket payload;
if (typeClassMap.containsKey(this.type)) {
Class<? extends IPacket> clazz = typeClassMap.get(this.type);
@@ -123,11 +122,11 @@
} else {
payload = new Data();
}
-
+
this.payload = new Data();
this.payload = payload.deserialize(data, bb.position(), bb.limit() - bb.position());
this.payload.setParent(this);
-
+
return this;
}
@@ -156,17 +155,17 @@
return false;
BSN other = (BSN) obj;
return (type == other.type &&
- version == other.version);
+ version == other.version);
}
-
+
public String toString() {
- StringBuffer sb = new StringBuffer("\n");
- sb.append("BSN packet");
+ StringBuffer sb = new StringBuffer("\n");
+ sb.append("BSN packet");
if (typeClassMap.containsKey(this.type))
- sb.append(" type: " + typeClassMap.get(this.type).getCanonicalName());
+ sb.append(" type: " + typeClassMap.get(this.type).getCanonicalName());
else
- sb.append(" type: " + this.type);
-
- return sb.toString();
+ sb.append(" type: " + this.type);
+
+ return sb.toString();
}
}
diff --git a/src/main/java/net/onrc/onos/core/packet/BSNPROBE.java b/src/main/java/net/onrc/onos/core/packet/BSNPROBE.java
index 24dbe90..e411b7e 100644
--- a/src/main/java/net/onrc/onos/core/packet/BSNPROBE.java
+++ b/src/main/java/net/onrc/onos/core/packet/BSNPROBE.java
@@ -1,21 +1,21 @@
/**
-* Copyright 2012, Big Switch Networks, Inc.
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2012, Big Switch Networks, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
/**
- *
+ *
*/
package net.onrc.onos.core.packet;
@@ -26,15 +26,14 @@
/**
* @author Shudong Zhou (shudong.zhou@bigswitch.com)
- *
*/
-public class BSNPROBE extends BasePacket {
- protected long controllerId;
- protected int sequenceId;
- protected byte[] srcMac;
- protected byte[] dstMac;
- protected long srcSwDpid;
- protected int srcPortNo;
+public class BSNPROBE extends BasePacket {
+ protected long controllerId;
+ protected int sequenceId;
+ protected byte[] srcMac;
+ protected byte[] dstMac;
+ protected long srcSwDpid;
+ protected int srcPortNo;
public BSNPROBE() {
srcMac = new byte[6];
@@ -42,24 +41,24 @@
}
- public long getControllerId() {
- return this.controllerId;
- }
+ public long getControllerId() {
+ return this.controllerId;
+ }
- public BSNPROBE setControllerId(long controllerId) {
- this.controllerId = controllerId;
- return this;
- }
+ public BSNPROBE setControllerId(long controllerId) {
+ this.controllerId = controllerId;
+ return this;
+ }
- public int getSequenceId() {
- return sequenceId;
- }
+ public int getSequenceId() {
+ return sequenceId;
+ }
- public BSNPROBE setSequenceId(int sequenceId) {
- this.sequenceId = sequenceId;
- return this;
- }
-
+ public BSNPROBE setSequenceId(int sequenceId) {
+ this.sequenceId = sequenceId;
+ return this;
+ }
+
public byte[] getSrcMac() {
return this.srcMac;
}
@@ -68,46 +67,46 @@
this.srcMac = srcMac;
return this;
}
-
- public byte[] getDstMac() {
- return dstMac;
- }
- public BSNPROBE setDstMac(byte[] dstMac) {
- this.dstMac = dstMac;
- return this;
- }
+ public byte[] getDstMac() {
+ return dstMac;
+ }
- public long getSrcSwDpid() {
- return srcSwDpid;
- }
+ public BSNPROBE setDstMac(byte[] dstMac) {
+ this.dstMac = dstMac;
+ return this;
+ }
- public BSNPROBE setSrcSwDpid(long srcSwDpid) {
- this.srcSwDpid = srcSwDpid;
- return this;
- }
+ public long getSrcSwDpid() {
+ return srcSwDpid;
+ }
- public int getSrcPortNo() {
- return srcPortNo;
- }
+ public BSNPROBE setSrcSwDpid(long srcSwDpid) {
+ this.srcSwDpid = srcSwDpid;
+ return this;
+ }
- public BSNPROBE setSrcPortNo(int srcPortNo) {
- this.srcPortNo = srcPortNo;
- return this;
- }
+ public int getSrcPortNo() {
+ return srcPortNo;
+ }
+
+ public BSNPROBE setSrcPortNo(int srcPortNo) {
+ this.srcPortNo = srcPortNo;
+ return this;
+ }
@Override
public byte[] serialize() {
- short length = 8 /* controllerId */ + 4 /* seqId */
- + 12 /* srcMac dstMac */ + 8 /* srcSwDpid */ + 4 /* srcPortNo */;
-
- byte[] payloadData = null;
- if (this.payload != null) {
+ short length = 8 /* controllerId */ + 4 /* seqId */
+ + 12 /* srcMac dstMac */ + 8 /* srcSwDpid */ + 4 /* srcPortNo */;
+
+ byte[] payloadData = null;
+ if (this.payload != null) {
payload.setParent(this);
payloadData = payload.serialize();
length += payloadData.length;
}
-
+
byte[] data = new byte[length];
ByteBuffer bb = ByteBuffer.wrap(data);
bb.putLong(this.controllerId);
@@ -117,10 +116,10 @@
bb.putLong(this.srcSwDpid);
bb.putInt(this.srcPortNo);
if (payloadData != null)
- bb.put(payloadData);
+ bb.put(payloadData);
if (this.parent != null && this.parent instanceof BSN)
- ((BSN)this.parent).setType(BSN.BSN_TYPE_PROBE);
+ ((BSN) this.parent).setType(BSN.BSN_TYPE_PROBE);
return data;
}
@@ -128,20 +127,20 @@
@Override
public IPacket deserialize(byte[] data, int offset, int length) {
ByteBuffer bb = ByteBuffer.wrap(data, offset, length);
-
+
controllerId = bb.getLong();
sequenceId = bb.getInt();
bb.get(this.srcMac, 0, 6);
bb.get(this.dstMac, 0, 6);
this.srcSwDpid = bb.getLong();
this.srcPortNo = bb.getInt();
-
+
if (bb.hasRemaining()) {
- this.payload = new Data();
- this.payload = payload.deserialize(data, bb.position(), bb.limit() - bb.position());
- this.payload.setParent(this);
+ this.payload = new Data();
+ this.payload = payload.deserialize(data, bb.position(), bb.limit() - bb.position());
+ this.payload.setParent(this);
}
-
+
return this;
}
@@ -174,25 +173,25 @@
if (!Arrays.equals(srcMac, other.srcMac))
return false;
if (!Arrays.equals(dstMac, other.dstMac))
- return false;
+ return false;
return (sequenceId == other.sequenceId &&
- srcSwDpid == other.srcSwDpid &&
- srcPortNo == other.srcPortNo
- );
+ srcSwDpid == other.srcSwDpid &&
+ srcPortNo == other.srcPortNo
+ );
}
-
+
public String toString() {
- StringBuffer sb = new StringBuffer("\n");
- sb.append("BSN Probe packet");
- sb.append("\nSource Mac: ");
- sb.append(HexString.toHexString(srcMac));
- sb.append("\nDestination Mac: ");
- sb.append(HexString.toHexString(dstMac));
- sb.append("\nSource Switch: ");
- sb.append(HexString.toHexString(srcSwDpid));
- sb.append(" port: " + srcPortNo);
- sb.append("\nSequence No.:" + sequenceId);
-
- return sb.toString();
+ StringBuffer sb = new StringBuffer("\n");
+ sb.append("BSN Probe packet");
+ sb.append("\nSource Mac: ");
+ sb.append(HexString.toHexString(srcMac));
+ sb.append("\nDestination Mac: ");
+ sb.append(HexString.toHexString(dstMac));
+ sb.append("\nSource Switch: ");
+ sb.append(HexString.toHexString(srcSwDpid));
+ sb.append(" port: " + srcPortNo);
+ sb.append("\nSequence No.:" + sequenceId);
+
+ return sb.toString();
}
}
diff --git a/src/main/java/net/onrc/onos/core/packet/BasePacket.java b/src/main/java/net/onrc/onos/core/packet/BasePacket.java
index d3b382b..4f4f478 100644
--- a/src/main/java/net/onrc/onos/core/packet/BasePacket.java
+++ b/src/main/java/net/onrc/onos/core/packet/BasePacket.java
@@ -1,27 +1,26 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.packet;
/**
-*
-* @author David Erickson (daviderickson@cs.stanford.edu)
-*/
+ * @author David Erickson (daviderickson@cs.stanford.edu)
+ */
public abstract class BasePacket implements IPacket {
protected IPacket parent;
protected IPacket payload;
@@ -59,7 +58,7 @@
this.payload = payload;
return this;
}
-
+
@Override
public void resetChecksum() {
if (this.parent != null)
@@ -96,7 +95,7 @@
return false;
return true;
}
-
+
@Override
public Object clone() {
IPacket pkt;
diff --git a/src/main/java/net/onrc/onos/core/packet/DHCP.java b/src/main/java/net/onrc/onos/core/packet/DHCP.java
index 16cc22f..ee3052b 100644
--- a/src/main/java/net/onrc/onos/core/packet/DHCP.java
+++ b/src/main/java/net/onrc/onos/core/packet/DHCP.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.packet;
@@ -24,7 +24,6 @@
import java.util.ListIterator;
/**
- *
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public class DHCP extends BasePacket {
@@ -52,7 +51,6 @@
* ------------------------------------------
* | options (312) |
* ------------------------------------------
- *
*/
// Header + magic without options
public static int MIN_HEADER_LENGTH = 240;
@@ -60,30 +58,30 @@
public static byte OPCODE_REPLY = 0x2;
public static byte HWTYPE_ETHERNET = 0x1;
-
+
public enum DHCPOptionCode {
- OptionCode_SubnetMask ((byte)1),
- OptionCode_RequestedIP ((byte)50),
- OptionCode_LeaseTime ((byte)51),
- OptionCode_MessageType ((byte)53),
- OptionCode_DHCPServerIp ((byte)54),
- OptionCode_RequestedParameters ((byte)55),
- OptionCode_RenewalTime ((byte)58),
- OPtionCode_RebindingTime ((byte)59),
- OptionCode_ClientID ((byte)61),
- OptionCode_END ((byte)255);
-
+ OptionCode_SubnetMask((byte) 1),
+ OptionCode_RequestedIP((byte) 50),
+ OptionCode_LeaseTime((byte) 51),
+ OptionCode_MessageType((byte) 53),
+ OptionCode_DHCPServerIp((byte) 54),
+ OptionCode_RequestedParameters((byte) 55),
+ OptionCode_RenewalTime((byte) 58),
+ OPtionCode_RebindingTime((byte) 59),
+ OptionCode_ClientID((byte) 61),
+ OptionCode_END((byte) 255);
+
protected byte value;
-
+
private DHCPOptionCode(byte value) {
this.value = value;
}
-
+
public byte getValue() {
return value;
}
}
-
+
protected byte opCode;
protected byte hardwareType;
protected byte hardwareAddressLength;
@@ -279,9 +277,10 @@
this.clientHardwareAddress = clientHardwareAddress;
return this;
}
-
+
/**
* Gets a specific DHCP option parameter
+ *
* @param opetionCode The option code to get
* @return The value of the option if it exists, null otherwise
*/
@@ -322,7 +321,7 @@
}
return null;
}
-
+
/**
* @return the serverName
*/
@@ -364,14 +363,14 @@
if (option.getCode() == 0 || option.getCode() == 255) {
optionsLength += 1;
} else {
- optionsLength += 2 + (int)(0xff & option.getLength());
+ optionsLength += 2 + (int) (0xff & option.getLength());
}
}
int optionsPadLength = 0;
if (optionsLength < 60)
optionsPadLength = 60 - optionsLength;
- byte[] data = new byte[240+optionsLength+optionsPadLength];
+ byte[] data = new byte[240 + optionsLength + optionsPadLength];
ByteBuffer bb = ByteBuffer.wrap(data);
bb.put(this.opCode);
bb.put(this.hardwareType);
@@ -417,7 +416,7 @@
} else {
byte[] bytes = null;
try {
- bytes = string.getBytes("ascii");
+ bytes = string.getBytes("ascii");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Failure encoding server name", e);
}
@@ -438,7 +437,7 @@
if (bb.remaining() < MIN_HEADER_LENGTH) {
return this;
}
-
+
this.opCode = bb.get();
this.hardwareType = bb.get();
this.hardwareAddressLength = bb.get();
@@ -483,13 +482,13 @@
} else {
// Skip the invalid option and set the END option
code = 0xff;
- option.setCode((byte)code);
+ option.setCode((byte) code);
option.setLength((byte) 0);
}
} else {
// Skip the invalid option and set the END option
code = 0xff;
- option.setCode((byte)code);
+ option.setCode((byte) code);
option.setLength((byte) 0);
}
}
diff --git a/src/main/java/net/onrc/onos/core/packet/DHCPOption.java b/src/main/java/net/onrc/onos/core/packet/DHCPOption.java
index 4681e0b..7c56a34 100644
--- a/src/main/java/net/onrc/onos/core/packet/DHCPOption.java
+++ b/src/main/java/net/onrc/onos/core/packet/DHCPOption.java
@@ -1,26 +1,25 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.packet;
import java.util.Arrays;
/**
- *
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public class DHCPOption {
diff --git a/src/main/java/net/onrc/onos/core/packet/DHCPPacketType.java b/src/main/java/net/onrc/onos/core/packet/DHCPPacketType.java
index d68c22f..9d83c15 100644
--- a/src/main/java/net/onrc/onos/core/packet/DHCPPacketType.java
+++ b/src/main/java/net/onrc/onos/core/packet/DHCPPacketType.java
@@ -1,55 +1,55 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.packet;
public enum DHCPPacketType {
// From RFC 1533
- DHCPDISCOVER (1),
- DHCPOFFER (2),
- DHCPREQUEST (3),
- DHCPDECLINE (4),
- DHCPACK (5),
- DHCPNAK (6),
- DHCPRELEASE (7),
-
+ DHCPDISCOVER(1),
+ DHCPOFFER(2),
+ DHCPREQUEST(3),
+ DHCPDECLINE(4),
+ DHCPACK(5),
+ DHCPNAK(6),
+ DHCPRELEASE(7),
+
// From RFC2132
- DHCPINFORM (8),
-
+ DHCPINFORM(8),
+
// From RFC3203
- DHCPFORCERENEW (9),
-
+ DHCPFORCERENEW(9),
+
// From RFC4388
- DHCPLEASEQUERY (10),
- DHCPLEASEUNASSIGNED (11),
- DHCPLEASEUNKNOWN (12),
- DHCPLEASEACTIVE (13);
-
+ DHCPLEASEQUERY(10),
+ DHCPLEASEUNASSIGNED(11),
+ DHCPLEASEUNKNOWN(12),
+ DHCPLEASEACTIVE(13);
+
protected int value;
-
+
private DHCPPacketType(int value) {
this.value = value;
}
-
+
public int getValue() {
return value;
}
-
- public String toString(){
+
+ public String toString() {
switch (value) {
case 1:
return "DHCPDISCOVER";
@@ -78,9 +78,10 @@
case 13:
return "DHCPLEASEACTIVE";
}
-
+
return null;
}
+
public static DHCPPacketType getType(int value) {
switch (value) {
case 1:
@@ -110,7 +111,7 @@
case 13:
return DHCPLEASEACTIVE;
}
-
+
return null;
}
}
diff --git a/src/main/java/net/onrc/onos/core/packet/Data.java b/src/main/java/net/onrc/onos/core/packet/Data.java
index e8617ad..f6f9138 100644
--- a/src/main/java/net/onrc/onos/core/packet/Data.java
+++ b/src/main/java/net/onrc/onos/core/packet/Data.java
@@ -1,33 +1,32 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.packet;
import java.util.Arrays;
/**
- *
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public class Data extends BasePacket {
protected byte[] data;
/**
- *
+ *
*/
public Data() {
}
diff --git a/src/main/java/net/onrc/onos/core/packet/Ethernet.java b/src/main/java/net/onrc/onos/core/packet/Ethernet.java
index 794b3b7..8a4b0fb 100644
--- a/src/main/java/net/onrc/onos/core/packet/Ethernet.java
+++ b/src/main/java/net/onrc/onos/core/packet/Ethernet.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.packet;
@@ -27,7 +27,6 @@
import org.openflow.util.HexString;
/**
- *
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public class Ethernet extends BasePacket {
@@ -37,7 +36,7 @@
public static final short TYPE_IPv4 = 0x0800;
public static final short TYPE_LLDP = (short) 0x88cc;
public static final short TYPE_BSN = (short) 0x8942;
- public static final short VLAN_UNTAGGED = (short)0xffff;
+ public static final short VLAN_UNTAGGED = (short) 0xffff;
public static final short DATALAYER_ADDRESS_LENGTH = 6; // bytes
public static Map<Short, Class<? extends IPacket>> etherTypeClassMap;
@@ -64,14 +63,14 @@
super();
this.vlanID = VLAN_UNTAGGED;
}
-
+
/**
* @return the destination MAC as a byte array
*/
public byte[] getDestinationMACAddress() {
return destinationMACAddress.toBytes();
}
-
+
/**
* @return the destination MAC
*/
@@ -101,7 +100,7 @@
public byte[] getSourceMACAddress() {
return sourceMACAddress.toBytes();
}
-
+
/**
* @return the source MACAddress
*/
@@ -169,23 +168,25 @@
this.etherType = etherType;
return this;
}
-
+
/**
* @return True if the Ethernet frame is broadcast, false otherwise
*/
public boolean isBroadcast() {
- assert(destinationMACAddress.length() == 6);
+ assert (destinationMACAddress.length() == 6);
return destinationMACAddress.isBroadcast();
}
-
+
/**
* @return True is the Ethernet frame is multicast, False otherwise
*/
public boolean isMulticast() {
return destinationMACAddress.isMulticast();
}
+
/**
* Pad this packet to 60 bytes minimum, filling with zeros?
+ *
* @return the pad
*/
public boolean isPad() {
@@ -194,6 +195,7 @@
/**
* Pad this packet to 60 bytes minimum, filling with zeros?
+ *
* @param pad the pad to set
*/
public Ethernet setPad(boolean pad) {
@@ -208,7 +210,7 @@
payloadData = payload.serialize();
}
int length = 14 + ((vlanID == VLAN_UNTAGGED) ? 0 : 4) +
- ((payloadData == null) ? 0 : payloadData.length);
+ ((payloadData == null) ? 0 : payloadData.length);
if (pad && length < 60) {
length = 60;
}
@@ -224,7 +226,7 @@
if (payloadData != null)
bb.put(payloadData);
if (pad) {
- Arrays.fill(data, bb.position(), data.length, (byte)0x0);
+ Arrays.fill(data, bb.position(), data.length, (byte) 0x0);
}
return data;
}
@@ -256,7 +258,7 @@
this.vlanID = VLAN_UNTAGGED;
}
this.etherType = etherType;
-
+
IPacket payload;
if (Ethernet.etherTypeClassMap.containsKey(this.etherType)) {
Class<? extends IPacket> clazz = Ethernet.etherTypeClassMap.get(this.etherType);
@@ -268,13 +270,14 @@
} else {
payload = new Data();
}
- this.payload = payload.deserialize(data, bb.position(), bb.limit()-bb.position());
+ this.payload = payload.deserialize(data, bb.position(), bb.limit() - bb.position());
this.payload.setParent(this);
return this;
}
/**
* Checks to see if a string is a valid MAC address.
+ *
* @param macAddress
* @return True if macAddress is a valid MAC, False otherwise
*/
@@ -283,8 +286,8 @@
if (macBytes.length != 6)
return false;
for (int i = 0; i < 6; ++i) {
- if (HEXES.indexOf(macBytes[i].toUpperCase().charAt(0)) == -1 ||
- HEXES.indexOf(macBytes[i].toUpperCase().charAt(1)) == -1) {
+ if (HEXES.indexOf(macBytes[i].toUpperCase().charAt(0)) == -1 ||
+ HEXES.indexOf(macBytes[i].toUpperCase().charAt(1)) == -1) {
return false;
}
}
@@ -294,8 +297,9 @@
/**
* Accepts a MAC address of the form 00:aa:11:bb:22:cc, case does not
* matter, and returns a corresponding byte[].
+ *
* @param macAddress The MAC address to convert into a bye array
- * @return The macAddress as a byte array
+ * @return The macAddress as a byte array
*/
public static byte[] toMACAddress(String macAddress) {
return MACAddress.valueOf(macAddress).toBytes();
@@ -305,6 +309,7 @@
/**
* Accepts a MAC address and returns the corresponding long, where the
* MAC bytes are set on the lower order bytes of the long.
+ *
* @param macAddress
* @return a long containing the mac address bytes
*/
@@ -314,13 +319,14 @@
/**
* Convert a long MAC address to a byte array
+ *
* @param macAddress
* @return the bytes of the mac address
*/
public static byte[] toByteArray(long macAddress) {
return MACAddress.valueOf(macAddress).toBytes();
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@@ -363,7 +369,7 @@
return false;
return true;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#toString(java.lang.Object)
*/
@@ -384,7 +390,7 @@
sb.append("ip");
else if (pkt instanceof DHCP)
sb.append("dhcp");
- else sb.append(this.getEtherType());
+ else sb.append(this.getEtherType());
sb.append("\ndl_vlan: ");
if (this.getVlanID() == Ethernet.VLAN_UNTAGGED)
@@ -405,18 +411,15 @@
sb.append(IPv4.fromIPv4Address(IPv4.toIPv4Address(p.getSenderProtocolAddress())));
sb.append("\nnw_dst: ");
sb.append(IPv4.fromIPv4Address(IPv4.toIPv4Address(p.getTargetProtocolAddress())));
- }
- else if (pkt instanceof LLDP) {
+ } else if (pkt instanceof LLDP) {
sb.append("lldp packet");
- }
- else if (pkt instanceof ICMP) {
+ } else if (pkt instanceof ICMP) {
ICMP icmp = (ICMP) pkt;
sb.append("\nicmp_type: ");
sb.append(icmp.getIcmpType());
sb.append("\nicmp_code: ");
sb.append(icmp.getIcmpCode());
- }
- else if (pkt instanceof IPv4) {
+ } else if (pkt instanceof IPv4) {
IPv4 p = (IPv4) pkt;
sb.append("\nnw_src: ");
sb.append(IPv4.fromIPv4Address(p.getSourceAddress()));
@@ -448,20 +451,15 @@
sb.append(icmp.getIcmpCode());
}
- }
- else if (pkt instanceof DHCP) {
+ } else if (pkt instanceof DHCP) {
sb.append("\ndhcp packet");
- }
- else if (pkt instanceof Data) {
+ } else if (pkt instanceof Data) {
sb.append("\ndata packet");
- }
- else if (pkt instanceof LLC) {
+ } else if (pkt instanceof LLC) {
sb.append("\nllc packet");
- }
- else if (pkt instanceof BPDU) {
+ } else if (pkt instanceof BPDU) {
sb.append("\nbpdu packet");
- }
- else sb.append("\nunknwon packet");
+ } else sb.append("\nunknwon packet");
return sb.toString();
}
diff --git a/src/main/java/net/onrc/onos/core/packet/ICMP.java b/src/main/java/net/onrc/onos/core/packet/ICMP.java
index b575878..4b80c94 100644
--- a/src/main/java/net/onrc/onos/core/packet/ICMP.java
+++ b/src/main/java/net/onrc/onos/core/packet/ICMP.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.packet;
@@ -21,6 +21,7 @@
/**
* Implements ICMP packet format
+ *
* @author shudong.zhou@bigswitch.com
*/
public class ICMP extends BasePacket {
@@ -76,8 +77,8 @@
/**
* Serializes the packet. Will compute and set the following fields if they
* are set to specific values at the time serialize is called:
- * -checksum : 0
- * -length : 0
+ * -checksum : 0
+ * -length : 0
*/
public byte[] serialize() {
int length = 4;
@@ -98,7 +99,7 @@
bb.put(payloadData);
if (this.parent != null && this.parent instanceof IPv4)
- ((IPv4)this.parent).setProtocol(IPv4.PROTOCOL_ICMP);
+ ((IPv4) this.parent).setProtocol(IPv4.PROTOCOL_ICMP);
// compute checksum if needed
if (this.checksum == 0) {
@@ -161,9 +162,9 @@
this.icmpType = bb.get();
this.icmpCode = bb.get();
this.checksum = bb.getShort();
-
+
this.payload = new Data();
- this.payload = payload.deserialize(data, bb.position(), bb.limit()-bb.position());
+ this.payload = payload.deserialize(data, bb.position(), bb.limit() - bb.position());
this.payload.setParent(this);
return this;
}
diff --git a/src/main/java/net/onrc/onos/core/packet/IPacket.java b/src/main/java/net/onrc/onos/core/packet/IPacket.java
index 0cfc51f..8f31960 100644
--- a/src/main/java/net/onrc/onos/core/packet/IPacket.java
+++ b/src/main/java/net/onrc/onos/core/packet/IPacket.java
@@ -1,48 +1,43 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.packet;
/**
-*
-* @author David Erickson (daviderickson@cs.stanford.edu)
-*/
+ * @author David Erickson (daviderickson@cs.stanford.edu)
+ */
public interface IPacket {
/**
- *
* @return
*/
public IPacket getPayload();
/**
- *
* @param packet
* @return
*/
public IPacket setPayload(IPacket packet);
/**
- *
* @return
*/
public IPacket getParent();
/**
- *
* @param packet
* @return
*/
@@ -52,25 +47,28 @@
* Reset any checksums as needed, and call resetChecksum on all parents
*/
public void resetChecksum();
-
+
/**
- * Sets all payloads parent packet if applicable, then serializes this
+ * Sets all payloads parent packet if applicable, then serializes this
* packet and all payloads
+ *
* @return a byte[] containing this packet and payloads
*/
public byte[] serialize();
/**
* Deserializes this packet layer and all possible payloads
+ *
* @param data
* @param offset offset to start deserializing from
* @param length length of the data to deserialize
* @return the deserialized data
*/
public IPacket deserialize(byte[] data, int offset, int length);
-
- /** Clone this packet and its payload packet but not its parent.
- *
+
+ /**
+ * Clone this packet and its payload packet but not its parent.
+ *
* @return
*/
public Object clone();
diff --git a/src/main/java/net/onrc/onos/core/packet/IPv4.java b/src/main/java/net/onrc/onos/core/packet/IPv4.java
index 7f9db1a..1195c7c 100644
--- a/src/main/java/net/onrc/onos/core/packet/IPv4.java
+++ b/src/main/java/net/onrc/onos/core/packet/IPv4.java
@@ -1,22 +1,22 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
/**
- *
+ *
*/
package net.onrc.onos.core.packet;
@@ -28,10 +28,9 @@
/**
* @author David Erickson (daviderickson@cs.stanford.edu)
- *
*/
public class IPv4 extends BasePacket {
- public static final int ADDRESS_LENGTH = 4;
+ public static final int ADDRESS_LENGTH = 4;
public static final byte PROTOCOL_ICMP = 0x1;
public static final byte PROTOCOL_TCP = 0x6;
public static final byte PROTOCOL_UDP = 0x11;
@@ -210,6 +209,7 @@
this.checksum = checksum;
return this;
}
+
@Override
public void resetChecksum() {
this.checksum = 0;
@@ -283,9 +283,9 @@
/**
* Serializes the packet. Will compute and set the following fields if they
* are set to specific values at the time serialize is called:
- * -checksum : 0
- * -headerLength : 0
- * -totalLength : 0
+ * -checksum : 0
+ * -headerLength : 0
+ * -totalLength : 0
*/
public byte[] serialize() {
byte[] payloadData = null;
@@ -372,7 +372,7 @@
} else {
payload = new Data();
}
- this.payload = payload.deserialize(data, bb.position(), bb.limit()-bb.position());
+ this.payload = payload.deserialize(data, bb.position(), bb.limit() - bb.position());
this.payload.setParent(this);
if (this.totalLength != length)
@@ -386,21 +386,22 @@
/**
* Accepts an IPv4 address of the form xxx.xxx.xxx.xxx, ie 192.168.0.1 and
* returns the corresponding 32 bit integer.
+ *
* @param ipAddress
* @return
*/
public static int toIPv4Address(String ipAddress) {
if (ipAddress == null)
throw new IllegalArgumentException("Specified IPv4 address must" +
- "contain 4 sets of numerical digits separated by periods");
+ "contain 4 sets of numerical digits separated by periods");
String[] octets = ipAddress.split("\\.");
- if (octets.length != 4)
+ if (octets.length != 4)
throw new IllegalArgumentException("Specified IPv4 address must" +
- "contain 4 sets of numerical digits separated by periods");
+ "contain 4 sets of numerical digits separated by periods");
int result = 0;
for (int i = 0; i < 4; ++i) {
- result |= Integer.valueOf(octets[i]) << ((3-i)*8);
+ result |= Integer.valueOf(octets[i]) << ((3 - i) * 8);
}
return result;
}
@@ -408,14 +409,15 @@
/**
* Accepts an IPv4 address in a byte array and returns the corresponding
* 32-bit integer value.
+ *
* @param ipAddress
* @return
*/
public static int toIPv4Address(byte[] ipAddress) {
int ip = 0;
for (int i = 0; i < 4; i++) {
- int t = (ipAddress[i] & 0xff) << ((3-i)*8);
- ip |= t;
+ int t = (ipAddress[i] & 0xff) << ((3 - i) * 8);
+ ip |= t;
}
return ip;
}
@@ -423,7 +425,7 @@
/**
* Accepts an IPv4 address and returns of string of the form xxx.xxx.xxx.xxx
* ie 192.168.0.1
- *
+ *
* @param ipAddress
* @return
*/
@@ -431,7 +433,7 @@
StringBuffer sb = new StringBuffer();
int result = 0;
for (int i = 0; i < 4; ++i) {
- result = (ipAddress >> ((3-i)*8)) & 0xff;
+ result = (ipAddress >> ((3 - i) * 8)) & 0xff;
sb.append(Integer.valueOf(result).toString());
if (i != 3)
sb.append(".");
@@ -443,7 +445,7 @@
* Accepts a collection of IPv4 addresses as integers and returns a single
* String useful in toString method's containing collections of IP
* addresses.
- *
+ *
* @param ipAddresses collection
* @return
*/
@@ -456,21 +458,22 @@
sb.append(fromIPv4Address(ip));
sb.append(",");
}
- sb.replace(sb.length()-1, sb.length(), "]");
+ sb.replace(sb.length() - 1, sb.length(), "]");
return sb.toString();
}
/**
* Accepts an IPv4 address of the form xxx.xxx.xxx.xxx, ie 192.168.0.1 and
* returns the corresponding byte array.
+ *
* @param ipAddress The IP address in the form xx.xxx.xxx.xxx.
* @return The IP address separated into bytes
*/
public static byte[] toIPv4AddressBytes(String ipAddress) {
String[] octets = ipAddress.split("\\.");
- if (octets.length != 4)
+ if (octets.length != 4)
throw new IllegalArgumentException("Specified IPv4 address must" +
- "contain 4 sets of numerical digits separated by periods");
+ "contain 4 sets of numerical digits separated by periods");
byte[] result = new byte[4];
for (int i = 0; i < 4; ++i) {
@@ -478,19 +481,20 @@
}
return result;
}
-
+
/**
* Accepts an IPv4 address in the form of an integer and
* returns the corresponding byte array.
+ *
* @param ipAddress The IP address as an integer.
* @return The IP address separated into bytes.
*/
public static byte[] toIPv4AddressBytes(int ipAddress) {
- return new byte[] {
- (byte)(ipAddress >>> 24),
- (byte)(ipAddress >>> 16),
- (byte)(ipAddress >>> 8),
- (byte)ipAddress};
+ return new byte[]{
+ (byte) (ipAddress >>> 24),
+ (byte) (ipAddress >>> 16),
+ (byte) (ipAddress >>> 8),
+ (byte) ipAddress};
}
/* (non-Javadoc)
diff --git a/src/main/java/net/onrc/onos/core/packet/LLC.java b/src/main/java/net/onrc/onos/core/packet/LLC.java
index c4f0c27..d809f12 100644
--- a/src/main/java/net/onrc/onos/core/packet/LLC.java
+++ b/src/main/java/net/onrc/onos/core/packet/LLC.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.packet;
@@ -22,14 +22,14 @@
/**
* This class represents an Link Local Control
* header that is used in Ethernet 802.3.
- * @author alexreimers
*
+ * @author alexreimers
*/
public class LLC extends BasePacket {
private byte dsap = 0;
private byte ssap = 0;
private byte ctrl = 0;
-
+
public byte getDsap() {
return dsap;
}
diff --git a/src/main/java/net/onrc/onos/core/packet/LLDP.java b/src/main/java/net/onrc/onos/core/packet/LLDP.java
index 307a052..0b0f9ec 100644
--- a/src/main/java/net/onrc/onos/core/packet/LLDP.java
+++ b/src/main/java/net/onrc/onos/core/packet/LLDP.java
@@ -1,22 +1,22 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
/**
- *
+ *
*/
package net.onrc.onos.core.packet;
@@ -26,7 +26,6 @@
/**
* @author David Erickson (daviderickson@cs.stanford.edu)
- *
*/
public class LLDP extends BasePacket {
protected LLDPTLV chassisId;
@@ -102,8 +101,8 @@
@Override
public byte[] serialize() {
- int length = 2+this.chassisId.getLength() + 2+this.portId.getLength() +
- 2+this.ttl.getLength() + 2;
+ int length = 2 + this.chassisId.getLength() + 2 + this.portId.getLength() +
+ 2 + this.ttl.getLength() + 2;
for (LLDPTLV tlv : this.optionalTLVList) {
length += 2 + tlv.getLength();
}
@@ -119,7 +118,7 @@
bb.putShort((short) 0); // End of LLDPDU
if (this.parent != null && this.parent instanceof Ethernet)
- ((Ethernet)this.parent).setEtherType(ethType);
+ ((Ethernet) this.parent).setEtherType(ethType);
return data;
}
diff --git a/src/main/java/net/onrc/onos/core/packet/LLDPOrganizationalTLV.java b/src/main/java/net/onrc/onos/core/packet/LLDPOrganizationalTLV.java
index f3cd655..beae222 100644
--- a/src/main/java/net/onrc/onos/core/packet/LLDPOrganizationalTLV.java
+++ b/src/main/java/net/onrc/onos/core/packet/LLDPOrganizationalTLV.java
@@ -39,13 +39,14 @@
/**
* Set the value of OUI.
+ *
* @param oui The value of OUI to be set.
* @return This LLDP Organizationally Specific TLV.
*/
public LLDPOrganizationalTLV setOUI(byte[] oui) {
if (oui.length != OUI_LENGTH) {
throw new IllegalArgumentException("The length of OUI must be " + OUI_LENGTH +
- ", but it is " + oui.length);
+ ", but it is " + oui.length);
}
this.oui = Arrays.copyOf(oui, oui.length);
return this;
@@ -53,6 +54,7 @@
/**
* Returns the value of the OUI.
+ *
* @return The value of the OUI .
*/
public byte[] getOUI() {
@@ -61,6 +63,7 @@
/**
* Set the value of sub type.
+ *
* @param subType The value of sub type to be set.
* @return This LLDP Organizationally Specific TLV.
*/
@@ -71,6 +74,7 @@
/**
* Returns the value of the sub type.
+ *
* @return The value of the sub type.
*/
public byte getSubType() {
@@ -79,6 +83,7 @@
/**
* Set the value of information string.
+ *
* @param infoString the byte array of the value of information string.
* @return This LLDP Organizationally Specific TLV.
*/
@@ -93,6 +98,7 @@
/**
* Set the value of information string.
* The String value is automatically converted into byte array with UTF-8 encoding.
+ *
* @param infoString the String value of information string.
* @return This LLDP Organizationally Specific TLV.
*/
@@ -103,6 +109,7 @@
/**
* Returns the value of information string.
+ *
* @return the value of information string.
*/
public byte[] getInfoString() {
@@ -159,7 +166,7 @@
return false;
}
- LLDPOrganizationalTLV other = (LLDPOrganizationalTLV)o;
+ LLDPOrganizationalTLV other = (LLDPOrganizationalTLV) o;
if (this.type != other.type) {
return false;
}
diff --git a/src/main/java/net/onrc/onos/core/packet/LLDPTLV.java b/src/main/java/net/onrc/onos/core/packet/LLDPTLV.java
index d7bcc68..7b852e2 100644
--- a/src/main/java/net/onrc/onos/core/packet/LLDPTLV.java
+++ b/src/main/java/net/onrc/onos/core/packet/LLDPTLV.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.packet;
@@ -21,8 +21,6 @@
import java.util.Arrays;
/**
- *
- *
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public class LLDPTLV {
@@ -80,7 +78,7 @@
// info string length 9 bits, each value == byte
// info string
short scratch = (short) (((0x7f & this.type) << 9) | (0x1ff & this.length));
- byte[] data = new byte[2+this.length];
+ byte[] data = new byte[2 + this.length];
ByteBuffer bb = ByteBuffer.wrap(data);
bb.putShort(scratch);
if (this.value != null)
diff --git a/src/main/java/net/onrc/onos/core/packet/TCP.java b/src/main/java/net/onrc/onos/core/packet/TCP.java
index 7eb78bd..ec74f46 100644
--- a/src/main/java/net/onrc/onos/core/packet/TCP.java
+++ b/src/main/java/net/onrc/onos/core/packet/TCP.java
@@ -1,26 +1,25 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.packet;
import java.nio.ByteBuffer;
/**
- *
* @author shudong.zhou@bigswitch.com
*/
public class TCP extends BasePacket {
@@ -71,71 +70,86 @@
public short getChecksum() {
return checksum;
}
-
+
public int getSequence() {
return this.sequence;
}
+
public TCP setSequence(int seq) {
this.sequence = seq;
return this;
}
+
public int getAcknowledge() {
return this.acknowledge;
}
+
public TCP setAcknowledge(int ack) {
this.acknowledge = ack;
return this;
}
+
public byte getDataOffset() {
return this.dataOffset;
}
+
public TCP setDataOffset(byte offset) {
this.dataOffset = offset;
return this;
}
+
public short getFlags() {
return this.flags;
}
+
public TCP setFlags(short flags) {
this.flags = flags;
return this;
}
+
public short getWindowSize() {
return this.windowSize;
}
+
public TCP setWindowSize(short windowSize) {
this.windowSize = windowSize;
return this;
}
+
public short getTcpChecksum() {
return this.checksum;
}
+
public TCP setTcpChecksum(short checksum) {
this.checksum = checksum;
return this;
}
-
+
@Override
public void resetChecksum() {
this.checksum = 0;
super.resetChecksum();
}
-
+
public short getUrgentPointer(short urgentPointer) {
return this.urgentPointer;
}
+
public TCP setUrgentPointer(short urgentPointer) {
- this.urgentPointer= urgentPointer;
+ this.urgentPointer = urgentPointer;
return this;
}
+
public byte[] getOptions() {
return this.options;
}
+
public TCP setOptions(byte[] options) {
this.options = options;
this.dataOffset = (byte) ((20 + options.length + 3) >> 2);
return this;
}
+
/**
* @param checksum the checksum to set
*/
@@ -147,8 +161,8 @@
/**
* Serializes the packet. Will compute and set the following fields if they
* are set to specific values at the time serialize is called:
- * -checksum : 0
- * -length : 0
+ * -checksum : 0
+ * -length : 0
*/
public byte[] serialize() {
int length;
@@ -184,7 +198,7 @@
bb.put(payloadData);
if (this.parent != null && this.parent instanceof IPv4)
- ((IPv4)this.parent).setProtocol(IPv4.PROTOCOL_TCP);
+ ((IPv4) this.parent).setProtocol(IPv4.PROTOCOL_TCP);
// compute checksum if needed
if (this.checksum == 0) {
@@ -245,15 +259,15 @@
TCP other = (TCP) obj;
// May want to compare fields based on the flags set
return (checksum == other.checksum) &&
- (destinationPort == other.destinationPort) &&
- (sourcePort == other.sourcePort) &&
- (sequence == other.sequence) &&
- (acknowledge == other.acknowledge) &&
- (dataOffset == other.dataOffset) &&
- (flags == other.flags) &&
- (windowSize == other.windowSize) &&
- (urgentPointer == other.urgentPointer) &&
- (dataOffset == 5 || options.equals(other.options));
+ (destinationPort == other.destinationPort) &&
+ (sourcePort == other.sourcePort) &&
+ (sequence == other.sequence) &&
+ (acknowledge == other.acknowledge) &&
+ (dataOffset == other.dataOffset) &&
+ (flags == other.flags) &&
+ (windowSize == other.windowSize) &&
+ (urgentPointer == other.urgentPointer) &&
+ (dataOffset == 5 || options.equals(other.options));
}
@Override
@@ -271,7 +285,7 @@
this.urgentPointer = bb.getShort();
if (this.dataOffset > 5) {
int optLength = (dataOffset << 2) - 20;
- if (bb.limit() < bb.position()+optLength) {
+ if (bb.limit() < bb.position() + optLength) {
optLength = bb.limit() - bb.position();
}
try {
@@ -281,9 +295,9 @@
this.options = null;
}
}
-
+
this.payload = new Data();
- this.payload = payload.deserialize(data, bb.position(), bb.limit()-bb.position());
+ this.payload = payload.deserialize(data, bb.position(), bb.limit() - bb.position());
this.payload.setParent(this);
return this;
}
diff --git a/src/main/java/net/onrc/onos/core/packet/UDP.java b/src/main/java/net/onrc/onos/core/packet/UDP.java
index 950afaf..6b7cee6 100644
--- a/src/main/java/net/onrc/onos/core/packet/UDP.java
+++ b/src/main/java/net/onrc/onos/core/packet/UDP.java
@@ -1,19 +1,19 @@
/**
-* Copyright 2011, Big Switch Networks, Inc.
-* Originally created by David Erickson, Stanford University
-*
-* Licensed under the Apache License, Version 2.0 (the "License"); you may
-* not use this file except in compliance with the License. You may obtain
-* a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-* License for the specific language governing permissions and limitations
-* under the License.
-**/
+ * Copyright 2011, Big Switch Networks, Inc.
+ * Originally created by David Erickson, Stanford University
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ **/
package net.onrc.onos.core.packet;
@@ -22,13 +22,12 @@
import java.util.Map;
/**
- *
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public class UDP extends BasePacket {
public static Map<Short, Class<? extends IPacket>> decodeMap;
- public static short DHCP_SERVER_PORT = (short)67;
- public static short DHCP_CLIENT_PORT = (short)68;
+ public static short DHCP_SERVER_PORT = (short) 67;
+ public static short DHCP_CLIENT_PORT = (short) 68;
static {
decodeMap = new HashMap<Short, Class<? extends IPacket>>();
@@ -37,7 +36,7 @@
*/
UDP.decodeMap.put(DHCP_SERVER_PORT, DHCP.class);
UDP.decodeMap.put(DHCP_CLIENT_PORT, DHCP.class);
-
+
}
protected short sourcePort;
@@ -106,8 +105,8 @@
/**
* Serializes the packet. Will compute and set the following fields if they
* are set to specific values at the time serialize is called:
- * -checksum : 0
- * -length : 0
+ * -checksum : 0
+ * -length : 0
*/
public byte[] serialize() {
byte[] payloadData = null;
@@ -130,7 +129,7 @@
bb.put(payloadData);
if (this.parent != null && this.parent instanceof IPv4)
- ((IPv4)this.parent).setProtocol(IPv4.PROTOCOL_UDP);
+ ((IPv4) this.parent).setProtocol(IPv4.PROTOCOL_UDP);
// compute checksum if needed
if (this.checksum == 0) {
@@ -224,7 +223,7 @@
} else {
this.payload = new Data();
}
- this.payload = payload.deserialize(data, bb.position(), bb.limit()-bb.position());
+ this.payload = payload.deserialize(data, bb.position(), bb.limit() - bb.position());
this.payload.setParent(this);
return this;
}
diff --git a/src/main/java/net/onrc/onos/core/registry/ControllerRegistryEntry.java b/src/main/java/net/onrc/onos/core/registry/ControllerRegistryEntry.java
index a4eee8a..7e13fdd 100644
--- a/src/main/java/net/onrc/onos/core/registry/ControllerRegistryEntry.java
+++ b/src/main/java/net/onrc/onos/core/registry/ControllerRegistryEntry.java
@@ -5,23 +5,23 @@
public class ControllerRegistryEntry implements Comparable<ControllerRegistryEntry> {
- private String controllerId;
- private int sequenceNumber;
-
- public ControllerRegistryEntry(String controllerId, int sequenceNumber) {
- this.controllerId = controllerId;
- this.sequenceNumber = sequenceNumber;
- }
-
- @JsonProperty("controllerId")
- public String getControllerId(){
- return controllerId;
- }
+ private String controllerId;
+ private int sequenceNumber;
- @Override
- public int compareTo(ControllerRegistryEntry o) {
- return sequenceNumber - o.sequenceNumber;
- //return 0;
- }
+ public ControllerRegistryEntry(String controllerId, int sequenceNumber) {
+ this.controllerId = controllerId;
+ this.sequenceNumber = sequenceNumber;
+ }
+
+ @JsonProperty("controllerId")
+ public String getControllerId() {
+ return controllerId;
+ }
+
+ @Override
+ public int compareTo(ControllerRegistryEntry o) {
+ return sequenceNumber - o.sequenceNumber;
+ //return 0;
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/registry/ControllerService.java b/src/main/java/net/onrc/onos/core/registry/ControllerService.java
index e1e15e9..3f96a3e 100644
--- a/src/main/java/net/onrc/onos/core/registry/ControllerService.java
+++ b/src/main/java/net/onrc/onos/core/registry/ControllerService.java
@@ -1,19 +1,18 @@
package net.onrc.onos.core.registry;
-
//@JsonRootName("controller")
public class ControllerService {
- private String controllerId;
-
- public ControllerService(){
- this("");
- }
-
- public ControllerService(String controllerId) {
- this.controllerId = controllerId;
- }
+ private String controllerId;
+
+ public ControllerService() {
+ this("");
+ }
+
+ public ControllerService(String controllerId) {
+ this.controllerId = controllerId;
+ }
public void setControllerId(String controllerId) {
this.controllerId = controllerId;
diff --git a/src/main/java/net/onrc/onos/core/registry/IControllerRegistryService.java b/src/main/java/net/onrc/onos/core/registry/IControllerRegistryService.java
index e271754..e06f158 100755
--- a/src/main/java/net/onrc/onos/core/registry/IControllerRegistryService.java
+++ b/src/main/java/net/onrc/onos/core/registry/IControllerRegistryService.java
@@ -10,11 +10,11 @@
* A registry service that allows ONOS to register controllers and switches
* in a way that is global to the entire ONOS cluster. The registry is the
* arbiter for allowing controllers to control switches.
- *
+ * <p/>
* The OVS/OF1.{2,3} fault tolerance model is a switch connects to multiple
* controllers, and the controllers send role requests to determine what their
* role is in controlling the switch.
- *
+ * <p/>
* The ONOS fault tolerance model allows only a single controller to have
* control of a switch (MASTER role) at once. Controllers therefore need a
* mechanism that enables them to decide who should control a each switch.
@@ -52,7 +52,7 @@
* @throws RegistryException Errors contacting the registry service
*/
public void requestControl(long dpid, ControlChangeCallback cb)
- throws RegistryException;
+ throws RegistryException;
/**
* Stop trying to take control of a switch. This removes the entry
@@ -94,12 +94,12 @@
* the registry can be used to take control of any switches.
*
* @param controllerId A unique string ID identifying this controller
- * in the cluster
+ * in the cluster
* @throws RegistryException for errors connecting to registry service,
- * controllerId already registered
+ * controllerId already registered
*/
public void registerController(String controllerId)
- throws RegistryException;
+ throws RegistryException;
/**
* Get all controllers in the cluster.
@@ -144,6 +144,7 @@
/**
* Get next unique id and retrieve a new range of ids if needed.
+ *
* @param range range to use for the identifier
* @return Id Block.
*/
diff --git a/src/main/java/net/onrc/onos/core/registry/IdBlock.java b/src/main/java/net/onrc/onos/core/registry/IdBlock.java
index deb02bf..d905917 100644
--- a/src/main/java/net/onrc/onos/core/registry/IdBlock.java
+++ b/src/main/java/net/onrc/onos/core/registry/IdBlock.java
@@ -1,31 +1,31 @@
package net.onrc.onos.core.registry;
public class IdBlock {
- private long start;
- private long end;
- private long size;
-
- public IdBlock(long start, long end, long size) {
- this.start = start;
- this.end = end;
- this.size = size;
- }
-
- public long getStart() {
- return start;
- }
+ private long start;
+ private long end;
+ private long size;
- public long getEnd() {
- return end;
- }
+ public IdBlock(long start, long end, long size) {
+ this.start = start;
+ this.end = end;
+ this.size = size;
+ }
- public long getSize() {
- return size;
- }
-
- @Override
- public String toString() {
- return "IdBlock [start=" + start + ", end=" + end + ", size=" + size
- + "]";
- }
+ public long getStart() {
+ return start;
+ }
+
+ public long getEnd() {
+ return end;
+ }
+
+ public long getSize() {
+ return size;
+ }
+
+ @Override
+ public String toString() {
+ return "IdBlock [start=" + start + ", end=" + end + ", size=" + size
+ + "]";
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/registry/RegistryException.java b/src/main/java/net/onrc/onos/core/registry/RegistryException.java
index 9bf0876..f05aef8 100644
--- a/src/main/java/net/onrc/onos/core/registry/RegistryException.java
+++ b/src/main/java/net/onrc/onos/core/registry/RegistryException.java
@@ -2,25 +2,25 @@
public class RegistryException extends Exception {
- private static final long serialVersionUID = -8276300722010217913L;
-
- /*
- public RegistryException() {
- // TODO Auto-generated constructor stub
- }
+ private static final long serialVersionUID = -8276300722010217913L;
- public RegistryException(Throwable cause) {
- super(cause);
- // TODO Auto-generated constructor stub
- }
- */
-
- public RegistryException(String message) {
- super(message);
- }
-
- public RegistryException(String message, Throwable cause) {
- super(message, cause);
- }
+ /*
+ public RegistryException() {
+ // TODO Auto-generated constructor stub
+ }
+
+ public RegistryException(Throwable cause) {
+ super(cause);
+ // TODO Auto-generated constructor stub
+ }
+ */
+
+ public RegistryException(String message) {
+ super(message);
+ }
+
+ public RegistryException(String message, Throwable cause) {
+ super(message, cause);
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/registry/StandaloneRegistry.java b/src/main/java/net/onrc/onos/core/registry/StandaloneRegistry.java
index 88125ed..0f2f94c 100755
--- a/src/main/java/net/onrc/onos/core/registry/StandaloneRegistry.java
+++ b/src/main/java/net/onrc/onos/core/registry/StandaloneRegistry.java
@@ -23,176 +23,176 @@
* Implementation of a registry that doesn't rely on any external registry
* service. This is designed to be used only in single-node setups (e.g. for
* development). All registry data is stored in local memory.
- * @author jono
*
+ * @author jono
*/
public class StandaloneRegistry implements IFloodlightModule,
- IControllerRegistryService {
- protected final static Logger log = LoggerFactory.getLogger(StandaloneRegistry.class);
-
- protected IRestApiService restApi;
-
- protected String controllerId = null;
- protected Map<String, ControlChangeCallback> switchCallbacks;
+ IControllerRegistryService {
+ protected final static Logger log = LoggerFactory.getLogger(StandaloneRegistry.class);
- //
- // Unique ID generation state
- //
- private static AtomicLong nextUniqueId = new AtomicLong(0);
+ protected IRestApiService restApi;
- @Override
- public void requestControl(long dpid, ControlChangeCallback cb)
- throws RegistryException {
- if (controllerId == null) {
- throw new RuntimeException(
- "Must register a controller before calling requestControl");
- }
-
- switchCallbacks.put(HexString.toHexString(dpid), cb);
-
- log.debug("Control granted for {}", HexString.toHexString(dpid));
-
- //Immediately grant request for control
- if (cb != null) {
- cb.controlChanged(dpid, true);
- }
- }
+ protected String controllerId = null;
+ protected Map<String, ControlChangeCallback> switchCallbacks;
- @Override
- public void releaseControl(long dpid) {
- ControlChangeCallback cb = switchCallbacks.remove(HexString.toHexString(dpid));
-
- log.debug("Control released for {}", HexString.toHexString(dpid));
-
- if (cb != null){
- cb.controlChanged(dpid, false);
- }
- }
+ //
+ // Unique ID generation state
+ //
+ private static AtomicLong nextUniqueId = new AtomicLong(0);
- @Override
- public boolean hasControl(long dpid) {
- return switchCallbacks.containsKey(HexString.toHexString(dpid));
- }
+ @Override
+ public void requestControl(long dpid, ControlChangeCallback cb)
+ throws RegistryException {
+ if (controllerId == null) {
+ throw new RuntimeException(
+ "Must register a controller before calling requestControl");
+ }
- @Override
- public boolean isClusterLeader() {
- return true;
- }
+ switchCallbacks.put(HexString.toHexString(dpid), cb);
- @Override
- public String getControllerId() {
- return controllerId;
- }
+ log.debug("Control granted for {}", HexString.toHexString(dpid));
- @Override
- public void registerController(String controllerId)
- throws RegistryException {
- if (this.controllerId != null) {
- throw new RegistryException(
- "Controller already registered with id " + this.controllerId);
- }
- this.controllerId = controllerId;
- }
+ //Immediately grant request for control
+ if (cb != null) {
+ cb.controlChanged(dpid, true);
+ }
+ }
- @Override
- public Collection<String> getAllControllers() throws RegistryException {
- List<String> l = new ArrayList<String>();
- l.add(controllerId);
- return l;
- }
+ @Override
+ public void releaseControl(long dpid) {
+ ControlChangeCallback cb = switchCallbacks.remove(HexString.toHexString(dpid));
- @Override
- public String getControllerForSwitch(long dpid) throws RegistryException {
- return (switchCallbacks.get(HexString.toHexString(dpid)) != null)? controllerId: null;
- }
+ log.debug("Control released for {}", HexString.toHexString(dpid));
- @Override
- public Map<String, List<ControllerRegistryEntry>> getAllSwitches() {
- Map<String, List<ControllerRegistryEntry>> switches =
- new HashMap<String, List<ControllerRegistryEntry>>();
-
- for (String strSwitch : switchCallbacks.keySet()){
- log.debug("Switch _{}", strSwitch);
- List<ControllerRegistryEntry> list = new ArrayList<ControllerRegistryEntry>();
- list.add(new ControllerRegistryEntry(controllerId, 0));
-
- switches.put(strSwitch, list);
- }
-
- return switches;
- }
+ if (cb != null) {
+ cb.controlChanged(dpid, false);
+ }
+ }
- @Override
- public Collection<Long> getSwitchesControlledByController(
- String controllerId) {
- throw new RuntimeException("Not yet implemented");
- }
-
- private long blockTop = 0L;
- private static final long BLOCK_SIZE = 0x1000000L;
-
- /**
- * Returns a block of IDs which are unique and unused.
- * Range of IDs is fixed size and is assigned incrementally as this method called.
- */
- @Override
- public synchronized IdBlock allocateUniqueIdBlock(){
- long blockHead = blockTop;
- long blockTail = blockTop + BLOCK_SIZE;
-
- IdBlock block = new IdBlock(blockHead, blockTail - 1, BLOCK_SIZE);
- blockTop = blockTail;
-
- return block;
- }
+ @Override
+ public boolean hasControl(long dpid) {
+ return switchCallbacks.containsKey(HexString.toHexString(dpid));
+ }
- /**
- * Get a globally unique ID.
- *
- * @return a globally unique ID.
- */
- @Override
- public long getNextUniqueId() {
- return nextUniqueId.incrementAndGet();
- }
+ @Override
+ public boolean isClusterLeader() {
+ return true;
+ }
- @Override
- public Collection<Class<? extends IFloodlightService>> getModuleServices() {
- Collection<Class<? extends IFloodlightService>> l =
- new ArrayList<Class<? extends IFloodlightService>>();
- l.add(IControllerRegistryService.class);
- return l;
- }
+ @Override
+ public String getControllerId() {
+ return controllerId;
+ }
- @Override
- public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
- Map<Class<? extends IFloodlightService>, IFloodlightService> m =
- new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
- m.put(IControllerRegistryService.class, this);
- return m;
- }
+ @Override
+ public void registerController(String controllerId)
+ throws RegistryException {
+ if (this.controllerId != null) {
+ throw new RegistryException(
+ "Controller already registered with id " + this.controllerId);
+ }
+ this.controllerId = controllerId;
+ }
- @Override
- public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
- Collection<Class<? extends IFloodlightService>> l =
+ @Override
+ public Collection<String> getAllControllers() throws RegistryException {
+ List<String> l = new ArrayList<String>();
+ l.add(controllerId);
+ return l;
+ }
+
+ @Override
+ public String getControllerForSwitch(long dpid) throws RegistryException {
+ return (switchCallbacks.get(HexString.toHexString(dpid)) != null) ? controllerId : null;
+ }
+
+ @Override
+ public Map<String, List<ControllerRegistryEntry>> getAllSwitches() {
+ Map<String, List<ControllerRegistryEntry>> switches =
+ new HashMap<String, List<ControllerRegistryEntry>>();
+
+ for (String strSwitch : switchCallbacks.keySet()) {
+ log.debug("Switch _{}", strSwitch);
+ List<ControllerRegistryEntry> list = new ArrayList<ControllerRegistryEntry>();
+ list.add(new ControllerRegistryEntry(controllerId, 0));
+
+ switches.put(strSwitch, list);
+ }
+
+ return switches;
+ }
+
+ @Override
+ public Collection<Long> getSwitchesControlledByController(
+ String controllerId) {
+ throw new RuntimeException("Not yet implemented");
+ }
+
+ private long blockTop = 0L;
+ private static final long BLOCK_SIZE = 0x1000000L;
+
+ /**
+ * Returns a block of IDs which are unique and unused.
+ * Range of IDs is fixed size and is assigned incrementally as this method called.
+ */
+ @Override
+ public synchronized IdBlock allocateUniqueIdBlock() {
+ long blockHead = blockTop;
+ long blockTail = blockTop + BLOCK_SIZE;
+
+ IdBlock block = new IdBlock(blockHead, blockTail - 1, BLOCK_SIZE);
+ blockTop = blockTail;
+
+ return block;
+ }
+
+ /**
+ * Get a globally unique ID.
+ *
+ * @return a globally unique ID.
+ */
+ @Override
+ public long getNextUniqueId() {
+ return nextUniqueId.incrementAndGet();
+ }
+
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleServices() {
+ Collection<Class<? extends IFloodlightService>> l =
new ArrayList<Class<? extends IFloodlightService>>();
- l.add(IFloodlightProviderService.class);
- l.add(IRestApiService.class);
- return l;
- }
+ l.add(IControllerRegistryService.class);
+ return l;
+ }
- @Override
- public void init(FloodlightModuleContext context)
- throws FloodlightModuleException {
- restApi = context.getServiceImpl(IRestApiService.class);
-
- switchCallbacks = new HashMap<String, ControlChangeCallback>();
- }
+ @Override
+ public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
+ Map<Class<? extends IFloodlightService>, IFloodlightService> m =
+ new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
+ m.put(IControllerRegistryService.class, this);
+ return m;
+ }
- @Override
- public void startUp(FloodlightModuleContext context) {
- restApi.addRestletRoutable(new RegistryWebRoutable());
- }
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
+ Collection<Class<? extends IFloodlightService>> l =
+ new ArrayList<Class<? extends IFloodlightService>>();
+ l.add(IFloodlightProviderService.class);
+ l.add(IRestApiService.class);
+ return l;
+ }
+
+ @Override
+ public void init(FloodlightModuleContext context)
+ throws FloodlightModuleException {
+ restApi = context.getServiceImpl(IRestApiService.class);
+
+ switchCallbacks = new HashMap<String, ControlChangeCallback>();
+ }
+
+ @Override
+ public void startUp(FloodlightModuleContext context) {
+ restApi.addRestletRoutable(new RegistryWebRoutable());
+ }
@Override
public IdBlock allocateUniqueIdBlock(long range) {
diff --git a/src/main/java/net/onrc/onos/core/registry/SwitchLeadershipData.java b/src/main/java/net/onrc/onos/core/registry/SwitchLeadershipData.java
index 9ccd47b..62a6b58 100644
--- a/src/main/java/net/onrc/onos/core/registry/SwitchLeadershipData.java
+++ b/src/main/java/net/onrc/onos/core/registry/SwitchLeadershipData.java
@@ -6,28 +6,28 @@
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
public class SwitchLeadershipData {
-
- private final LeaderLatch latch;
- private final ControlChangeCallback cb;
- private final LeaderLatchListener listener;
- public SwitchLeadershipData(LeaderLatch latch, ControlChangeCallback cb,
- LeaderLatchListener listener) {
- this.latch = latch;
- this.cb = cb;
- this.listener = listener;
- }
-
- public LeaderLatch getLatch(){
- return latch;
- }
-
- public ControlChangeCallback getCallback(){
- return cb;
- }
-
- public LeaderLatchListener getListener() {
- return listener;
- }
+ private final LeaderLatch latch;
+ private final ControlChangeCallback cb;
+ private final LeaderLatchListener listener;
+
+ public SwitchLeadershipData(LeaderLatch latch, ControlChangeCallback cb,
+ LeaderLatchListener listener) {
+ this.latch = latch;
+ this.cb = cb;
+ this.listener = listener;
+ }
+
+ public LeaderLatch getLatch() {
+ return latch;
+ }
+
+ public ControlChangeCallback getCallback() {
+ return cb;
+ }
+
+ public LeaderLatchListener getListener() {
+ return listener;
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/registry/ZookeeperRegistry.java b/src/main/java/net/onrc/onos/core/registry/ZookeeperRegistry.java
index aa3e98b..1897631 100755
--- a/src/main/java/net/onrc/onos/core/registry/ZookeeperRegistry.java
+++ b/src/main/java/net/onrc/onos/core/registry/ZookeeperRegistry.java
@@ -51,600 +51,603 @@
/**
* A registry service that uses Zookeeper. All data is stored in Zookeeper,
* so this can be used as a global registry in a multi-node ONOS cluster.
- * @author jono
*
+ * @author jono
*/
public class ZookeeperRegistry implements IFloodlightModule, IControllerRegistryService {
- protected final static Logger log = LoggerFactory.getLogger(ZookeeperRegistry.class);
- protected String controllerId = null;
-
- protected IRestApiService restApi;
-
- //This is the default, it's overwritten by the connectionString configuration parameter
- protected String connectionString = "localhost:2181";
-
- private final String namespace = "onos";
- private final String switchLatchesPath = "/switches";
- private final String CLUSTER_LEADER_PATH = "/cluster/leader";
+ protected final static Logger log = LoggerFactory.getLogger(ZookeeperRegistry.class);
+ protected String controllerId = null;
- private final String SERVICES_PATH = "/"; //i.e. the root of our namespace
- private final String CONTROLLER_SERVICE_NAME = "controllers";
-
- protected CuratorFramework client;
-
- protected PathChildrenCache switchCache;
+ protected IRestApiService restApi;
- protected ConcurrentHashMap<String, SwitchLeadershipData> switches;
- protected Map<String, PathChildrenCache> switchPathCaches;
+ //This is the default, it's overwritten by the connectionString configuration parameter
+ protected String connectionString = "localhost:2181";
- protected LeaderLatch clusterLeaderLatch;
- protected ClusterLeaderListener clusterLeaderListener;
- private static final long CLUSTER_LEADER_ELECTION_RETRY_MS = 100;
+ private final String namespace = "onos";
+ private final String switchLatchesPath = "/switches";
+ private final String CLUSTER_LEADER_PATH = "/cluster/leader";
- private final String ID_COUNTER_PATH = "/flowidcounter";
- private final Long ID_BLOCK_SIZE = 0x100000000L;
- protected DistributedAtomicLong distributedIdCounter;
-
- //Zookeeper performance-related configuration
- protected static final int sessionTimeout = 5000;
- protected static final int connectionTimeout = 7000;
+ private final String SERVICES_PATH = "/"; //i.e. the root of our namespace
+ private final String CONTROLLER_SERVICE_NAME = "controllers";
- //
- // Unique ID generation state
- // TODO: The implementation must be updated to use the Zookeeper
- // instead of a ramdon generator.
- //
- private static Random randomGenerator = new Random();
- private static int nextUniqueIdPrefix = 0;
- private static int nextUniqueIdSuffix = 0;
+ protected CuratorFramework client;
- private final BlockingQueue<SwitchLeaderEvent> switchLeadershipEvents =
- new LinkedBlockingQueue<SwitchLeaderEvent>();
-
+ protected PathChildrenCache switchCache;
+
+ protected ConcurrentHashMap<String, SwitchLeadershipData> switches;
+ protected Map<String, PathChildrenCache> switchPathCaches;
+
+ protected LeaderLatch clusterLeaderLatch;
+ protected ClusterLeaderListener clusterLeaderListener;
+ private static final long CLUSTER_LEADER_ELECTION_RETRY_MS = 100;
+
+ private final String ID_COUNTER_PATH = "/flowidcounter";
+ private final Long ID_BLOCK_SIZE = 0x100000000L;
+ protected DistributedAtomicLong distributedIdCounter;
+
+ //Zookeeper performance-related configuration
+ protected static final int sessionTimeout = 5000;
+ protected static final int connectionTimeout = 7000;
+
+ //
+ // Unique ID generation state
+ // TODO: The implementation must be updated to use the Zookeeper
+ // instead of a ramdon generator.
+ //
+ private static Random randomGenerator = new Random();
+ private static int nextUniqueIdPrefix = 0;
+ private static int nextUniqueIdSuffix = 0;
+
+ private final BlockingQueue<SwitchLeaderEvent> switchLeadershipEvents =
+ new LinkedBlockingQueue<SwitchLeaderEvent>();
+
private ExecutorService eventThreadExecutorService;
-
+
private static class SwitchLeaderEvent {
- public final long dpid;
- public final boolean isLeader;
-
- public SwitchLeaderEvent(long dpid, boolean isLeader) {
- this.dpid = dpid;
- this.isLeader = isLeader;
- }
+ public final long dpid;
+ public final boolean isLeader;
+
+ public SwitchLeaderEvent(long dpid, boolean isLeader) {
+ this.dpid = dpid;
+ this.isLeader = isLeader;
+ }
}
-
+
/*
* Dispatcher thread for leadership change events coming from Curator.
*/
private void dispatchEvents() {
- while (!Thread.currentThread().isInterrupted()) {
- try {
- SwitchLeaderEvent event = switchLeadershipEvents.take();
- SwitchLeadershipData swData = switches.get(HexString.toHexString(event.dpid));
- if (swData == null) {
- log.debug("Leadership data {} not found", event.dpid);
- continue;
- }
-
- swData.getCallback().controlChanged(event.dpid, event.isLeader);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- break;
- } catch (Exception e) {
- log.error("Exception in registry event thread", e);
- }
- }
+ while (!Thread.currentThread().isInterrupted()) {
+ try {
+ SwitchLeaderEvent event = switchLeadershipEvents.take();
+ SwitchLeadershipData swData = switches.get(HexString.toHexString(event.dpid));
+ if (swData == null) {
+ log.debug("Leadership data {} not found", event.dpid);
+ continue;
+ }
+
+ swData.getCallback().controlChanged(event.dpid, event.isLeader);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ break;
+ } catch (Exception e) {
+ log.error("Exception in registry event thread", e);
+ }
+ }
}
- protected class SwitchLeaderListener implements LeaderLatchListener{
- String dpid;
- LeaderLatch latch;
-
- public SwitchLeaderListener(String dpid, LeaderLatch latch){
- this.dpid = dpid;
- this.latch = latch;
- }
+ protected class SwitchLeaderListener implements LeaderLatchListener {
+ String dpid;
+ LeaderLatch latch;
- @Override
- public void isLeader() {
- log.debug("Became leader for {}", dpid);
-
- switchLeadershipEvents.offer(new SwitchLeaderEvent(HexString.toLong(dpid), true));
- }
+ public SwitchLeaderListener(String dpid, LeaderLatch latch) {
+ this.dpid = dpid;
+ this.latch = latch;
+ }
- @Override
- public void notLeader() {
- log.debug("Lost leadership for {}", dpid);
-
- switchLeadershipEvents.offer(new SwitchLeaderEvent(HexString.toLong(dpid), false));
- }
- }
-
- protected class SwitchPathCacheListener implements PathChildrenCacheListener {
- @Override
- public void childEvent(CuratorFramework client,
- PathChildrenCacheEvent event) throws Exception {
-
- String strSwitch = null;
- if (event.getData() != null){
- String[] splitted = event.getData().getPath().split("/");
- strSwitch = splitted[splitted.length - 1];
- }
-
- switch (event.getType()){
- case CHILD_ADDED:
- case CHILD_UPDATED:
- //Check we have a PathChildrenCache for this child, add one if not
- synchronized (switchPathCaches){
- if (switchPathCaches.get(strSwitch) == null){
- PathChildrenCache pc = new PathChildrenCache(client,
- event.getData().getPath(), true);
- pc.start(StartMode.NORMAL);
- switchPathCaches.put(strSwitch, pc);
- }
- }
- break;
- case CHILD_REMOVED:
- //Remove our PathChildrenCache for this child
- PathChildrenCache pc = null;
- synchronized(switchPathCaches){
- pc = switchPathCaches.remove(strSwitch);
- }
- if (pc != null){
- pc.close();
- }
- break;
- default:
- //All other switchLeadershipEvents are connection status switchLeadershipEvents. We don't need to
- //do anything as the path cache handles these on its own.
- break;
- }
-
- }
- };
+ @Override
+ public void isLeader() {
+ log.debug("Became leader for {}", dpid);
- protected class ClusterLeaderListener implements LeaderLatchListener {
- LeaderLatch latch;
+ switchLeadershipEvents.offer(new SwitchLeaderEvent(HexString.toLong(dpid), true));
+ }
- public ClusterLeaderListener(LeaderLatch latch) {
- this.latch = latch;
- }
+ @Override
+ public void notLeader() {
+ log.debug("Lost leadership for {}", dpid);
- //
- // NOTE: If we need to support callbacks when the
- // leadership changes, those should be called here.
- //
-
- @Override
- public void isLeader() {
- log.debug("Cluster leadership aquired");
- }
+ switchLeadershipEvents.offer(new SwitchLeaderEvent(HexString.toLong(dpid), false));
+ }
+ }
- @Override
- public void notLeader() {
- log.debug("Cluster leadership lost");
- }
- }
+ protected class SwitchPathCacheListener implements PathChildrenCacheListener {
+ @Override
+ public void childEvent(CuratorFramework client,
+ PathChildrenCacheEvent event) throws Exception {
- /**
- * Listens for changes to the switch znodes in Zookeeper. This maintains
- * the second level of PathChildrenCaches that hold the controllers
- * contending for each switch - there's one for each switch.
- */
- PathChildrenCacheListener switchPathCacheListener = new SwitchPathCacheListener();
- protected ServiceDiscovery<ControllerService> serviceDiscovery;
- protected ServiceCache<ControllerService> serviceCache;
-
-
- @Override
- public void requestControl(long dpid, ControlChangeCallback cb) throws RegistryException {
- log.info("Requesting control for {}", HexString.toHexString(dpid));
-
- if (controllerId == null){
- throw new RuntimeException("Must register a controller before calling requestControl");
- }
-
- String dpidStr = HexString.toHexString(dpid);
- String latchPath = switchLatchesPath + "/" + dpidStr;
-
- if (switches.get(dpidStr) != null){
- log.debug("Already contesting {}, returning", HexString.toHexString(dpid));
- throw new RegistryException("Already contesting control for " + dpidStr);
- }
-
- LeaderLatch latch = new LeaderLatch(client, latchPath, controllerId);
- SwitchLeaderListener listener = new SwitchLeaderListener(dpidStr, latch);
- latch.addListener(listener);
-
-
- SwitchLeadershipData swData = new SwitchLeadershipData(latch, cb, listener);
- SwitchLeadershipData oldData = switches.putIfAbsent(dpidStr, swData);
-
- if (oldData != null){
- //There was already data for that key in the map
- //i.e. someone else got here first so we can't succeed
- log.debug("Already requested control for {}", dpidStr);
- throw new RegistryException("Already requested control for " + dpidStr);
- }
-
- //Now that we know we were able to add our latch to the collection,
- //we can start the leader election in Zookeeper. However I don't know
- //how to handle if the start fails - the latch is already in our
- //switches list.
- //TODO seems like there's a Curator bug when latch.start is called when
- //there's no Zookeeper connection which causes two znodes to be put in
- //Zookeeper at the latch path when we reconnect to Zookeeper.
- try {
- latch.start();
- } catch (Exception e) {
- log.warn("Error starting leader latch: {}", e.getMessage());
- throw new RegistryException("Error starting leader latch for " + dpidStr, e);
- }
-
- }
-
- @Override
- public void releaseControl(long dpid) {
- log.info("Releasing control for {}", HexString.toHexString(dpid));
-
- String dpidStr = HexString.toHexString(dpid);
-
- SwitchLeadershipData swData = switches.remove(dpidStr);
-
- if (swData == null) {
- log.debug("Trying to release control of a switch we are not contesting");
- return;
- }
-
- LeaderLatch latch = swData.getLatch();
-
- latch.removeListener(swData.getListener());
-
- try {
- latch.close();
- } catch (IOException e) {
- //I think it's OK not to do anything here. Either the node got
- //deleted correctly, or the connection went down and the node got deleted.
- log.debug("releaseControl: caught IOException {}", dpidStr);
- }
- }
-
- @Override
- public boolean hasControl(long dpid) {
- String dpidStr = HexString.toHexString(dpid);
-
- SwitchLeadershipData swData = switches.get(dpidStr);
-
- if (swData == null) {
- log.warn("No leader latch for dpid {}", dpidStr);
- return false;
- }
-
- return swData.getLatch().hasLeadership();
- }
-
- @Override
- public boolean isClusterLeader() {
- return clusterLeaderLatch.hasLeadership();
- }
-
- @Override
- public String getControllerId() {
- return controllerId;
- }
-
- @Override
- public Collection<String> getAllControllers() throws RegistryException {
- log.debug("Getting all controllers");
-
- List<String> controllers = new ArrayList<String>();
- for (ServiceInstance<ControllerService> instance : serviceCache.getInstances()){
- String id = instance.getPayload().getControllerId();
- if (!controllers.contains(id)){
- controllers.add(id);
- }
- }
-
- return controllers;
- }
-
- @Override
- public void registerController(String id) throws RegistryException {
- if (controllerId != null) {
- throw new RegistryException(
- "Controller already registered with id " + controllerId);
- }
-
- controllerId = id;
-
- try {
- ServiceInstance<ControllerService> thisInstance = ServiceInstance.<ControllerService>builder()
- .name(CONTROLLER_SERVICE_NAME)
- .payload(new ControllerService(controllerId))
- //.port((int)(65535 * Math.random())) // in a real application, you'd use a common port
- //.uriSpec(uriSpec)
- .build();
-
- serviceDiscovery.registerService(thisInstance);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- }
-
- @Override
- public String getControllerForSwitch(long dpid) throws RegistryException {
- String dpidStr = HexString.toHexString(dpid);
-
- PathChildrenCache switchCache = switchPathCaches.get(dpidStr);
-
- if (switchCache == null){
- log.warn("Tried to get controller for non-existent switch");
- return null;
- }
-
- try {
- //We've seen issues with these caches get stuck out of date, so we'll have to
- //force them to refresh before each read. This slows down the method as it
- //blocks on a Zookeeper query, however at the moment only the cleanup thread
- //uses this and that isn't particularly time-sensitive.
- switchCache.rebuild();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- List<ChildData> sortedData = new ArrayList<ChildData>(switchCache.getCurrentData());
-
- Collections.sort(
- sortedData,
- new Comparator<ChildData>(){
- private String getSequenceNumber(String path){
- return path.substring(path.lastIndexOf('-') + 1);
- }
- @Override
- public int compare(ChildData lhs, ChildData rhs) {
- return getSequenceNumber(lhs.getPath()).
- compareTo(getSequenceNumber(rhs.getPath()));
- }
- }
- );
-
- if (sortedData.size() == 0){
- return null;
- }
-
- return new String(sortedData.get(0).getData(), Charsets.UTF_8);
- }
-
- @Override
- public Collection<Long> getSwitchesControlledByController(String controllerId) {
- //TODO remove this if not needed
- throw new RuntimeException("Not yet implemented");
- }
-
-
- //TODO what should happen when there's no ZK connection? Currently we just return
- //the cache but this may lead to false impressions - i.e. we don't actually know
- //what's in ZK so we shouldn't say we do
- @Override
- public Map<String, List<ControllerRegistryEntry>> getAllSwitches() {
- Map<String, List<ControllerRegistryEntry>> data =
- new HashMap<String, List<ControllerRegistryEntry>>();
-
- for (Map.Entry<String, PathChildrenCache> entry : switchPathCaches.entrySet()){
- List<ControllerRegistryEntry> contendingControllers =
- new ArrayList<ControllerRegistryEntry>();
-
- if (entry.getValue().getCurrentData().size() < 1){
- //TODO prevent even having the PathChildrenCache in this case
- //log.info("Switch entry with no leader elections: {}", entry.getKey());
- continue;
- }
-
- for (ChildData d : entry.getValue().getCurrentData()) {
-
- String controllerId = new String(d.getData(), Charsets.UTF_8);
-
- String[] splitted = d.getPath().split("-");
- int sequenceNumber = Integer.parseInt(splitted[splitted.length - 1]);
-
- contendingControllers.add(new ControllerRegistryEntry(controllerId, sequenceNumber));
- }
-
- Collections.sort(contendingControllers);
- data.put(entry.getKey(), contendingControllers);
- }
- return data;
- }
-
- public IdBlock allocateUniqueIdBlock(long range) {
- try {
- AtomicValue<Long> result = null;
- do {
- result = distributedIdCounter.add(range);
- } while (result == null || !result.succeeded());
-
- return new IdBlock(result.preValue(), result.postValue() - 1, range);
- } catch (Exception e) {
- log.error("Error allocating ID block");
+ String strSwitch = null;
+ if (event.getData() != null) {
+ String[] splitted = event.getData().getPath().split("/");
+ strSwitch = splitted[splitted.length - 1];
}
+
+ switch (event.getType()) {
+ case CHILD_ADDED:
+ case CHILD_UPDATED:
+ //Check we have a PathChildrenCache for this child, add one if not
+ synchronized (switchPathCaches) {
+ if (switchPathCaches.get(strSwitch) == null) {
+ PathChildrenCache pc = new PathChildrenCache(client,
+ event.getData().getPath(), true);
+ pc.start(StartMode.NORMAL);
+ switchPathCaches.put(strSwitch, pc);
+ }
+ }
+ break;
+ case CHILD_REMOVED:
+ //Remove our PathChildrenCache for this child
+ PathChildrenCache pc = null;
+ synchronized (switchPathCaches) {
+ pc = switchPathCaches.remove(strSwitch);
+ }
+ if (pc != null) {
+ pc.close();
+ }
+ break;
+ default:
+ //All other switchLeadershipEvents are connection status switchLeadershipEvents. We don't need to
+ //do anything as the path cache handles these on its own.
+ break;
+ }
+
+ }
+ }
+
+ ;
+
+ protected class ClusterLeaderListener implements LeaderLatchListener {
+ LeaderLatch latch;
+
+ public ClusterLeaderListener(LeaderLatch latch) {
+ this.latch = latch;
+ }
+
+ //
+ // NOTE: If we need to support callbacks when the
+ // leadership changes, those should be called here.
+ //
+
+ @Override
+ public void isLeader() {
+ log.debug("Cluster leadership aquired");
+ }
+
+ @Override
+ public void notLeader() {
+ log.debug("Cluster leadership lost");
+ }
+ }
+
+ /**
+ * Listens for changes to the switch znodes in Zookeeper. This maintains
+ * the second level of PathChildrenCaches that hold the controllers
+ * contending for each switch - there's one for each switch.
+ */
+ PathChildrenCacheListener switchPathCacheListener = new SwitchPathCacheListener();
+ protected ServiceDiscovery<ControllerService> serviceDiscovery;
+ protected ServiceCache<ControllerService> serviceCache;
+
+
+ @Override
+ public void requestControl(long dpid, ControlChangeCallback cb) throws RegistryException {
+ log.info("Requesting control for {}", HexString.toHexString(dpid));
+
+ if (controllerId == null) {
+ throw new RuntimeException("Must register a controller before calling requestControl");
+ }
+
+ String dpidStr = HexString.toHexString(dpid);
+ String latchPath = switchLatchesPath + "/" + dpidStr;
+
+ if (switches.get(dpidStr) != null) {
+ log.debug("Already contesting {}, returning", HexString.toHexString(dpid));
+ throw new RegistryException("Already contesting control for " + dpidStr);
+ }
+
+ LeaderLatch latch = new LeaderLatch(client, latchPath, controllerId);
+ SwitchLeaderListener listener = new SwitchLeaderListener(dpidStr, latch);
+ latch.addListener(listener);
+
+
+ SwitchLeadershipData swData = new SwitchLeadershipData(latch, cb, listener);
+ SwitchLeadershipData oldData = switches.putIfAbsent(dpidStr, swData);
+
+ if (oldData != null) {
+ //There was already data for that key in the map
+ //i.e. someone else got here first so we can't succeed
+ log.debug("Already requested control for {}", dpidStr);
+ throw new RegistryException("Already requested control for " + dpidStr);
+ }
+
+ //Now that we know we were able to add our latch to the collection,
+ //we can start the leader election in Zookeeper. However I don't know
+ //how to handle if the start fails - the latch is already in our
+ //switches list.
+ //TODO seems like there's a Curator bug when latch.start is called when
+ //there's no Zookeeper connection which causes two znodes to be put in
+ //Zookeeper at the latch path when we reconnect to Zookeeper.
+ try {
+ latch.start();
+ } catch (Exception e) {
+ log.warn("Error starting leader latch: {}", e.getMessage());
+ throw new RegistryException("Error starting leader latch for " + dpidStr, e);
+ }
+
+ }
+
+ @Override
+ public void releaseControl(long dpid) {
+ log.info("Releasing control for {}", HexString.toHexString(dpid));
+
+ String dpidStr = HexString.toHexString(dpid);
+
+ SwitchLeadershipData swData = switches.remove(dpidStr);
+
+ if (swData == null) {
+ log.debug("Trying to release control of a switch we are not contesting");
+ return;
+ }
+
+ LeaderLatch latch = swData.getLatch();
+
+ latch.removeListener(swData.getListener());
+
+ try {
+ latch.close();
+ } catch (IOException e) {
+ //I think it's OK not to do anything here. Either the node got
+ //deleted correctly, or the connection went down and the node got deleted.
+ log.debug("releaseControl: caught IOException {}", dpidStr);
+ }
+ }
+
+ @Override
+ public boolean hasControl(long dpid) {
+ String dpidStr = HexString.toHexString(dpid);
+
+ SwitchLeadershipData swData = switches.get(dpidStr);
+
+ if (swData == null) {
+ log.warn("No leader latch for dpid {}", dpidStr);
+ return false;
+ }
+
+ return swData.getLatch().hasLeadership();
+ }
+
+ @Override
+ public boolean isClusterLeader() {
+ return clusterLeaderLatch.hasLeadership();
+ }
+
+ @Override
+ public String getControllerId() {
+ return controllerId;
+ }
+
+ @Override
+ public Collection<String> getAllControllers() throws RegistryException {
+ log.debug("Getting all controllers");
+
+ List<String> controllers = new ArrayList<String>();
+ for (ServiceInstance<ControllerService> instance : serviceCache.getInstances()) {
+ String id = instance.getPayload().getControllerId();
+ if (!controllers.contains(id)) {
+ controllers.add(id);
+ }
+ }
+
+ return controllers;
+ }
+
+ @Override
+ public void registerController(String id) throws RegistryException {
+ if (controllerId != null) {
+ throw new RegistryException(
+ "Controller already registered with id " + controllerId);
+ }
+
+ controllerId = id;
+
+ try {
+ ServiceInstance<ControllerService> thisInstance = ServiceInstance.<ControllerService>builder()
+ .name(CONTROLLER_SERVICE_NAME)
+ .payload(new ControllerService(controllerId))
+ //.port((int)(65535 * Math.random())) // in a real application, you'd use a common port
+ //.uriSpec(uriSpec)
+ .build();
+
+ serviceDiscovery.registerService(thisInstance);
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ }
+
+ @Override
+ public String getControllerForSwitch(long dpid) throws RegistryException {
+ String dpidStr = HexString.toHexString(dpid);
+
+ PathChildrenCache switchCache = switchPathCaches.get(dpidStr);
+
+ if (switchCache == null) {
+ log.warn("Tried to get controller for non-existent switch");
return null;
}
-
- /**
- * Returns a block of IDs which are unique and unused.
- * Range of IDs is fixed size and is assigned incrementally as this method called.
- * Since the range of IDs is managed by Zookeeper in distributed way, this method may block when
- * requests come up simultaneously.
- */
- @Override
- public IdBlock allocateUniqueIdBlock(){
- return allocateUniqueIdBlock(ID_BLOCK_SIZE);
- }
- /**
- * Get a globally unique ID.
- *
- * @return a globally unique ID.
- */
- @Override
- public synchronized long getNextUniqueId() {
- //
- // Generate the next Unique ID.
- //
- // TODO: For now, the higher 32 bits are random, and
- // the lower 32 bits are sequential.
- // The implementation must be updated to use the Zookeeper
- // to allocate the higher 32 bits (globally unique).
- //
- if ((nextUniqueIdSuffix & 0xffffffffL) == 0xffffffffL) {
- nextUniqueIdPrefix = randomGenerator.nextInt();
- nextUniqueIdSuffix = 0;
- } else {
- nextUniqueIdSuffix++;
- }
- long result = (long)nextUniqueIdPrefix << 32;
- result = result | (0xffffffffL & nextUniqueIdSuffix);
- return result;
- }
+ try {
+ //We've seen issues with these caches get stuck out of date, so we'll have to
+ //force them to refresh before each read. This slows down the method as it
+ //blocks on a Zookeeper query, however at the moment only the cleanup thread
+ //uses this and that isn't particularly time-sensitive.
+ switchCache.rebuild();
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
- /*
- * IFloodlightModule
- */
-
- @Override
- public Collection<Class<? extends IFloodlightService>> getModuleServices() {
- Collection<Class<? extends IFloodlightService>> l =
- new ArrayList<Class<? extends IFloodlightService>>();
- l.add(IControllerRegistryService.class);
- return l;
- }
-
- @Override
- public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
- Map<Class<? extends IFloodlightService>, IFloodlightService> m =
- new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
- m.put(IControllerRegistryService.class, this);
- return m;
- }
-
- @Override
- public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
- Collection<Class<? extends IFloodlightService>> l =
+ List<ChildData> sortedData = new ArrayList<ChildData>(switchCache.getCurrentData());
+
+ Collections.sort(
+ sortedData,
+ new Comparator<ChildData>() {
+ private String getSequenceNumber(String path) {
+ return path.substring(path.lastIndexOf('-') + 1);
+ }
+
+ @Override
+ public int compare(ChildData lhs, ChildData rhs) {
+ return getSequenceNumber(lhs.getPath()).
+ compareTo(getSequenceNumber(rhs.getPath()));
+ }
+ }
+ );
+
+ if (sortedData.size() == 0) {
+ return null;
+ }
+
+ return new String(sortedData.get(0).getData(), Charsets.UTF_8);
+ }
+
+ @Override
+ public Collection<Long> getSwitchesControlledByController(String controllerId) {
+ //TODO remove this if not needed
+ throw new RuntimeException("Not yet implemented");
+ }
+
+
+ //TODO what should happen when there's no ZK connection? Currently we just return
+ //the cache but this may lead to false impressions - i.e. we don't actually know
+ //what's in ZK so we shouldn't say we do
+ @Override
+ public Map<String, List<ControllerRegistryEntry>> getAllSwitches() {
+ Map<String, List<ControllerRegistryEntry>> data =
+ new HashMap<String, List<ControllerRegistryEntry>>();
+
+ for (Map.Entry<String, PathChildrenCache> entry : switchPathCaches.entrySet()) {
+ List<ControllerRegistryEntry> contendingControllers =
+ new ArrayList<ControllerRegistryEntry>();
+
+ if (entry.getValue().getCurrentData().size() < 1) {
+ //TODO prevent even having the PathChildrenCache in this case
+ //log.info("Switch entry with no leader elections: {}", entry.getKey());
+ continue;
+ }
+
+ for (ChildData d : entry.getValue().getCurrentData()) {
+
+ String controllerId = new String(d.getData(), Charsets.UTF_8);
+
+ String[] splitted = d.getPath().split("-");
+ int sequenceNumber = Integer.parseInt(splitted[splitted.length - 1]);
+
+ contendingControllers.add(new ControllerRegistryEntry(controllerId, sequenceNumber));
+ }
+
+ Collections.sort(contendingControllers);
+ data.put(entry.getKey(), contendingControllers);
+ }
+ return data;
+ }
+
+ public IdBlock allocateUniqueIdBlock(long range) {
+ try {
+ AtomicValue<Long> result = null;
+ do {
+ result = distributedIdCounter.add(range);
+ } while (result == null || !result.succeeded());
+
+ return new IdBlock(result.preValue(), result.postValue() - 1, range);
+ } catch (Exception e) {
+ log.error("Error allocating ID block");
+ }
+ return null;
+ }
+
+ /**
+ * Returns a block of IDs which are unique and unused.
+ * Range of IDs is fixed size and is assigned incrementally as this method called.
+ * Since the range of IDs is managed by Zookeeper in distributed way, this method may block when
+ * requests come up simultaneously.
+ */
+ @Override
+ public IdBlock allocateUniqueIdBlock() {
+ return allocateUniqueIdBlock(ID_BLOCK_SIZE);
+ }
+
+ /**
+ * Get a globally unique ID.
+ *
+ * @return a globally unique ID.
+ */
+ @Override
+ public synchronized long getNextUniqueId() {
+ //
+ // Generate the next Unique ID.
+ //
+ // TODO: For now, the higher 32 bits are random, and
+ // the lower 32 bits are sequential.
+ // The implementation must be updated to use the Zookeeper
+ // to allocate the higher 32 bits (globally unique).
+ //
+ if ((nextUniqueIdSuffix & 0xffffffffL) == 0xffffffffL) {
+ nextUniqueIdPrefix = randomGenerator.nextInt();
+ nextUniqueIdSuffix = 0;
+ } else {
+ nextUniqueIdSuffix++;
+ }
+ long result = (long) nextUniqueIdPrefix << 32;
+ result = result | (0xffffffffL & nextUniqueIdSuffix);
+ return result;
+ }
+
+ /*
+ * IFloodlightModule
+ */
+
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleServices() {
+ Collection<Class<? extends IFloodlightService>> l =
new ArrayList<Class<? extends IFloodlightService>>();
- l.add(IFloodlightProviderService.class);
- l.add(IRestApiService.class);
- return l;
- }
-
- //TODO currently blocks startup when it can't get a Zookeeper connection.
- //Do we support starting up with no Zookeeper connection?
- @Override
- public void init (FloodlightModuleContext context) throws FloodlightModuleException {
- log.info("Initialising the Zookeeper Registry - Zookeeper connection required");
-
- //Read the Zookeeper connection string from the config
- Map<String, String> configParams = context.getConfigParams(this);
- String connectionString = configParams.get("connectionString");
- if (connectionString != null){
- this.connectionString = connectionString;
- }
- log.info("Setting Zookeeper connection string to {}", this.connectionString);
+ l.add(IControllerRegistryService.class);
+ return l;
+ }
- //
- // Initialize the Unique ID generator
- // TODO: This must be replaced by Zookeeper-based allocation
- //
- nextUniqueIdPrefix = randomGenerator.nextInt();
+ @Override
+ public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
+ Map<Class<? extends IFloodlightService>, IFloodlightService> m =
+ new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
+ m.put(IControllerRegistryService.class, this);
+ return m;
+ }
- restApi = context.getServiceImpl(IRestApiService.class);
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
+ Collection<Class<? extends IFloodlightService>> l =
+ new ArrayList<Class<? extends IFloodlightService>>();
+ l.add(IFloodlightProviderService.class);
+ l.add(IRestApiService.class);
+ return l;
+ }
- switches = new ConcurrentHashMap<String, SwitchLeadershipData>();
- //switchPathCaches = new HashMap<String, PathChildrenCache>();
- switchPathCaches = new ConcurrentHashMap<String, PathChildrenCache>();
-
- RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
- client = CuratorFrameworkFactory.newClient(this.connectionString,
- sessionTimeout, connectionTimeout, retryPolicy);
-
- client.start();
- client = client.usingNamespace(namespace);
+ //TODO currently blocks startup when it can't get a Zookeeper connection.
+ //Do we support starting up with no Zookeeper connection?
+ @Override
+ public void init(FloodlightModuleContext context) throws FloodlightModuleException {
+ log.info("Initialising the Zookeeper Registry - Zookeeper connection required");
- distributedIdCounter = new DistributedAtomicLong(
- client,
- ID_COUNTER_PATH,
- new RetryOneTime(100));
-
- switchCache = new PathChildrenCache(client, switchLatchesPath, true);
- switchCache.getListenable().addListener(switchPathCacheListener);
-
- //Build the service discovery object
- serviceDiscovery = ServiceDiscoveryBuilder.builder(ControllerService.class)
- .client(client).basePath(SERVICES_PATH).build();
-
- //We read the list of services very frequently (GUI periodically queries them)
- //so we'll cache them to cut down on Zookeeper queries.
- serviceCache = serviceDiscovery.serviceCacheBuilder()
- .name(CONTROLLER_SERVICE_NAME).build();
-
-
- try {
- serviceDiscovery.start();
- serviceCache.start();
-
- //Don't prime the cache, we want a notification for each child node in the path
- switchCache.start(StartMode.NORMAL);
- } catch (Exception e) {
- throw new FloodlightModuleException("Error initialising ZookeeperRegistry: "
- + e.getMessage());
- }
-
- eventThreadExecutorService = Executors.newSingleThreadExecutor();
- eventThreadExecutorService.execute(
- new Runnable() {
- @Override
- public void run(){
- dispatchEvents();
- }
- });
- }
+ //Read the Zookeeper connection string from the config
+ Map<String, String> configParams = context.getConfigParams(this);
+ String connectionString = configParams.get("connectionString");
+ if (connectionString != null) {
+ this.connectionString = connectionString;
+ }
+ log.info("Setting Zookeeper connection string to {}", this.connectionString);
- @Override
- public void startUp (FloodlightModuleContext context) {
- //
- // Cluster Leader election setup.
- // NOTE: We have to do it here, because during the init stage
- // we don't know the Controller ID.
- //
- if (controllerId == null) {
- log.error("Error on startup: unknown ControllerId");
- }
- clusterLeaderLatch = new LeaderLatch(client,
- CLUSTER_LEADER_PATH,
- controllerId);
- clusterLeaderListener = new ClusterLeaderListener(clusterLeaderLatch);
- clusterLeaderLatch.addListener(clusterLeaderListener);
- try {
- clusterLeaderLatch.start();
- } catch (Exception e) {
- log.error("Error on startup starting the cluster leader election: {}", e.getMessage());
- }
+ //
+ // Initialize the Unique ID generator
+ // TODO: This must be replaced by Zookeeper-based allocation
+ //
+ nextUniqueIdPrefix = randomGenerator.nextInt();
- // Keep trying until there is a cluster leader
- do {
- try {
- Participant leader = clusterLeaderLatch.getLeader();
- if (! leader.getId().isEmpty())
- break;
- Thread.sleep(CLUSTER_LEADER_ELECTION_RETRY_MS);
- } catch (Exception e) {
- log.error("Error on startup waiting for cluster leader election: {}", e.getMessage());
- }
- } while (true);
+ restApi = context.getServiceImpl(IRestApiService.class);
- restApi.addRestletRoutable(new RegistryWebRoutable());
- }
+ switches = new ConcurrentHashMap<String, SwitchLeadershipData>();
+ //switchPathCaches = new HashMap<String, PathChildrenCache>();
+ switchPathCaches = new ConcurrentHashMap<String, PathChildrenCache>();
+
+ RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
+ client = CuratorFrameworkFactory.newClient(this.connectionString,
+ sessionTimeout, connectionTimeout, retryPolicy);
+
+ client.start();
+ client = client.usingNamespace(namespace);
+
+ distributedIdCounter = new DistributedAtomicLong(
+ client,
+ ID_COUNTER_PATH,
+ new RetryOneTime(100));
+
+ switchCache = new PathChildrenCache(client, switchLatchesPath, true);
+ switchCache.getListenable().addListener(switchPathCacheListener);
+
+ //Build the service discovery object
+ serviceDiscovery = ServiceDiscoveryBuilder.builder(ControllerService.class)
+ .client(client).basePath(SERVICES_PATH).build();
+
+ //We read the list of services very frequently (GUI periodically queries them)
+ //so we'll cache them to cut down on Zookeeper queries.
+ serviceCache = serviceDiscovery.serviceCacheBuilder()
+ .name(CONTROLLER_SERVICE_NAME).build();
+
+
+ try {
+ serviceDiscovery.start();
+ serviceCache.start();
+
+ //Don't prime the cache, we want a notification for each child node in the path
+ switchCache.start(StartMode.NORMAL);
+ } catch (Exception e) {
+ throw new FloodlightModuleException("Error initialising ZookeeperRegistry: "
+ + e.getMessage());
+ }
+
+ eventThreadExecutorService = Executors.newSingleThreadExecutor();
+ eventThreadExecutorService.execute(
+ new Runnable() {
+ @Override
+ public void run() {
+ dispatchEvents();
+ }
+ });
+ }
+
+ @Override
+ public void startUp(FloodlightModuleContext context) {
+ //
+ // Cluster Leader election setup.
+ // NOTE: We have to do it here, because during the init stage
+ // we don't know the Controller ID.
+ //
+ if (controllerId == null) {
+ log.error("Error on startup: unknown ControllerId");
+ }
+ clusterLeaderLatch = new LeaderLatch(client,
+ CLUSTER_LEADER_PATH,
+ controllerId);
+ clusterLeaderListener = new ClusterLeaderListener(clusterLeaderLatch);
+ clusterLeaderLatch.addListener(clusterLeaderListener);
+ try {
+ clusterLeaderLatch.start();
+ } catch (Exception e) {
+ log.error("Error on startup starting the cluster leader election: {}", e.getMessage());
+ }
+
+ // Keep trying until there is a cluster leader
+ do {
+ try {
+ Participant leader = clusterLeaderLatch.getLeader();
+ if (!leader.getId().isEmpty())
+ break;
+ Thread.sleep(CLUSTER_LEADER_ELECTION_RETRY_MS);
+ } catch (Exception e) {
+ log.error("Error on startup waiting for cluster leader election: {}", e.getMessage());
+ }
+ } while (true);
+
+ restApi.addRestletRoutable(new RegistryWebRoutable());
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/registry/web/ControllerRegistryResource.java b/src/main/java/net/onrc/onos/core/registry/web/ControllerRegistryResource.java
index 94e7e62..ee2b5f4 100644
--- a/src/main/java/net/onrc/onos/core/registry/web/ControllerRegistryResource.java
+++ b/src/main/java/net/onrc/onos/core/registry/web/ControllerRegistryResource.java
@@ -13,26 +13,26 @@
public class ControllerRegistryResource extends ServerResource {
- protected final static Logger log = LoggerFactory.getLogger(ControllerRegistryResource.class);
+ protected final static Logger log = LoggerFactory.getLogger(ControllerRegistryResource.class);
- @Get("json")
- public Collection<String> getControllers() {
- IControllerRegistryService registry =
- (IControllerRegistryService) getContext().getAttributes().
- get(IControllerRegistryService.class.getCanonicalName());
-
- Collection<String> controllers = null;
- try {
- controllers = registry.getAllControllers();
- } catch (RegistryException e) {
- log.warn("Error retrieving controller list: {}", e.getMessage());
- }
-
- if (controllers == null){
- controllers = new ArrayList<String>();
- }
-
- return controllers;
- }
-
+ @Get("json")
+ public Collection<String> getControllers() {
+ IControllerRegistryService registry =
+ (IControllerRegistryService) getContext().getAttributes().
+ get(IControllerRegistryService.class.getCanonicalName());
+
+ Collection<String> controllers = null;
+ try {
+ controllers = registry.getAllControllers();
+ } catch (RegistryException e) {
+ log.warn("Error retrieving controller list: {}", e.getMessage());
+ }
+
+ if (controllers == null) {
+ controllers = new ArrayList<String>();
+ }
+
+ return controllers;
+ }
+
}
diff --git a/src/main/java/net/onrc/onos/core/registry/web/RegistryWebRoutable.java b/src/main/java/net/onrc/onos/core/registry/web/RegistryWebRoutable.java
index e6bf552..fc32c96 100644
--- a/src/main/java/net/onrc/onos/core/registry/web/RegistryWebRoutable.java
+++ b/src/main/java/net/onrc/onos/core/registry/web/RegistryWebRoutable.java
@@ -8,17 +8,17 @@
public class RegistryWebRoutable implements RestletRoutable {
- @Override
- public Restlet getRestlet(Context context) {
- Router router = new Router(context);
- router.attach("/controllers/json", ControllerRegistryResource.class);
- router.attach("/switches/json", SwitchRegistryResource.class);
- return router;
- }
+ @Override
+ public Restlet getRestlet(Context context) {
+ Router router = new Router(context);
+ router.attach("/controllers/json", ControllerRegistryResource.class);
+ router.attach("/switches/json", SwitchRegistryResource.class);
+ return router;
+ }
- @Override
- public String basePath() {
- return "/wm/onos/registry";
- }
+ @Override
+ public String basePath() {
+ return "/wm/onos/registry";
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/registry/web/SwitchRegistryResource.java b/src/main/java/net/onrc/onos/core/registry/web/SwitchRegistryResource.java
index 60c4798..1db2560 100644
--- a/src/main/java/net/onrc/onos/core/registry/web/SwitchRegistryResource.java
+++ b/src/main/java/net/onrc/onos/core/registry/web/SwitchRegistryResource.java
@@ -11,20 +11,20 @@
import org.restlet.resource.ServerResource;
public class SwitchRegistryResource extends ServerResource {
-
- @Get("json")
- public Map<String, List<ControllerRegistryEntry>> getAllControllers(){
- IControllerRegistryService registry =
- (IControllerRegistryService) getContext().getAttributes().
- get(IControllerRegistryService.class.getCanonicalName());
-
- Map<String, List<ControllerRegistryEntry>> switches = null;
- switches = registry.getAllSwitches();
-
- if (switches == null){
- switches = new HashMap<String, List<ControllerRegistryEntry>>();
- }
-
- return switches;
- }
+
+ @Get("json")
+ public Map<String, List<ControllerRegistryEntry>> getAllControllers() {
+ IControllerRegistryService registry =
+ (IControllerRegistryService) getContext().getAttributes().
+ get(IControllerRegistryService.class.getCanonicalName());
+
+ Map<String, List<ControllerRegistryEntry>> switches = null;
+ switches = registry.getAllSwitches();
+
+ if (switches == null) {
+ switches = new HashMap<String, List<ControllerRegistryEntry>>();
+ }
+
+ return switches;
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/Device.java b/src/main/java/net/onrc/onos/core/topology/Device.java
index 25a27be..48035b3 100644
--- a/src/main/java/net/onrc/onos/core/topology/Device.java
+++ b/src/main/java/net/onrc/onos/core/topology/Device.java
@@ -7,12 +7,11 @@
/**
* Interface of Device Object exposed to the "NB" read-only Topology.
- *
+ * <p/>
* TODO What a Device Object represent is unclear at the moment.
- *
+ * <p/>
* Everything returned by these interfaces must be either Unmodifiable view,
* immutable object, or a copy of the original "SB" In-memory Topology.
- *
*/
public interface Device {
/**
@@ -31,7 +30,7 @@
/**
* Get the device attachment points.
- *
+ * <p/>
* Add requirement for Iteration order? Latest observed port first.
*
* @return the device attachment points.
@@ -40,7 +39,7 @@
/**
* Get the device last seen time.
- *
+ * <p/>
* TODO: what is the time definition?
*
* @return the device last seen time.
diff --git a/src/main/java/net/onrc/onos/core/topology/DeviceEvent.java b/src/main/java/net/onrc/onos/core/topology/DeviceEvent.java
index f7331a0..48d50e4 100644
--- a/src/main/java/net/onrc/onos/core/topology/DeviceEvent.java
+++ b/src/main/java/net/onrc/onos/core/topology/DeviceEvent.java
@@ -12,16 +12,15 @@
/**
* Self-contained Device event(s) Object
- *
+ * <p/>
* Device event differ from other events.
* Device Event represent add/remove of attachmentPoint or ipAddress.
* Not add/remove of the DeviceObject itself.
- *
+ * <p/>
* Multiple attachmentPoints can be specified to batch events into 1 object.
* Each should be treated as independent events.
- *
+ * <p/>
* TODO: We probably want common base class/interface for Self-Contained Event Object
- *
*/
public class DeviceEvent {
private final MACAddress mac;
@@ -34,24 +33,24 @@
*/
@Deprecated
public DeviceEvent() {
- mac = null;
+ mac = null;
}
public DeviceEvent(MACAddress mac) {
- if (mac == null) {
- throw new IllegalArgumentException("Device mac cannot be null");
- }
- this.mac = mac;
- this.attachmentPoints = new LinkedList<>();
- this.ipAddresses = new HashSet<>();
+ if (mac == null) {
+ throw new IllegalArgumentException("Device mac cannot be null");
+ }
+ this.mac = mac;
+ this.attachmentPoints = new LinkedList<>();
+ this.ipAddresses = new HashSet<>();
}
public MACAddress getMac() {
- return mac;
+ return mac;
}
public List<SwitchPort> getAttachmentPoints() {
- return attachmentPoints;
+ return attachmentPoints;
}
public Set<InetAddress> getIpAddresses() {
@@ -59,46 +58,46 @@
}
public void setAttachmentPoints(List<SwitchPort> attachmentPoints) {
- this.attachmentPoints = attachmentPoints;
+ this.attachmentPoints = attachmentPoints;
}
public void addAttachmentPoint(SwitchPort attachmentPoint) {
- // may need to maintain uniqness
- this.attachmentPoints.add(0, attachmentPoint);
+ // may need to maintain uniqness
+ this.attachmentPoints.add(0, attachmentPoint);
}
public boolean addIpAddress(InetAddress addr) {
- return this.ipAddresses.add(addr);
+ return this.ipAddresses.add(addr);
}
public boolean removeIpAddress(InetAddress addr) {
- return this.ipAddresses.remove(addr);
+ return this.ipAddresses.remove(addr);
}
@Override
public String toString() {
- return "[DeviceEvent " + mac + " attachmentPoints:" + attachmentPoints + " ipAddr:" + ipAddresses + "]";
+ return "[DeviceEvent " + mac + " attachmentPoints:" + attachmentPoints + " ipAddr:" + ipAddresses + "]";
}
// Assuming mac is unique cluster-wide
public static ByteBuffer getDeviceID(final byte[] mac) {
- return (ByteBuffer) ByteBuffer.allocate(2 + mac.length).putChar('D').put(mac).flip();
+ return (ByteBuffer) ByteBuffer.allocate(2 + mac.length).putChar('D').put(mac).flip();
}
public byte[] getID() {
- return getDeviceID(mac.toBytes()).array();
+ return getDeviceID(mac.toBytes()).array();
}
public ByteBuffer getIDasByteBuffer() {
- return getDeviceID(mac.toBytes());
+ return getDeviceID(mac.toBytes());
}
- public long getLastSeenTime() {
- return lastSeenTime;
- }
+ public long getLastSeenTime() {
+ return lastSeenTime;
+ }
- public void setLastSeenTime(long lastSeenTime) {
- this.lastSeenTime = lastSeenTime;
- }
+ public void setLastSeenTime(long lastSeenTime) {
+ this.lastSeenTime = lastSeenTime;
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/DeviceImpl.java b/src/main/java/net/onrc/onos/core/topology/DeviceImpl.java
index 5b96e08..6a4f16b 100644
--- a/src/main/java/net/onrc/onos/core/topology/DeviceImpl.java
+++ b/src/main/java/net/onrc/onos/core/topology/DeviceImpl.java
@@ -20,71 +20,75 @@
private long lastSeenTime;
public DeviceImpl(NetworkGraph graph, MACAddress mac) {
- super(graph);
- this.macAddr = mac;
- this.attachmentPoints = new LinkedList<>();
- this.ipAddresses = new HashSet<>();
+ super(graph);
+ this.macAddr = mac;
+ this.attachmentPoints = new LinkedList<>();
+ this.ipAddresses = new HashSet<>();
}
@Override
public MACAddress getMacAddress() {
- return this.macAddr;
+ return this.macAddr;
}
@Override
public Collection<InetAddress> getIpAddress() {
- return Collections.unmodifiableSet(ipAddresses);
+ return Collections.unmodifiableSet(ipAddresses);
}
@Override
public Iterable<Port> getAttachmentPoints() {
- return Collections.unmodifiableList(this.attachmentPoints);
+ return Collections.unmodifiableList(this.attachmentPoints);
}
@Override
public long getLastSeenTime() {
- return lastSeenTime;
+ return lastSeenTime;
}
@Override
public String toString() {
- return macAddr.toString();
+ return macAddr.toString();
}
-
+
void setLastSeenTime(long lastSeenTime) {
- this.lastSeenTime = lastSeenTime;
+ this.lastSeenTime = lastSeenTime;
}
/**
* Only {@link TopologyManager} should use this method
+ *
* @param p
*/
void addAttachmentPoint(Port p) {
- this.attachmentPoints.remove(p);
- this.attachmentPoints.addFirst(p);
+ this.attachmentPoints.remove(p);
+ this.attachmentPoints.addFirst(p);
}
/**
* Only {@link TopologyManager} should use this method
+ *
* @param p
*/
boolean removeAttachmentPoint(Port p) {
- return this.attachmentPoints.remove(p);
+ return this.attachmentPoints.remove(p);
}
/**
* Only {@link TopologyManager} should use this method
+ *
* @param p
*/
boolean addIpAddress(InetAddress addr) {
- return this.ipAddresses.add(addr);
+ return this.ipAddresses.add(addr);
}
/**
* Only {@link TopologyManager} should use this method
+ *
* @param p
*/
boolean removeIpAddress(InetAddress addr) {
- return this.ipAddresses.remove(addr);
+ return this.ipAddresses.remove(addr);
}
}
diff --git a/src/main/java/net/onrc/onos/core/topology/INetworkGraphListener.java b/src/main/java/net/onrc/onos/core/topology/INetworkGraphListener.java
index c64b126..9e53222 100644
--- a/src/main/java/net/onrc/onos/core/topology/INetworkGraphListener.java
+++ b/src/main/java/net/onrc/onos/core/topology/INetworkGraphListener.java
@@ -9,36 +9,36 @@
public interface INetworkGraphListener {
/**
* Network Graph events.
- *
+ * <p/>
* The recommended ordering rules for applying/processing the events is:
- * (a) Process "added" events before "removed" events.
- * (b) The ordering of the "added" events should be:
- * addedSwitchEvents, addedPortEvents, addedLinkEvents,
- * addedDeviceEvents
- * The above ordering guarantees that adding a port for example
- * will be processed after the corresponding switch itself is added.
- * (c) The ordering of the "removed" events should be:
- * removedDeviceEvents, removedLinkEvents, removedPortEvents,
- * removedSwitchEvents
- * The above ordering guarantees that removing a port for example
- * will be processed before the corresponding switch itself is
- * removed.
+ * (a) Process "added" events before "removed" events.
+ * (b) The ordering of the "added" events should be:
+ * addedSwitchEvents, addedPortEvents, addedLinkEvents,
+ * addedDeviceEvents
+ * The above ordering guarantees that adding a port for example
+ * will be processed after the corresponding switch itself is added.
+ * (c) The ordering of the "removed" events should be:
+ * removedDeviceEvents, removedLinkEvents, removedPortEvents,
+ * removedSwitchEvents
+ * The above ordering guarantees that removing a port for example
+ * will be processed before the corresponding switch itself is
+ * removed.
*
- * @param addedSwitchEvents the Added Switch Events.
+ * @param addedSwitchEvents the Added Switch Events.
* @param removedSwitchEvents the Removed Switch Events.
- * @param addedPortEvents the Added Port Events.
- * @param removedPortEvents the Removed Port Events.
- * @param addedLinkEvents the Added Link Events.
- * @param removedLinkEvents the Removed Link Events.
- * @param addedDeviceEvents the Added Device Events.
+ * @param addedPortEvents the Added Port Events.
+ * @param removedPortEvents the Removed Port Events.
+ * @param addedLinkEvents the Added Link Events.
+ * @param removedLinkEvents the Removed Link Events.
+ * @param addedDeviceEvents the Added Device Events.
* @param removedDeviceEvents the Removed Device Events.
*/
public void networkGraphEvents(Collection<SwitchEvent> addedSwitchEvents,
- Collection<SwitchEvent> removedSwitchEvents,
- Collection<PortEvent> addedPortEvents,
- Collection<PortEvent> removedPortEvents,
- Collection<LinkEvent> addedLinkEvents,
- Collection<LinkEvent> removedLinkEvents,
- Collection<DeviceEvent> addedDeviceEvents,
- Collection<DeviceEvent> removedDeviceEvents);
+ Collection<SwitchEvent> removedSwitchEvents,
+ Collection<PortEvent> addedPortEvents,
+ Collection<PortEvent> removedPortEvents,
+ Collection<LinkEvent> addedLinkEvents,
+ Collection<LinkEvent> removedLinkEvents,
+ Collection<DeviceEvent> addedDeviceEvents,
+ Collection<DeviceEvent> removedDeviceEvents);
}
diff --git a/src/main/java/net/onrc/onos/core/topology/INetworkGraphService.java b/src/main/java/net/onrc/onos/core/topology/INetworkGraphService.java
index 9d4cb3a..18eb785 100644
--- a/src/main/java/net/onrc/onos/core/topology/INetworkGraphService.java
+++ b/src/main/java/net/onrc/onos/core/topology/INetworkGraphService.java
@@ -6,13 +6,15 @@
* Interface for providing the Network Graph Service to other modules.
*/
public interface INetworkGraphService extends IFloodlightService {
- /**
- * Allows a module to get a reference to the global network graph object.
- * @return
- */
+ /**
+ * Allows a module to get a reference to the global network graph object.
+ *
+ * @return
+ */
public NetworkGraph getNetworkGraph();
public void registerNetworkGraphListener(INetworkGraphListener listener);
+
public void deregisterNetworkGraphListener(INetworkGraphListener listener);
/**
@@ -20,6 +22,7 @@
* the network graph.
* TODO Figure out how to hide the southbound interface from
* applications/modules that shouldn't touch it
+ *
* @return
*/
public NetworkGraphDiscoveryInterface getNetworkGraphDiscoveryInterface();
diff --git a/src/main/java/net/onrc/onos/core/topology/Link.java b/src/main/java/net/onrc/onos/core/topology/Link.java
index f73bccf..2acf7dc 100644
--- a/src/main/java/net/onrc/onos/core/topology/Link.java
+++ b/src/main/java/net/onrc/onos/core/topology/Link.java
@@ -2,10 +2,9 @@
/**
* Interface of Link Object exposed to the "NB" read-only Topology.
- *
+ * <p/>
* Everything returned by these interfaces must be either Unmodifiable view,
* immutable object, or a copy of the original "SB" In-memory Topology.
- *
*/
public interface Link {
/**
@@ -38,7 +37,7 @@
/**
* Get the last seen time for the link.
- *
+ * <p/>
* TODO: Not implemented yet.
* TODO: what is the time definition?
*
@@ -48,7 +47,7 @@
/**
* Get the link cost.
- *
+ * <p/>
* TODO: What is the unit?
*
* @param return the link cost.
@@ -57,7 +56,7 @@
/**
* Get the link capacity.
- *
+ * <p/>
* TODO: What is the unit?
*
* @return the link capacity.
diff --git a/src/main/java/net/onrc/onos/core/topology/LinkEvent.java b/src/main/java/net/onrc/onos/core/topology/LinkEvent.java
index bf43155..7434ad9 100644
--- a/src/main/java/net/onrc/onos/core/topology/LinkEvent.java
+++ b/src/main/java/net/onrc/onos/core/topology/LinkEvent.java
@@ -6,9 +6,8 @@
/**
* Self-contained Link event Object
- *
+ * <p/>
* TODO: We probably want common base class/interface for Self-Contained Event Object
- *
*/
public class LinkEvent {
protected final SwitchPort src;
@@ -19,83 +18,83 @@
*/
@Deprecated
public LinkEvent() {
- src = null;
- dst = null;
+ src = null;
+ dst = null;
}
public LinkEvent(Long src_dpid, Long src_port_no, Long dst_dpid,
- Long dst_port_no) {
- src = new SwitchPort(src_dpid, src_port_no);
- dst = new SwitchPort(dst_dpid, dst_port_no);
+ Long dst_port_no) {
+ src = new SwitchPort(src_dpid, src_port_no);
+ dst = new SwitchPort(dst_dpid, dst_port_no);
}
public LinkEvent(Link link) {
- src = new SwitchPort(link.getSrcSwitch().getDpid(),
- link.getSrcPort().getNumber());
- dst = new SwitchPort(link.getDstSwitch().getDpid(),
- link.getDstPort().getNumber());
+ src = new SwitchPort(link.getSrcSwitch().getDpid(),
+ link.getSrcPort().getNumber());
+ dst = new SwitchPort(link.getDstSwitch().getDpid(),
+ link.getDstPort().getNumber());
}
public SwitchPort getSrc() {
- return src;
+ return src;
}
public SwitchPort getDst() {
- return dst;
+ return dst;
}
@Override
public String toString() {
- return "[LinkEvent " + src + "->" + dst + "]";
+ return "[LinkEvent " + src + "->" + dst + "]";
}
public static final int LINKID_BYTES = 2 + PortEvent.PORTID_BYTES * 2;
public static ByteBuffer getLinkID(Long src_dpid, Long src_port_no,
- Long dst_dpid, Long dst_port_no) {
- return (ByteBuffer) ByteBuffer.allocate(LinkEvent.LINKID_BYTES).putChar('L')
- .put(PortEvent.getPortID(src_dpid, src_port_no))
- .put(PortEvent.getPortID(dst_dpid, dst_port_no)).flip();
+ Long dst_dpid, Long dst_port_no) {
+ return (ByteBuffer) ByteBuffer.allocate(LinkEvent.LINKID_BYTES).putChar('L')
+ .put(PortEvent.getPortID(src_dpid, src_port_no))
+ .put(PortEvent.getPortID(dst_dpid, dst_port_no)).flip();
}
public byte[] getID() {
- return getLinkID(src.getDpid(), src.getNumber(),
- dst.getDpid(), dst.getNumber()).array();
+ return getLinkID(src.getDpid(), src.getNumber(),
+ dst.getDpid(), dst.getNumber()).array();
}
public ByteBuffer getIDasByteBuffer() {
- return getLinkID(src.getDpid(), src.getNumber(),
- dst.getDpid(), dst.getNumber());
+ return getLinkID(src.getDpid(), src.getNumber(),
+ dst.getDpid(), dst.getNumber());
}
@Override
public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((dst == null) ? 0 : dst.hashCode());
- result = prime * result + ((src == null) ? 0 : src.hashCode());
- return result;
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((dst == null) ? 0 : dst.hashCode());
+ result = prime * result + ((src == null) ? 0 : src.hashCode());
+ return result;
}
@Override
public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- LinkEvent other = (LinkEvent) obj;
- if (dst == null) {
- if (other.dst != null)
- return false;
- } else if (!dst.equals(other.dst))
- return false;
- if (src == null) {
- if (other.src != null)
- return false;
- } else if (!src.equals(other.src))
- return false;
- return true;
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ LinkEvent other = (LinkEvent) obj;
+ if (dst == null) {
+ if (other.dst != null)
+ return false;
+ } else if (!dst.equals(other.dst))
+ return false;
+ if (src == null) {
+ if (other.src != null)
+ return false;
+ } else if (!src.equals(other.src))
+ return false;
+ return true;
}
}
\ No newline at end of file
diff --git a/src/main/java/net/onrc/onos/core/topology/LinkImpl.java b/src/main/java/net/onrc/onos/core/topology/LinkImpl.java
index d95d4fd..4333e38 100644
--- a/src/main/java/net/onrc/onos/core/topology/LinkImpl.java
+++ b/src/main/java/net/onrc/onos/core/topology/LinkImpl.java
@@ -2,93 +2,94 @@
/**
* Link Object stored in In-memory Topology.
- *
+ * <p/>
* TODO REMOVE following design memo: This object itself may hold the DBObject,
* but this Object itself will not issue any read/write to the DataStore.
*/
public class LinkImpl extends NetworkGraphObject implements Link {
- protected Port srcPort;
- protected Port dstPort;
+ protected Port srcPort;
+ protected Port dstPort;
- protected static final Double DEFAULT_CAPACITY = Double.POSITIVE_INFINITY;
- protected Double capacity = DEFAULT_CAPACITY;
+ protected static final Double DEFAULT_CAPACITY = Double.POSITIVE_INFINITY;
+ protected Double capacity = DEFAULT_CAPACITY;
- protected static final int DEFAULT_COST = 1;
- protected int cost = DEFAULT_COST;
+ protected static final int DEFAULT_COST = 1;
+ protected int cost = DEFAULT_COST;
- /**
- * Constructor for when a link is read from the database and the Ports
- * already exist in the in-memory network graph.
- * @param graph
- * @param srcPort
- * @param dstPort
- */
- public LinkImpl(NetworkGraph graph, Port srcPort, Port dstPort) {
- super(graph);
- this.srcPort = srcPort;
- this.dstPort = dstPort;
- setToPorts();
- }
+ /**
+ * Constructor for when a link is read from the database and the Ports
+ * already exist in the in-memory network graph.
+ *
+ * @param graph
+ * @param srcPort
+ * @param dstPort
+ */
+ public LinkImpl(NetworkGraph graph, Port srcPort, Port dstPort) {
+ super(graph);
+ this.srcPort = srcPort;
+ this.dstPort = dstPort;
+ setToPorts();
+ }
- @Override
- public Switch getSrcSwitch() {
- return srcPort.getSwitch();
- }
+ @Override
+ public Switch getSrcSwitch() {
+ return srcPort.getSwitch();
+ }
- @Override
- public Port getSrcPort() {
- return srcPort;
- }
+ @Override
+ public Port getSrcPort() {
+ return srcPort;
+ }
- @Override
- public Switch getDstSwitch() {
- return dstPort.getSwitch();
- }
+ @Override
+ public Switch getDstSwitch() {
+ return dstPort.getSwitch();
+ }
- @Override
- public Port getDstPort() {
- return dstPort;
- }
+ @Override
+ public Port getDstPort() {
+ return dstPort;
+ }
- protected void setToPorts() {
- ((PortImpl)srcPort).setOutgoingLink(this);
- ((PortImpl)dstPort).setIncomingLink(this);
- }
+ protected void setToPorts() {
+ ((PortImpl) srcPort).setOutgoingLink(this);
+ ((PortImpl) dstPort).setIncomingLink(this);
+ }
- protected void unsetFromPorts() {
- ((PortImpl)srcPort).setOutgoingLink(null);
- ((PortImpl)dstPort).setIncomingLink(null);
- }
+ protected void unsetFromPorts() {
+ ((PortImpl) srcPort).setOutgoingLink(null);
+ ((PortImpl) dstPort).setIncomingLink(null);
+ }
- @Override
- public long getLastSeenTime() {
- // TODO Auto-generated method stub
- return 0;
- }
+ @Override
+ public long getLastSeenTime() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
- @Override
- public int getCost() {
- return cost;
- }
+ @Override
+ public int getCost() {
+ return cost;
+ }
- public void setCost(int cost) {
- this.cost = cost;
- }
+ public void setCost(int cost) {
+ this.cost = cost;
+ }
- @Override
- public Double getCapacity() {
- return capacity;
- }
+ @Override
+ public Double getCapacity() {
+ return capacity;
+ }
- public void setCapacity(Double capacity) {
- this.capacity = capacity;
- }
+ public void setCapacity(Double capacity) {
+ this.capacity = capacity;
+ }
- @Override
- public String toString() {
- return String.format("%s --(cap:%f Mbps)--> %s",
- getSrcPort().toString(),
- getCapacity(),
- getDstPort().toString());
- }
+ @Override
+ public String toString() {
+ return String.format("%s --(cap:%f Mbps)--> %s",
+ getSrcPort().toString(),
+ getCapacity(),
+ getDstPort().toString());
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/NetworkGraph.java b/src/main/java/net/onrc/onos/core/topology/NetworkGraph.java
index 4e83263..3c583b4 100644
--- a/src/main/java/net/onrc/onos/core/topology/NetworkGraph.java
+++ b/src/main/java/net/onrc/onos/core/topology/NetworkGraph.java
@@ -28,7 +28,7 @@
/**
* Get the port on a switch.
*
- * @param dpid the switch DPID.
+ * @param dpid the switch DPID.
* @param number the switch port number.
* @return the switch port if found, otherwise null.
*/
@@ -37,7 +37,7 @@
/**
* Get the outgoing link for a switch and a port.
*
- * @param dpid the switch DPID.
+ * @param dpid the switch DPID.
* @param number the switch port number.
* @return the outgoing link if found, otherwise null.
*/
@@ -47,18 +47,18 @@
* Get the outgoing link from a switch and a port to another switch and
* a port.
*
- * @param srcDpid the source switch DPID.
+ * @param srcDpid the source switch DPID.
* @param srcNumber the source switch port number.
- * @param dstDpid the destination switch DPID.
+ * @param dstDpid the destination switch DPID.
* @param dstNumber the destination switch port number.
* @return the outgoing link if found, otherwise null.
*/
public Link getLink(Long srcDpid, Long srcNumber, Long dstDpid,
- Long dstNumber);
+ Long dstNumber);
/**
* Get all links in the network.
- *
+ * <p/>
* TODO: Not clear if this method is needed. Remove if not used.
*
* @return all links in the network.
@@ -80,15 +80,15 @@
* @return the network device for the MAC address if found, otherwise null.
*/
public Device getDeviceByMac(MACAddress address);
-
+
/**
- * Acquire a read lock on the entire topology. The topology will not
- * change while readers have the lock. Must be released using
+ * Acquire a read lock on the entire topology. The topology will not
+ * change while readers have the lock. Must be released using
* {@link releaseReadLock()}. This method will block until a read lock is
* available.
*/
public void acquireReadLock();
-
+
/**
* Release the read lock on the topology.
*/
diff --git a/src/main/java/net/onrc/onos/core/topology/NetworkGraphDatastore.java b/src/main/java/net/onrc/onos/core/topology/NetworkGraphDatastore.java
index 8488297..488915f 100644
--- a/src/main/java/net/onrc/onos/core/topology/NetworkGraphDatastore.java
+++ b/src/main/java/net/onrc/onos/core/topology/NetworkGraphDatastore.java
@@ -26,203 +26,202 @@
* mutate the graph. This class will maintain the invariants of the network
* graph. The southbound discovery modules will use this interface to update
* the network graph as they learn about the state of the network.
- *
+ * <p/>
* Modification to the Network Map by this module will:
* 1. Writes to Cluster-wide DataStore.
* 2. Update ONOS instance In-memory Network Map.
* 3. Send-out Notification. (TBD)
- * (XXX: To update other instances In-memory Network Map,
- * notification should be triggered here.
- * But if we want to aggregate notification to minimize notification,
- * It might be better for the caller to trigger notification.)
- *
+ * (XXX: To update other instances In-memory Network Map,
+ * notification should be triggered here.
+ * But if we want to aggregate notification to minimize notification,
+ * It might be better for the caller to trigger notification.)
*/
public class NetworkGraphDatastore {
- private static final Logger log = LoggerFactory.getLogger(NetworkGraphDatastore.class);
+ private static final Logger log = LoggerFactory.getLogger(NetworkGraphDatastore.class);
- /**
- * Add a switch to the database.
- *
- * @param sw the switch to add.
- * @param portEvents the corresponding switch ports to add.
- * @return true on success, otherwise false.
- */
- public boolean addSwitch(SwitchEvent sw,
- Collection<PortEvent> portEvents) {
- log.debug("Adding switch {}", sw);
- ArrayList<WriteOp> groupOp = new ArrayList<>();
+ /**
+ * Add a switch to the database.
+ *
+ * @param sw the switch to add.
+ * @param portEvents the corresponding switch ports to add.
+ * @return true on success, otherwise false.
+ */
+ public boolean addSwitch(SwitchEvent sw,
+ Collection<PortEvent> portEvents) {
+ log.debug("Adding switch {}", sw);
+ ArrayList<WriteOp> groupOp = new ArrayList<>();
- KVSwitch rcSwitch = new KVSwitch(sw.getDpid());
- rcSwitch.setStatus(KVSwitch.STATUS.ACTIVE);
+ KVSwitch rcSwitch = new KVSwitch(sw.getDpid());
+ rcSwitch.setStatus(KVSwitch.STATUS.ACTIVE);
- IKVClient client = DataStoreClient.getClient();
+ IKVClient client = DataStoreClient.getClient();
- // XXX Is ForceCreating Switch on DB OK here?
- // If ForceCreating, who ever is calling this method needs
- // to assure that DPID is unique cluster-wide, etc.
- groupOp.add(rcSwitch.forceCreateOp(client));
+ // XXX Is ForceCreating Switch on DB OK here?
+ // If ForceCreating, who ever is calling this method needs
+ // to assure that DPID is unique cluster-wide, etc.
+ groupOp.add(rcSwitch.forceCreateOp(client));
- for (PortEvent portEvent : portEvents) {
- KVPort rcPort = new KVPort(sw.getDpid(), portEvent.getNumber());
- rcPort.setStatus(KVPort.STATUS.ACTIVE);
+ for (PortEvent portEvent : portEvents) {
+ KVPort rcPort = new KVPort(sw.getDpid(), portEvent.getNumber());
+ rcPort.setStatus(KVPort.STATUS.ACTIVE);
- groupOp.add(rcPort.forceCreateOp(client));
- }
+ groupOp.add(rcPort.forceCreateOp(client));
+ }
- boolean failed = KVObject.multiWrite(groupOp);
+ boolean failed = KVObject.multiWrite(groupOp);
- if (failed) {
- log.error("Adding Switch {} and its ports failed.", sw.getDpid());
- for (WriteOp op : groupOp) {
- log.debug("Operation:{} for {} - Result:{}", op.getOp(), op.getObject(), op.getStatus() );
+ if (failed) {
+ log.error("Adding Switch {} and its ports failed.", sw.getDpid());
+ for (WriteOp op : groupOp) {
+ log.debug("Operation:{} for {} - Result:{}", op.getOp(), op.getObject(), op.getStatus());
- // If we changed the operation from ForceCreate to
- // Conditional operation (Create/Update) then we should retry here.
- }
- }
- return !failed;
- }
+ // If we changed the operation from ForceCreate to
+ // Conditional operation (Create/Update) then we should retry here.
+ }
+ }
+ return !failed;
+ }
- /**
- * Update a switch as inactive in the database.
- *
- * @param sw the switch to update.
- * @param portEvents the corresponding switch ports to update.
- * @return true on success, otherwise false.
- */
- public boolean deactivateSwitch(SwitchEvent sw,
- Collection<PortEvent> portEvents) {
- log.debug("Deactivating switch {}", sw);
- KVSwitch rcSwitch = new KVSwitch(sw.getDpid());
+ /**
+ * Update a switch as inactive in the database.
+ *
+ * @param sw the switch to update.
+ * @param portEvents the corresponding switch ports to update.
+ * @return true on success, otherwise false.
+ */
+ public boolean deactivateSwitch(SwitchEvent sw,
+ Collection<PortEvent> portEvents) {
+ log.debug("Deactivating switch {}", sw);
+ KVSwitch rcSwitch = new KVSwitch(sw.getDpid());
- IKVClient client = DataStoreClient.getClient();
+ IKVClient client = DataStoreClient.getClient();
- List<WriteOp> groupOp = new ArrayList<>();
- rcSwitch.setStatus(KVSwitch.STATUS.INACTIVE);
+ List<WriteOp> groupOp = new ArrayList<>();
+ rcSwitch.setStatus(KVSwitch.STATUS.INACTIVE);
- groupOp.add(rcSwitch.forceCreateOp(client));
+ groupOp.add(rcSwitch.forceCreateOp(client));
- for (PortEvent portEvent : portEvents) {
- KVPort rcPort = new KVPort(sw.getDpid(), portEvent.getNumber());
- rcPort.setStatus(KVPort.STATUS.INACTIVE);
+ for (PortEvent portEvent : portEvents) {
+ KVPort rcPort = new KVPort(sw.getDpid(), portEvent.getNumber());
+ rcPort.setStatus(KVPort.STATUS.INACTIVE);
- groupOp.add(rcPort.forceCreateOp(client));
- }
+ groupOp.add(rcPort.forceCreateOp(client));
+ }
- boolean failed = KVObject.multiWrite(groupOp);
+ boolean failed = KVObject.multiWrite(groupOp);
- return !failed;
- }
+ return !failed;
+ }
- /**
- * Add a port to the database.
- *
- * @param port the port to add.
- * @return true on success, otherwise false.
- */
- public boolean addPort(PortEvent port) {
- log.debug("Adding port {}", port);
+ /**
+ * Add a port to the database.
+ *
+ * @param port the port to add.
+ * @return true on success, otherwise false.
+ */
+ public boolean addPort(PortEvent port) {
+ log.debug("Adding port {}", port);
- KVPort rcPort = new KVPort(port.getDpid(), port.getNumber());
- rcPort.setStatus(KVPort.STATUS.ACTIVE);
- rcPort.forceCreate();
- // TODO add description into KVPort
- //rcPort.setDescription(port.getDescription());
+ KVPort rcPort = new KVPort(port.getDpid(), port.getNumber());
+ rcPort.setStatus(KVPort.STATUS.ACTIVE);
+ rcPort.forceCreate();
+ // TODO add description into KVPort
+ //rcPort.setDescription(port.getDescription());
- return true;
- }
+ return true;
+ }
- /**
- * Update a port as inactive in the database.
- *
- * @param port the port to update.
- * @return true on success, otherwise false.
- */
- public boolean deactivatePort(PortEvent port) {
- log.debug("Deactivating port {}", port);
+ /**
+ * Update a port as inactive in the database.
+ *
+ * @param port the port to update.
+ * @return true on success, otherwise false.
+ */
+ public boolean deactivatePort(PortEvent port) {
+ log.debug("Deactivating port {}", port);
- KVPort rcPort = new KVPort(port.getDpid(), port.getNumber());
- rcPort.setStatus(STATUS.INACTIVE);
+ KVPort rcPort = new KVPort(port.getDpid(), port.getNumber());
+ rcPort.setStatus(STATUS.INACTIVE);
- rcPort.forceCreate();
+ rcPort.forceCreate();
- return true;
- }
+ return true;
+ }
- /**
- * Add a link to the database.
- *
- * @param link the link to add.
- * @return true on success, otherwise false.
- */
- public boolean addLink(LinkEvent link) {
- log.debug("Adding link {}", link);
+ /**
+ * Add a link to the database.
+ *
+ * @param link the link to add.
+ * @return true on success, otherwise false.
+ */
+ public boolean addLink(LinkEvent link) {
+ log.debug("Adding link {}", link);
- KVLink rcLink = new KVLink(link.getSrc().getDpid(),
- link.getSrc().getNumber(),
- link.getDst().getDpid(),
- link.getDst().getNumber());
+ KVLink rcLink = new KVLink(link.getSrc().getDpid(),
+ link.getSrc().getNumber(),
+ link.getDst().getDpid(),
+ link.getDst().getNumber());
- // XXX This method is called only by discovery,
- // which means what we are trying to write currently is the truth
- // so we can force write here
- //
- // TODO: We need to check for errors
- rcLink.setStatus(KVLink.STATUS.ACTIVE);
- rcLink.forceCreate();
+ // XXX This method is called only by discovery,
+ // which means what we are trying to write currently is the truth
+ // so we can force write here
+ //
+ // TODO: We need to check for errors
+ rcLink.setStatus(KVLink.STATUS.ACTIVE);
+ rcLink.forceCreate();
- return true; // Success
- }
+ return true; // Success
+ }
- public boolean removeLink(LinkEvent linkEvent) {
- log.debug("Removing link {}", linkEvent);
+ public boolean removeLink(LinkEvent linkEvent) {
+ log.debug("Removing link {}", linkEvent);
- KVLink rcLink = new KVLink(linkEvent.getSrc().getDpid(), linkEvent.getSrc().getNumber(),
- linkEvent.getDst().getDpid(), linkEvent.getDst().getNumber());
- rcLink.forceDelete();
+ KVLink rcLink = new KVLink(linkEvent.getSrc().getDpid(), linkEvent.getSrc().getNumber(),
+ linkEvent.getDst().getDpid(), linkEvent.getDst().getNumber());
+ rcLink.forceDelete();
- return true;
- }
+ return true;
+ }
- /**
- * Add a device to the database.
- *
- * @param device the device to add.
- * @return true on success, otherwise false.
- */
- public boolean addDevice(DeviceEvent device) {
- log.debug("Adding device into DB. mac {}", device.getMac());
+ /**
+ * Add a device to the database.
+ *
+ * @param device the device to add.
+ * @return true on success, otherwise false.
+ */
+ public boolean addDevice(DeviceEvent device) {
+ log.debug("Adding device into DB. mac {}", device.getMac());
- KVDevice rcDevice = new KVDevice(device.getMac().toBytes());
- rcDevice.setLastSeenTime(device.getLastSeenTime());
-
- for(SwitchPort sp : device.getAttachmentPoints()) {
- byte[] portId = KVPort.getPortID(sp.getDpid(), sp.getNumber());
- rcDevice.addPortId(portId);
- }
-
- for(InetAddress addr : device.getIpAddresses()) {
- //It assume only one ip on a device now.
- rcDevice.setIp(InetAddresses.coerceToInteger(addr));
- }
+ KVDevice rcDevice = new KVDevice(device.getMac().toBytes());
+ rcDevice.setLastSeenTime(device.getLastSeenTime());
- rcDevice.forceCreate();
-
- return true;
- }
+ for (SwitchPort sp : device.getAttachmentPoints()) {
+ byte[] portId = KVPort.getPortID(sp.getDpid(), sp.getNumber());
+ rcDevice.addPortId(portId);
+ }
- /**
- * Remove a device from the database.
- *
- * @param device the device to remove.
- * @return true on success, otherwise false.
- */
- public boolean removeDevice(DeviceEvent device) {
- log.debug("Removing device into DB. mac {}", device.getMac());
-
- KVDevice rcDevice = new KVDevice(device.getMac().toBytes());
- rcDevice.forceDelete();
-
- return true;
- }
+ for (InetAddress addr : device.getIpAddresses()) {
+ //It assume only one ip on a device now.
+ rcDevice.setIp(InetAddresses.coerceToInteger(addr));
+ }
+
+ rcDevice.forceCreate();
+
+ return true;
+ }
+
+ /**
+ * Remove a device from the database.
+ *
+ * @param device the device to remove.
+ * @return true on success, otherwise false.
+ */
+ public boolean removeDevice(DeviceEvent device) {
+ log.debug("Removing device into DB. mac {}", device.getMac());
+
+ KVDevice rcDevice = new KVDevice(device.getMac().toBytes());
+ rcDevice.forceDelete();
+
+ return true;
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/NetworkGraphDiscoveryInterface.java b/src/main/java/net/onrc/onos/core/topology/NetworkGraphDiscoveryInterface.java
index 14ef0ea..219417f 100644
--- a/src/main/java/net/onrc/onos/core/topology/NetworkGraphDiscoveryInterface.java
+++ b/src/main/java/net/onrc/onos/core/topology/NetworkGraphDiscoveryInterface.java
@@ -11,10 +11,10 @@
* Switch discovered event.
*
* @param switchEvent the switch event.
- * @param portEvents the corresponding port events for the switch.
+ * @param portEvents the corresponding port events for the switch.
*/
public void putSwitchDiscoveryEvent(SwitchEvent switchEvent,
- Collection<PortEvent> portEvents);
+ Collection<PortEvent> portEvents);
/**
* Switch removed event.
diff --git a/src/main/java/net/onrc/onos/core/topology/NetworkGraphImpl.java b/src/main/java/net/onrc/onos/core/topology/NetworkGraphImpl.java
index 902ffa6..a60e390 100644
--- a/src/main/java/net/onrc/onos/core/topology/NetworkGraphImpl.java
+++ b/src/main/java/net/onrc/onos/core/topology/NetworkGraphImpl.java
@@ -18,143 +18,143 @@
import org.slf4j.LoggerFactory;
public class NetworkGraphImpl implements NetworkGraph {
- @SuppressWarnings("unused")
- private static final Logger log = LoggerFactory.getLogger(NetworkGraphImpl.class);
+ @SuppressWarnings("unused")
+ private static final Logger log = LoggerFactory.getLogger(NetworkGraphImpl.class);
- // DPID -> Switch
- private ConcurrentMap<Long, Switch> switches;
+ // DPID -> Switch
+ private ConcurrentMap<Long, Switch> switches;
- private ConcurrentMap<InetAddress, Set<Device>> addr2Device;
- private ConcurrentMap<MACAddress, Device> mac2Device;
+ private ConcurrentMap<InetAddress, Set<Device>> addr2Device;
+ private ConcurrentMap<MACAddress, Device> mac2Device;
- private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
- private Lock readLock = readWriteLock.readLock();
- // TODO use the write lock after refactor
- private Lock writeLock = readWriteLock.writeLock();
+ private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
+ private Lock readLock = readWriteLock.readLock();
+ // TODO use the write lock after refactor
+ private Lock writeLock = readWriteLock.writeLock();
- public NetworkGraphImpl() {
- // TODO: Does these object need to be stored in Concurrent Collection?
- switches = new ConcurrentHashMap<>();
- addr2Device = new ConcurrentHashMap<>();
- mac2Device = new ConcurrentHashMap<>();
- }
+ public NetworkGraphImpl() {
+ // TODO: Does these object need to be stored in Concurrent Collection?
+ switches = new ConcurrentHashMap<>();
+ addr2Device = new ConcurrentHashMap<>();
+ mac2Device = new ConcurrentHashMap<>();
+ }
- @Override
- public Switch getSwitch(Long dpid) {
- // TODO Check if it is safe to directly return this Object.
- return switches.get(dpid);
- }
+ @Override
+ public Switch getSwitch(Long dpid) {
+ // TODO Check if it is safe to directly return this Object.
+ return switches.get(dpid);
+ }
- protected void putSwitch(Switch sw) {
- switches.put(sw.getDpid(), sw);
- }
+ protected void putSwitch(Switch sw) {
+ switches.put(sw.getDpid(), sw);
+ }
- protected void removeSwitch(Long dpid) {
- switches.remove(dpid);
- }
+ protected void removeSwitch(Long dpid) {
+ switches.remove(dpid);
+ }
- @Override
- public Iterable<Switch> getSwitches() {
- // TODO Check if it is safe to directly return this Object.
- return Collections.unmodifiableCollection(switches.values());
- }
+ @Override
+ public Iterable<Switch> getSwitches() {
+ // TODO Check if it is safe to directly return this Object.
+ return Collections.unmodifiableCollection(switches.values());
+ }
- @Override
- public Port getPort(Long dpid, Long number) {
- Switch sw = getSwitch(dpid);
- if (sw != null) {
- return sw.getPort(number);
- }
- return null;
- }
+ @Override
+ public Port getPort(Long dpid, Long number) {
+ Switch sw = getSwitch(dpid);
+ if (sw != null) {
+ return sw.getPort(number);
+ }
+ return null;
+ }
- @Override
- public Link getLink(Long dpid, Long number) {
- Port srcPort = getPort(dpid, number);
- if (srcPort == null)
- return null;
- return srcPort.getOutgoingLink();
- }
+ @Override
+ public Link getLink(Long dpid, Long number) {
+ Port srcPort = getPort(dpid, number);
+ if (srcPort == null)
+ return null;
+ return srcPort.getOutgoingLink();
+ }
- @Override
- public Link getLink(Long srcDpid, Long srcNumber, Long dstDpid,
- Long dstNumber) {
- Link link = getLink(srcDpid, srcNumber);
- if (link == null)
- return null;
- if (!link.getDstSwitch().getDpid().equals(dstDpid))
- return null;
- if (!link.getDstPort().getNumber().equals(dstNumber))
- return null;
- return link;
- }
+ @Override
+ public Link getLink(Long srcDpid, Long srcNumber, Long dstDpid,
+ Long dstNumber) {
+ Link link = getLink(srcDpid, srcNumber);
+ if (link == null)
+ return null;
+ if (!link.getDstSwitch().getDpid().equals(dstDpid))
+ return null;
+ if (!link.getDstPort().getNumber().equals(dstNumber))
+ return null;
+ return link;
+ }
- @Override
- public Iterable<Link> getLinks() {
- List<Link> linklist = new LinkedList<>();
+ @Override
+ public Iterable<Link> getLinks() {
+ List<Link> linklist = new LinkedList<>();
- for (Switch sw : switches.values()) {
- Iterable<Link> links = sw.getOutgoingLinks();
- for (Link l : links) {
- linklist.add(l);
- }
- }
- return linklist;
- }
+ for (Switch sw : switches.values()) {
+ Iterable<Link> links = sw.getOutgoingLinks();
+ for (Link l : links) {
+ linklist.add(l);
+ }
+ }
+ return linklist;
+ }
- @Override
- public Iterable<Device> getDevicesByIp(InetAddress ipAddress) {
- Set<Device> devices = addr2Device.get(ipAddress);
- if (devices == null) {
- return Collections.emptySet();
- }
- return Collections.unmodifiableCollection(devices);
- }
+ @Override
+ public Iterable<Device> getDevicesByIp(InetAddress ipAddress) {
+ Set<Device> devices = addr2Device.get(ipAddress);
+ if (devices == null) {
+ return Collections.emptySet();
+ }
+ return Collections.unmodifiableCollection(devices);
+ }
- @Override
- public Device getDeviceByMac(MACAddress address) {
- return mac2Device.get(address);
- }
+ @Override
+ public Device getDeviceByMac(MACAddress address) {
+ return mac2Device.get(address);
+ }
- protected void putDevice(Device device) {
- mac2Device.put(device.getMacAddress(), device);
- for (InetAddress ipAddr : device.getIpAddress()) {
- Set<Device> devices = addr2Device.get(ipAddr);
- if (devices == null) {
- devices = new HashSet<>();
- addr2Device.put(ipAddr, devices);
- }
- devices.add(device);
- }
- }
+ protected void putDevice(Device device) {
+ mac2Device.put(device.getMacAddress(), device);
+ for (InetAddress ipAddr : device.getIpAddress()) {
+ Set<Device> devices = addr2Device.get(ipAddr);
+ if (devices == null) {
+ devices = new HashSet<>();
+ addr2Device.put(ipAddr, devices);
+ }
+ devices.add(device);
+ }
+ }
- protected void removeDevice(Device device) {
- mac2Device.remove(device.getMacAddress());
- for (InetAddress ipAddr : device.getIpAddress()) {
- Set<Device> devices = addr2Device.get(ipAddr);
- if (devices != null) {
- devices.remove(device);
- if (devices.isEmpty())
- addr2Device.remove(ipAddr);
- }
- }
- }
+ protected void removeDevice(Device device) {
+ mac2Device.remove(device.getMacAddress());
+ for (InetAddress ipAddr : device.getIpAddress()) {
+ Set<Device> devices = addr2Device.get(ipAddr);
+ if (devices != null) {
+ devices.remove(device);
+ if (devices.isEmpty())
+ addr2Device.remove(ipAddr);
+ }
+ }
+ }
- @Override
- public void acquireReadLock() {
- readLock.lock();
- }
+ @Override
+ public void acquireReadLock() {
+ readLock.lock();
+ }
- @Override
- public void releaseReadLock() {
- readLock.unlock();
- }
+ @Override
+ public void releaseReadLock() {
+ readLock.unlock();
+ }
- protected void acquireWriteLock() {
- writeLock.lock();
- }
+ protected void acquireWriteLock() {
+ writeLock.lock();
+ }
- protected void releaseWriteLock() {
- writeLock.unlock();
- }
+ protected void releaseWriteLock() {
+ writeLock.unlock();
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/NetworkGraphModule.java b/src/main/java/net/onrc/onos/core/topology/NetworkGraphModule.java
index c693df5..77981d6 100644
--- a/src/main/java/net/onrc/onos/core/topology/NetworkGraphModule.java
+++ b/src/main/java/net/onrc/onos/core/topology/NetworkGraphModule.java
@@ -18,80 +18,80 @@
public class NetworkGraphModule implements IFloodlightModule, INetworkGraphService {
- // This is initialized as a module for now
+ // This is initialized as a module for now
- private TopologyManager topologyManager;
- //private NetworkGraphDatastore southboundNetworkGraph;
- private IDatagridService datagridService;
- private IControllerRegistryService registryService;
+ private TopologyManager topologyManager;
+ //private NetworkGraphDatastore southboundNetworkGraph;
+ private IDatagridService datagridService;
+ private IControllerRegistryService registryService;
- private CopyOnWriteArrayList<INetworkGraphListener> networkGraphListeners;
+ private CopyOnWriteArrayList<INetworkGraphListener> networkGraphListeners;
- private IRestApiService restApi;
+ private IRestApiService restApi;
- @Override
- public Collection<Class<? extends IFloodlightService>> getModuleServices() {
- List<Class<? extends IFloodlightService>> services =
- new ArrayList<Class<? extends IFloodlightService>>();
- services.add(INetworkGraphService.class);
- return services;
- }
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleServices() {
+ List<Class<? extends IFloodlightService>> services =
+ new ArrayList<Class<? extends IFloodlightService>>();
+ services.add(INetworkGraphService.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(INetworkGraphService.class, this);
- return impls;
- }
+ @Override
+ public Map<Class<? extends IFloodlightService>, IFloodlightService>
+ getServiceImpls() {
+ Map<Class<? extends IFloodlightService>, IFloodlightService> impls =
+ new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
+ impls.put(INetworkGraphService.class, this);
+ return impls;
+ }
- @Override
- public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
- List<Class<? extends IFloodlightService>> dependencies =
- new ArrayList<Class<? extends IFloodlightService>>();
- dependencies.add(IDatagridService.class);
- dependencies.add(IRestApiService.class);
- dependencies.add(IControllerRegistryService.class);
- return dependencies;
- }
+ @Override
+ public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
+ List<Class<? extends IFloodlightService>> dependencies =
+ new ArrayList<Class<? extends IFloodlightService>>();
+ dependencies.add(IDatagridService.class);
+ dependencies.add(IRestApiService.class);
+ dependencies.add(IControllerRegistryService.class);
+ return dependencies;
+ }
- @Override
- public void init(FloodlightModuleContext context)
- throws FloodlightModuleException {
- restApi = context.getServiceImpl(IRestApiService.class);
- datagridService = context.getServiceImpl(IDatagridService.class);
- registryService = context.getServiceImpl(IControllerRegistryService.class);
+ @Override
+ public void init(FloodlightModuleContext context)
+ throws FloodlightModuleException {
+ restApi = context.getServiceImpl(IRestApiService.class);
+ datagridService = context.getServiceImpl(IDatagridService.class);
+ registryService = context.getServiceImpl(IControllerRegistryService.class);
- networkGraphListeners = new CopyOnWriteArrayList<>();
- topologyManager = new TopologyManager(registryService, networkGraphListeners);
- //southboundNetworkGraph = new NetworkGraphDatastore(networkGraph);
- }
+ networkGraphListeners = new CopyOnWriteArrayList<>();
+ topologyManager = new TopologyManager(registryService, networkGraphListeners);
+ //southboundNetworkGraph = new NetworkGraphDatastore(networkGraph);
+ }
- @Override
- public void startUp(FloodlightModuleContext context) {
- restApi.addRestletRoutable(new NetworkGraphWebRoutable());
- topologyManager.startup(datagridService);
- }
+ @Override
+ public void startUp(FloodlightModuleContext context) {
+ restApi.addRestletRoutable(new NetworkGraphWebRoutable());
+ topologyManager.startup(datagridService);
+ }
- @Override
- public NetworkGraph getNetworkGraph() {
- return topologyManager.getNetworkGraph();
- }
+ @Override
+ public NetworkGraph getNetworkGraph() {
+ return topologyManager.getNetworkGraph();
+ }
- @Override
- public NetworkGraphDiscoveryInterface getNetworkGraphDiscoveryInterface() {
- return topologyManager;
- }
+ @Override
+ public NetworkGraphDiscoveryInterface getNetworkGraphDiscoveryInterface() {
+ return topologyManager;
+ }
- @Override
- public void registerNetworkGraphListener(INetworkGraphListener listener) {
- networkGraphListeners.addIfAbsent(listener);
- }
+ @Override
+ public void registerNetworkGraphListener(INetworkGraphListener listener) {
+ networkGraphListeners.addIfAbsent(listener);
+ }
- @Override
- public void deregisterNetworkGraphListener(INetworkGraphListener listener) {
- networkGraphListeners.remove(listener);
- }
+ @Override
+ public void deregisterNetworkGraphListener(INetworkGraphListener listener) {
+ networkGraphListeners.remove(listener);
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/NetworkGraphObject.java b/src/main/java/net/onrc/onos/core/topology/NetworkGraphObject.java
index fde4a44..bef0e11 100644
--- a/src/main/java/net/onrc/onos/core/topology/NetworkGraphObject.java
+++ b/src/main/java/net/onrc/onos/core/topology/NetworkGraphObject.java
@@ -3,10 +3,10 @@
public class NetworkGraphObject {
- protected final NetworkGraph graph;
-
- public NetworkGraphObject(NetworkGraph graph) {
- this.graph = graph;
- }
+ protected final NetworkGraph graph;
+
+ public NetworkGraphObject(NetworkGraph graph) {
+ this.graph = graph;
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/NetworkGraphPublisher.java b/src/main/java/net/onrc/onos/core/topology/NetworkGraphPublisher.java
index fef71e7..bc72e00 100644
--- a/src/main/java/net/onrc/onos/core/topology/NetworkGraphPublisher.java
+++ b/src/main/java/net/onrc/onos/core/topology/NetworkGraphPublisher.java
@@ -37,13 +37,12 @@
* The NetworkGraphPublisher subscribes to topology network events from the
* discovery modules. These events are reformatted and relayed to the topology
* part of the network graph
- *
*/
public class NetworkGraphPublisher implements /*IOFSwitchListener,*/
- IOFSwitchPortListener,
- ILinkDiscoveryListener,
- IFloodlightModule,
- IOnosDeviceListener {
+ IOFSwitchPortListener,
+ ILinkDiscoveryListener,
+ IFloodlightModule,
+ IOnosDeviceListener {
private static final Logger log =
LoggerFactory.getLogger(NetworkGraphPublisher.class);
@@ -96,7 +95,7 @@
log.trace("Checking for inactive switches");
}
// For each switch check if a controller exists in controller registry
- for (Switch sw: switches) {
+ for (Switch sw : switches) {
try {
String controller =
registryService.getControllerForSwitch(sw.getDpid());
@@ -115,7 +114,8 @@
* Second half of the switch cleanup operation. If the registry grants
* control of a switch, we can be sure no other instance is writing
* this switch to the network graph, so we can remove it now.
- * @param dpid the dpid of the switch we requested control for
+ *
+ * @param dpid the dpid of the switch we requested control for
* @param hasControl whether we got control or not
*/
@Override
@@ -139,17 +139,17 @@
(long) update.getDstPort());
switch (update.getOperation()) {
- case LINK_ADDED:
- networkGraphDiscoveryInterface.putLinkDiscoveryEvent(linkEvent);
- break;
- case LINK_UPDATED:
- // We don't use the LINK_UPDATED event (unsure what it means)
- break;
- case LINK_REMOVED:
- networkGraphDiscoveryInterface.removeLinkDiscoveryEvent(linkEvent);
- break;
- default:
- break;
+ case LINK_ADDED:
+ networkGraphDiscoveryInterface.putLinkDiscoveryEvent(linkEvent);
+ break;
+ case LINK_UPDATED:
+ // We don't use the LINK_UPDATED event (unsure what it means)
+ break;
+ case LINK_REMOVED:
+ networkGraphDiscoveryInterface.removeLinkDiscoveryEvent(linkEvent);
+ break;
+ default:
+ break;
}
}
@@ -180,7 +180,7 @@
portEvents.add(new PortEvent(sw.getId(), (long) port.getPortNumber()));
}
networkGraphDiscoveryInterface
- .putSwitchDiscoveryEvent(switchEvent, portEvents);
+ .putSwitchDiscoveryEvent(switchEvent, portEvents);
for (OFPhysicalPort port : sw.getPorts()) {
// Allow links to be discovered on this port now that it's
@@ -222,7 +222,7 @@
@Override
public Collection<Class<? extends IFloodlightService>>
- getModuleDependencies() {
+ getModuleDependencies() {
Collection<Class<? extends IFloodlightService>> l =
new ArrayList<Class<? extends IFloodlightService>>();
l.add(IFloodlightProviderService.class);
diff --git a/src/main/java/net/onrc/onos/core/topology/Path.java b/src/main/java/net/onrc/onos/core/topology/Path.java
index 1d15fc7..9c5118d 100644
--- a/src/main/java/net/onrc/onos/core/topology/Path.java
+++ b/src/main/java/net/onrc/onos/core/topology/Path.java
@@ -5,20 +5,21 @@
/**
* Base class for Path representation
+ *
* @author Toshio Koide (t-koide@onlab.us)
*/
public class Path extends LinkedList<LinkEvent> {
- private static final long serialVersionUID = 7127274096495173415L;
+ private static final long serialVersionUID = 7127274096495173415L;
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- Iterator<LinkEvent> i = this.iterator();
- while (i.hasNext()) {
- builder.append(i.next().toString());
- if (i.hasNext())
- builder.append(", ");
- }
- return builder.toString();
- }
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ Iterator<LinkEvent> i = this.iterator();
+ while (i.hasNext()) {
+ builder.append(i.next().toString());
+ if (i.hasNext())
+ builder.append(", ");
+ }
+ return builder.toString();
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/Port.java b/src/main/java/net/onrc/onos/core/topology/Port.java
index e9f6bb8..216d4b8 100644
--- a/src/main/java/net/onrc/onos/core/topology/Port.java
+++ b/src/main/java/net/onrc/onos/core/topology/Port.java
@@ -1,24 +1,26 @@
package net.onrc.onos.core.topology;
-
/**
* Interface of Port Object exposed to the "NB" read-only Topology.
- *
+ * <p/>
* Everything returned by these interfaces must be either Unmodifiable view,
* immutable object, or a copy of the original "SB" In-memory Topology.
- *
*/
public interface Port {
- public Long getDpid();
- public Long getNumber();
- public Long getHardwareAddress();
- public String getDescription();
+ public Long getDpid();
- public Switch getSwitch();
+ public Long getNumber();
- public Link getOutgoingLink();
- public Link getIncomingLink();
+ public Long getHardwareAddress();
- public Iterable<Device> getDevices();
+ public String getDescription();
+
+ public Switch getSwitch();
+
+ public Link getOutgoingLink();
+
+ public Link getIncomingLink();
+
+ public Iterable<Device> getDevices();
}
diff --git a/src/main/java/net/onrc/onos/core/topology/PortEvent.java b/src/main/java/net/onrc/onos/core/topology/PortEvent.java
index 65d0b94..2a18c08 100644
--- a/src/main/java/net/onrc/onos/core/topology/PortEvent.java
+++ b/src/main/java/net/onrc/onos/core/topology/PortEvent.java
@@ -4,23 +4,22 @@
/**
* Self-contained Port event Object
- *
+ * <p/>
* TODO: We probably want common base class/interface for Self-Contained Event Object
- *
*/
public class PortEvent {
public static class SwitchPort {
- public final Long dpid;
- public final Long number;
+ public final Long dpid;
+ public final Long number;
- /**
- * Default constructor for Serializer to use.
- */
- @Deprecated
- public SwitchPort() {
- dpid = null;
- number = null;
- }
+ /**
+ * Default constructor for Serializer to use.
+ */
+ @Deprecated
+ public SwitchPort() {
+ dpid = null;
+ number = null;
+ }
public SwitchPort(Long dpid, Long number) {
this.dpid = dpid;
@@ -46,29 +45,29 @@
int result = 1;
result = prime * result + ((dpid == null) ? 0 : dpid.hashCode());
result = prime * result
- + ((number == null) ? 0 : number.hashCode());
+ + ((number == null) ? 0 : number.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
- return true;
+ return true;
if (obj == null)
- return false;
+ return false;
if (getClass() != obj.getClass())
- return false;
+ return false;
SwitchPort other = (SwitchPort) obj;
if (dpid == null) {
- if (other.dpid != null)
- return false;
+ if (other.dpid != null)
+ return false;
} else if (!dpid.equals(other.dpid))
- return false;
+ return false;
if (number == null) {
- if (other.number != null)
- return false;
+ if (other.number != null)
+ return false;
} else if (!number.equals(other.number))
- return false;
+ return false;
return true;
}
}
@@ -82,44 +81,44 @@
*/
@Deprecated
public PortEvent() {
- id = null;
+ id = null;
}
public PortEvent(Long dpid, Long number) {
- this.id = new SwitchPort(dpid, number);
+ this.id = new SwitchPort(dpid, number);
}
public Long getDpid() {
- return id.dpid;
+ return id.dpid;
}
public Long getNumber() {
- return id.number;
+ return id.number;
}
@Override
public String toString() {
- return "[PortEvent 0x" + Long.toHexString(id.dpid) + "@" + id.number + "]";
+ return "[PortEvent 0x" + Long.toHexString(id.dpid) + "@" + id.number + "]";
}
public static final int PORTID_BYTES = SwitchEvent.SWITCHID_BYTES + 2 + 8;
public static ByteBuffer getPortID(Long dpid, Long number) {
- if (dpid == null) {
- throw new IllegalArgumentException("dpid cannot be null");
- }
- if (number == null) {
- throw new IllegalArgumentException("number cannot be null");
- }
- return (ByteBuffer) ByteBuffer.allocate(PortEvent.PORTID_BYTES).putChar('S').putLong(dpid)
- .putChar('P').putLong(number).flip();
+ if (dpid == null) {
+ throw new IllegalArgumentException("dpid cannot be null");
+ }
+ if (number == null) {
+ throw new IllegalArgumentException("number cannot be null");
+ }
+ return (ByteBuffer) ByteBuffer.allocate(PortEvent.PORTID_BYTES).putChar('S').putLong(dpid)
+ .putChar('P').putLong(number).flip();
}
public byte[] getID() {
- return getPortID(getDpid(), getNumber()).array();
+ return getPortID(getDpid(), getNumber()).array();
}
public ByteBuffer getIDasByteBuffer() {
- return getPortID(getDpid(), getNumber());
+ return getPortID(getDpid(), getNumber());
}
}
diff --git a/src/main/java/net/onrc/onos/core/topology/PortImpl.java b/src/main/java/net/onrc/onos/core/topology/PortImpl.java
index cd7d82b..32646d0 100644
--- a/src/main/java/net/onrc/onos/core/topology/PortImpl.java
+++ b/src/main/java/net/onrc/onos/core/topology/PortImpl.java
@@ -6,108 +6,106 @@
/**
* Port Object stored in In-memory Topology.
- *
+ * <p/>
* TODO REMOVE following design memo: This object itself may hold the DBObject,
* but this Object itself will not issue any read/write to the DataStore.
*/
public class PortImpl extends NetworkGraphObject implements Port {
- private Switch sw;
+ private Switch sw;
- private Long number;
- private String description;
+ private Long number;
+ private String description;
- protected Link outgoingLink;
- protected Link incomingLink;
- // These needs to be ConcurrentCollecton if allowing Graph to be accessed Concurrently
- protected Set<Device> devices;
+ protected Link outgoingLink;
+ protected Link incomingLink;
+ // These needs to be ConcurrentCollecton if allowing Graph to be accessed Concurrently
+ protected Set<Device> devices;
- public PortImpl(NetworkGraph graph, Switch parentSwitch, Long number) {
- super(graph);
- this.sw = parentSwitch;
- this.number = number;
- this.devices = new HashSet<>();
- }
+ public PortImpl(NetworkGraph graph, Switch parentSwitch, Long number) {
+ super(graph);
+ this.sw = parentSwitch;
+ this.number = number;
+ this.devices = new HashSet<>();
+ }
- @Override
- public Long getDpid() {
- return sw.getDpid();
- }
+ @Override
+ public Long getDpid() {
+ return sw.getDpid();
+ }
- @Override
- public Long getNumber() {
- return number;
- }
+ @Override
+ public Long getNumber() {
+ return number;
+ }
- @Override
- public String getDescription() {
- return description;
- }
+ @Override
+ public String getDescription() {
+ return description;
+ }
- public void setDescription(String description) {
- this.description = description;
- }
+ public void setDescription(String description) {
+ this.description = description;
+ }
- @Override
- public Long getHardwareAddress() {
- // TODO Auto-generated method stub
- return 0L;
- }
+ @Override
+ public Long getHardwareAddress() {
+ // TODO Auto-generated method stub
+ return 0L;
+ }
- @Override
- public Switch getSwitch() {
- return sw;
- }
+ @Override
+ public Switch getSwitch() {
+ return sw;
+ }
- @Override
- public Link getOutgoingLink() {
- return outgoingLink;
- }
+ @Override
+ public Link getOutgoingLink() {
+ return outgoingLink;
+ }
- @Override
- public Link getIncomingLink() {
- return incomingLink;
- }
+ @Override
+ public Link getIncomingLink() {
+ return incomingLink;
+ }
- @Override
- public Iterable<Device> getDevices() {
- return Collections.unmodifiableSet(this.devices);
- }
+ @Override
+ public Iterable<Device> getDevices() {
+ return Collections.unmodifiableSet(this.devices);
+ }
- public void setOutgoingLink(Link link) {
- outgoingLink = link;
- }
+ public void setOutgoingLink(Link link) {
+ outgoingLink = link;
+ }
- public void setIncomingLink(Link link) {
- incomingLink = link;
- }
+ public void setIncomingLink(Link link) {
+ incomingLink = link;
+ }
- /**
- *
- * @param d
- * @return true if successfully added
- */
- public boolean addDevice(Device d) {
- return this.devices.add(d);
- }
+ /**
+ * @param d
+ * @return true if successfully added
+ */
+ public boolean addDevice(Device d) {
+ return this.devices.add(d);
+ }
- /**
- *
- * @param d
- * @return true if device existed and was removed
- */
- public boolean removeDevice(Device d) {
- return this.devices.remove(d);
- }
+ /**
+ * @param d
+ * @return true if device existed and was removed
+ */
+ public boolean removeDevice(Device d) {
+ return this.devices.remove(d);
+ }
- public void removeAllDevice() {
- this.devices.clear();
- }
+ public void removeAllDevice() {
+ this.devices.clear();
+ }
- @Override
- public String toString() {
- return String.format("%d:%d",
- getSwitch().getDpid(),
- getNumber());
- }
+ @Override
+ public String toString() {
+ return String.format("%d:%d",
+ getSwitch().getDpid(),
+ getNumber());
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/Switch.java b/src/main/java/net/onrc/onos/core/topology/Switch.java
index 0b97dfa..d9796be 100644
--- a/src/main/java/net/onrc/onos/core/topology/Switch.java
+++ b/src/main/java/net/onrc/onos/core/topology/Switch.java
@@ -4,28 +4,28 @@
/**
* Interface of Switch Object exposed to the "NB" read-only Topology.
- *
+ * <p/>
* Everything returned by these interfaces must be either Unmodifiable view,
* immutable object, or a copy of the original "SB" In-memory Topology.
- *
*/
public interface Switch {
- public Long getDpid();
+ public Long getDpid();
- public Collection<Port> getPorts();
+ public Collection<Port> getPorts();
- public Port getPort(Long number);
+ public Port getPort(Long number);
- // Graph traversal API
- // XXX What is the Definition of neighbor? Link exist in both direction or one-way is sufficient to be a neighbor, etc.
- public Iterable<Switch> getNeighbors();
+ // Graph traversal API
+ // XXX What is the Definition of neighbor? Link exist in both direction or one-way is sufficient to be a neighbor, etc.
+ public Iterable<Switch> getNeighbors();
- public Iterable<Link> getOutgoingLinks();
- public Iterable<Link> getIncomingLinks();
+ public Iterable<Link> getOutgoingLinks();
- public Link getLinkToNeighbor(Long dpid);
+ public Iterable<Link> getIncomingLinks();
- // XXX Iterable or Collection?
- public Collection<Device> getDevices();
+ public Link getLinkToNeighbor(Long dpid);
+
+ // XXX Iterable or Collection?
+ public Collection<Device> getDevices();
}
diff --git a/src/main/java/net/onrc/onos/core/topology/SwitchEvent.java b/src/main/java/net/onrc/onos/core/topology/SwitchEvent.java
index b36eba2..7ed65d8 100644
--- a/src/main/java/net/onrc/onos/core/topology/SwitchEvent.java
+++ b/src/main/java/net/onrc/onos/core/topology/SwitchEvent.java
@@ -4,9 +4,8 @@
/**
* Self-contained Switch Object
- *
+ * <p/>
* TODO: We probably want common base class/interface for Self-Contained Event Object
- *
*/
public class SwitchEvent {
protected final Long dpid;
@@ -16,36 +15,36 @@
*/
@Deprecated
public SwitchEvent() {
- dpid = null;
+ dpid = null;
}
public SwitchEvent(Long dpid) {
- this.dpid = dpid;
+ this.dpid = dpid;
}
public Long getDpid() {
- return dpid;
+ return dpid;
}
@Override
public String toString() {
- return "[SwitchEvent 0x" + Long.toHexString(dpid) + "]";
+ return "[SwitchEvent 0x" + Long.toHexString(dpid) + "]";
}
public static final int SWITCHID_BYTES = 2 + 8;
public static ByteBuffer getSwitchID(Long dpid) {
- if (dpid == null) {
- throw new IllegalArgumentException("dpid cannot be null");
- }
- return (ByteBuffer) ByteBuffer.allocate(SwitchEvent.SWITCHID_BYTES).putChar('S').putLong(dpid).flip();
+ if (dpid == null) {
+ throw new IllegalArgumentException("dpid cannot be null");
+ }
+ return (ByteBuffer) ByteBuffer.allocate(SwitchEvent.SWITCHID_BYTES).putChar('S').putLong(dpid).flip();
}
public byte[] getID() {
- return getSwitchID(dpid).array();
+ return getSwitchID(dpid).array();
}
public ByteBuffer getIDasByteBuffer() {
- return getSwitchID(dpid);
+ return getSwitchID(dpid);
}
}
diff --git a/src/main/java/net/onrc/onos/core/topology/SwitchImpl.java b/src/main/java/net/onrc/onos/core/topology/SwitchImpl.java
index 8a45b76..3fe053c 100644
--- a/src/main/java/net/onrc/onos/core/topology/SwitchImpl.java
+++ b/src/main/java/net/onrc/onos/core/topology/SwitchImpl.java
@@ -12,111 +12,111 @@
/**
* Switch Object stored in In-memory Topology.
- *
+ * <p/>
* TODO REMOVE following design memo: This object itself may hold the DBObject,
* but this Object itself will not issue any read/write to the DataStore.
*/
public class SwitchImpl extends NetworkGraphObject implements Switch {
- private Long dpid;
- // These needs to be ConcurrentCollecton if allowing Graph to be accessed Concurrently
- private final Map<Long, Port> ports;
+ private Long dpid;
+ // These needs to be ConcurrentCollecton if allowing Graph to be accessed Concurrently
+ private final Map<Long, Port> ports;
- public SwitchImpl(NetworkGraph graph, Long dpid) {
- super(graph);
- this.dpid = dpid;
- ports = new HashMap<Long, Port>();
- }
+ public SwitchImpl(NetworkGraph graph, Long dpid) {
+ super(graph);
+ this.dpid = dpid;
+ ports = new HashMap<Long, Port>();
+ }
- @Override
- public Long getDpid() {
- return dpid;
- }
+ @Override
+ public Long getDpid() {
+ return dpid;
+ }
- @Override
- public Collection<Port> getPorts() {
- return Collections.unmodifiableCollection(ports.values());
- }
+ @Override
+ public Collection<Port> getPorts() {
+ return Collections.unmodifiableCollection(ports.values());
+ }
- @Override
- public Port getPort(Long number) {
- return ports.get(number);
- }
+ @Override
+ public Port getPort(Long number) {
+ return ports.get(number);
+ }
- @Override
- public Iterable<Switch> getNeighbors() {
- Set<Switch> neighbors = new HashSet<>();
- for (Link link : getOutgoingLinks()) {
- neighbors.add(link.getDstSwitch());
- }
- // XXX should incoming considered neighbor?
- for (Link link : getIncomingLinks()) {
- neighbors.add(link.getSrcSwitch());
- }
- return neighbors;
- }
+ @Override
+ public Iterable<Switch> getNeighbors() {
+ Set<Switch> neighbors = new HashSet<>();
+ for (Link link : getOutgoingLinks()) {
+ neighbors.add(link.getDstSwitch());
+ }
+ // XXX should incoming considered neighbor?
+ for (Link link : getIncomingLinks()) {
+ neighbors.add(link.getSrcSwitch());
+ }
+ return neighbors;
+ }
- @Override
- public Link getLinkToNeighbor(Long neighborDpid) {
- for (Link link : getOutgoingLinks()) {
- if (link.getDstSwitch().getDpid().equals(neighborDpid) ) {
- return link;
- }
- }
- return null;
- }
+ @Override
+ public Link getLinkToNeighbor(Long neighborDpid) {
+ for (Link link : getOutgoingLinks()) {
+ if (link.getDstSwitch().getDpid().equals(neighborDpid)) {
+ return link;
+ }
+ }
+ return null;
+ }
- @Override
- public Collection<Device> getDevices() {
- // TODO Should switch also store a list of attached devices to avoid
- // calculating this every time?
- List<Device> devices = new ArrayList<Device>();
+ @Override
+ public Collection<Device> getDevices() {
+ // TODO Should switch also store a list of attached devices to avoid
+ // calculating this every time?
+ List<Device> devices = new ArrayList<Device>();
- for (Port port : ports.values()) {
- for (Device device : port.getDevices()) {
- devices.add(device);
- }
- }
+ for (Port port : ports.values()) {
+ for (Device device : port.getDevices()) {
+ devices.add(device);
+ }
+ }
- return devices;
- }
+ return devices;
+ }
- public void addPort(Port port) {
- this.ports.put(port.getNumber(), port);
- }
+ public void addPort(Port port) {
+ this.ports.put(port.getNumber(), port);
+ }
- public Port removePort(Port port) {
- Port p = this.ports.remove(port.getNumber());
- return p;
- }
+ public Port removePort(Port port) {
+ Port p = this.ports.remove(port.getNumber());
+ return p;
+ }
- public Port addPort(Long portNumber) {
- PortImpl port = new PortImpl(graph, this, portNumber);
- ports.put(port.getNumber(), port);
- return port;
- }
+ public Port addPort(Long portNumber) {
+ PortImpl port = new PortImpl(graph, this, portNumber);
+ ports.put(port.getNumber(), port);
+ return port;
+ }
- @Override
- public Iterable<Link> getOutgoingLinks() {
- LinkedList<Link> links = new LinkedList<Link>();
- for (Port port: getPorts()) {
- Link link = port.getOutgoingLink();
- if (link != null) {
- links.add(link);
- }
- }
- return links;
- }
+ @Override
+ public Iterable<Link> getOutgoingLinks() {
+ LinkedList<Link> links = new LinkedList<Link>();
+ for (Port port : getPorts()) {
+ Link link = port.getOutgoingLink();
+ if (link != null) {
+ links.add(link);
+ }
+ }
+ return links;
+ }
- @Override
- public Iterable<Link> getIncomingLinks() {
- LinkedList<Link> links = new LinkedList<Link>();
- for (Port port: getPorts()) {
- Link link = port.getIncomingLink();
- if (link != null) {
- links.add(link);
- }
- }
- return links;
- }
+ @Override
+ public Iterable<Link> getIncomingLinks() {
+ LinkedList<Link> links = new LinkedList<Link>();
+ for (Port port : getPorts()) {
+ Link link = port.getIncomingLink();
+ if (link != null) {
+ links.add(link);
+ }
+ }
+ return links;
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/TopologyEvent.java b/src/main/java/net/onrc/onos/core/topology/TopologyEvent.java
index 84cd5cb..4f3dd20 100644
--- a/src/main/java/net/onrc/onos/core/topology/TopologyEvent.java
+++ b/src/main/java/net/onrc/onos/core/topology/TopologyEvent.java
@@ -2,16 +2,16 @@
/**
* Self-contained Topology event Object
- *
+ * <p/>
* TODO: For now the topology event contains one of the following events:
* Switch, Port, Link, Device. In the future it will contain multiple events
* in a single transaction.
*/
public class TopologyEvent {
- SwitchEvent switchEvent = null; // Set for Switch event
- PortEvent portEvent = null; // Set for Port event
- LinkEvent linkEvent = null; // Set for Link event
- DeviceEvent deviceEvent = null; // Set for Device event
+ SwitchEvent switchEvent = null; // Set for Switch event
+ PortEvent portEvent = null; // Set for Port event
+ LinkEvent linkEvent = null; // Set for Link event
+ DeviceEvent deviceEvent = null; // Set for Device event
/**
* Default constructor.
@@ -25,7 +25,7 @@
* @param switchEvent the Switch event to use.
*/
TopologyEvent(SwitchEvent switchEvent) {
- this.switchEvent = switchEvent;
+ this.switchEvent = switchEvent;
}
/**
@@ -34,7 +34,7 @@
* @param portEvent the Port event to use.
*/
TopologyEvent(PortEvent portEvent) {
- this.portEvent = portEvent;
+ this.portEvent = portEvent;
}
/**
@@ -43,7 +43,7 @@
* @param linkEvent the Link event to use.
*/
TopologyEvent(LinkEvent linkEvent) {
- this.linkEvent = linkEvent;
+ this.linkEvent = linkEvent;
}
/**
@@ -52,7 +52,7 @@
* @param deviceEvent the Device event to use.
*/
TopologyEvent(DeviceEvent deviceEvent) {
- this.deviceEvent = deviceEvent;
+ this.deviceEvent = deviceEvent;
}
/**
@@ -62,15 +62,15 @@
*/
@Override
public String toString() {
- if (switchEvent != null)
- return switchEvent.toString();
- if (portEvent != null)
- return portEvent.toString();
- if (linkEvent != null)
- return linkEvent.toString();
- if (deviceEvent != null)
- return deviceEvent.toString();
- return "[Empty TopologyEvent]";
+ if (switchEvent != null)
+ return switchEvent.toString();
+ if (portEvent != null)
+ return portEvent.toString();
+ if (linkEvent != null)
+ return linkEvent.toString();
+ if (deviceEvent != null)
+ return deviceEvent.toString();
+ return "[Empty TopologyEvent]";
}
/**
@@ -79,14 +79,14 @@
* @return the Topology event ID.
*/
public byte[] getID() {
- if (switchEvent != null)
- return switchEvent.getID();
- if (portEvent != null)
- return portEvent.getID();
- if (linkEvent != null)
- return linkEvent.getID();
- if (deviceEvent != null)
- return deviceEvent.getID();
- return null;
+ if (switchEvent != null)
+ return switchEvent.getID();
+ if (portEvent != null)
+ return portEvent.getID();
+ if (linkEvent != null)
+ return linkEvent.getID();
+ if (deviceEvent != null)
+ return deviceEvent.getID();
+ return null;
}
}
diff --git a/src/main/java/net/onrc/onos/core/topology/TopologyManager.java b/src/main/java/net/onrc/onos/core/topology/TopologyManager.java
index b12eaae..4788641 100644
--- a/src/main/java/net/onrc/onos/core/topology/TopologyManager.java
+++ b/src/main/java/net/onrc/onos/core/topology/TopologyManager.java
@@ -29,22 +29,21 @@
/**
* The "NB" read-only Network Map.
- *
+ * <p/>
* - Maintain Invariant/Relationships between Topology Objects.
- *
+ * <p/>
* TODO To be synchronized based on TopologyEvent Notification.
- *
+ * <p/>
* TODO TBD: Caller is expected to maintain parent/child calling order. Parent
* Object must exist before adding sub component(Add Switch -> Port).
- *
+ * <p/>
* TODO TBD: This class may delay the requested change to handle event
* re-ordering. e.g.) Link Add came in, but Switch was not there.
- *
*/
public class TopologyManager implements NetworkGraphDiscoveryInterface {
private static final Logger log = LoggerFactory
- .getLogger(TopologyManager.class);
+ .getLogger(TopologyManager.class);
private IEventChannel<byte[], TopologyEvent> eventChannel;
public static final String EVENT_CHANNEL_NAME = "onos.topology";
@@ -60,11 +59,11 @@
// NOTE: Switch Events are not affected by the event reordering.
//
private Map<ByteBuffer, PortEvent> reorderedAddedPortEvents =
- new HashMap<ByteBuffer, PortEvent>();
+ new HashMap<ByteBuffer, PortEvent>();
private Map<ByteBuffer, LinkEvent> reorderedAddedLinkEvents =
- new HashMap<ByteBuffer, LinkEvent>();
+ new HashMap<ByteBuffer, LinkEvent>();
private Map<ByteBuffer, DeviceEvent> reorderedAddedDeviceEvents =
- new HashMap<ByteBuffer, DeviceEvent>();
+ new HashMap<ByteBuffer, DeviceEvent>();
//
// Local state for keeping track of locally discovered events so we can
@@ -77,11 +76,11 @@
// and Device events.
//
private Map<Long, Map<ByteBuffer, PortEvent>> discoveredAddedPortEvents =
- new HashMap<>();
+ new HashMap<>();
private Map<Long, Map<ByteBuffer, LinkEvent>> discoveredAddedLinkEvents =
- new HashMap<>();
+ new HashMap<>();
private Map<Long, Map<ByteBuffer, DeviceEvent>> discoveredAddedDeviceEvents =
- new HashMap<>();
+ new HashMap<>();
//
// Local state for keeping track of the application event notifications
@@ -98,15 +97,15 @@
/**
* Constructor.
*
- * @param registryService the Registry Service to use.
+ * @param registryService the Registry Service to use.
* @param networkGraphListeners the collection of Network Graph Listeners
- * to use.
+ * to use.
*/
public TopologyManager(IControllerRegistryService registryService,
- CopyOnWriteArrayList<INetworkGraphListener> networkGraphListeners) {
- datastore = new NetworkGraphDatastore();
- this.registryService = registryService;
- this.networkGraphListeners = networkGraphListeners;
+ CopyOnWriteArrayList<INetworkGraphListener> networkGraphListeners) {
+ datastore = new NetworkGraphDatastore();
+ this.registryService = registryService;
+ this.networkGraphListeners = networkGraphListeners;
}
/**
@@ -115,247 +114,246 @@
* @return the Network Graph.
*/
NetworkGraph getNetworkGraph() {
- return networkGraph;
+ return networkGraph;
}
/**
* Event handler class.
*/
private class EventHandler extends Thread implements
- IEventChannelListener<byte[], TopologyEvent> {
- private BlockingQueue<EventEntry<TopologyEvent>> topologyEvents =
- new LinkedBlockingQueue<EventEntry<TopologyEvent>>();
+ IEventChannelListener<byte[], TopologyEvent> {
+ private BlockingQueue<EventEntry<TopologyEvent>> topologyEvents =
+ new LinkedBlockingQueue<EventEntry<TopologyEvent>>();
- /**
- * Startup processing.
- */
- private void startup() {
- //
- // TODO: Read all state from the database:
- //
- // Collection<EventEntry<TopologyEvent>> collection =
- // readWholeTopologyFromDB();
- //
- // For now, as a shortcut we read it from the datagrid
- //
- Collection<TopologyEvent> topologyEvents =
- eventChannel.getAllEntries();
- Collection<EventEntry<TopologyEvent>> collection =
- new LinkedList<EventEntry<TopologyEvent>>();
+ /**
+ * Startup processing.
+ */
+ private void startup() {
+ //
+ // TODO: Read all state from the database:
+ //
+ // Collection<EventEntry<TopologyEvent>> collection =
+ // readWholeTopologyFromDB();
+ //
+ // For now, as a shortcut we read it from the datagrid
+ //
+ Collection<TopologyEvent> topologyEvents =
+ eventChannel.getAllEntries();
+ Collection<EventEntry<TopologyEvent>> collection =
+ new LinkedList<EventEntry<TopologyEvent>>();
- for (TopologyEvent topologyEvent : topologyEvents) {
- EventEntry<TopologyEvent> eventEntry =
- new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
- topologyEvent);
- collection.add(eventEntry);
- }
- processEvents(collection);
- }
+ for (TopologyEvent topologyEvent : topologyEvents) {
+ EventEntry<TopologyEvent> eventEntry =
+ new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
+ topologyEvent);
+ collection.add(eventEntry);
+ }
+ processEvents(collection);
+ }
- /**
- * Run the thread.
- */
- @Override
- public void run() {
- Collection<EventEntry<TopologyEvent>> collection =
- new LinkedList<EventEntry<TopologyEvent>>();
+ /**
+ * Run the thread.
+ */
+ @Override
+ public void run() {
+ Collection<EventEntry<TopologyEvent>> collection =
+ new LinkedList<EventEntry<TopologyEvent>>();
- this.setName("TopologyManager.EventHandler " + this.getId());
- startup();
+ this.setName("TopologyManager.EventHandler " + this.getId());
+ startup();
- //
- // The main loop
- //
- try {
- while (true) {
- EventEntry<TopologyEvent> eventEntry = topologyEvents.take();
- collection.add(eventEntry);
- topologyEvents.drainTo(collection);
+ //
+ // The main loop
+ //
+ try {
+ while (true) {
+ EventEntry<TopologyEvent> eventEntry = topologyEvents.take();
+ collection.add(eventEntry);
+ topologyEvents.drainTo(collection);
- processEvents(collection);
- collection.clear();
- }
- } catch (Exception exception) {
- log.debug("Exception processing Topology Events: ", exception);
- }
- }
+ processEvents(collection);
+ collection.clear();
+ }
+ } catch (Exception exception) {
+ log.debug("Exception processing Topology Events: ", exception);
+ }
+ }
- /**
- * Process all topology events.
- *
- * @param events the events to process.
- */
- private void processEvents(Collection<EventEntry<TopologyEvent>> events) {
- // Local state for computing the final set of events
- Map<ByteBuffer, SwitchEvent> addedSwitchEvents = new HashMap<>();
- Map<ByteBuffer, SwitchEvent> removedSwitchEvents = new HashMap<>();
- Map<ByteBuffer, PortEvent> addedPortEvents = new HashMap<>();
- Map<ByteBuffer, PortEvent> removedPortEvents = new HashMap<>();
- Map<ByteBuffer, LinkEvent> addedLinkEvents = new HashMap<>();
- Map<ByteBuffer, LinkEvent> removedLinkEvents = new HashMap<>();
- Map<ByteBuffer, DeviceEvent> addedDeviceEvents = new HashMap<>();
- Map<ByteBuffer, DeviceEvent> removedDeviceEvents = new HashMap<>();
+ /**
+ * Process all topology events.
+ *
+ * @param events the events to process.
+ */
+ private void processEvents(Collection<EventEntry<TopologyEvent>> events) {
+ // Local state for computing the final set of events
+ Map<ByteBuffer, SwitchEvent> addedSwitchEvents = new HashMap<>();
+ Map<ByteBuffer, SwitchEvent> removedSwitchEvents = new HashMap<>();
+ Map<ByteBuffer, PortEvent> addedPortEvents = new HashMap<>();
+ Map<ByteBuffer, PortEvent> removedPortEvents = new HashMap<>();
+ Map<ByteBuffer, LinkEvent> addedLinkEvents = new HashMap<>();
+ Map<ByteBuffer, LinkEvent> removedLinkEvents = new HashMap<>();
+ Map<ByteBuffer, DeviceEvent> addedDeviceEvents = new HashMap<>();
+ Map<ByteBuffer, DeviceEvent> removedDeviceEvents = new HashMap<>();
- //
- // Classify and suppress matching events
- //
- for (EventEntry<TopologyEvent> event : events) {
- TopologyEvent topologyEvent = event.eventData();
- SwitchEvent switchEvent = topologyEvent.switchEvent;
- PortEvent portEvent = topologyEvent.portEvent;
- LinkEvent linkEvent = topologyEvent.linkEvent;
- DeviceEvent deviceEvent = topologyEvent.deviceEvent;
+ //
+ // Classify and suppress matching events
+ //
+ for (EventEntry<TopologyEvent> event : events) {
+ TopologyEvent topologyEvent = event.eventData();
+ SwitchEvent switchEvent = topologyEvent.switchEvent;
+ PortEvent portEvent = topologyEvent.portEvent;
+ LinkEvent linkEvent = topologyEvent.linkEvent;
+ DeviceEvent deviceEvent = topologyEvent.deviceEvent;
- //
- // Extract the events
- //
- switch (event.eventType()) {
- case ENTRY_ADD:
- log.debug("Topology event ENTRY_ADD: {}", topologyEvent);
- if (switchEvent != null) {
- ByteBuffer id = switchEvent.getIDasByteBuffer();
- addedSwitchEvents.put(id, switchEvent);
- removedSwitchEvents.remove(id);
- // Switch Events are not affected by event reordering
- }
- if (portEvent != null) {
- ByteBuffer id = portEvent.getIDasByteBuffer();
- addedPortEvents.put(id, portEvent);
- removedPortEvents.remove(id);
- reorderedAddedPortEvents.remove(id);
- }
- if (linkEvent != null) {
- ByteBuffer id = linkEvent.getIDasByteBuffer();
- addedLinkEvents.put(id, linkEvent);
- removedLinkEvents.remove(id);
- reorderedAddedLinkEvents.remove(id);
- }
- if (deviceEvent != null) {
- ByteBuffer id = deviceEvent.getIDasByteBuffer();
- addedDeviceEvents.put(id, deviceEvent);
- removedDeviceEvents.remove(id);
- reorderedAddedDeviceEvents.remove(id);
- }
- break;
- case ENTRY_REMOVE:
- log.debug("Topology event ENTRY_REMOVE: {}", topologyEvent);
- if (switchEvent != null) {
- ByteBuffer id = switchEvent.getIDasByteBuffer();
- addedSwitchEvents.remove(id);
- removedSwitchEvents.put(id, switchEvent);
- // Switch Events are not affected by event reordering
- }
- if (portEvent != null) {
- ByteBuffer id = portEvent.getIDasByteBuffer();
- addedPortEvents.remove(id);
- removedPortEvents.put(id, portEvent);
- reorderedAddedPortEvents.remove(id);
- }
- if (linkEvent != null) {
- ByteBuffer id = linkEvent.getIDasByteBuffer();
- addedLinkEvents.remove(id);
- removedLinkEvents.put(id, linkEvent);
- reorderedAddedLinkEvents.remove(id);
- }
- if (deviceEvent != null) {
- ByteBuffer id = deviceEvent.getIDasByteBuffer();
- addedDeviceEvents.remove(id);
- removedDeviceEvents.put(id, deviceEvent);
- reorderedAddedDeviceEvents.remove(id);
- }
- break;
- }
- }
+ //
+ // Extract the events
+ //
+ switch (event.eventType()) {
+ case ENTRY_ADD:
+ log.debug("Topology event ENTRY_ADD: {}", topologyEvent);
+ if (switchEvent != null) {
+ ByteBuffer id = switchEvent.getIDasByteBuffer();
+ addedSwitchEvents.put(id, switchEvent);
+ removedSwitchEvents.remove(id);
+ // Switch Events are not affected by event reordering
+ }
+ if (portEvent != null) {
+ ByteBuffer id = portEvent.getIDasByteBuffer();
+ addedPortEvents.put(id, portEvent);
+ removedPortEvents.remove(id);
+ reorderedAddedPortEvents.remove(id);
+ }
+ if (linkEvent != null) {
+ ByteBuffer id = linkEvent.getIDasByteBuffer();
+ addedLinkEvents.put(id, linkEvent);
+ removedLinkEvents.remove(id);
+ reorderedAddedLinkEvents.remove(id);
+ }
+ if (deviceEvent != null) {
+ ByteBuffer id = deviceEvent.getIDasByteBuffer();
+ addedDeviceEvents.put(id, deviceEvent);
+ removedDeviceEvents.remove(id);
+ reorderedAddedDeviceEvents.remove(id);
+ }
+ break;
+ case ENTRY_REMOVE:
+ log.debug("Topology event ENTRY_REMOVE: {}", topologyEvent);
+ if (switchEvent != null) {
+ ByteBuffer id = switchEvent.getIDasByteBuffer();
+ addedSwitchEvents.remove(id);
+ removedSwitchEvents.put(id, switchEvent);
+ // Switch Events are not affected by event reordering
+ }
+ if (portEvent != null) {
+ ByteBuffer id = portEvent.getIDasByteBuffer();
+ addedPortEvents.remove(id);
+ removedPortEvents.put(id, portEvent);
+ reorderedAddedPortEvents.remove(id);
+ }
+ if (linkEvent != null) {
+ ByteBuffer id = linkEvent.getIDasByteBuffer();
+ addedLinkEvents.remove(id);
+ removedLinkEvents.put(id, linkEvent);
+ reorderedAddedLinkEvents.remove(id);
+ }
+ if (deviceEvent != null) {
+ ByteBuffer id = deviceEvent.getIDasByteBuffer();
+ addedDeviceEvents.remove(id);
+ removedDeviceEvents.put(id, deviceEvent);
+ reorderedAddedDeviceEvents.remove(id);
+ }
+ break;
+ }
+ }
- //
- // Lock the Network Graph while it is modified
- //
- networkGraph.acquireWriteLock();
+ //
+ // Lock the Network Graph while it is modified
+ //
+ networkGraph.acquireWriteLock();
- try {
- //
- // Apply the classified events.
- //
- // Apply the "add" events in the proper order:
- // switch, port, link, device
- //
- for (SwitchEvent switchEvent : addedSwitchEvents.values())
- addSwitch(switchEvent);
- for (PortEvent portEvent : addedPortEvents.values())
- addPort(portEvent);
- for (LinkEvent linkEvent : addedLinkEvents.values())
- addLink(linkEvent);
- for (DeviceEvent deviceEvent : addedDeviceEvents.values())
- addDevice(deviceEvent);
- //
- // Apply the "remove" events in the reverse order:
- // device, link, port, switch
- //
- for (DeviceEvent deviceEvent : removedDeviceEvents.values())
- removeDevice(deviceEvent);
- for (LinkEvent linkEvent : removedLinkEvents.values())
- removeLink(linkEvent);
- for (PortEvent portEvent : removedPortEvents.values())
- removePort(portEvent);
- for (SwitchEvent switchEvent : removedSwitchEvents.values())
- removeSwitch(switchEvent);
+ try {
+ //
+ // Apply the classified events.
+ //
+ // Apply the "add" events in the proper order:
+ // switch, port, link, device
+ //
+ for (SwitchEvent switchEvent : addedSwitchEvents.values())
+ addSwitch(switchEvent);
+ for (PortEvent portEvent : addedPortEvents.values())
+ addPort(portEvent);
+ for (LinkEvent linkEvent : addedLinkEvents.values())
+ addLink(linkEvent);
+ for (DeviceEvent deviceEvent : addedDeviceEvents.values())
+ addDevice(deviceEvent);
+ //
+ // Apply the "remove" events in the reverse order:
+ // device, link, port, switch
+ //
+ for (DeviceEvent deviceEvent : removedDeviceEvents.values())
+ removeDevice(deviceEvent);
+ for (LinkEvent linkEvent : removedLinkEvents.values())
+ removeLink(linkEvent);
+ for (PortEvent portEvent : removedPortEvents.values())
+ removePort(portEvent);
+ for (SwitchEvent switchEvent : removedSwitchEvents.values())
+ removeSwitch(switchEvent);
- //
- // Apply reordered events
- //
- applyReorderedEvents(! addedSwitchEvents.isEmpty(),
- ! addedPortEvents.isEmpty());
+ //
+ // Apply reordered events
+ //
+ applyReorderedEvents(!addedSwitchEvents.isEmpty(),
+ !addedPortEvents.isEmpty());
- }
- finally {
- //
- // Network Graph modifications completed: Release the lock
- //
- networkGraph.releaseWriteLock();
- }
+ } finally {
+ //
+ // Network Graph modifications completed: Release the lock
+ //
+ networkGraph.releaseWriteLock();
+ }
- //
- // Dispatch the Topology Notification Events to the applications
- //
- dispatchNetworkGraphEvents();
- }
+ //
+ // Dispatch the Topology Notification Events to the applications
+ //
+ dispatchNetworkGraphEvents();
+ }
- /**
- * Receive a notification that an entry is added.
- *
- * @param value the value for the entry.
- */
- @Override
- public void entryAdded(TopologyEvent value) {
- EventEntry<TopologyEvent> eventEntry =
- new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
- value);
- topologyEvents.add(eventEntry);
- }
+ /**
+ * Receive a notification that an entry is added.
+ *
+ * @param value the value for the entry.
+ */
+ @Override
+ public void entryAdded(TopologyEvent value) {
+ EventEntry<TopologyEvent> eventEntry =
+ new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
+ value);
+ topologyEvents.add(eventEntry);
+ }
- /**
- * Receive a notification that an entry is removed.
- *
- * @param value the value for the entry.
- */
- @Override
- public void entryRemoved(TopologyEvent value) {
- EventEntry<TopologyEvent> eventEntry =
- new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_REMOVE,
- value);
- topologyEvents.add(eventEntry);
- }
+ /**
+ * Receive a notification that an entry is removed.
+ *
+ * @param value the value for the entry.
+ */
+ @Override
+ public void entryRemoved(TopologyEvent value) {
+ EventEntry<TopologyEvent> eventEntry =
+ new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_REMOVE,
+ value);
+ topologyEvents.add(eventEntry);
+ }
- /**
- * Receive a notification that an entry is updated.
- *
- * @param value the value for the entry.
- */
- @Override
- public void entryUpdated(TopologyEvent value) {
- // NOTE: The ADD and UPDATE events are processed in same way
- entryAdded(value);
- }
+ /**
+ * Receive a notification that an entry is updated.
+ *
+ * @param value the value for the entry.
+ */
+ @Override
+ public void entryUpdated(TopologyEvent value) {
+ // NOTE: The ADD and UPDATE events are processed in same way
+ entryAdded(value);
+ }
}
/**
@@ -364,175 +362,175 @@
* @param datagridService the datagrid service to use.
*/
void startup(IDatagridService datagridService) {
- eventChannel = datagridService.addListener(EVENT_CHANNEL_NAME,
- eventHandler,
- byte[].class,
- TopologyEvent.class);
- eventHandler.start();
+ eventChannel = datagridService.addListener(EVENT_CHANNEL_NAME,
+ eventHandler,
+ byte[].class,
+ TopologyEvent.class);
+ eventHandler.start();
}
/**
* Dispatch Network Graph Events to the listeners.
*/
private void dispatchNetworkGraphEvents() {
- if (apiAddedSwitchEvents.isEmpty() &&
- apiRemovedSwitchEvents.isEmpty() &&
- apiAddedPortEvents.isEmpty() &&
- apiRemovedPortEvents.isEmpty() &&
- apiAddedLinkEvents.isEmpty() &&
- apiRemovedLinkEvents.isEmpty() &&
- apiAddedDeviceEvents.isEmpty() &&
- apiRemovedDeviceEvents.isEmpty()) {
- return; // No events to dispatch
- }
+ if (apiAddedSwitchEvents.isEmpty() &&
+ apiRemovedSwitchEvents.isEmpty() &&
+ apiAddedPortEvents.isEmpty() &&
+ apiRemovedPortEvents.isEmpty() &&
+ apiAddedLinkEvents.isEmpty() &&
+ apiRemovedLinkEvents.isEmpty() &&
+ apiAddedDeviceEvents.isEmpty() &&
+ apiRemovedDeviceEvents.isEmpty()) {
+ return; // No events to dispatch
+ }
- if (log.isDebugEnabled()) {
- //
- // Debug statements
- // TODO: Those statements should be removed in the future
- //
- for (SwitchEvent switchEvent : apiAddedSwitchEvents)
- log.debug("Dispatch Network Graph Event: ADDED {}", switchEvent);
- for (SwitchEvent switchEvent : apiRemovedSwitchEvents)
- log.debug("Dispatch Network Graph Event: REMOVED {}", switchEvent);
- for (PortEvent portEvent : apiAddedPortEvents)
- log.debug("Dispatch Network Graph Event: ADDED {}", portEvent);
- for (PortEvent portEvent : apiRemovedPortEvents)
- log.debug("Dispatch Network Graph Event: REMOVED {}", portEvent);
- for (LinkEvent linkEvent : apiAddedLinkEvents)
- log.debug("Dispatch Network Graph Event: ADDED {}", linkEvent);
- for (LinkEvent linkEvent : apiRemovedLinkEvents)
- log.debug("Dispatch Network Graph Event: REMOVED {}", linkEvent);
- for (DeviceEvent deviceEvent : apiAddedDeviceEvents)
- log.debug("Dispatch Network Graph Event: ADDED {}", deviceEvent);
- for (DeviceEvent deviceEvent : apiRemovedDeviceEvents)
- log.debug("Dispatch Network Graph Event: REMOVED {}", deviceEvent);
- }
+ if (log.isDebugEnabled()) {
+ //
+ // Debug statements
+ // TODO: Those statements should be removed in the future
+ //
+ for (SwitchEvent switchEvent : apiAddedSwitchEvents)
+ log.debug("Dispatch Network Graph Event: ADDED {}", switchEvent);
+ for (SwitchEvent switchEvent : apiRemovedSwitchEvents)
+ log.debug("Dispatch Network Graph Event: REMOVED {}", switchEvent);
+ for (PortEvent portEvent : apiAddedPortEvents)
+ log.debug("Dispatch Network Graph Event: ADDED {}", portEvent);
+ for (PortEvent portEvent : apiRemovedPortEvents)
+ log.debug("Dispatch Network Graph Event: REMOVED {}", portEvent);
+ for (LinkEvent linkEvent : apiAddedLinkEvents)
+ log.debug("Dispatch Network Graph Event: ADDED {}", linkEvent);
+ for (LinkEvent linkEvent : apiRemovedLinkEvents)
+ log.debug("Dispatch Network Graph Event: REMOVED {}", linkEvent);
+ for (DeviceEvent deviceEvent : apiAddedDeviceEvents)
+ log.debug("Dispatch Network Graph Event: ADDED {}", deviceEvent);
+ for (DeviceEvent deviceEvent : apiRemovedDeviceEvents)
+ log.debug("Dispatch Network Graph Event: REMOVED {}", deviceEvent);
+ }
- // Deliver the events
- for (INetworkGraphListener listener : this.networkGraphListeners) {
- // TODO: Should copy before handing them over to listener?
- listener.networkGraphEvents(apiAddedSwitchEvents,
- apiRemovedSwitchEvents,
- apiAddedPortEvents,
- apiRemovedPortEvents,
- apiAddedLinkEvents,
- apiRemovedLinkEvents,
- apiAddedDeviceEvents,
- apiRemovedDeviceEvents);
- }
+ // Deliver the events
+ for (INetworkGraphListener listener : this.networkGraphListeners) {
+ // TODO: Should copy before handing them over to listener?
+ listener.networkGraphEvents(apiAddedSwitchEvents,
+ apiRemovedSwitchEvents,
+ apiAddedPortEvents,
+ apiRemovedPortEvents,
+ apiAddedLinkEvents,
+ apiRemovedLinkEvents,
+ apiAddedDeviceEvents,
+ apiRemovedDeviceEvents);
+ }
- //
- // Cleanup
- //
- apiAddedSwitchEvents.clear();
- apiRemovedSwitchEvents.clear();
- apiAddedPortEvents.clear();
- apiRemovedPortEvents.clear();
- apiAddedLinkEvents.clear();
- apiRemovedLinkEvents.clear();
- apiAddedDeviceEvents.clear();
- apiRemovedDeviceEvents.clear();
+ //
+ // Cleanup
+ //
+ apiAddedSwitchEvents.clear();
+ apiRemovedSwitchEvents.clear();
+ apiAddedPortEvents.clear();
+ apiRemovedPortEvents.clear();
+ apiAddedLinkEvents.clear();
+ apiRemovedLinkEvents.clear();
+ apiAddedDeviceEvents.clear();
+ apiRemovedDeviceEvents.clear();
}
/**
* Apply reordered events.
*
* @param hasAddedSwitchEvents true if there were Added Switch Events.
- * @param hasAddedPortEvents true if there were Added Port Events.
+ * @param hasAddedPortEvents true if there were Added Port Events.
*/
private void applyReorderedEvents(boolean hasAddedSwitchEvents,
- boolean hasAddedPortEvents) {
- if (! (hasAddedSwitchEvents || hasAddedPortEvents))
- return; // Nothing to do
+ boolean hasAddedPortEvents) {
+ if (!(hasAddedSwitchEvents || hasAddedPortEvents))
+ return; // Nothing to do
- //
- // Try to apply the reordered events.
- //
- // NOTE: For simplicity we try to apply all events of a particular
- // type if any "parent" type event was processed:
- // - Apply reordered Port Events if Switches were added
- // - Apply reordered Link and Device Events if Switches or Ports
- // were added
- //
+ //
+ // Try to apply the reordered events.
+ //
+ // NOTE: For simplicity we try to apply all events of a particular
+ // type if any "parent" type event was processed:
+ // - Apply reordered Port Events if Switches were added
+ // - Apply reordered Link and Device Events if Switches or Ports
+ // were added
+ //
- //
- // Apply reordered Port Events if Switches were added
- //
- if (hasAddedSwitchEvents) {
- Map<ByteBuffer, PortEvent> portEvents = reorderedAddedPortEvents;
- reorderedAddedPortEvents = new HashMap<>();
- for (PortEvent portEvent : portEvents.values())
- addPort(portEvent);
- }
- //
- // Apply reordered Link and Device Events if Switches or Ports
- // were added.
- //
- Map<ByteBuffer, LinkEvent> linkEvents = reorderedAddedLinkEvents;
- reorderedAddedLinkEvents = new HashMap<>();
- for (LinkEvent linkEvent : linkEvents.values())
- addLink(linkEvent);
- //
- Map<ByteBuffer, DeviceEvent> deviceEvents = reorderedAddedDeviceEvents;
- reorderedAddedDeviceEvents = new HashMap<>();
- for (DeviceEvent deviceEvent : deviceEvents.values())
- addDevice(deviceEvent);
+ //
+ // Apply reordered Port Events if Switches were added
+ //
+ if (hasAddedSwitchEvents) {
+ Map<ByteBuffer, PortEvent> portEvents = reorderedAddedPortEvents;
+ reorderedAddedPortEvents = new HashMap<>();
+ for (PortEvent portEvent : portEvents.values())
+ addPort(portEvent);
+ }
+ //
+ // Apply reordered Link and Device Events if Switches or Ports
+ // were added.
+ //
+ Map<ByteBuffer, LinkEvent> linkEvents = reorderedAddedLinkEvents;
+ reorderedAddedLinkEvents = new HashMap<>();
+ for (LinkEvent linkEvent : linkEvents.values())
+ addLink(linkEvent);
+ //
+ Map<ByteBuffer, DeviceEvent> deviceEvents = reorderedAddedDeviceEvents;
+ reorderedAddedDeviceEvents = new HashMap<>();
+ for (DeviceEvent deviceEvent : deviceEvents.values())
+ addDevice(deviceEvent);
}
/**
* Switch discovered event.
*
* @param switchEvent the switch event.
- * @param portEvents the corresponding port events for the switch.
+ * @param portEvents the corresponding port events for the switch.
*/
@Override
public void putSwitchDiscoveryEvent(SwitchEvent switchEvent,
- Collection<PortEvent> portEvents) {
- if (datastore.addSwitch(switchEvent, portEvents)) {
- // Send out notification
- TopologyEvent topologyEvent = new TopologyEvent(switchEvent);
- eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
-
- // Send out notification for each port
- for (PortEvent portEvent : portEvents) {
- topologyEvent = new TopologyEvent(portEvent);
- eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
- }
+ Collection<PortEvent> portEvents) {
+ if (datastore.addSwitch(switchEvent, portEvents)) {
+ // Send out notification
+ TopologyEvent topologyEvent = new TopologyEvent(switchEvent);
+ eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
- //
- // Keep track of the added ports
- //
- // Get the old Port Events
- Map<ByteBuffer, PortEvent> oldPortEvents =
- discoveredAddedPortEvents.get(switchEvent.getDpid());
- if (oldPortEvents == null)
- oldPortEvents = new HashMap<>();
+ // Send out notification for each port
+ for (PortEvent portEvent : portEvents) {
+ topologyEvent = new TopologyEvent(portEvent);
+ eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
+ }
- // Store the new Port Events in the local cache
- Map<ByteBuffer, PortEvent> newPortEvents = new HashMap<>();
- for (PortEvent portEvent : portEvents) {
- ByteBuffer id = portEvent.getIDasByteBuffer();
- newPortEvents.put(id, portEvent);
- }
- discoveredAddedPortEvents.put(switchEvent.getDpid(),
- newPortEvents);
+ //
+ // Keep track of the added ports
+ //
+ // Get the old Port Events
+ Map<ByteBuffer, PortEvent> oldPortEvents =
+ discoveredAddedPortEvents.get(switchEvent.getDpid());
+ if (oldPortEvents == null)
+ oldPortEvents = new HashMap<>();
- //
- // Extract the removed ports
- //
- List<PortEvent> removedPortEvents = new LinkedList<>();
- for (Map.Entry<ByteBuffer, PortEvent> entry : oldPortEvents.entrySet()) {
- ByteBuffer key = entry.getKey();
- PortEvent portEvent = entry.getValue();
- if (! newPortEvents.containsKey(key))
- removedPortEvents.add(portEvent);
- }
+ // Store the new Port Events in the local cache
+ Map<ByteBuffer, PortEvent> newPortEvents = new HashMap<>();
+ for (PortEvent portEvent : portEvents) {
+ ByteBuffer id = portEvent.getIDasByteBuffer();
+ newPortEvents.put(id, portEvent);
+ }
+ discoveredAddedPortEvents.put(switchEvent.getDpid(),
+ newPortEvents);
- // Cleanup old removed ports
- for (PortEvent portEvent : removedPortEvents)
- removePortDiscoveryEvent(portEvent);
- }
+ //
+ // Extract the removed ports
+ //
+ List<PortEvent> removedPortEvents = new LinkedList<>();
+ for (Map.Entry<ByteBuffer, PortEvent> entry : oldPortEvents.entrySet()) {
+ ByteBuffer key = entry.getKey();
+ PortEvent portEvent = entry.getValue();
+ if (!newPortEvents.containsKey(key))
+ removedPortEvents.add(portEvent);
+ }
+
+ // Cleanup old removed ports
+ for (PortEvent portEvent : removedPortEvents)
+ removePortDiscoveryEvent(portEvent);
+ }
}
/**
@@ -542,47 +540,47 @@
*/
@Override
public void removeSwitchDiscoveryEvent(SwitchEvent switchEvent) {
- // Get the old Port Events
- Map<ByteBuffer, PortEvent> oldPortEvents =
- discoveredAddedPortEvents.get(switchEvent.getDpid());
- if (oldPortEvents == null)
- oldPortEvents = new HashMap<>();
+ // Get the old Port Events
+ Map<ByteBuffer, PortEvent> oldPortEvents =
+ discoveredAddedPortEvents.get(switchEvent.getDpid());
+ if (oldPortEvents == null)
+ oldPortEvents = new HashMap<>();
- if (datastore.deactivateSwitch(switchEvent, oldPortEvents.values())) {
- // Send out notification
- eventChannel.removeEntry(switchEvent.getID());
+ if (datastore.deactivateSwitch(switchEvent, oldPortEvents.values())) {
+ // Send out notification
+ eventChannel.removeEntry(switchEvent.getID());
- //
- // Send out notification for each port.
- //
- // NOTE: We don't use removePortDiscoveryEvent() for the cleanup,
- // because it will attempt to remove the port from the database,
- // and the deactiveSwitch() call above already removed all ports.
- //
- for (PortEvent portEvent : oldPortEvents.values())
- eventChannel.removeEntry(portEvent.getID());
- discoveredAddedPortEvents.remove(switchEvent.getDpid());
+ //
+ // Send out notification for each port.
+ //
+ // NOTE: We don't use removePortDiscoveryEvent() for the cleanup,
+ // because it will attempt to remove the port from the database,
+ // and the deactiveSwitch() call above already removed all ports.
+ //
+ for (PortEvent portEvent : oldPortEvents.values())
+ eventChannel.removeEntry(portEvent.getID());
+ discoveredAddedPortEvents.remove(switchEvent.getDpid());
- // Cleanup for each link
- Map<ByteBuffer, LinkEvent> oldLinkEvents =
- discoveredAddedLinkEvents.get(switchEvent.getDpid());
- if (oldLinkEvents != null) {
- for (LinkEvent linkEvent : new ArrayList<>(oldLinkEvents.values())) {
- removeLinkDiscoveryEvent(linkEvent);
- }
- discoveredAddedLinkEvents.remove(switchEvent.getDpid());
- }
+ // Cleanup for each link
+ Map<ByteBuffer, LinkEvent> oldLinkEvents =
+ discoveredAddedLinkEvents.get(switchEvent.getDpid());
+ if (oldLinkEvents != null) {
+ for (LinkEvent linkEvent : new ArrayList<>(oldLinkEvents.values())) {
+ removeLinkDiscoveryEvent(linkEvent);
+ }
+ discoveredAddedLinkEvents.remove(switchEvent.getDpid());
+ }
- // Cleanup for each device
- Map<ByteBuffer, DeviceEvent> oldDeviceEvents =
- discoveredAddedDeviceEvents.get(switchEvent.getDpid());
- if (oldDeviceEvents != null) {
- for (DeviceEvent deviceEvent : new ArrayList<>(oldDeviceEvents.values())) {
- removeDeviceDiscoveryEvent(deviceEvent);
- }
- discoveredAddedDeviceEvents.remove(switchEvent.getDpid());
- }
- }
+ // Cleanup for each device
+ Map<ByteBuffer, DeviceEvent> oldDeviceEvents =
+ discoveredAddedDeviceEvents.get(switchEvent.getDpid());
+ if (oldDeviceEvents != null) {
+ for (DeviceEvent deviceEvent : new ArrayList<>(oldDeviceEvents.values())) {
+ removeDeviceDiscoveryEvent(deviceEvent);
+ }
+ discoveredAddedDeviceEvents.remove(switchEvent.getDpid());
+ }
+ }
}
/**
@@ -592,22 +590,22 @@
*/
@Override
public void putPortDiscoveryEvent(PortEvent portEvent) {
- if (datastore.addPort(portEvent)) {
- // Send out notification
- TopologyEvent topologyEvent = new TopologyEvent(portEvent);
- eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
+ if (datastore.addPort(portEvent)) {
+ // Send out notification
+ TopologyEvent topologyEvent = new TopologyEvent(portEvent);
+ eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
- // Store the new Port Event in the local cache
- Map<ByteBuffer, PortEvent> oldPortEvents =
- discoveredAddedPortEvents.get(portEvent.getDpid());
- if (oldPortEvents == null) {
- oldPortEvents = new HashMap<>();
- discoveredAddedPortEvents.put(portEvent.getDpid(),
- oldPortEvents);
- }
- ByteBuffer id = portEvent.getIDasByteBuffer();
- oldPortEvents.put(id, portEvent);
- }
+ // Store the new Port Event in the local cache
+ Map<ByteBuffer, PortEvent> oldPortEvents =
+ discoveredAddedPortEvents.get(portEvent.getDpid());
+ if (oldPortEvents == null) {
+ oldPortEvents = new HashMap<>();
+ discoveredAddedPortEvents.put(portEvent.getDpid(),
+ oldPortEvents);
+ }
+ ByteBuffer id = portEvent.getIDasByteBuffer();
+ oldPortEvents.put(id, portEvent);
+ }
}
/**
@@ -617,49 +615,49 @@
*/
@Override
public void removePortDiscoveryEvent(PortEvent portEvent) {
- if (datastore.deactivatePort(portEvent)) {
- // Send out notification
- eventChannel.removeEntry(portEvent.getID());
+ if (datastore.deactivatePort(portEvent)) {
+ // Send out notification
+ eventChannel.removeEntry(portEvent.getID());
- // Cleanup the Port Event from the local cache
- Map<ByteBuffer, PortEvent> oldPortEvents =
- discoveredAddedPortEvents.get(portEvent.getDpid());
- if (oldPortEvents != null) {
- ByteBuffer id = portEvent.getIDasByteBuffer();
- oldPortEvents.remove(id);
- }
+ // Cleanup the Port Event from the local cache
+ Map<ByteBuffer, PortEvent> oldPortEvents =
+ discoveredAddedPortEvents.get(portEvent.getDpid());
+ if (oldPortEvents != null) {
+ ByteBuffer id = portEvent.getIDasByteBuffer();
+ oldPortEvents.remove(id);
+ }
- // Cleanup for the incoming link
- Map<ByteBuffer, LinkEvent> oldLinkEvents =
- discoveredAddedLinkEvents.get(portEvent.getDpid());
- if (oldLinkEvents != null) {
- for (LinkEvent linkEvent : new ArrayList<>(oldLinkEvents.values())) {
- if (linkEvent.getDst().equals(portEvent.id)) {
- removeLinkDiscoveryEvent(linkEvent);
- // XXX If we change our model to allow multiple Link on
- // a Port, this loop must be fixed to allow continuing.
- break;
- }
- }
- }
+ // Cleanup for the incoming link
+ Map<ByteBuffer, LinkEvent> oldLinkEvents =
+ discoveredAddedLinkEvents.get(portEvent.getDpid());
+ if (oldLinkEvents != null) {
+ for (LinkEvent linkEvent : new ArrayList<>(oldLinkEvents.values())) {
+ if (linkEvent.getDst().equals(portEvent.id)) {
+ removeLinkDiscoveryEvent(linkEvent);
+ // XXX If we change our model to allow multiple Link on
+ // a Port, this loop must be fixed to allow continuing.
+ break;
+ }
+ }
+ }
- // Cleanup for the connected devices
- // TODO: The implementation below is probably wrong
- List<DeviceEvent> removedDeviceEvents = new LinkedList<>();
- Map<ByteBuffer, DeviceEvent> oldDeviceEvents =
- discoveredAddedDeviceEvents.get(portEvent.getDpid());
- if (oldDeviceEvents != null) {
- for (DeviceEvent deviceEvent : new ArrayList<>(oldDeviceEvents.values())) {
- for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
- if (swp.equals(portEvent.id)) {
- removedDeviceEvents.add(deviceEvent);
- }
- }
- }
- for (DeviceEvent deviceEvent : removedDeviceEvents)
- removeDeviceDiscoveryEvent(deviceEvent);
- }
- }
+ // Cleanup for the connected devices
+ // TODO: The implementation below is probably wrong
+ List<DeviceEvent> removedDeviceEvents = new LinkedList<>();
+ Map<ByteBuffer, DeviceEvent> oldDeviceEvents =
+ discoveredAddedDeviceEvents.get(portEvent.getDpid());
+ if (oldDeviceEvents != null) {
+ for (DeviceEvent deviceEvent : new ArrayList<>(oldDeviceEvents.values())) {
+ for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
+ if (swp.equals(portEvent.id)) {
+ removedDeviceEvents.add(deviceEvent);
+ }
+ }
+ }
+ for (DeviceEvent deviceEvent : removedDeviceEvents)
+ removeDeviceDiscoveryEvent(deviceEvent);
+ }
+ }
}
/**
@@ -669,22 +667,22 @@
*/
@Override
public void putLinkDiscoveryEvent(LinkEvent linkEvent) {
- if (datastore.addLink(linkEvent)) {
- // Send out notification
- TopologyEvent topologyEvent = new TopologyEvent(linkEvent);
- eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
+ if (datastore.addLink(linkEvent)) {
+ // Send out notification
+ TopologyEvent topologyEvent = new TopologyEvent(linkEvent);
+ eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
- // Store the new Link Event in the local cache
- Map<ByteBuffer, LinkEvent> oldLinkEvents =
- discoveredAddedLinkEvents.get(linkEvent.getDst().getDpid());
- if (oldLinkEvents == null) {
- oldLinkEvents = new HashMap<>();
- discoveredAddedLinkEvents.put(linkEvent.getDst().getDpid(),
- oldLinkEvents);
- }
- ByteBuffer id = linkEvent.getIDasByteBuffer();
- oldLinkEvents.put(id, linkEvent);
- }
+ // Store the new Link Event in the local cache
+ Map<ByteBuffer, LinkEvent> oldLinkEvents =
+ discoveredAddedLinkEvents.get(linkEvent.getDst().getDpid());
+ if (oldLinkEvents == null) {
+ oldLinkEvents = new HashMap<>();
+ discoveredAddedLinkEvents.put(linkEvent.getDst().getDpid(),
+ oldLinkEvents);
+ }
+ ByteBuffer id = linkEvent.getIDasByteBuffer();
+ oldLinkEvents.put(id, linkEvent);
+ }
}
/**
@@ -694,18 +692,18 @@
*/
@Override
public void removeLinkDiscoveryEvent(LinkEvent linkEvent) {
- if (datastore.removeLink(linkEvent)) {
- // Send out notification
- eventChannel.removeEntry(linkEvent.getID());
+ if (datastore.removeLink(linkEvent)) {
+ // Send out notification
+ eventChannel.removeEntry(linkEvent.getID());
- // Cleanup the Link Event from the local cache
- Map<ByteBuffer, LinkEvent> oldLinkEvents =
- discoveredAddedLinkEvents.get(linkEvent.getDst().getDpid());
- if (oldLinkEvents != null) {
- ByteBuffer id = linkEvent.getIDasByteBuffer();
- oldLinkEvents.remove(id);
- }
- }
+ // Cleanup the Link Event from the local cache
+ Map<ByteBuffer, LinkEvent> oldLinkEvents =
+ discoveredAddedLinkEvents.get(linkEvent.getDst().getDpid());
+ if (oldLinkEvents != null) {
+ ByteBuffer id = linkEvent.getIDasByteBuffer();
+ oldLinkEvents.remove(id);
+ }
+ }
}
/**
@@ -715,26 +713,26 @@
*/
@Override
public void putDeviceDiscoveryEvent(DeviceEvent deviceEvent) {
- if (datastore.addDevice(deviceEvent)) {
- // Send out notification
- TopologyEvent topologyEvent = new TopologyEvent(deviceEvent);
- eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
- log.debug("Put the device info into the cache of the graph. mac {}", deviceEvent.getMac());
-
- // Store the new Device Event in the local cache
- // TODO: The implementation below is probably wrong
- for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
- Map<ByteBuffer, DeviceEvent> oldDeviceEvents =
- discoveredAddedDeviceEvents.get(swp.getDpid());
- if (oldDeviceEvents == null) {
- oldDeviceEvents = new HashMap<>();
- discoveredAddedDeviceEvents.put(swp.getDpid(),
- oldDeviceEvents);
- }
- ByteBuffer id = deviceEvent.getIDasByteBuffer();
- oldDeviceEvents.put(id, deviceEvent);
- }
- }
+ if (datastore.addDevice(deviceEvent)) {
+ // Send out notification
+ TopologyEvent topologyEvent = new TopologyEvent(deviceEvent);
+ eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
+ log.debug("Put the device info into the cache of the graph. mac {}", deviceEvent.getMac());
+
+ // Store the new Device Event in the local cache
+ // TODO: The implementation below is probably wrong
+ for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
+ Map<ByteBuffer, DeviceEvent> oldDeviceEvents =
+ discoveredAddedDeviceEvents.get(swp.getDpid());
+ if (oldDeviceEvents == null) {
+ oldDeviceEvents = new HashMap<>();
+ discoveredAddedDeviceEvents.put(swp.getDpid(),
+ oldDeviceEvents);
+ }
+ ByteBuffer id = deviceEvent.getIDasByteBuffer();
+ oldDeviceEvents.put(id, deviceEvent);
+ }
+ }
}
/**
@@ -744,22 +742,22 @@
*/
@Override
public void removeDeviceDiscoveryEvent(DeviceEvent deviceEvent) {
- if (datastore.removeDevice(deviceEvent)) {
- // Send out notification
- eventChannel.removeEntry(deviceEvent.getID());
- log.debug("Remove the device info into the cache of the graph. mac {}", deviceEvent.getMac());
+ if (datastore.removeDevice(deviceEvent)) {
+ // Send out notification
+ eventChannel.removeEntry(deviceEvent.getID());
+ log.debug("Remove the device info into the cache of the graph. mac {}", deviceEvent.getMac());
- // Cleanup the Device Event from the local cache
- // TODO: The implementation below is probably wrong
- ByteBuffer id = ByteBuffer.wrap(deviceEvent.getID());
- for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
- Map<ByteBuffer, DeviceEvent> oldDeviceEvents =
- discoveredAddedDeviceEvents.get(swp.getDpid());
- if (oldDeviceEvents != null) {
- oldDeviceEvents.remove(id);
- }
- }
- }
+ // Cleanup the Device Event from the local cache
+ // TODO: The implementation below is probably wrong
+ ByteBuffer id = ByteBuffer.wrap(deviceEvent.getID());
+ for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
+ Map<ByteBuffer, DeviceEvent> oldDeviceEvents =
+ discoveredAddedDeviceEvents.get(swp.getDpid());
+ if (oldDeviceEvents != null) {
+ oldDeviceEvents.remove(id);
+ }
+ }
+ }
}
/**
@@ -768,15 +766,15 @@
* @param switchEvent the Switch Event with the switch to add.
*/
private void addSwitch(SwitchEvent switchEvent) {
- Switch sw = networkGraph.getSwitch(switchEvent.getDpid());
- if (sw == null) {
- sw = new SwitchImpl(networkGraph, switchEvent.getDpid());
- networkGraph.putSwitch(sw);
- } else {
- // TODO: Update the switch attributes
- // TODO: Nothing to do for now
- }
- apiAddedSwitchEvents.add(switchEvent);
+ Switch sw = networkGraph.getSwitch(switchEvent.getDpid());
+ if (sw == null) {
+ sw = new SwitchImpl(networkGraph, switchEvent.getDpid());
+ networkGraph.putSwitch(sw);
+ } else {
+ // TODO: Update the switch attributes
+ // TODO: Nothing to do for now
+ }
+ apiAddedSwitchEvents.add(switchEvent);
}
/**
@@ -785,28 +783,28 @@
* @param switchEvent the Switch Event with the switch to remove.
*/
private void removeSwitch(SwitchEvent switchEvent) {
- Switch sw = networkGraph.getSwitch(switchEvent.getDpid());
- if (sw == null) {
- log.warn("Switch {} already removed, ignoring", switchEvent);
- return;
- }
+ Switch sw = networkGraph.getSwitch(switchEvent.getDpid());
+ if (sw == null) {
+ log.warn("Switch {} already removed, ignoring", switchEvent);
+ return;
+ }
- //
- // Remove all Ports on the Switch
- //
- ArrayList<PortEvent> portsToRemove = new ArrayList<>();
- for (Port port : sw.getPorts()) {
- log.warn("Port {} on Switch {} should be removed prior to removing Switch. Removing Port now.",
- port, switchEvent);
- PortEvent portEvent = new PortEvent(port.getDpid(),
- port.getNumber());
- portsToRemove.add(portEvent);
- }
- for (PortEvent portEvent : portsToRemove)
- removePort(portEvent);
+ //
+ // Remove all Ports on the Switch
+ //
+ ArrayList<PortEvent> portsToRemove = new ArrayList<>();
+ for (Port port : sw.getPorts()) {
+ log.warn("Port {} on Switch {} should be removed prior to removing Switch. Removing Port now.",
+ port, switchEvent);
+ PortEvent portEvent = new PortEvent(port.getDpid(),
+ port.getNumber());
+ portsToRemove.add(portEvent);
+ }
+ for (PortEvent portEvent : portsToRemove)
+ removePort(portEvent);
- networkGraph.removeSwitch(switchEvent.getDpid());
- apiRemovedSwitchEvents.add(switchEvent);
+ networkGraph.removeSwitch(switchEvent.getDpid());
+ apiRemovedSwitchEvents.add(switchEvent);
}
/**
@@ -815,23 +813,23 @@
* @param portEvent the Port Event with the port to add.
*/
private void addPort(PortEvent portEvent) {
- Switch sw = networkGraph.getSwitch(portEvent.getDpid());
- if (sw == null) {
- // Reordered event: delay the event in local cache
- ByteBuffer id = portEvent.getIDasByteBuffer();
- reorderedAddedPortEvents.put(id, portEvent);
- return;
- }
- SwitchImpl switchImpl = getSwitchImpl(sw);
+ Switch sw = networkGraph.getSwitch(portEvent.getDpid());
+ if (sw == null) {
+ // Reordered event: delay the event in local cache
+ ByteBuffer id = portEvent.getIDasByteBuffer();
+ reorderedAddedPortEvents.put(id, portEvent);
+ return;
+ }
+ SwitchImpl switchImpl = getSwitchImpl(sw);
- Port port = sw.getPort(portEvent.getNumber());
- if (port == null) {
- port = new PortImpl(networkGraph, sw, portEvent.getNumber());
- switchImpl.addPort(port);
- } else {
- // TODO: Update the port attributes
- }
- apiAddedPortEvents.add(portEvent);
+ Port port = sw.getPort(portEvent.getNumber());
+ if (port == null) {
+ port = new PortImpl(networkGraph, sw, portEvent.getNumber());
+ switchImpl.addPort(port);
+ } else {
+ // TODO: Update the port attributes
+ }
+ apiAddedPortEvents.add(portEvent);
}
/**
@@ -840,59 +838,59 @@
* @param portEvent the Port Event with the port to remove.
*/
private void removePort(PortEvent portEvent) {
- Switch sw = networkGraph.getSwitch(portEvent.getDpid());
- if (sw == null) {
- log.warn("Parent Switch for Port {} already removed, ignoring",
- portEvent);
- return;
- }
+ Switch sw = networkGraph.getSwitch(portEvent.getDpid());
+ if (sw == null) {
+ log.warn("Parent Switch for Port {} already removed, ignoring",
+ portEvent);
+ return;
+ }
- Port port = sw.getPort(portEvent.getNumber());
- if (port == null) {
- log.warn("Port {} already removed, ignoring", portEvent);
- return;
- }
+ Port port = sw.getPort(portEvent.getNumber());
+ if (port == null) {
+ log.warn("Port {} already removed, ignoring", portEvent);
+ return;
+ }
- //
- // Remove all Devices attached to the Port
- //
- ArrayList<DeviceEvent> devicesToRemove = new ArrayList<>();
- for (Device device : port.getDevices()) {
- log.debug("Removing Device {} on Port {}", device, portEvent);
- DeviceEvent deviceEvent = new DeviceEvent(device.getMacAddress());
- SwitchPort switchPort = new SwitchPort(port.getSwitch().getDpid(),
- port.getNumber());
- deviceEvent.addAttachmentPoint(switchPort);
- devicesToRemove.add(deviceEvent);
- }
- for (DeviceEvent deviceEvent : devicesToRemove)
- removeDevice(deviceEvent);
+ //
+ // Remove all Devices attached to the Port
+ //
+ ArrayList<DeviceEvent> devicesToRemove = new ArrayList<>();
+ for (Device device : port.getDevices()) {
+ log.debug("Removing Device {} on Port {}", device, portEvent);
+ DeviceEvent deviceEvent = new DeviceEvent(device.getMacAddress());
+ SwitchPort switchPort = new SwitchPort(port.getSwitch().getDpid(),
+ port.getNumber());
+ deviceEvent.addAttachmentPoint(switchPort);
+ devicesToRemove.add(deviceEvent);
+ }
+ for (DeviceEvent deviceEvent : devicesToRemove)
+ removeDevice(deviceEvent);
- //
- // Remove all Links connected to the Port
- //
- Set<Link> links = new HashSet<>();
- links.add(port.getOutgoingLink());
- links.add(port.getIncomingLink());
- ArrayList<LinkEvent> linksToRemove = new ArrayList<>();
- for (Link link : links) {
- if (link == null)
- continue;
- log.debug("Removing Link {} on Port {}", link, portEvent);
- LinkEvent linkEvent = new LinkEvent(link.getSrcSwitch().getDpid(),
- link.getSrcPort().getNumber(),
- link.getDstSwitch().getDpid(),
- link.getDstPort().getNumber());
- linksToRemove.add(linkEvent);
- }
- for (LinkEvent linkEvent : linksToRemove)
- removeLink(linkEvent);
+ //
+ // Remove all Links connected to the Port
+ //
+ Set<Link> links = new HashSet<>();
+ links.add(port.getOutgoingLink());
+ links.add(port.getIncomingLink());
+ ArrayList<LinkEvent> linksToRemove = new ArrayList<>();
+ for (Link link : links) {
+ if (link == null)
+ continue;
+ log.debug("Removing Link {} on Port {}", link, portEvent);
+ LinkEvent linkEvent = new LinkEvent(link.getSrcSwitch().getDpid(),
+ link.getSrcPort().getNumber(),
+ link.getDstSwitch().getDpid(),
+ link.getDstPort().getNumber());
+ linksToRemove.add(linkEvent);
+ }
+ for (LinkEvent linkEvent : linksToRemove)
+ removeLink(linkEvent);
- // Remove the Port from the Switch
- SwitchImpl switchImpl = getSwitchImpl(sw);
- switchImpl.removePort(port);
+ // Remove the Port from the Switch
+ SwitchImpl switchImpl = getSwitchImpl(sw);
+ switchImpl.removePort(port);
- apiRemovedPortEvents.add(portEvent);
+ apiRemovedPortEvents.add(portEvent);
}
/**
@@ -901,52 +899,52 @@
* @param linkEvent the Link Event with the link to add.
*/
private void addLink(LinkEvent linkEvent) {
- Port srcPort = networkGraph.getPort(linkEvent.getSrc().dpid,
- linkEvent.getSrc().number);
- Port dstPort = networkGraph.getPort(linkEvent.getDst().dpid,
- linkEvent.getDst().number);
- if ((srcPort == null) || (dstPort == null)) {
- // Reordered event: delay the event in local cache
- ByteBuffer id = linkEvent.getIDasByteBuffer();
- reorderedAddedLinkEvents.put(id, linkEvent);
- return;
- }
+ Port srcPort = networkGraph.getPort(linkEvent.getSrc().dpid,
+ linkEvent.getSrc().number);
+ Port dstPort = networkGraph.getPort(linkEvent.getDst().dpid,
+ linkEvent.getDst().number);
+ if ((srcPort == null) || (dstPort == null)) {
+ // Reordered event: delay the event in local cache
+ ByteBuffer id = linkEvent.getIDasByteBuffer();
+ reorderedAddedLinkEvents.put(id, linkEvent);
+ return;
+ }
- // Get the Link instance from the Destination Port Incoming Link
- Link link = dstPort.getIncomingLink();
- assert(link == srcPort.getOutgoingLink());
- if (link == null) {
- link = new LinkImpl(networkGraph, srcPort, dstPort);
- PortImpl srcPortImpl = getPortImpl(srcPort);
- PortImpl dstPortImpl = getPortImpl(dstPort);
- srcPortImpl.setOutgoingLink(link);
- dstPortImpl.setIncomingLink(link);
+ // Get the Link instance from the Destination Port Incoming Link
+ Link link = dstPort.getIncomingLink();
+ assert (link == srcPort.getOutgoingLink());
+ if (link == null) {
+ link = new LinkImpl(networkGraph, srcPort, dstPort);
+ PortImpl srcPortImpl = getPortImpl(srcPort);
+ PortImpl dstPortImpl = getPortImpl(dstPort);
+ srcPortImpl.setOutgoingLink(link);
+ dstPortImpl.setIncomingLink(link);
- // Remove all Devices attached to the Ports
- ArrayList<DeviceEvent> devicesToRemove = new ArrayList<>();
- ArrayList<Port> ports = new ArrayList<>();
- ports.add(srcPort);
- ports.add(dstPort);
- for (Port port : ports) {
- for (Device device : port.getDevices()) {
- log.error("Device {} on Port {} should have been removed prior to adding Link {}",
- device, port, linkEvent);
- DeviceEvent deviceEvent =
- new DeviceEvent(device.getMacAddress());
- SwitchPort switchPort =
- new SwitchPort(port.getSwitch().getDpid(),
- port.getNumber());
- deviceEvent.addAttachmentPoint(switchPort);
- devicesToRemove.add(deviceEvent);
- }
- }
- for (DeviceEvent deviceEvent : devicesToRemove)
- removeDevice(deviceEvent);
- } else {
- // TODO: Update the link attributes
- }
+ // Remove all Devices attached to the Ports
+ ArrayList<DeviceEvent> devicesToRemove = new ArrayList<>();
+ ArrayList<Port> ports = new ArrayList<>();
+ ports.add(srcPort);
+ ports.add(dstPort);
+ for (Port port : ports) {
+ for (Device device : port.getDevices()) {
+ log.error("Device {} on Port {} should have been removed prior to adding Link {}",
+ device, port, linkEvent);
+ DeviceEvent deviceEvent =
+ new DeviceEvent(device.getMacAddress());
+ SwitchPort switchPort =
+ new SwitchPort(port.getSwitch().getDpid(),
+ port.getNumber());
+ deviceEvent.addAttachmentPoint(switchPort);
+ devicesToRemove.add(deviceEvent);
+ }
+ }
+ for (DeviceEvent deviceEvent : devicesToRemove)
+ removeDevice(deviceEvent);
+ } else {
+ // TODO: Update the link attributes
+ }
- apiAddedLinkEvents.add(linkEvent);
+ apiAddedLinkEvents.add(linkEvent);
}
/**
@@ -955,43 +953,43 @@
* @param linkEvent the Link Event with the link to remove.
*/
private void removeLink(LinkEvent linkEvent) {
- Port srcPort = networkGraph.getPort(linkEvent.getSrc().dpid,
- linkEvent.getSrc().number);
- if (srcPort == null) {
- log.warn("Src Port for Link {} already removed, ignoring",
- linkEvent);
- return;
- }
+ Port srcPort = networkGraph.getPort(linkEvent.getSrc().dpid,
+ linkEvent.getSrc().number);
+ if (srcPort == null) {
+ log.warn("Src Port for Link {} already removed, ignoring",
+ linkEvent);
+ return;
+ }
- Port dstPort = networkGraph.getPort(linkEvent.getDst().dpid,
- linkEvent.getDst().number);
- if (dstPort == null) {
- log.warn("Dst Port for Link {} already removed, ignoring",
- linkEvent);
- return;
- }
+ Port dstPort = networkGraph.getPort(linkEvent.getDst().dpid,
+ linkEvent.getDst().number);
+ if (dstPort == null) {
+ log.warn("Dst Port for Link {} already removed, ignoring",
+ linkEvent);
+ return;
+ }
- //
- // Remove the Link instance from the Destination Port Incoming Link
- // and the Source Port Outgoing Link.
- //
- Link link = dstPort.getIncomingLink();
- if (link == null) {
- log.warn("Link {} already removed on destination Port", linkEvent);
- }
- link = srcPort.getOutgoingLink();
- if (link == null) {
- log.warn("Link {} already removed on src Port", linkEvent);
- }
- getPortImpl(dstPort).setIncomingLink(null);
- getPortImpl(srcPort).setOutgoingLink(null);
+ //
+ // Remove the Link instance from the Destination Port Incoming Link
+ // and the Source Port Outgoing Link.
+ //
+ Link link = dstPort.getIncomingLink();
+ if (link == null) {
+ log.warn("Link {} already removed on destination Port", linkEvent);
+ }
+ link = srcPort.getOutgoingLink();
+ if (link == null) {
+ log.warn("Link {} already removed on src Port", linkEvent);
+ }
+ getPortImpl(dstPort).setIncomingLink(null);
+ getPortImpl(srcPort).setOutgoingLink(null);
- apiRemovedLinkEvents.add(linkEvent);
+ apiRemovedLinkEvents.add(linkEvent);
}
/**
* Add a device to the Network Graph.
- *
+ * <p/>
* TODO: Device-related work is incomplete.
* TODO: Eventually, we might need to consider reordering
* or addLink() and addDevice() events on the same port.
@@ -999,86 +997,86 @@
* @param deviceEvent the Device Event with the device to add.
*/
private void addDevice(DeviceEvent deviceEvent) {
- Device device = networkGraph.getDeviceByMac(deviceEvent.getMac());
-
- if (device == null) {
- log.debug("Existing device was not found in networkGraph. New device. mac {}", deviceEvent.getMac());
- device = new DeviceImpl(networkGraph, deviceEvent.getMac());
- }
-
- DeviceImpl deviceImpl = getDeviceImpl(device);
+ Device device = networkGraph.getDeviceByMac(deviceEvent.getMac());
- // Update the IP addresses
- for (InetAddress ipAddr : deviceEvent.getIpAddresses())
- deviceImpl.addIpAddress(ipAddr);
+ if (device == null) {
+ log.debug("Existing device was not found in networkGraph. New device. mac {}", deviceEvent.getMac());
+ device = new DeviceImpl(networkGraph, deviceEvent.getMac());
+ }
- // Process each attachment point
- boolean attachmentFound = false;
- for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
- // Attached Ports must exist
- Port port = networkGraph.getPort(swp.dpid, swp.number);
- if (port == null) {
- // Reordered event: delay the event in local cache
- ByteBuffer id = deviceEvent.getIDasByteBuffer();
- reorderedAddedDeviceEvents.put(id, deviceEvent);
- continue;
- }
- // Attached Ports must not have Link
- if (port.getOutgoingLink() != null ||
- port.getIncomingLink() != null) {
- log.warn("Link (Out:{},In:{}) exist on the attachment point, skipping mutation.",
- port.getOutgoingLink(),
- port.getIncomingLink());
- continue;
- }
+ DeviceImpl deviceImpl = getDeviceImpl(device);
- // Add Device <-> Port attachment
- PortImpl portImpl = getPortImpl(port);
- portImpl.addDevice(device);
- deviceImpl.addAttachmentPoint(port);
- attachmentFound = true;
- }
+ // Update the IP addresses
+ for (InetAddress ipAddr : deviceEvent.getIpAddresses())
+ deviceImpl.addIpAddress(ipAddr);
- // Update the device in the Network Graph
- if (attachmentFound) {
- log.debug("Storing the info into networkGraph. mac {}", deviceEvent.getMac());
- networkGraph.putDevice(device);
- apiAddedDeviceEvents.add(deviceEvent);
- }
+ // Process each attachment point
+ boolean attachmentFound = false;
+ for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
+ // Attached Ports must exist
+ Port port = networkGraph.getPort(swp.dpid, swp.number);
+ if (port == null) {
+ // Reordered event: delay the event in local cache
+ ByteBuffer id = deviceEvent.getIDasByteBuffer();
+ reorderedAddedDeviceEvents.put(id, deviceEvent);
+ continue;
+ }
+ // Attached Ports must not have Link
+ if (port.getOutgoingLink() != null ||
+ port.getIncomingLink() != null) {
+ log.warn("Link (Out:{},In:{}) exist on the attachment point, skipping mutation.",
+ port.getOutgoingLink(),
+ port.getIncomingLink());
+ continue;
+ }
+
+ // Add Device <-> Port attachment
+ PortImpl portImpl = getPortImpl(port);
+ portImpl.addDevice(device);
+ deviceImpl.addAttachmentPoint(port);
+ attachmentFound = true;
+ }
+
+ // Update the device in the Network Graph
+ if (attachmentFound) {
+ log.debug("Storing the info into networkGraph. mac {}", deviceEvent.getMac());
+ networkGraph.putDevice(device);
+ apiAddedDeviceEvents.add(deviceEvent);
+ }
}
/**
* Remove a device from the Network Graph.
- *
+ * <p/>
* TODO: Device-related work is incomplete.
*
* @param deviceEvent the Device Event with the device to remove.
*/
private void removeDevice(DeviceEvent deviceEvent) {
- Device device = networkGraph.getDeviceByMac(deviceEvent.getMac());
- if (device == null) {
- log.warn("Device {} already removed, ignoring", deviceEvent);
- return;
- }
- DeviceImpl deviceImpl = getDeviceImpl(device);
+ Device device = networkGraph.getDeviceByMac(deviceEvent.getMac());
+ if (device == null) {
+ log.warn("Device {} already removed, ignoring", deviceEvent);
+ return;
+ }
+ DeviceImpl deviceImpl = getDeviceImpl(device);
- // Process each attachment point
- for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
- // Attached Ports must exist
- Port port = networkGraph.getPort(swp.dpid, swp.number);
- if (port == null) {
- log.warn("Port for the attachment point {} did not exist. skipping attachment point mutation", swp);
- continue;
- }
+ // Process each attachment point
+ for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
+ // Attached Ports must exist
+ Port port = networkGraph.getPort(swp.dpid, swp.number);
+ if (port == null) {
+ log.warn("Port for the attachment point {} did not exist. skipping attachment point mutation", swp);
+ continue;
+ }
- // Remove Device <-> Port attachment
- PortImpl portImpl = getPortImpl(port);
- portImpl.removeDevice(device);
- deviceImpl.removeAttachmentPoint(port);
- }
+ // Remove Device <-> Port attachment
+ PortImpl portImpl = getPortImpl(port);
+ portImpl.removeDevice(device);
+ deviceImpl.removeAttachmentPoint(port);
+ }
- networkGraph.removeDevice(device);
- apiRemovedDeviceEvents.add(deviceEvent);
+ networkGraph.removeDevice(device);
+ apiRemovedDeviceEvents.add(deviceEvent);
}
/**
@@ -1088,10 +1086,10 @@
* @return the SwitchImpl-casted switch implementation.
*/
private SwitchImpl getSwitchImpl(Switch sw) {
- if (sw instanceof SwitchImpl) {
- return (SwitchImpl)sw;
- }
- throw new ClassCastException("SwitchImpl expected, but found: " + sw);
+ if (sw instanceof SwitchImpl) {
+ return (SwitchImpl) sw;
+ }
+ throw new ClassCastException("SwitchImpl expected, but found: " + sw);
}
/**
@@ -1101,10 +1099,10 @@
* @return the PortImpl-casted port implementation.
*/
private PortImpl getPortImpl(Port port) {
- if (port instanceof PortImpl) {
- return (PortImpl)port;
- }
- throw new ClassCastException("PortImpl expected, but found: " + port);
+ if (port instanceof PortImpl) {
+ return (PortImpl) port;
+ }
+ throw new ClassCastException("PortImpl expected, but found: " + port);
}
/**
@@ -1114,10 +1112,10 @@
* @return the LinkImpl-casted link implementation.
*/
private LinkImpl getLinkImpl(Link link) {
- if (link instanceof LinkImpl) {
- return (LinkImpl)link;
- }
- throw new ClassCastException("LinkImpl expected, but found: " + link);
+ if (link instanceof LinkImpl) {
+ return (LinkImpl) link;
+ }
+ throw new ClassCastException("LinkImpl expected, but found: " + link);
}
/**
@@ -1127,10 +1125,10 @@
* @return the DeviceImpl-casted device implementation.
*/
private DeviceImpl getDeviceImpl(Device device) {
- if (device instanceof DeviceImpl) {
- return (DeviceImpl)device;
- }
- throw new ClassCastException("DeviceImpl expected, but found: " + device);
+ if (device instanceof DeviceImpl) {
+ return (DeviceImpl) device;
+ }
+ throw new ClassCastException("DeviceImpl expected, but found: " + device);
}
/**
@@ -1140,60 +1138,60 @@
* the whole topology.
*/
private Collection<EventEntry<TopologyEvent>> readWholeTopologyFromDB() {
- Collection<EventEntry<TopologyEvent>> collection =
- new LinkedList<EventEntry<TopologyEvent>>();
+ Collection<EventEntry<TopologyEvent>> collection =
+ new LinkedList<EventEntry<TopologyEvent>>();
- // XXX May need to clear whole topology first, depending on
- // how we initially subscribe to replication events
+ // XXX May need to clear whole topology first, depending on
+ // how we initially subscribe to replication events
- // Add all active switches
- for (KVSwitch sw : KVSwitch.getAllSwitches()) {
- if (sw.getStatus() != KVSwitch.STATUS.ACTIVE) {
- continue;
- }
+ // Add all active switches
+ for (KVSwitch sw : KVSwitch.getAllSwitches()) {
+ if (sw.getStatus() != KVSwitch.STATUS.ACTIVE) {
+ continue;
+ }
- SwitchEvent switchEvent = new SwitchEvent(sw.getDpid());
- TopologyEvent topologyEvent = new TopologyEvent(switchEvent);
- EventEntry<TopologyEvent> eventEntry =
- new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
- topologyEvent);
- collection.add(eventEntry);
- }
+ SwitchEvent switchEvent = new SwitchEvent(sw.getDpid());
+ TopologyEvent topologyEvent = new TopologyEvent(switchEvent);
+ EventEntry<TopologyEvent> eventEntry =
+ new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
+ topologyEvent);
+ collection.add(eventEntry);
+ }
- // Add all active ports
- for (KVPort p : KVPort.getAllPorts()) {
- if (p.getStatus() != KVPort.STATUS.ACTIVE) {
- continue;
- }
+ // Add all active ports
+ for (KVPort p : KVPort.getAllPorts()) {
+ if (p.getStatus() != KVPort.STATUS.ACTIVE) {
+ continue;
+ }
- PortEvent portEvent = new PortEvent(p.getDpid(), p.getNumber());
- TopologyEvent topologyEvent = new TopologyEvent(portEvent);
- EventEntry<TopologyEvent> eventEntry =
- new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
- topologyEvent);
- collection.add(eventEntry);
- }
+ PortEvent portEvent = new PortEvent(p.getDpid(), p.getNumber());
+ TopologyEvent topologyEvent = new TopologyEvent(portEvent);
+ EventEntry<TopologyEvent> eventEntry =
+ new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
+ topologyEvent);
+ collection.add(eventEntry);
+ }
- // TODO Is Device going to be in DB? If so, read from DB.
- // for (KVDevice d : KVDevice.getAllDevices()) {
- // DeviceEvent devEvent = new DeviceEvent( MACAddress.valueOf(d.getMac()) );
- // for (byte[] portId : d.getAllPortIds() ) {
- // devEvent.addAttachmentPoint( new SwitchPort( KVPort.getDpidFromKey(portId), KVPort.getNumberFromKey(portId) ));
- // }
- // }
+ // TODO Is Device going to be in DB? If so, read from DB.
+ // for (KVDevice d : KVDevice.getAllDevices()) {
+ // DeviceEvent devEvent = new DeviceEvent( MACAddress.valueOf(d.getMac()) );
+ // for (byte[] portId : d.getAllPortIds() ) {
+ // devEvent.addAttachmentPoint( new SwitchPort( KVPort.getDpidFromKey(portId), KVPort.getNumberFromKey(portId) ));
+ // }
+ // }
- for (KVLink l : KVLink.getAllLinks()) {
- LinkEvent linkEvent = new LinkEvent(l.getSrc().dpid,
- l.getSrc().number,
- l.getDst().dpid,
- l.getDst().number);
- TopologyEvent topologyEvent = new TopologyEvent(linkEvent);
- EventEntry<TopologyEvent> eventEntry =
- new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
- topologyEvent);
- collection.add(eventEntry);
- }
+ for (KVLink l : KVLink.getAllLinks()) {
+ LinkEvent linkEvent = new LinkEvent(l.getSrc().dpid,
+ l.getSrc().number,
+ l.getDst().dpid,
+ l.getDst().number);
+ TopologyEvent topologyEvent = new TopologyEvent(linkEvent);
+ EventEntry<TopologyEvent> eventEntry =
+ new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
+ topologyEvent);
+ collection.add(eventEntry);
+ }
- return collection;
+ return collection;
}
}
diff --git a/src/main/java/net/onrc/onos/core/topology/serializers/LinkSerializer.java b/src/main/java/net/onrc/onos/core/topology/serializers/LinkSerializer.java
index 93bce90..61a3b34 100644
--- a/src/main/java/net/onrc/onos/core/topology/serializers/LinkSerializer.java
+++ b/src/main/java/net/onrc/onos/core/topology/serializers/LinkSerializer.java
@@ -12,24 +12,24 @@
public class LinkSerializer extends SerializerBase<Link> {
- public LinkSerializer() {
- super(Link.class);
- }
+ public LinkSerializer() {
+ super(Link.class);
+ }
- @Override
- public void serialize(Link link, JsonGenerator jsonGenerator,
- SerializerProvider serializerProvider)
- throws IOException, JsonGenerationException {
- jsonGenerator.writeStartObject();
- jsonGenerator.writeStringField("src-switch",
- HexString.toHexString(link.getSrcSwitch().getDpid()));
- jsonGenerator.writeNumberField("src-port",
- link.getSrcPort().getNumber());
- jsonGenerator.writeStringField("dst-switch",
- HexString.toHexString(link.getDstSwitch().getDpid()));
- jsonGenerator.writeNumberField("dst-port",
- link.getDstPort().getNumber());
- jsonGenerator.writeEndObject();
- }
+ @Override
+ public void serialize(Link link, JsonGenerator jsonGenerator,
+ SerializerProvider serializerProvider)
+ throws IOException, JsonGenerationException {
+ jsonGenerator.writeStartObject();
+ jsonGenerator.writeStringField("src-switch",
+ HexString.toHexString(link.getSrcSwitch().getDpid()));
+ jsonGenerator.writeNumberField("src-port",
+ link.getSrcPort().getNumber());
+ jsonGenerator.writeStringField("dst-switch",
+ HexString.toHexString(link.getDstSwitch().getDpid()));
+ jsonGenerator.writeNumberField("dst-port",
+ link.getDstPort().getNumber());
+ jsonGenerator.writeEndObject();
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/serializers/PortSerializer.java b/src/main/java/net/onrc/onos/core/topology/serializers/PortSerializer.java
index 25e64d0..ae75dff 100644
--- a/src/main/java/net/onrc/onos/core/topology/serializers/PortSerializer.java
+++ b/src/main/java/net/onrc/onos/core/topology/serializers/PortSerializer.java
@@ -11,21 +11,21 @@
public class PortSerializer extends SerializerBase<Port> {
- public PortSerializer() {
- super(Port.class);
- }
+ public PortSerializer() {
+ super(Port.class);
+ }
- @Override
- public void serialize(Port port, JsonGenerator jsonGenerator,
- SerializerProvider serializerProvider)
- throws IOException, JsonProcessingException {
- jsonGenerator.writeStartObject();
- jsonGenerator.writeStringField("state", "ACTIVE");
- jsonGenerator.writeNumberField("number", port.getNumber());
- jsonGenerator.writeStringField("desc", port.getDescription());
- jsonGenerator.writeArrayFieldStart("devices");
- jsonGenerator.writeEndArray();
- jsonGenerator.writeEndObject();
- }
+ @Override
+ public void serialize(Port port, JsonGenerator jsonGenerator,
+ SerializerProvider serializerProvider)
+ throws IOException, JsonProcessingException {
+ jsonGenerator.writeStartObject();
+ jsonGenerator.writeStringField("state", "ACTIVE");
+ jsonGenerator.writeNumberField("number", port.getNumber());
+ jsonGenerator.writeStringField("desc", port.getDescription());
+ jsonGenerator.writeArrayFieldStart("devices");
+ jsonGenerator.writeEndArray();
+ jsonGenerator.writeEndObject();
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/serializers/SwitchSerializer.java b/src/main/java/net/onrc/onos/core/topology/serializers/SwitchSerializer.java
index e36d35c..00bdcad 100644
--- a/src/main/java/net/onrc/onos/core/topology/serializers/SwitchSerializer.java
+++ b/src/main/java/net/onrc/onos/core/topology/serializers/SwitchSerializer.java
@@ -13,24 +13,24 @@
public class SwitchSerializer extends SerializerBase<Switch> {
- public SwitchSerializer() {
- super(Switch.class);
- }
+ public SwitchSerializer() {
+ super(Switch.class);
+ }
- @Override
- public void serialize(Switch sw, JsonGenerator jsonGenerator,
- SerializerProvider serializerProvider) throws IOException,
- JsonProcessingException {
-
- jsonGenerator.writeStartObject();
- jsonGenerator.writeStringField("dpid", HexString.toHexString(sw.getDpid()));
- jsonGenerator.writeStringField("state", "ACTIVE");
- jsonGenerator.writeArrayFieldStart("ports");
- for (Port port : sw.getPorts()) {
- jsonGenerator.writeObject(port);
- }
- jsonGenerator.writeEndArray();
- jsonGenerator.writeEndObject();
- }
+ @Override
+ public void serialize(Switch sw, JsonGenerator jsonGenerator,
+ SerializerProvider serializerProvider) throws IOException,
+ JsonProcessingException {
+
+ jsonGenerator.writeStartObject();
+ jsonGenerator.writeStringField("dpid", HexString.toHexString(sw.getDpid()));
+ jsonGenerator.writeStringField("state", "ACTIVE");
+ jsonGenerator.writeArrayFieldStart("ports");
+ for (Port port : sw.getPorts()) {
+ jsonGenerator.writeObject(port);
+ }
+ jsonGenerator.writeEndArray();
+ jsonGenerator.writeEndObject();
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/web/DatastoreLinksResource.java b/src/main/java/net/onrc/onos/core/topology/web/DatastoreLinksResource.java
index 4837055..0f3b85c 100644
--- a/src/main/java/net/onrc/onos/core/topology/web/DatastoreLinksResource.java
+++ b/src/main/java/net/onrc/onos/core/topology/web/DatastoreLinksResource.java
@@ -7,8 +7,8 @@
public class DatastoreLinksResource extends ServerResource {
- @Get("json")
- public Iterable<KVLink> retrieve() {
- return KVLink.getAllLinks();
- }
+ @Get("json")
+ public Iterable<KVLink> retrieve() {
+ return KVLink.getAllLinks();
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/web/DatastorePortsResource.java b/src/main/java/net/onrc/onos/core/topology/web/DatastorePortsResource.java
index 46eaf1a..2ffb476 100644
--- a/src/main/java/net/onrc/onos/core/topology/web/DatastorePortsResource.java
+++ b/src/main/java/net/onrc/onos/core/topology/web/DatastorePortsResource.java
@@ -7,8 +7,8 @@
public class DatastorePortsResource extends ServerResource {
- @Get("json")
- public Iterable<KVPort> retrieve() {
- return KVPort.getAllPorts();
- }
+ @Get("json")
+ public Iterable<KVPort> retrieve() {
+ return KVPort.getAllPorts();
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/web/DatastoreSwitchesResource.java b/src/main/java/net/onrc/onos/core/topology/web/DatastoreSwitchesResource.java
index fe2cfcd..9459764 100644
--- a/src/main/java/net/onrc/onos/core/topology/web/DatastoreSwitchesResource.java
+++ b/src/main/java/net/onrc/onos/core/topology/web/DatastoreSwitchesResource.java
@@ -6,10 +6,10 @@
import org.restlet.resource.ServerResource;
public class DatastoreSwitchesResource extends ServerResource {
-
- @Get("json")
- public Iterable<KVSwitch> retrieve() {
- return KVSwitch.getAllSwitches();
- }
+
+ @Get("json")
+ public Iterable<KVSwitch> retrieve() {
+ return KVSwitch.getAllSwitches();
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/web/NetworkGraphLinksResource.java b/src/main/java/net/onrc/onos/core/topology/web/NetworkGraphLinksResource.java
index 5886aa5..8d4bc93 100644
--- a/src/main/java/net/onrc/onos/core/topology/web/NetworkGraphLinksResource.java
+++ b/src/main/java/net/onrc/onos/core/topology/web/NetworkGraphLinksResource.java
@@ -15,29 +15,29 @@
import org.slf4j.LoggerFactory;
public class NetworkGraphLinksResource extends ServerResource {
-
- private static final Logger log = LoggerFactory.getLogger(NetworkGraphLinksResource.class);
- @Get("json")
- public String retrieve() {
- INetworkGraphService networkGraphService = (INetworkGraphService) getContext().getAttributes().
- get(INetworkGraphService.class.getCanonicalName());
-
- NetworkGraph graph = networkGraphService.getNetworkGraph();
+ private static final Logger log = LoggerFactory.getLogger(NetworkGraphLinksResource.class);
- ObjectMapper mapper = new ObjectMapper();
- SimpleModule module = new SimpleModule("module", new Version(1, 0, 0, null));
- module.addSerializer(new LinkSerializer());
- mapper.registerModule(module);
-
- try {
- graph.acquireReadLock();
- return mapper.writeValueAsString(graph.getLinks());
- } catch (IOException e) {
- log.error("Error writing link list to JSON", e);
- return "";
- } finally {
- graph.releaseReadLock();
- }
- }
+ @Get("json")
+ public String retrieve() {
+ INetworkGraphService networkGraphService = (INetworkGraphService) getContext().getAttributes().
+ get(INetworkGraphService.class.getCanonicalName());
+
+ NetworkGraph graph = networkGraphService.getNetworkGraph();
+
+ ObjectMapper mapper = new ObjectMapper();
+ SimpleModule module = new SimpleModule("module", new Version(1, 0, 0, null));
+ module.addSerializer(new LinkSerializer());
+ mapper.registerModule(module);
+
+ try {
+ graph.acquireReadLock();
+ return mapper.writeValueAsString(graph.getLinks());
+ } catch (IOException e) {
+ log.error("Error writing link list to JSON", e);
+ return "";
+ } finally {
+ graph.releaseReadLock();
+ }
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/web/NetworkGraphShortestPathResource.java b/src/main/java/net/onrc/onos/core/topology/web/NetworkGraphShortestPathResource.java
index 1d4164b..6650efc 100644
--- a/src/main/java/net/onrc/onos/core/topology/web/NetworkGraphShortestPathResource.java
+++ b/src/main/java/net/onrc/onos/core/topology/web/NetworkGraphShortestPathResource.java
@@ -28,54 +28,54 @@
@Get("json")
public String retrieve() {
- INetworkGraphService networkGraphService =
- (INetworkGraphService)getContext().getAttributes().
- get(INetworkGraphService.class.getCanonicalName());
+ INetworkGraphService networkGraphService =
+ (INetworkGraphService) getContext().getAttributes().
+ get(INetworkGraphService.class.getCanonicalName());
- NetworkGraph graph = networkGraphService.getNetworkGraph();
+ NetworkGraph graph = networkGraphService.getNetworkGraph();
- ObjectMapper mapper = new ObjectMapper();
- SimpleModule module = new SimpleModule("module", new Version(1, 0, 0, null));
- module.addSerializer(new LinkSerializer());
- mapper.registerModule(module);
+ ObjectMapper mapper = new ObjectMapper();
+ SimpleModule module = new SimpleModule("module", new Version(1, 0, 0, null));
+ module.addSerializer(new LinkSerializer());
+ mapper.registerModule(module);
- //
- // Fetch the attributes
- //
- String srcDpidStr = (String)getRequestAttributes().get("src-dpid");
- String dstDpidStr = (String)getRequestAttributes().get("dst-dpid");
- Dpid srcDpid = new Dpid(srcDpidStr);
- Dpid dstDpid = new Dpid(dstDpidStr);
- log.debug("Getting Shortest Path {}--{}", srcDpidStr, dstDpidStr);
+ //
+ // Fetch the attributes
+ //
+ String srcDpidStr = (String) getRequestAttributes().get("src-dpid");
+ String dstDpidStr = (String) getRequestAttributes().get("dst-dpid");
+ Dpid srcDpid = new Dpid(srcDpidStr);
+ Dpid dstDpid = new Dpid(dstDpidStr);
+ log.debug("Getting Shortest Path {}--{}", srcDpidStr, dstDpidStr);
- //
- // Do the Shortest Path computation and return the result: list of
- // links.
- //
- try {
- graph.acquireReadLock();
- Switch srcSwitch = graph.getSwitch(srcDpid.value());
- Switch dstSwitch = graph.getSwitch(dstDpid.value());
- if ((srcSwitch == null) || (dstSwitch == null))
- return "";
- ConstrainedBFSTree bfsTree = new ConstrainedBFSTree(srcSwitch);
- Path path = bfsTree.getPath(dstSwitch);
- List<Link> links = new LinkedList<>();
- for (LinkEvent linkEvent : path) {
- Link link = graph.getLink(linkEvent.getSrc().getDpid(),
- linkEvent.getSrc().getNumber(),
- linkEvent.getDst().getDpid(),
- linkEvent.getDst().getNumber());
- if (link == null)
- return "";
- links.add(link);
- }
- return mapper.writeValueAsString(links);
- } catch (IOException e) {
- log.error("Error writing Shortest Path to JSON", e);
- return "";
- } finally {
- graph.releaseReadLock();
- }
+ //
+ // Do the Shortest Path computation and return the result: list of
+ // links.
+ //
+ try {
+ graph.acquireReadLock();
+ Switch srcSwitch = graph.getSwitch(srcDpid.value());
+ Switch dstSwitch = graph.getSwitch(dstDpid.value());
+ if ((srcSwitch == null) || (dstSwitch == null))
+ return "";
+ ConstrainedBFSTree bfsTree = new ConstrainedBFSTree(srcSwitch);
+ Path path = bfsTree.getPath(dstSwitch);
+ List<Link> links = new LinkedList<>();
+ for (LinkEvent linkEvent : path) {
+ Link link = graph.getLink(linkEvent.getSrc().getDpid(),
+ linkEvent.getSrc().getNumber(),
+ linkEvent.getDst().getDpid(),
+ linkEvent.getDst().getNumber());
+ if (link == null)
+ return "";
+ links.add(link);
+ }
+ return mapper.writeValueAsString(links);
+ } catch (IOException e) {
+ log.error("Error writing Shortest Path to JSON", e);
+ return "";
+ } finally {
+ graph.releaseReadLock();
+ }
}
}
diff --git a/src/main/java/net/onrc/onos/core/topology/web/NetworkGraphSwitchesResource.java b/src/main/java/net/onrc/onos/core/topology/web/NetworkGraphSwitchesResource.java
index 059771f..3a053e5 100644
--- a/src/main/java/net/onrc/onos/core/topology/web/NetworkGraphSwitchesResource.java
+++ b/src/main/java/net/onrc/onos/core/topology/web/NetworkGraphSwitchesResource.java
@@ -16,30 +16,30 @@
import org.slf4j.LoggerFactory;
public class NetworkGraphSwitchesResource extends ServerResource {
-
- private static final Logger log = LoggerFactory.getLogger(NetworkGraphSwitchesResource.class);
- @Get("json")
- public String retrieve() {
- INetworkGraphService networkGraphService = (INetworkGraphService) getContext().getAttributes().
- get(INetworkGraphService.class.getCanonicalName());
-
- NetworkGraph graph = networkGraphService.getNetworkGraph();
-
- ObjectMapper mapper = new ObjectMapper();
- SimpleModule module = new SimpleModule("module", new Version(1, 0, 0, null));
- module.addSerializer(new SwitchSerializer());
- module.addSerializer(new PortSerializer());
- mapper.registerModule(module);
-
- try {
- graph.acquireReadLock();
- return mapper.writeValueAsString(graph.getSwitches());
- } catch (IOException e) {
- log.error("Error writing switch list to JSON", e);
- return "";
- } finally {
- graph.releaseReadLock();
- }
- }
+ private static final Logger log = LoggerFactory.getLogger(NetworkGraphSwitchesResource.class);
+
+ @Get("json")
+ public String retrieve() {
+ INetworkGraphService networkGraphService = (INetworkGraphService) getContext().getAttributes().
+ get(INetworkGraphService.class.getCanonicalName());
+
+ NetworkGraph graph = networkGraphService.getNetworkGraph();
+
+ ObjectMapper mapper = new ObjectMapper();
+ SimpleModule module = new SimpleModule("module", new Version(1, 0, 0, null));
+ module.addSerializer(new SwitchSerializer());
+ module.addSerializer(new PortSerializer());
+ mapper.registerModule(module);
+
+ try {
+ graph.acquireReadLock();
+ return mapper.writeValueAsString(graph.getSwitches());
+ } catch (IOException e) {
+ log.error("Error writing switch list to JSON", e);
+ return "";
+ } finally {
+ graph.releaseReadLock();
+ }
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/topology/web/NetworkGraphWebRoutable.java b/src/main/java/net/onrc/onos/core/topology/web/NetworkGraphWebRoutable.java
index c6791e5..8f32f8a 100644
--- a/src/main/java/net/onrc/onos/core/topology/web/NetworkGraphWebRoutable.java
+++ b/src/main/java/net/onrc/onos/core/topology/web/NetworkGraphWebRoutable.java
@@ -8,33 +8,33 @@
public class NetworkGraphWebRoutable implements RestletRoutable {
- @Override
- public Restlet getRestlet(Context context) {
- Router router = new Router(context);
- // leaving old path there for compatibility
- router.attach("/rc/switches/json", DatastoreSwitchesResource.class);
- router.attach("/rc/links/json", DatastoreLinksResource.class);
- router.attach("/rc/ports/json", DatastorePortsResource.class);
+ @Override
+ public Restlet getRestlet(Context context) {
+ Router router = new Router(context);
+ // leaving old path there for compatibility
+ router.attach("/rc/switches/json", DatastoreSwitchesResource.class);
+ router.attach("/rc/links/json", DatastoreLinksResource.class);
+ router.attach("/rc/ports/json", DatastorePortsResource.class);
- // debug API to dump datastore content
- router.attach("/ds/switches/json", DatastoreSwitchesResource.class);
- router.attach("/ds/links/json", DatastoreLinksResource.class);
- router.attach("/ds/ports/json", DatastorePortsResource.class);
+ // debug API to dump datastore content
+ router.attach("/ds/switches/json", DatastoreSwitchesResource.class);
+ router.attach("/ds/links/json", DatastoreLinksResource.class);
+ router.attach("/ds/ports/json", DatastorePortsResource.class);
- router.attach("/ng/switches/json", NetworkGraphSwitchesResource.class);
- router.attach("/ng/links/json", NetworkGraphLinksResource.class);
- router.attach("/ng/shortest-path/{src-dpid}/{dst-dpid}/json", NetworkGraphShortestPathResource.class);
-
- // Old URLs for compatibility
- router.attach("/topology/switches/json", NetworkGraphSwitchesResource.class);
- router.attach("/topology/links/json", NetworkGraphLinksResource.class);
-
- return router;
- }
+ router.attach("/ng/switches/json", NetworkGraphSwitchesResource.class);
+ router.attach("/ng/links/json", NetworkGraphLinksResource.class);
+ router.attach("/ng/shortest-path/{src-dpid}/{dst-dpid}/json", NetworkGraphShortestPathResource.class);
- @Override
- public String basePath() {
- return "/wm/onos";
- }
+ // Old URLs for compatibility
+ router.attach("/topology/switches/json", NetworkGraphSwitchesResource.class);
+ router.attach("/topology/links/json", NetworkGraphLinksResource.class);
+
+ return router;
+ }
+
+ @Override
+ public String basePath() {
+ return "/wm/onos";
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/util/CallerId.java b/src/main/java/net/onrc/onos/core/util/CallerId.java
index bcd9704..f58d69f 100644
--- a/src/main/java/net/onrc/onos/core/util/CallerId.java
+++ b/src/main/java/net/onrc/onos/core/util/CallerId.java
@@ -11,15 +11,17 @@
/**
* Default constructor.
*/
- public CallerId() {}
-
+ public CallerId() {
+ }
+
/**
* Copy constructor
+ *
* @param otherCallerId
*/
public CallerId(CallerId otherCallerId) {
- // Note: make a full copy if we change value to a mutable type
- value = otherCallerId.value;
+ // Note: make a full copy if we change value to a mutable type
+ value = otherCallerId.value;
}
/**
@@ -28,7 +30,7 @@
* @param value the value to use.
*/
public CallerId(String value) {
- this.value = value;
+ this.value = value;
}
/**
@@ -37,7 +39,9 @@
* @return the value of the Caller ID.
*/
@JsonProperty("value")
- public String value() { return value; }
+ public String value() {
+ return value;
+ }
/**
* Set the value of the Caller ID.
@@ -46,7 +50,7 @@
*/
@JsonProperty("value")
public void setValue(String value) {
- this.value = value;
+ this.value = value;
}
/**
@@ -56,22 +60,22 @@
*/
@Override
public String toString() {
- return value;
+ return value;
}
-
+
@Override
public boolean equals(Object other) {
- if (!(other instanceof CallerId)) {
- return false;
+ if (!(other instanceof CallerId)) {
+ return false;
+ }
+
+ CallerId otherCallerId = (CallerId) other;
+
+ return value.equals(otherCallerId.value);
}
-
- CallerId otherCallerId = (CallerId) other;
-
- return value.equals(otherCallerId.value);
- }
-
+
@Override
public int hashCode() {
- return value.hashCode();
+ return value.hashCode();
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/DataPath.java b/src/main/java/net/onrc/onos/core/util/DataPath.java
index 7dd1f51..1aa514c 100644
--- a/src/main/java/net/onrc/onos/core/util/DataPath.java
+++ b/src/main/java/net/onrc/onos/core/util/DataPath.java
@@ -8,17 +8,17 @@
* The data forwarding path state from a source to a destination.
*/
public class DataPath {
- private SwitchPort srcPort; // The source port
- private SwitchPort dstPort; // The destination port
- private ArrayList<FlowEntry> flowEntries; // The Flow Entries
+ private SwitchPort srcPort; // The source port
+ private SwitchPort dstPort; // The destination port
+ private ArrayList<FlowEntry> flowEntries; // The Flow Entries
/**
* Default constructor.
*/
public DataPath() {
- srcPort = new SwitchPort();
- dstPort = new SwitchPort();
- flowEntries = new ArrayList<FlowEntry>();
+ srcPort = new SwitchPort();
+ dstPort = new SwitchPort();
+ flowEntries = new ArrayList<FlowEntry>();
}
/**
@@ -27,7 +27,9 @@
* @return the data path source port.
*/
@JsonProperty("srcPort")
- public SwitchPort srcPort() { return srcPort; }
+ public SwitchPort srcPort() {
+ return srcPort;
+ }
/**
* Set the data path source port.
@@ -36,7 +38,7 @@
*/
@JsonProperty("srcPort")
public void setSrcPort(SwitchPort srcPort) {
- this.srcPort = srcPort;
+ this.srcPort = srcPort;
}
/**
@@ -45,7 +47,9 @@
* @return the data path destination port.
*/
@JsonProperty("dstPort")
- public SwitchPort dstPort() { return dstPort; }
+ public SwitchPort dstPort() {
+ return dstPort;
+ }
/**
* Set the data path destination port.
@@ -54,7 +58,7 @@
*/
@JsonProperty("dstPort")
public void setDstPort(SwitchPort dstPort) {
- this.dstPort = dstPort;
+ this.dstPort = dstPort;
}
/**
@@ -63,7 +67,9 @@
* @return the data path flow entries.
*/
@JsonProperty("flowEntries")
- public ArrayList<FlowEntry> flowEntries() { return flowEntries; }
+ public ArrayList<FlowEntry> flowEntries() {
+ return flowEntries;
+ }
/**
* Set the data path flow entries.
@@ -72,7 +78,7 @@
*/
@JsonProperty("flowEntries")
public void setFlowEntries(ArrayList<FlowEntry> flowEntries) {
- this.flowEntries = flowEntries;
+ this.flowEntries = flowEntries;
}
/**
@@ -81,63 +87,63 @@
* @param flowPathFlags the Flow Path Flags to apply.
*/
public void applyFlowPathFlags(FlowPathFlags flowPathFlags) {
- if (flowPathFlags == null)
- return; // Nothing to do
+ if (flowPathFlags == null)
+ return; // Nothing to do
- // Discard the first Flow Entry
- if (flowPathFlags.isDiscardFirstHopEntry()) {
- if (flowEntries.size() > 0)
- flowEntries.remove(0);
- }
+ // Discard the first Flow Entry
+ if (flowPathFlags.isDiscardFirstHopEntry()) {
+ if (flowEntries.size() > 0)
+ flowEntries.remove(0);
+ }
- // Keep only the first Flow Entry
- if (flowPathFlags.isKeepOnlyFirstHopEntry()) {
- if (flowEntries.size() > 1) {
- FlowEntry flowEntry = flowEntries.get(0);
- flowEntries.clear();
- flowEntries.add(flowEntry);
- }
- }
+ // Keep only the first Flow Entry
+ if (flowPathFlags.isKeepOnlyFirstHopEntry()) {
+ if (flowEntries.size() > 1) {
+ FlowEntry flowEntry = flowEntries.get(0);
+ flowEntries.clear();
+ flowEntries.add(flowEntry);
+ }
+ }
}
/**
* Remove Flow Entries that were deleted.
*/
public void removeDeletedFlowEntries() {
- //
- // NOTE: We create a new ArrayList, and add only the Flow Entries
- // that are NOT FE_USER_DELETE.
- // This is sub-optimal: if it adds notable processing cost,
- // the Flow Entries container should be changed to LinkedList
- // or some other container that has O(1) cost of removing an entry.
- //
+ //
+ // NOTE: We create a new ArrayList, and add only the Flow Entries
+ // that are NOT FE_USER_DELETE.
+ // This is sub-optimal: if it adds notable processing cost,
+ // the Flow Entries container should be changed to LinkedList
+ // or some other container that has O(1) cost of removing an entry.
+ //
- // Test first whether any Flow Entry was deleted
- boolean foundDeletedFlowEntry = false;
- for (FlowEntry flowEntry : this.flowEntries) {
- if (flowEntry.flowEntryUserState() ==
- FlowEntryUserState.FE_USER_DELETE) {
- foundDeletedFlowEntry = true;
- break;
- }
- }
- if (! foundDeletedFlowEntry)
- return; // Nothing to do
+ // Test first whether any Flow Entry was deleted
+ boolean foundDeletedFlowEntry = false;
+ for (FlowEntry flowEntry : this.flowEntries) {
+ if (flowEntry.flowEntryUserState() ==
+ FlowEntryUserState.FE_USER_DELETE) {
+ foundDeletedFlowEntry = true;
+ break;
+ }
+ }
+ if (!foundDeletedFlowEntry)
+ return; // Nothing to do
- // Create a new collection and exclude the deleted flow entries
- ArrayList<FlowEntry> newFlowEntries = new ArrayList<FlowEntry>();
- for (FlowEntry flowEntry : this.flowEntries()) {
- if (flowEntry.flowEntryUserState() !=
- FlowEntryUserState.FE_USER_DELETE) {
- newFlowEntries.add(flowEntry);
- }
- }
- setFlowEntries(newFlowEntries);
+ // Create a new collection and exclude the deleted flow entries
+ ArrayList<FlowEntry> newFlowEntries = new ArrayList<FlowEntry>();
+ for (FlowEntry flowEntry : this.flowEntries()) {
+ if (flowEntry.flowEntryUserState() !=
+ FlowEntryUserState.FE_USER_DELETE) {
+ newFlowEntries.add(flowEntry);
+ }
+ }
+ setFlowEntries(newFlowEntries);
}
/**
* Convert the data path to a string.
- *
+ * <p/>
* The string has the following form:
* [src=01:01:01:01:01:01:01:01/1111 flowEntry=<entry1> flowEntry=<entry2> flowEntry=<entry3> dst=02:02:02:02:02:02:02:02/2222]
*
@@ -145,13 +151,13 @@
*/
@Override
public String toString() {
- String ret = "[src=" + this.srcPort.toString();
+ String ret = "[src=" + this.srcPort.toString();
- for (FlowEntry fe : flowEntries) {
- ret += " flowEntry=" + fe.toString();
- }
- ret += " dst=" + this.dstPort.toString() + "]";
+ for (FlowEntry fe : flowEntries) {
+ ret += " flowEntry=" + fe.toString();
+ }
+ ret += " dst=" + this.dstPort.toString() + "]";
- return ret;
+ return ret;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/DataPathEndpoints.java b/src/main/java/net/onrc/onos/core/util/DataPathEndpoints.java
index eeb5aaa..70edfee 100644
--- a/src/main/java/net/onrc/onos/core/util/DataPathEndpoints.java
+++ b/src/main/java/net/onrc/onos/core/util/DataPathEndpoints.java
@@ -7,8 +7,8 @@
* The class representing the Data Path Endpoints.
*/
public class DataPathEndpoints {
- private SwitchPort srcPort; // The source port
- private SwitchPort dstPort; // The destination port
+ private SwitchPort srcPort; // The source port
+ private SwitchPort dstPort; // The destination port
/**
* Default constructor.
@@ -23,8 +23,8 @@
* @param dstPort the destination port to use.
*/
public DataPathEndpoints(SwitchPort srcPort, SwitchPort dstPort) {
- this.srcPort = srcPort;
- this.dstPort = dstPort;
+ this.srcPort = srcPort;
+ this.dstPort = dstPort;
}
/**
@@ -33,7 +33,9 @@
* @return the data path source port.
*/
@JsonProperty("srcPort")
- public SwitchPort srcPort() { return srcPort; }
+ public SwitchPort srcPort() {
+ return srcPort;
+ }
/**
* Set the data path source port.
@@ -42,7 +44,7 @@
*/
@JsonProperty("srcPort")
public void setSrcPort(SwitchPort srcPort) {
- this.srcPort = srcPort;
+ this.srcPort = srcPort;
}
/**
@@ -51,7 +53,9 @@
* @return the data path destination port.
*/
@JsonProperty("dstPort")
- public SwitchPort dstPort() { return dstPort; }
+ public SwitchPort dstPort() {
+ return dstPort;
+ }
/**
* Set the data path destination port.
@@ -60,12 +64,12 @@
*/
@JsonProperty("dstPort")
public void setDstPort(SwitchPort dstPort) {
- this.dstPort = dstPort;
+ this.dstPort = dstPort;
}
/**
* Convert the data path endpoints to a string.
- *
+ * <p/>
* The string has the following form:
* [src=01:01:01:01:01:01:01:01/1111 dst=02:02:02:02:02:02:02:02/2222]
*
@@ -73,8 +77,8 @@
*/
@Override
public String toString() {
- String ret = "[src=" + this.srcPort.toString() +
- " dst=" + this.dstPort.toString() + "]";
- return ret;
+ String ret = "[src=" + this.srcPort.toString() +
+ " dst=" + this.dstPort.toString() + "]";
+ return ret;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/Dpid.java b/src/main/java/net/onrc/onos/core/util/Dpid.java
index dcc3a7c..80ebc15 100644
--- a/src/main/java/net/onrc/onos/core/util/Dpid.java
+++ b/src/main/java/net/onrc/onos/core/util/Dpid.java
@@ -10,8 +10,8 @@
/**
* The class representing a network switch DPID.
*/
-@JsonDeserialize(using=DpidDeserializer.class)
-@JsonSerialize(using=DpidSerializer.class)
+@JsonDeserialize(using = DpidDeserializer.class)
+@JsonSerialize(using = DpidSerializer.class)
public class Dpid {
static public final long UNKNOWN = 0;
@@ -21,7 +21,7 @@
* Default constructor.
*/
public Dpid() {
- this.value = Dpid.UNKNOWN;
+ this.value = Dpid.UNKNOWN;
}
/**
@@ -30,7 +30,7 @@
* @param value the value to use.
*/
public Dpid(long value) {
- this.value = value;
+ this.value = value;
}
/**
@@ -39,7 +39,7 @@
* @param value the value to use.
*/
public Dpid(String value) {
- this.value = HexString.toLong(value);
+ this.value = HexString.toLong(value);
}
/**
@@ -47,7 +47,9 @@
*
* @return the value of the DPID.
*/
- public long value() { return value; }
+ public long value() {
+ return value;
+ }
/**
* Set the value of the DPID.
@@ -55,7 +57,7 @@
* @param value the value to set.
*/
public void setValue(long value) {
- this.value = value;
+ this.value = value;
}
/**
@@ -65,24 +67,24 @@
*/
@Override
public String toString() {
- return HexString.toHexString(this.value);
+ return HexString.toHexString(this.value);
}
@Override
public boolean equals(Object other) {
- if (!(other instanceof Dpid)) {
- return false;
- }
+ if (!(other instanceof Dpid)) {
+ return false;
+ }
- Dpid otherDpid = (Dpid) other;
+ Dpid otherDpid = (Dpid) other;
- return value == otherDpid.value;
+ return value == otherDpid.value;
}
@Override
public int hashCode() {
- int hash = 17;
- hash += 31 * hash + (int)(value ^ value >>> 32);
- return hash;
+ int hash = 17;
+ hash += 31 * hash + (int) (value ^ value >>> 32);
+ return hash;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/EventEntry.java b/src/main/java/net/onrc/onos/core/util/EventEntry.java
index fe4c3ac..e1abcaf 100644
--- a/src/main/java/net/onrc/onos/core/util/EventEntry.java
+++ b/src/main/java/net/onrc/onos/core/util/EventEntry.java
@@ -8,12 +8,12 @@
* The event types.
*/
public enum Type {
- ENTRY_ADD, // Add or update an entry
- ENTRY_REMOVE // Remove an entry
+ ENTRY_ADD, // Add or update an entry
+ ENTRY_REMOVE // Remove an entry
}
- private Type eventType; // The event type
- private T eventData; // The relevant event data entry
+ private Type eventType; // The event type
+ private T eventData; // The relevant event data entry
/**
* Constructor for a given event type and event-related data entry.
@@ -22,8 +22,8 @@
* @param eventData the event data entry.
*/
public EventEntry(EventEntry.Type eventType, T eventData) {
- this.eventType = eventType;
- this.eventData = eventData;
+ this.eventType = eventType;
+ this.eventData = eventData;
}
/**
@@ -32,7 +32,7 @@
* @return true if the event type is ENTRY_ADD, otherwise false.
*/
public boolean isAdd() {
- return (this.eventType == Type.ENTRY_ADD);
+ return (this.eventType == Type.ENTRY_ADD);
}
/**
@@ -41,7 +41,7 @@
* @return true if the event type is ENTRY_REMOVE, otherwise false.
*/
public boolean isRemove() {
- return (this.eventType == Type.ENTRY_REMOVE);
+ return (this.eventType == Type.ENTRY_REMOVE);
}
/**
@@ -50,7 +50,7 @@
* @return the event type.
*/
public EventEntry.Type eventType() {
- return this.eventType;
+ return this.eventType;
}
/**
@@ -59,6 +59,6 @@
* @return the event-related data entry.
*/
public T eventData() {
- return this.eventData;
+ return this.eventData;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/FlowEntry.java b/src/main/java/net/onrc/onos/core/util/FlowEntry.java
index fb5e3a3..0204590 100644
--- a/src/main/java/net/onrc/onos/core/util/FlowEntry.java
+++ b/src/main/java/net/onrc/onos/core/util/FlowEntry.java
@@ -6,25 +6,25 @@
/**
* The class representing the Flow Entry.
- *
+ * <p/>
* NOTE: The specification is incomplete. E.g., the entry needs to
* support multiple in-ports and multiple out-ports.
*/
public class FlowEntry {
- private FlowId flowId; // FlowID of the Flow Entry
- private FlowEntryId flowEntryId; // The Flow Entry ID
- private int idleTimeout; // The Flow idle timeout
- private int hardTimeout; // The Flow hard timeout
- private int priority; // The Flow priority
- private FlowEntryMatch flowEntryMatch; // The Flow Entry Match
- private FlowEntryActions flowEntryActions; // The Flow Entry Actions
- private Dpid dpid; // The Switch DPID
- private Port inPort; // The Switch incoming port. Used only
- // when the entry is used to return
- // Shortest Path computation.
- private Port outPort; // The Switch outgoing port. Used only
- // when the entry is used to return
- // Shortest Path computation.
+ private FlowId flowId; // FlowID of the Flow Entry
+ private FlowEntryId flowEntryId; // The Flow Entry ID
+ private int idleTimeout; // The Flow idle timeout
+ private int hardTimeout; // The Flow hard timeout
+ private int priority; // The Flow priority
+ private FlowEntryMatch flowEntryMatch; // The Flow Entry Match
+ private FlowEntryActions flowEntryActions; // The Flow Entry Actions
+ private Dpid dpid; // The Switch DPID
+ private Port inPort; // The Switch incoming port. Used only
+ // when the entry is used to return
+ // Shortest Path computation.
+ private Port outPort; // The Switch outgoing port. Used only
+ // when the entry is used to return
+ // Shortest Path computation.
private FlowEntryUserState flowEntryUserState; // The Flow Entry User state
private FlowEntrySwitchState flowEntrySwitchState; // The Flow Entry Switch state
// The Flow Entry Error state (if FlowEntrySwitchState is FE_SWITCH_FAILED)
@@ -34,88 +34,88 @@
* Default constructor.
*/
public FlowEntry() {
- // TODO: Test code
- /*
- MACAddress mac = MACAddress.valueOf("01:02:03:04:05:06");
- IPv4 ipv4 = new IPv4("1.2.3.4");
- IPv4Net ipv4net = new IPv4Net("5.6.7.0/24");
+ // TODO: Test code
+ /*
+ MACAddress mac = MACAddress.valueOf("01:02:03:04:05:06");
+ IPv4 ipv4 = new IPv4("1.2.3.4");
+ IPv4Net ipv4net = new IPv4Net("5.6.7.0/24");
- flowEntryMatch = new FlowEntryMatch();
- flowEntryMatch.enableInPort(new Port((short)10));
- flowEntryMatch.enableSrcMac(mac);
- flowEntryMatch.enableDstMac(mac);
- flowEntryMatch.enableVlanId((short)20);
- flowEntryMatch.enableVlanPriority((byte)30);
- flowEntryMatch.enableEthernetFrameType((short)40);
- flowEntryMatch.enableIpToS((byte)50);
- flowEntryMatch.enableIpProto((byte)60);
- flowEntryMatch.enableSrcIPv4Net(ipv4net);
- flowEntryMatch.enableDstIPv4Net(ipv4net);
- flowEntryMatch.enableSrcTcpUdpPort((short)70);
- flowEntryMatch.enableDstTcpUdpPort((short)80);
+ flowEntryMatch = new FlowEntryMatch();
+ flowEntryMatch.enableInPort(new Port((short)10));
+ flowEntryMatch.enableSrcMac(mac);
+ flowEntryMatch.enableDstMac(mac);
+ flowEntryMatch.enableVlanId((short)20);
+ flowEntryMatch.enableVlanPriority((byte)30);
+ flowEntryMatch.enableEthernetFrameType((short)40);
+ flowEntryMatch.enableIpToS((byte)50);
+ flowEntryMatch.enableIpProto((byte)60);
+ flowEntryMatch.enableSrcIPv4Net(ipv4net);
+ flowEntryMatch.enableDstIPv4Net(ipv4net);
+ flowEntryMatch.enableSrcTcpUdpPort((short)70);
+ flowEntryMatch.enableDstTcpUdpPort((short)80);
- FlowEntryAction action = null;
- FlowEntryActions actions = new FlowEntryActions();
+ FlowEntryAction action = null;
+ FlowEntryActions actions = new FlowEntryActions();
- action = new FlowEntryAction();
- action.setActionOutput(new Port((short)12));
- actions.addAction(action);
+ action = new FlowEntryAction();
+ action.setActionOutput(new Port((short)12));
+ actions.addAction(action);
- action = new FlowEntryAction();
- action.setActionOutputToController((short)13);
- actions.addAction(action);
+ action = new FlowEntryAction();
+ action.setActionOutputToController((short)13);
+ actions.addAction(action);
- action = new FlowEntryAction();
- action.setActionSetVlanId((short)14);
- actions.addAction(action);
+ action = new FlowEntryAction();
+ action.setActionSetVlanId((short)14);
+ actions.addAction(action);
- action = new FlowEntryAction();
- action.setActionSetVlanPriority((byte)15);
- actions.addAction(action);
+ action = new FlowEntryAction();
+ action.setActionSetVlanPriority((byte)15);
+ actions.addAction(action);
- action = new FlowEntryAction();
- action.setActionStripVlan(true);
- actions.addAction(action);
+ action = new FlowEntryAction();
+ action.setActionStripVlan(true);
+ actions.addAction(action);
- action = new FlowEntryAction();
- action.setActionSetEthernetSrcAddr(mac);
- actions.addAction(action);
+ action = new FlowEntryAction();
+ action.setActionSetEthernetSrcAddr(mac);
+ actions.addAction(action);
- action = new FlowEntryAction();
- action.setActionSetEthernetDstAddr(mac);
- actions.addAction(action);
+ action = new FlowEntryAction();
+ action.setActionSetEthernetDstAddr(mac);
+ actions.addAction(action);
- action = new FlowEntryAction();
- action.setActionSetIPv4SrcAddr(ipv4);
- actions.addAction(action);
+ action = new FlowEntryAction();
+ action.setActionSetIPv4SrcAddr(ipv4);
+ actions.addAction(action);
- action = new FlowEntryAction();
- action.setActionSetIPv4DstAddr(ipv4);
- actions.addAction(action);
+ action = new FlowEntryAction();
+ action.setActionSetIPv4DstAddr(ipv4);
+ actions.addAction(action);
- action = new FlowEntryAction();
- action.setActionSetIpToS((byte)16);
- actions.addAction(action);
+ action = new FlowEntryAction();
+ action.setActionSetIpToS((byte)16);
+ actions.addAction(action);
- action = new FlowEntryAction();
- action.setActionSetTcpUdpSrcPort((short)17);
- actions.addAction(action);
+ action = new FlowEntryAction();
+ action.setActionSetTcpUdpSrcPort((short)17);
+ actions.addAction(action);
- action = new FlowEntryAction();
- action.setActionSetTcpUdpDstPort((short)18);
- actions.addAction(action);
+ action = new FlowEntryAction();
+ action.setActionSetTcpUdpDstPort((short)18);
+ actions.addAction(action);
- action = new FlowEntryAction();
- action.setActionEnqueue(new Port((short)19), 20);
- actions.addAction(action);
+ action = new FlowEntryAction();
+ action.setActionEnqueue(new Port((short)19), 20);
+ actions.addAction(action);
- setFlowEntryActions(actions);
- */
+ setFlowEntryActions(actions);
+ */
- priority = FlowPath.PRIORITY_DEFAULT;
- flowEntryActions = new FlowEntryActions();
- flowEntryUserState = FlowEntryUserState.FE_USER_UNKNOWN;
- flowEntrySwitchState = FlowEntrySwitchState.FE_SWITCH_UNKNOWN;
+ priority = FlowPath.PRIORITY_DEFAULT;
+ flowEntryActions = new FlowEntryActions();
+ flowEntryUserState = FlowEntryUserState.FE_USER_UNKNOWN;
+ flowEntrySwitchState = FlowEntrySwitchState.FE_SWITCH_UNKNOWN;
}
/**
@@ -124,7 +124,9 @@
* @return the Flow ID.
*/
@JsonIgnore
- public FlowId flowId() { return flowId; }
+ public FlowId flowId() {
+ return flowId;
+ }
/**
* Set the Flow ID.
@@ -132,7 +134,7 @@
* @param flowId the Flow ID to set.
*/
public void setFlowId(FlowId flowId) {
- this.flowId = flowId;
+ this.flowId = flowId;
}
/**
@@ -142,9 +144,9 @@
*/
@JsonIgnore
public boolean isValidFlowId() {
- if (this.flowId == null)
- return false;
- return (this.flowId.isValid());
+ if (this.flowId == null)
+ return false;
+ return (this.flowId.isValid());
}
/**
@@ -153,7 +155,9 @@
* @return the Flow Entry ID.
*/
@JsonProperty("flowEntryId")
- public FlowEntryId flowEntryId() { return flowEntryId; }
+ public FlowEntryId flowEntryId() {
+ return flowEntryId;
+ }
/**
* Set the Flow Entry ID.
@@ -162,7 +166,7 @@
*/
@JsonProperty("flowEntryId")
public void setFlowEntryId(FlowEntryId flowEntryId) {
- this.flowEntryId = flowEntryId;
+ this.flowEntryId = flowEntryId;
}
/**
@@ -172,25 +176,27 @@
*/
@JsonIgnore
public boolean isValidFlowEntryId() {
- if (this.flowEntryId == null)
- return false;
- return (this.flowEntryId.isValid());
+ if (this.flowEntryId == null)
+ return false;
+ return (this.flowEntryId.isValid());
}
/**
* Get the flow idle timeout in seconds.
- *
+ * <p/>
* It should be an unsigned integer in the interval [0, 65535].
* If zero, the timeout is not set.
*
* @return the flow idle timeout.
*/
@JsonProperty("idleTimeout")
- public int idleTimeout() { return idleTimeout; }
+ public int idleTimeout() {
+ return idleTimeout;
+ }
/**
* Set the flow idle timeout in seconds.
- *
+ * <p/>
* It should be an unsigned integer in the interval [0, 65535].
* If zero, the timeout is not set.
*
@@ -198,23 +204,25 @@
*/
@JsonProperty("idleTimeout")
public void setIdleTimeout(int idleTimeout) {
- this.idleTimeout = 0xffff & idleTimeout;
+ this.idleTimeout = 0xffff & idleTimeout;
}
/**
* Get the flow hard timeout in seconds.
- *
+ * <p/>
* It should be an unsigned integer in the interval [0, 65535].
* If zero, the timeout is not set.
*
* @return the flow hard timeout.
*/
@JsonProperty("hardTimeout")
- public int hardTimeout() { return hardTimeout; }
+ public int hardTimeout() {
+ return hardTimeout;
+ }
/**
* Set the flow hard timeout in seconds.
- *
+ * <p/>
* It should be an unsigned integer in the interval [0, 65535].
* If zero, the timeout is not set.
*
@@ -222,29 +230,31 @@
*/
@JsonProperty("hardTimeout")
public void setHardTimeout(int hardTimeout) {
- this.hardTimeout = 0xffff & hardTimeout;
+ this.hardTimeout = 0xffff & hardTimeout;
}
/**
* Get the flow priority.
- *
+ * <p/>
* It should be an unsigned integer in the interval [0, 65535].
*
* @return the flow priority.
*/
@JsonProperty("priority")
- public int priority() { return priority; }
+ public int priority() {
+ return priority;
+ }
/**
* Set the flow priority.
- *
+ * <p/>
* It should be an unsigned integer in the interval [0, 65535].
*
* @param priority the flow priority to set.
*/
@JsonProperty("priority")
public void setPriority(int priority) {
- this.priority = 0xffff & priority;
+ this.priority = 0xffff & priority;
}
/**
@@ -253,7 +263,9 @@
* @return the Flow Entry Match.
*/
@JsonProperty("flowEntryMatch")
- public FlowEntryMatch flowEntryMatch() { return flowEntryMatch; }
+ public FlowEntryMatch flowEntryMatch() {
+ return flowEntryMatch;
+ }
/**
* Set the Flow Entry Match.
@@ -262,7 +274,7 @@
*/
@JsonProperty("flowEntryMatch")
public void setFlowEntryMatch(FlowEntryMatch flowEntryMatch) {
- this.flowEntryMatch = flowEntryMatch;
+ this.flowEntryMatch = flowEntryMatch;
}
/**
@@ -272,7 +284,7 @@
*/
@JsonProperty("flowEntryActions")
public FlowEntryActions flowEntryActions() {
- return flowEntryActions;
+ return flowEntryActions;
}
/**
@@ -282,7 +294,7 @@
*/
@JsonProperty("flowEntryActions")
public void setFlowEntryActions(FlowEntryActions flowEntryActions) {
- this.flowEntryActions = flowEntryActions;
+ this.flowEntryActions = flowEntryActions;
}
/**
@@ -291,7 +303,9 @@
* @return the Switch DPID.
*/
@JsonProperty("dpid")
- public Dpid dpid() { return dpid; }
+ public Dpid dpid() {
+ return dpid;
+ }
/**
* Set the Switch DPID.
@@ -300,51 +314,55 @@
*/
@JsonProperty("dpid")
public void setDpid(Dpid dpid) {
- this.dpid = dpid;
+ this.dpid = dpid;
}
/**
* Get the Switch incoming port.
- *
+ * <p/>
* Used only when the entry is used to return Shortest Path computation.
*
* @return the Switch incoming port.
*/
@JsonProperty("inPort")
- public Port inPort() { return inPort; }
+ public Port inPort() {
+ return inPort;
+ }
/**
* Set the Switch incoming port.
- *
+ * <p/>
* Used only when the entry is used to return Shortest Path computation.
*
* @param inPort the Switch incoming port to set.
*/
@JsonProperty("inPort")
public void setInPort(Port inPort) {
- this.inPort = inPort;
+ this.inPort = inPort;
}
/**
* Get the Switch outgoing port.
- *
+ * <p/>
* Used only when the entry is used to return Shortest Path computation.
*
* @return the Switch outgoing port.
*/
@JsonProperty("outPort")
- public Port outPort() { return outPort; }
+ public Port outPort() {
+ return outPort;
+ }
/**
* Set the Switch outgoing port.
- *
+ * <p/>
* Used only when the entry is used to return Shortest Path computation.
*
* @param outPort the Switch outgoing port to set.
*/
@JsonProperty("outPort")
public void setOutPort(Port outPort) {
- this.outPort = outPort;
+ this.outPort = outPort;
}
/**
@@ -354,7 +372,7 @@
*/
@JsonProperty("flowEntryUserState")
public FlowEntryUserState flowEntryUserState() {
- return flowEntryUserState;
+ return flowEntryUserState;
}
/**
@@ -364,12 +382,12 @@
*/
@JsonProperty("flowEntryUserState")
public void setFlowEntryUserState(FlowEntryUserState flowEntryUserState) {
- this.flowEntryUserState = flowEntryUserState;
+ this.flowEntryUserState = flowEntryUserState;
}
/**
* Get the Flow Entry Switch state.
- *
+ * <p/>
* The Flow Entry Error state is used if FlowEntrySwitchState is
* FE_SWITCH_FAILED.
*
@@ -377,12 +395,12 @@
*/
@JsonProperty("flowEntrySwitchState")
public FlowEntrySwitchState flowEntrySwitchState() {
- return flowEntrySwitchState;
+ return flowEntrySwitchState;
}
/**
* Set the Flow Entry Switch state.
- *
+ * <p/>
* The Flow Entry Error state is used if FlowEntrySwitchState is
* FE_SWITCH_FAILED.
*
@@ -390,7 +408,7 @@
*/
@JsonProperty("flowEntrySwitchState")
public void setFlowEntrySwitchState(FlowEntrySwitchState flowEntrySwitchState) {
- this.flowEntrySwitchState = flowEntrySwitchState;
+ this.flowEntrySwitchState = flowEntrySwitchState;
}
/**
@@ -400,7 +418,7 @@
*/
@JsonProperty("flowEntryErrorState")
public FlowEntryErrorState flowEntryErrorState() {
- return flowEntryErrorState;
+ return flowEntryErrorState;
}
/**
@@ -410,53 +428,54 @@
*/
@JsonProperty("flowEntryErrorState")
public void setFlowEntryErrorState(FlowEntryErrorState flowEntryErrorState) {
- this.flowEntryErrorState = flowEntryErrorState;
+ this.flowEntryErrorState = flowEntryErrorState;
}
/**
* Convert the flow entry to a string.
- *
+ * <p/>
* The string has the following form:
- * [flowEntryId=XXX idleTimeout=XXX hardTimeout=XXX priority=XXX
- * flowEntryMatch=XXX flowEntryActions=XXX dpid=XXX
- * inPort=XXX outPort=XXX flowEntryUserState=XXX flowEntrySwitchState=XXX
- * flowEntryErrorState=XXX]
+ * [flowEntryId=XXX idleTimeout=XXX hardTimeout=XXX priority=XXX
+ * flowEntryMatch=XXX flowEntryActions=XXX dpid=XXX
+ * inPort=XXX outPort=XXX flowEntryUserState=XXX flowEntrySwitchState=XXX
+ * flowEntryErrorState=XXX]
+ *
* @return the flow entry as a string.
*/
@Override
public String toString() {
- StringBuilder ret = new StringBuilder();
- if ( flowEntryId != null ) {
- ret.append("[flowEntryId=" + this.flowEntryId.toString());
- } else {
- ret.append("[");
- }
- if ( flowId != null ) {
- ret.append(" flowId=" + this.flowId.toString());
- }
- ret.append(" idleTimeout=" + this.idleTimeout);
- ret.append(" hardTimeout=" + this.hardTimeout);
- ret.append(" priority=" + this.priority);
- if ( flowEntryMatch != null ) {
- ret.append(" flowEntryMatch=" + this.flowEntryMatch.toString());
- }
- ret.append(" flowEntryActions=" + this.flowEntryActions.toString() );
- if ( dpid != null ) {
- ret.append(" dpid=" + this.dpid.toString());
- }
- if ( inPort != null ) {
- ret.append(" inPort=" + this.inPort.toString());
- }
- if ( outPort != null ) {
- ret.append(" outPort=" + this.outPort.toString());
- }
- ret.append(" flowEntryUserState=" + this.flowEntryUserState);
- ret.append(" flowEntrySwitchState=" + this.flowEntrySwitchState);
- if ( flowEntryErrorState != null ) {
- ret.append(" flowEntryErrorState=" + this.flowEntryErrorState.toString());
- }
- ret.append("]");
+ StringBuilder ret = new StringBuilder();
+ if (flowEntryId != null) {
+ ret.append("[flowEntryId=" + this.flowEntryId.toString());
+ } else {
+ ret.append("[");
+ }
+ if (flowId != null) {
+ ret.append(" flowId=" + this.flowId.toString());
+ }
+ ret.append(" idleTimeout=" + this.idleTimeout);
+ ret.append(" hardTimeout=" + this.hardTimeout);
+ ret.append(" priority=" + this.priority);
+ if (flowEntryMatch != null) {
+ ret.append(" flowEntryMatch=" + this.flowEntryMatch.toString());
+ }
+ ret.append(" flowEntryActions=" + this.flowEntryActions.toString());
+ if (dpid != null) {
+ ret.append(" dpid=" + this.dpid.toString());
+ }
+ if (inPort != null) {
+ ret.append(" inPort=" + this.inPort.toString());
+ }
+ if (outPort != null) {
+ ret.append(" outPort=" + this.outPort.toString());
+ }
+ ret.append(" flowEntryUserState=" + this.flowEntryUserState);
+ ret.append(" flowEntrySwitchState=" + this.flowEntrySwitchState);
+ if (flowEntryErrorState != null) {
+ ret.append(" flowEntryErrorState=" + this.flowEntryErrorState.toString());
+ }
+ ret.append("]");
- return ret.toString();
+ return ret.toString();
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/FlowEntryAction.java b/src/main/java/net/onrc/onos/core/util/FlowEntryAction.java
index da86ed3..f619fea 100644
--- a/src/main/java/net/onrc/onos/core/util/FlowEntryAction.java
+++ b/src/main/java/net/onrc/onos/core/util/FlowEntryAction.java
@@ -6,7 +6,7 @@
/**
* The class representing a single Flow Entry action.
- *
+ * <p/>
* A Flow Entry action that needs to be applied to each packet.
* Note that it contains only a single action. Multiple actions are
* listed in a list inside @ref FlowEntryActions.
@@ -14,482 +14,484 @@
public class FlowEntryAction {
/**
* Special action values.
- *
+ * <p/>
* Those values are taken as-is from the OpenFlow-v1.0.0 specification
* (pp 21-22).
*/
public enum ActionValues {
- ACTION_OUTPUT ((short)0x0), // Output to switch port
- ACTION_SET_VLAN_VID ((short)0x1), // Set the 802.1q VLAN id
- ACTION_SET_VLAN_PCP ((short)0x2), // Set the 802.1q priority
- ACTION_STRIP_VLAN ((short)0x3), // Strip the 802.1q header
- ACTION_SET_DL_SRC ((short)0x4), // Ethernet source address
- ACTION_SET_DL_DST ((short)0x5), // Ethernet destination address
- ACTION_SET_NW_SRC ((short)0x6), // IP source address
- ACTION_SET_NW_DST ((short)0x7), // IP destination address
- ACTION_SET_NW_TOS ((short)0x8), // IP ToS (DSCP field, 6 bits)
- ACTION_SET_TP_SRC ((short)0x9), // TCP/UDP source port
- ACTION_SET_TP_DST ((short)0xa), // TCP/UDP destination port
- ACTION_ENQUEUE ((short)0xb), // Output to queue on port
- ACTION_VENDOR ((short)0xffff); // Vendor-specific
+ ACTION_OUTPUT((short) 0x0), // Output to switch port
+ ACTION_SET_VLAN_VID((short) 0x1), // Set the 802.1q VLAN id
+ ACTION_SET_VLAN_PCP((short) 0x2), // Set the 802.1q priority
+ ACTION_STRIP_VLAN((short) 0x3), // Strip the 802.1q header
+ ACTION_SET_DL_SRC((short) 0x4), // Ethernet source address
+ ACTION_SET_DL_DST((short) 0x5), // Ethernet destination address
+ ACTION_SET_NW_SRC((short) 0x6), // IP source address
+ ACTION_SET_NW_DST((short) 0x7), // IP destination address
+ ACTION_SET_NW_TOS((short) 0x8), // IP ToS (DSCP field, 6 bits)
+ ACTION_SET_TP_SRC((short) 0x9), // TCP/UDP source port
+ ACTION_SET_TP_DST((short) 0xa), // TCP/UDP destination port
+ ACTION_ENQUEUE((short) 0xb), // Output to queue on port
+ ACTION_VENDOR((short) 0xffff); // Vendor-specific
- private final short value; // The value
+ private final short value; // The value
- /**
- * Constructor for a given value.
- *
- * @param value the value to use for the initialization.
- */
- private ActionValues(short value) {
- this.value = value;
- }
+ /**
+ * Constructor for a given value.
+ *
+ * @param value the value to use for the initialization.
+ */
+ private ActionValues(short value) {
+ this.value = value;
+ }
- /**
- * Get the value.
- *
- * @return the value.
- */
- public short getValue() { return value; }
+ /**
+ * Get the value.
+ *
+ * @return the value.
+ */
+ public short getValue() {
+ return value;
+ }
}
/**
* Action structure for ACTION_OUTPUT: Output to switch port.
*/
public static class ActionOutput {
- private Port port; // Output port
- private short maxLen; // Max. length (in bytes) to send to controller
- // if the port is set to PORT_CONTROLLER
+ private Port port; // Output port
+ private short maxLen; // Max. length (in bytes) to send to controller
+ // if the port is set to PORT_CONTROLLER
- /**
- * Default constructor.
- */
- public ActionOutput() {
- this.port = null;
- this.maxLen = 0;
- }
+ /**
+ * Default constructor.
+ */
+ public ActionOutput() {
+ this.port = null;
+ this.maxLen = 0;
+ }
- /**
- * Copy constructor.
- *
- * @param other the object to copy from.
- */
- public ActionOutput(ActionOutput other) {
- if (other.port != null)
- this.port = new Port(other.port);
- this.maxLen = other.maxLen;
- }
+ /**
+ * Copy constructor.
+ *
+ * @param other the object to copy from.
+ */
+ public ActionOutput(ActionOutput other) {
+ if (other.port != null)
+ this.port = new Port(other.port);
+ this.maxLen = other.maxLen;
+ }
- /**
- * Constructor from a string.
- *
- * The string has the following form:
- * [port=XXX maxLen=XXX]
- *
- * @param actionStr the action as a string.
- */
- public ActionOutput(String actionStr) {
- this.fromString(actionStr);
- }
+ /**
+ * Constructor from a string.
+ * <p/>
+ * The string has the following form:
+ * [port=XXX maxLen=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public ActionOutput(String actionStr) {
+ this.fromString(actionStr);
+ }
- /**
- * Constructor for a given output port and maximum length.
- *
- * @param port the output port to set.
- * @param maxLen the maximum length (in bytes) to send to controller
- * if the port is set to PORT_CONTROLLER.
- */
- public ActionOutput(Port port, short maxLen) {
- this.port = port;
- this.maxLen = maxLen;
- }
+ /**
+ * Constructor for a given output port and maximum length.
+ *
+ * @param port the output port to set.
+ * @param maxLen the maximum length (in bytes) to send to controller
+ * if the port is set to PORT_CONTROLLER.
+ */
+ public ActionOutput(Port port, short maxLen) {
+ this.port = port;
+ this.maxLen = maxLen;
+ }
- /**
- * Constructor for a given output port.
- *
- * @param port the output port to set.
- */
- public ActionOutput(Port port) {
- this.port = port;
- this.maxLen = 0;
- }
+ /**
+ * Constructor for a given output port.
+ *
+ * @param port the output port to set.
+ */
+ public ActionOutput(Port port) {
+ this.port = port;
+ this.maxLen = 0;
+ }
- /**
- * Get the output port.
- *
- * @return the output port.
- */
- @JsonProperty("port")
- public Port port() {
- return this.port;
- }
+ /**
+ * Get the output port.
+ *
+ * @return the output port.
+ */
+ @JsonProperty("port")
+ public Port port() {
+ return this.port;
+ }
- /**
- * Get the maximum length (in bytes) to send to controller if the
- * port is set to PORT_CONTROLLER.
- *
- * @return the maximum length (in bytes) to send to controller if the
- * port is set to PORT_CONTROLLER.
- */
- @JsonProperty("maxLen")
- public short maxLen() {
- return this.maxLen;
- }
+ /**
+ * Get the maximum length (in bytes) to send to controller if the
+ * port is set to PORT_CONTROLLER.
+ *
+ * @return the maximum length (in bytes) to send to controller if the
+ * port is set to PORT_CONTROLLER.
+ */
+ @JsonProperty("maxLen")
+ public short maxLen() {
+ return this.maxLen;
+ }
- /**
- * Convert the action to a string.
- *
- * The string has the following form:
- * [port=XXX maxLen=XXX]
- *
- * @return the action as a string.
- */
- @Override
- public String toString() {
- String ret = "[";
- ret += "port=" + port.toString();
- ret += " maxLen=" + maxLen;
- ret += "]";
+ /**
+ * Convert the action to a string.
+ * <p/>
+ * The string has the following form:
+ * [port=XXX maxLen=XXX]
+ *
+ * @return the action as a string.
+ */
+ @Override
+ public String toString() {
+ String ret = "[";
+ ret += "port=" + port.toString();
+ ret += " maxLen=" + maxLen;
+ ret += "]";
- return ret;
- }
+ return ret;
+ }
- /**
- * Convert a string to an action.
- *
- * The string has the following form:
- * [port=XXX maxLen=XXX]
- *
- * @param actionStr the action as a string.
- */
- public void fromString(String actionStr) {
- String[] parts = actionStr.split(" ");
- String decode = null;
+ /**
+ * Convert a string to an action.
+ * <p/>
+ * The string has the following form:
+ * [port=XXX maxLen=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public void fromString(String actionStr) {
+ String[] parts = actionStr.split(" ");
+ String decode = null;
- // Decode the "port=XXX" part
- if (parts.length > 0)
- decode = parts[0];
- if (decode != null) {
- String[] tokens = decode.split("port=");
- if (tokens.length > 1 && tokens[1] != null) {
- try {
- Short valueShort = Short.valueOf(tokens[1]);
- port = new Port(valueShort);
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException("Invalid action string");
- }
- }
- } else {
- throw new IllegalArgumentException("Invalid action string");
- }
+ // Decode the "port=XXX" part
+ if (parts.length > 0)
+ decode = parts[0];
+ if (decode != null) {
+ String[] tokens = decode.split("port=");
+ if (tokens.length > 1 && tokens[1] != null) {
+ try {
+ Short valueShort = Short.valueOf(tokens[1]);
+ port = new Port(valueShort);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ }
+ } else {
+ throw new IllegalArgumentException("Invalid action string");
+ }
- // Decode the "maxLen=XXX" part
- decode = null;
- if (parts.length > 1)
- decode = parts[1];
- if (decode != null) {
- decode = decode.replace("]", "");
- String[] tokens = decode.split("maxLen=");
- if (tokens.length > 1 && tokens[1] != null) {
- try {
- maxLen = Short.valueOf(tokens[1]);
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException("Invalid action string");
- }
- }
- } else {
- throw new IllegalArgumentException("Invalid action string");
- }
- }
+ // Decode the "maxLen=XXX" part
+ decode = null;
+ if (parts.length > 1)
+ decode = parts[1];
+ if (decode != null) {
+ decode = decode.replace("]", "");
+ String[] tokens = decode.split("maxLen=");
+ if (tokens.length > 1 && tokens[1] != null) {
+ try {
+ maxLen = Short.valueOf(tokens[1]);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ }
+ } else {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ }
}
/**
* Action structure for ACTION_SET_VLAN_VID: Set the 802.1q VLAN id
*/
public static class ActionSetVlanId {
- private short vlanId; // The VLAN ID to set
+ private short vlanId; // The VLAN ID to set
- /**
- * Default constructor.
- */
- public ActionSetVlanId() {
- this.vlanId = 0;
- }
+ /**
+ * Default constructor.
+ */
+ public ActionSetVlanId() {
+ this.vlanId = 0;
+ }
- /**
- * Copy constructor.
- *
- * @param other the object to copy from.
- */
- public ActionSetVlanId(ActionSetVlanId other) {
- this.vlanId = other.vlanId;
- }
+ /**
+ * Copy constructor.
+ *
+ * @param other the object to copy from.
+ */
+ public ActionSetVlanId(ActionSetVlanId other) {
+ this.vlanId = other.vlanId;
+ }
- /**
- * Constructor from a string.
- *
- * The string has the following form:
- * [vlanId=XXX]
- *
- * @param actionStr the action as a string.
- */
- public ActionSetVlanId(String actionStr) {
- this.fromString(actionStr);
- }
+ /**
+ * Constructor from a string.
+ * <p/>
+ * The string has the following form:
+ * [vlanId=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public ActionSetVlanId(String actionStr) {
+ this.fromString(actionStr);
+ }
- /**
- * Constructor for a given VLAN ID.
- *
- * @param vlanId the VLAN ID to set.
- */
- public ActionSetVlanId(short vlanId) {
- this.vlanId = vlanId;
- }
+ /**
+ * Constructor for a given VLAN ID.
+ *
+ * @param vlanId the VLAN ID to set.
+ */
+ public ActionSetVlanId(short vlanId) {
+ this.vlanId = vlanId;
+ }
- /**
- * Get the VLAN ID.
- *
- * @return the VLAN ID.
- */
- @JsonProperty("vlanId")
- public short vlanId() {
- return this.vlanId;
- }
+ /**
+ * Get the VLAN ID.
+ *
+ * @return the VLAN ID.
+ */
+ @JsonProperty("vlanId")
+ public short vlanId() {
+ return this.vlanId;
+ }
- /**
- * Convert the action to a string.
- *
- * The string has the following form:
- * [vlanId=XXX]
- *
- * @return the action as a string.
- */
- @Override
- public String toString() {
- String ret = "[";
- ret += "vlanId=" + this.vlanId;
- ret += "]";
+ /**
+ * Convert the action to a string.
+ * <p/>
+ * The string has the following form:
+ * [vlanId=XXX]
+ *
+ * @return the action as a string.
+ */
+ @Override
+ public String toString() {
+ String ret = "[";
+ ret += "vlanId=" + this.vlanId;
+ ret += "]";
- return ret;
- }
+ return ret;
+ }
- /**
- * Convert a string to an action.
- *
- * The string has the following form:
- * [vlanId=XXX]
- *
- * @param actionStr the action as a string.
- */
- public void fromString(String actionStr) {
- String[] parts = actionStr.split("vlanId=");
- String decode = null;
+ /**
+ * Convert a string to an action.
+ * <p/>
+ * The string has the following form:
+ * [vlanId=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public void fromString(String actionStr) {
+ String[] parts = actionStr.split("vlanId=");
+ String decode = null;
- // Decode the value
- if (parts.length > 1)
- decode = parts[1];
- if (decode != null) {
- decode = decode.replace("]", "");
- try {
- vlanId = Short.valueOf(decode);
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException("Invalid action string");
- }
- } else {
- throw new IllegalArgumentException("Invalid action string");
- }
- }
+ // Decode the value
+ if (parts.length > 1)
+ decode = parts[1];
+ if (decode != null) {
+ decode = decode.replace("]", "");
+ try {
+ vlanId = Short.valueOf(decode);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ } else {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ }
}
/**
* Action structure for ACTION_SET_VLAN_PCP: Set the 802.1q priority
*/
public static class ActionSetVlanPriority {
- private byte vlanPriority; // The VLAN priority to set
+ private byte vlanPriority; // The VLAN priority to set
- /**
- * Default constructor.
- */
- public ActionSetVlanPriority() {
- this.vlanPriority = 0;
- }
+ /**
+ * Default constructor.
+ */
+ public ActionSetVlanPriority() {
+ this.vlanPriority = 0;
+ }
- /**
- * Copy constructor.
- *
- * @param other the object to copy from.
- */
- public ActionSetVlanPriority(ActionSetVlanPriority other) {
- this.vlanPriority = other.vlanPriority;
- }
+ /**
+ * Copy constructor.
+ *
+ * @param other the object to copy from.
+ */
+ public ActionSetVlanPriority(ActionSetVlanPriority other) {
+ this.vlanPriority = other.vlanPriority;
+ }
- /**
- * Constructor from a string.
- *
- * The string has the following form:
- * [vlanPriority=XXX]
- *
- * @param actionStr the action as a string.
- */
- public ActionSetVlanPriority(String actionStr) {
- this.fromString(actionStr);
- }
+ /**
+ * Constructor from a string.
+ * <p/>
+ * The string has the following form:
+ * [vlanPriority=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public ActionSetVlanPriority(String actionStr) {
+ this.fromString(actionStr);
+ }
- /**
- * Constructor for a given VLAN priority.
- *
- * @param vlanPriority the VLAN priority to set.
- */
- public ActionSetVlanPriority(byte vlanPriority) {
- this.vlanPriority = vlanPriority;
- }
+ /**
+ * Constructor for a given VLAN priority.
+ *
+ * @param vlanPriority the VLAN priority to set.
+ */
+ public ActionSetVlanPriority(byte vlanPriority) {
+ this.vlanPriority = vlanPriority;
+ }
- /**
- * Get the VLAN priority.
- *
- * @return the VLAN priority.
- */
- @JsonProperty("vlanPriority")
- public byte vlanPriority() {
- return this.vlanPriority;
- }
+ /**
+ * Get the VLAN priority.
+ *
+ * @return the VLAN priority.
+ */
+ @JsonProperty("vlanPriority")
+ public byte vlanPriority() {
+ return this.vlanPriority;
+ }
- /**
- * Convert the action to a string.
- *
- * The string has the following form:
- * [vlanPriority=XXX]
- *
- * @return the action as a string.
- */
- @Override
- public String toString() {
- String ret = "[";
- ret += "vlanPriority=" + this.vlanPriority;
- ret += "]";
+ /**
+ * Convert the action to a string.
+ * <p/>
+ * The string has the following form:
+ * [vlanPriority=XXX]
+ *
+ * @return the action as a string.
+ */
+ @Override
+ public String toString() {
+ String ret = "[";
+ ret += "vlanPriority=" + this.vlanPriority;
+ ret += "]";
- return ret;
- }
+ return ret;
+ }
- /**
- * Convert a string to an action.
- *
- * The string has the following form:
- * [vlanPriority=XXX]
- *
- * @param actionStr the action as a string.
- */
- public void fromString(String actionStr) {
- String[] parts = actionStr.split("vlanPriority=");
- String decode = null;
+ /**
+ * Convert a string to an action.
+ * <p/>
+ * The string has the following form:
+ * [vlanPriority=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public void fromString(String actionStr) {
+ String[] parts = actionStr.split("vlanPriority=");
+ String decode = null;
- // Decode the value
- if (parts.length > 1)
- decode = parts[1];
- if (decode != null) {
- decode = decode.replace("]", "");
- try {
- vlanPriority = Byte.valueOf(decode);
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException("Invalid action string");
- }
- } else {
- throw new IllegalArgumentException("Invalid action string");
- }
- }
+ // Decode the value
+ if (parts.length > 1)
+ decode = parts[1];
+ if (decode != null) {
+ decode = decode.replace("]", "");
+ try {
+ vlanPriority = Byte.valueOf(decode);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ } else {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ }
}
/**
* Action structure for ACTION_STRIP_VLAN: Strip the 802.1q header
*/
public static class ActionStripVlan {
- private boolean stripVlan; // If true, strip the VLAN header
+ private boolean stripVlan; // If true, strip the VLAN header
- /**
- * Default constructor.
- */
- public ActionStripVlan() {
- this.stripVlan = false;
- }
+ /**
+ * Default constructor.
+ */
+ public ActionStripVlan() {
+ this.stripVlan = false;
+ }
- /**
- * Copy constructor.
- *
- * @param other the object to copy from.
- */
- public ActionStripVlan(ActionStripVlan other) {
- this.stripVlan = other.stripVlan;
- }
+ /**
+ * Copy constructor.
+ *
+ * @param other the object to copy from.
+ */
+ public ActionStripVlan(ActionStripVlan other) {
+ this.stripVlan = other.stripVlan;
+ }
- /**
- * Constructor from a string.
- *
- * The string has the following form:
- * [stripVlan=XXX]
- *
- * @param actionStr the action as a string.
- */
- public ActionStripVlan(String actionStr) {
- this.fromString(actionStr);
- }
+ /**
+ * Constructor from a string.
+ * <p/>
+ * The string has the following form:
+ * [stripVlan=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public ActionStripVlan(String actionStr) {
+ this.fromString(actionStr);
+ }
- /**
- * Constructor for a given boolean flag.
- *
- * @param stripVlan if true, strip the VLAN header.
- */
- public ActionStripVlan(boolean stripVlan) {
- this.stripVlan = stripVlan;
- }
+ /**
+ * Constructor for a given boolean flag.
+ *
+ * @param stripVlan if true, strip the VLAN header.
+ */
+ public ActionStripVlan(boolean stripVlan) {
+ this.stripVlan = stripVlan;
+ }
- /**
- * Get the boolean flag whether the VLAN header should be stripped.
- *
- * @return the boolean flag whether the VLAN header should be stripped.
- */
- @JsonProperty("stripVlan")
- public boolean stripVlan() {
- return this.stripVlan;
- }
+ /**
+ * Get the boolean flag whether the VLAN header should be stripped.
+ *
+ * @return the boolean flag whether the VLAN header should be stripped.
+ */
+ @JsonProperty("stripVlan")
+ public boolean stripVlan() {
+ return this.stripVlan;
+ }
- /**
- * Convert the action to a string.
- *
- * The string has the following form:
- * [stripVlan=XXX]
- *
- * @return the action as a string.
- */
- @Override
- public String toString() {
- String ret = "[";
- ret += "stripVlan=" + this.stripVlan;
- ret += "]";
+ /**
+ * Convert the action to a string.
+ * <p/>
+ * The string has the following form:
+ * [stripVlan=XXX]
+ *
+ * @return the action as a string.
+ */
+ @Override
+ public String toString() {
+ String ret = "[";
+ ret += "stripVlan=" + this.stripVlan;
+ ret += "]";
- return ret;
- }
+ return ret;
+ }
- /**
- * Convert a string to an action.
- *
- * The string has the following form:
- * [stripVlan=XXX]
- *
- * @param actionStr the action as a string.
- */
- public void fromString(String actionStr) {
- String[] parts = actionStr.split("stripVlan=");
- String decode = null;
+ /**
+ * Convert a string to an action.
+ * <p/>
+ * The string has the following form:
+ * [stripVlan=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public void fromString(String actionStr) {
+ String[] parts = actionStr.split("stripVlan=");
+ String decode = null;
- // Decode the value
- if (parts.length > 1)
- decode = parts[1];
- if (decode != null) {
- decode = decode.replace("]", "");
- stripVlan = Boolean.valueOf(decode);
- } else {
- throw new IllegalArgumentException("Invalid action string");
- }
- }
+ // Decode the value
+ if (parts.length > 1)
+ decode = parts[1];
+ if (decode != null) {
+ decode = decode.replace("]", "");
+ stripVlan = Boolean.valueOf(decode);
+ } else {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ }
}
/**
@@ -497,99 +499,99 @@
* Set the Ethernet source/destination address.
*/
public static class ActionSetEthernetAddr {
- private MACAddress addr; // The MAC address to set
+ private MACAddress addr; // The MAC address to set
- /**
- * Default constructor.
- */
- public ActionSetEthernetAddr() {
- this.addr = null;
- }
+ /**
+ * Default constructor.
+ */
+ public ActionSetEthernetAddr() {
+ this.addr = null;
+ }
- /**
- * Copy constructor.
- *
- * @param other the object to copy from.
- */
- public ActionSetEthernetAddr(ActionSetEthernetAddr other) {
- if (other.addr != null)
- this.addr = MACAddress.valueOf(other.addr.toLong());
- }
+ /**
+ * Copy constructor.
+ *
+ * @param other the object to copy from.
+ */
+ public ActionSetEthernetAddr(ActionSetEthernetAddr other) {
+ if (other.addr != null)
+ this.addr = MACAddress.valueOf(other.addr.toLong());
+ }
- /**
- * Constructor from a string.
- *
- * The string has the following form:
- * [addr=XXX]
- *
- * @param actionStr the action as a string.
- */
- public ActionSetEthernetAddr(String actionStr) {
- this.fromString(actionStr);
- }
+ /**
+ * Constructor from a string.
+ * <p/>
+ * The string has the following form:
+ * [addr=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public ActionSetEthernetAddr(String actionStr) {
+ this.fromString(actionStr);
+ }
- /**
- * Constructor for a given MAC address.
- *
- * @param addr the MAC address to set.
- */
- public ActionSetEthernetAddr(MACAddress addr) {
- this.addr = addr;
- }
+ /**
+ * Constructor for a given MAC address.
+ *
+ * @param addr the MAC address to set.
+ */
+ public ActionSetEthernetAddr(MACAddress addr) {
+ this.addr = addr;
+ }
- /**
- * Get the MAC address.
- *
- * @return the MAC address.
- */
- @JsonProperty("addr")
- public MACAddress addr() {
- return this.addr;
- }
+ /**
+ * Get the MAC address.
+ *
+ * @return the MAC address.
+ */
+ @JsonProperty("addr")
+ public MACAddress addr() {
+ return this.addr;
+ }
- /**
- * Convert the action to a string.
- *
- * The string has the following form:
- * [addr=XXX]
- *
- * @return the action as a string.
- */
- @Override
- public String toString() {
- String ret = "[";
- ret += "addr=" + addr.toString();
- ret += "]";
+ /**
+ * Convert the action to a string.
+ * <p/>
+ * The string has the following form:
+ * [addr=XXX]
+ *
+ * @return the action as a string.
+ */
+ @Override
+ public String toString() {
+ String ret = "[";
+ ret += "addr=" + addr.toString();
+ ret += "]";
- return ret;
- }
+ return ret;
+ }
- /**
- * Convert a string to an action.
- *
- * The string has the following form:
- * [addr=XXX]
- *
- * @param actionStr the action as a string.
- */
- public void fromString(String actionStr) {
- String[] parts = actionStr.split("addr=");
- String decode = null;
+ /**
+ * Convert a string to an action.
+ * <p/>
+ * The string has the following form:
+ * [addr=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public void fromString(String actionStr) {
+ String[] parts = actionStr.split("addr=");
+ String decode = null;
- // Decode the value
- if (parts.length > 1)
- decode = parts[1];
- if (decode != null) {
- decode = decode.replace("]", "");
- try {
- addr = MACAddress.valueOf(decode);
- } catch (IllegalArgumentException e) {
- throw new IllegalArgumentException("Invalid action string");
- }
- } else {
- throw new IllegalArgumentException("Invalid action string");
- }
- }
+ // Decode the value
+ if (parts.length > 1)
+ decode = parts[1];
+ if (decode != null) {
+ decode = decode.replace("]", "");
+ try {
+ addr = MACAddress.valueOf(decode);
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ } else {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ }
}
/**
@@ -597,99 +599,99 @@
* Set the IPv4 source/destination address.
*/
public static class ActionSetIPv4Addr {
- private IPv4 addr; // The IPv4 address to set
+ private IPv4 addr; // The IPv4 address to set
- /**
- * Default constructor.
- */
- public ActionSetIPv4Addr() {
- this.addr = null;
- }
+ /**
+ * Default constructor.
+ */
+ public ActionSetIPv4Addr() {
+ this.addr = null;
+ }
- /**
- * Copy constructor.
- *
- * @param other the object to copy from.
- */
- public ActionSetIPv4Addr(ActionSetIPv4Addr other) {
- if (other.addr != null)
- this.addr = new IPv4(other.addr);
- }
+ /**
+ * Copy constructor.
+ *
+ * @param other the object to copy from.
+ */
+ public ActionSetIPv4Addr(ActionSetIPv4Addr other) {
+ if (other.addr != null)
+ this.addr = new IPv4(other.addr);
+ }
- /**
- * Constructor from a string.
- *
- * The string has the following form:
- * [addr=XXX]
- *
- * @param actionStr the action as a string.
- */
- public ActionSetIPv4Addr(String actionStr) {
- this.fromString(actionStr);
- }
+ /**
+ * Constructor from a string.
+ * <p/>
+ * The string has the following form:
+ * [addr=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public ActionSetIPv4Addr(String actionStr) {
+ this.fromString(actionStr);
+ }
- /**
- * Constructor for a given IPv4 address.
- *
- * @param addr the IPv4 address to set.
- */
- public ActionSetIPv4Addr(IPv4 addr) {
- this.addr = addr;
- }
+ /**
+ * Constructor for a given IPv4 address.
+ *
+ * @param addr the IPv4 address to set.
+ */
+ public ActionSetIPv4Addr(IPv4 addr) {
+ this.addr = addr;
+ }
- /**
- * Get the IPv4 address.
- *
- * @return the IPv4 address.
- */
- @JsonProperty("addr")
- public IPv4 addr() {
- return this.addr;
- }
+ /**
+ * Get the IPv4 address.
+ *
+ * @return the IPv4 address.
+ */
+ @JsonProperty("addr")
+ public IPv4 addr() {
+ return this.addr;
+ }
- /**
- * Convert the action to a string.
- *
- * The string has the following form:
- * [addr=XXX]
- *
- * @return the action as a string.
- */
- @Override
- public String toString() {
- String ret = "[";
- ret += "addr=" + addr.toString();
- ret += "]";
+ /**
+ * Convert the action to a string.
+ * <p/>
+ * The string has the following form:
+ * [addr=XXX]
+ *
+ * @return the action as a string.
+ */
+ @Override
+ public String toString() {
+ String ret = "[";
+ ret += "addr=" + addr.toString();
+ ret += "]";
- return ret;
- }
+ return ret;
+ }
- /**
- * Convert a string to an action.
- *
- * The string has the following form:
- * [addr=XXX]
- *
- * @param actionStr the action as a string.
- */
- public void fromString(String actionStr) {
- String[] parts = actionStr.split("addr=");
- String decode = null;
+ /**
+ * Convert a string to an action.
+ * <p/>
+ * The string has the following form:
+ * [addr=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public void fromString(String actionStr) {
+ String[] parts = actionStr.split("addr=");
+ String decode = null;
- // Decode the value
- if (parts.length > 1)
- decode = parts[1];
- if (decode != null) {
- decode = decode.replace("]", "");
- try {
- addr = new IPv4(decode);
- } catch (IllegalArgumentException e) {
- throw new IllegalArgumentException("Invalid action string");
- }
- } else {
- throw new IllegalArgumentException("Invalid action string");
- }
- }
+ // Decode the value
+ if (parts.length > 1)
+ decode = parts[1];
+ if (decode != null) {
+ decode = decode.replace("]", "");
+ try {
+ addr = new IPv4(decode);
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ } else {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ }
}
/**
@@ -697,98 +699,98 @@
* Set the IP ToS (DSCP field, 6 bits).
*/
public static class ActionSetIpToS {
- private byte ipToS; // The IP ToS to set DSCP field, 6 bits)
+ private byte ipToS; // The IP ToS to set DSCP field, 6 bits)
- /**
- * Default constructor.
- */
- public ActionSetIpToS() {
- this.ipToS = 0;
- }
+ /**
+ * Default constructor.
+ */
+ public ActionSetIpToS() {
+ this.ipToS = 0;
+ }
- /**
- * Copy constructor.
- *
- * @param other the object to copy from.
- */
- public ActionSetIpToS(ActionSetIpToS other) {
- this.ipToS = other.ipToS;
- }
+ /**
+ * Copy constructor.
+ *
+ * @param other the object to copy from.
+ */
+ public ActionSetIpToS(ActionSetIpToS other) {
+ this.ipToS = other.ipToS;
+ }
- /**
- * Constructor from a string.
- *
- * The string has the following form:
- * [ipToS=XXX]
- *
- * @param actionStr the action as a string.
- */
- public ActionSetIpToS(String actionStr) {
- this.fromString(actionStr);
- }
+ /**
+ * Constructor from a string.
+ * <p/>
+ * The string has the following form:
+ * [ipToS=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public ActionSetIpToS(String actionStr) {
+ this.fromString(actionStr);
+ }
- /**
- * Constructor for a given IP ToS (DSCP field, 6 bits).
- *
- * @param ipToS the IP ToS (DSCP field, 6 bits) to set.
- */
- public ActionSetIpToS(byte ipToS) {
- this.ipToS = ipToS;
- }
+ /**
+ * Constructor for a given IP ToS (DSCP field, 6 bits).
+ *
+ * @param ipToS the IP ToS (DSCP field, 6 bits) to set.
+ */
+ public ActionSetIpToS(byte ipToS) {
+ this.ipToS = ipToS;
+ }
- /**
- * Get the IP ToS (DSCP field, 6 bits).
- *
- * @return the IP ToS (DSCP field, 6 bits).
- */
- @JsonProperty("ipToS")
- public byte ipToS() {
- return this.ipToS;
- }
+ /**
+ * Get the IP ToS (DSCP field, 6 bits).
+ *
+ * @return the IP ToS (DSCP field, 6 bits).
+ */
+ @JsonProperty("ipToS")
+ public byte ipToS() {
+ return this.ipToS;
+ }
- /**
- * Convert the action to a string.
- *
- * The string has the following form:
- * [ipToS=XXX]
- *
- * @return the action as a string.
- */
- @Override
- public String toString() {
- String ret = "[";
- ret += "ipToS=" + ipToS;
- ret += "]";
+ /**
+ * Convert the action to a string.
+ * <p/>
+ * The string has the following form:
+ * [ipToS=XXX]
+ *
+ * @return the action as a string.
+ */
+ @Override
+ public String toString() {
+ String ret = "[";
+ ret += "ipToS=" + ipToS;
+ ret += "]";
- return ret;
- }
+ return ret;
+ }
- /**
- * Convert a string to an action.
- *
- * The string has the following form:
- * [ipToS=XXX]
- *
- * @param actionStr the action as a string.
- */
- public void fromString(String actionStr) {
- String[] parts = actionStr.split("ipToS=");
- String decode = null;
+ /**
+ * Convert a string to an action.
+ * <p/>
+ * The string has the following form:
+ * [ipToS=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public void fromString(String actionStr) {
+ String[] parts = actionStr.split("ipToS=");
+ String decode = null;
- // Decode the value
- if (parts.length > 1)
- decode = parts[1];
- if (decode != null) {
- decode = decode.replace("]", "");
- try {
- ipToS = Byte.valueOf(decode);
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException("Invalid action string");
- }
- } else {
- throw new IllegalArgumentException("Invalid action string");
- }
- }
+ // Decode the value
+ if (parts.length > 1)
+ decode = parts[1];
+ if (decode != null) {
+ decode = decode.replace("]", "");
+ try {
+ ipToS = Byte.valueOf(decode);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ } else {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ }
}
/**
@@ -796,239 +798,239 @@
* Set the TCP/UDP source/destination port.
*/
public static class ActionSetTcpUdpPort {
- private short port; // The TCP/UDP port to set
+ private short port; // The TCP/UDP port to set
- /**
- * Default constructor.
- */
- public ActionSetTcpUdpPort() {
- this.port = 0;
- }
+ /**
+ * Default constructor.
+ */
+ public ActionSetTcpUdpPort() {
+ this.port = 0;
+ }
- /**
- * Copy constructor.
- *
- * @param other the object to copy from.
- */
- public ActionSetTcpUdpPort(ActionSetTcpUdpPort other) {
- this.port = other.port;
- }
+ /**
+ * Copy constructor.
+ *
+ * @param other the object to copy from.
+ */
+ public ActionSetTcpUdpPort(ActionSetTcpUdpPort other) {
+ this.port = other.port;
+ }
- /**
- * Constructor from a string.
- *
- * The string has the following form:
- * [port=XXX]
- *
- * @param actionStr the action as a string.
- */
- public ActionSetTcpUdpPort(String actionStr) {
- this.fromString(actionStr);
- }
+ /**
+ * Constructor from a string.
+ * <p/>
+ * The string has the following form:
+ * [port=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public ActionSetTcpUdpPort(String actionStr) {
+ this.fromString(actionStr);
+ }
- /**
- * Constructor for a given TCP/UDP port.
- *
- * @param port the TCP/UDP port to set.
- */
- public ActionSetTcpUdpPort(short port) {
- this.port = port;
- }
+ /**
+ * Constructor for a given TCP/UDP port.
+ *
+ * @param port the TCP/UDP port to set.
+ */
+ public ActionSetTcpUdpPort(short port) {
+ this.port = port;
+ }
- /**
- * Get the TCP/UDP port.
- *
- * @return the TCP/UDP port.
- */
- @JsonProperty("port")
- public short port() {
- return this.port;
- }
+ /**
+ * Get the TCP/UDP port.
+ *
+ * @return the TCP/UDP port.
+ */
+ @JsonProperty("port")
+ public short port() {
+ return this.port;
+ }
- /**
- * Convert the action to a string.
- *
- * The string has the following form:
- * [port=XXX]
- *
- * @return the action as a string.
- */
- @Override
- public String toString() {
- String ret = "[";
- ret += "port=" + port;
- ret += "]";
+ /**
+ * Convert the action to a string.
+ * <p/>
+ * The string has the following form:
+ * [port=XXX]
+ *
+ * @return the action as a string.
+ */
+ @Override
+ public String toString() {
+ String ret = "[";
+ ret += "port=" + port;
+ ret += "]";
- return ret;
- }
+ return ret;
+ }
- /**
- * Convert a string to an action.
- *
- * The string has the following form:
- * [port=XXX]
- *
- * @param actionStr the action as a string.
- */
- public void fromString(String actionStr) {
- String[] parts = actionStr.split("port=");
- String decode = null;
+ /**
+ * Convert a string to an action.
+ * <p/>
+ * The string has the following form:
+ * [port=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public void fromString(String actionStr) {
+ String[] parts = actionStr.split("port=");
+ String decode = null;
- // Decode the value
- if (parts.length > 1)
- decode = parts[1];
- if (decode != null) {
- decode = decode.replace("]", "");
- try {
- port = Short.valueOf(decode);
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException("Invalid action string");
- }
- } else {
- throw new IllegalArgumentException("Invalid action string");
- }
- }
+ // Decode the value
+ if (parts.length > 1)
+ decode = parts[1];
+ if (decode != null) {
+ decode = decode.replace("]", "");
+ try {
+ port = Short.valueOf(decode);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ } else {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ }
}
/**
* Action structure for ACTION_ENQUEUE: Output to queue on port.
*/
public static class ActionEnqueue {
- private Port port; // Port that queue belongs. Should
- // refer to a valid physical port
- // (i.e. < PORT_MAX) or PORT_IN_PORT
- private int queueId; // Where to enqueue the packets
+ private Port port; // Port that queue belongs. Should
+ // refer to a valid physical port
+ // (i.e. < PORT_MAX) or PORT_IN_PORT
+ private int queueId; // Where to enqueue the packets
- /**
- * Default constructor.
- */
- public ActionEnqueue() {
- this.port = null;
- this.queueId = 0;
- }
+ /**
+ * Default constructor.
+ */
+ public ActionEnqueue() {
+ this.port = null;
+ this.queueId = 0;
+ }
- /**
- * Copy constructor.
- *
- * @param other the object to copy from.
- */
- public ActionEnqueue(ActionEnqueue other) {
- if (other.port != null)
- this.port = new Port(other.port);
- this.queueId = other.queueId;
- }
+ /**
+ * Copy constructor.
+ *
+ * @param other the object to copy from.
+ */
+ public ActionEnqueue(ActionEnqueue other) {
+ if (other.port != null)
+ this.port = new Port(other.port);
+ this.queueId = other.queueId;
+ }
- /**
- * Constructor from a string.
- *
- * The string has the following form:
- * [port=XXX queueId=XXX]
- *
- * @param actionStr the action as a string.
- */
- public ActionEnqueue(String actionStr) {
- this.fromString(actionStr);
- }
+ /**
+ * Constructor from a string.
+ * <p/>
+ * The string has the following form:
+ * [port=XXX queueId=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public ActionEnqueue(String actionStr) {
+ this.fromString(actionStr);
+ }
- /**
- * Constructor for a given port and queue ID.
- *
- * @param port the port to set.
- * @param queueId the queue ID on the port.
- */
- public ActionEnqueue(Port port, int queueId) {
- this.port = port;
- this.queueId = queueId;
- }
+ /**
+ * Constructor for a given port and queue ID.
+ *
+ * @param port the port to set.
+ * @param queueId the queue ID on the port.
+ */
+ public ActionEnqueue(Port port, int queueId) {
+ this.port = port;
+ this.queueId = queueId;
+ }
- /**
- * Get the port.
- *
- * @return the port.
- */
- @JsonProperty("port")
- public Port port() {
- return this.port;
- }
+ /**
+ * Get the port.
+ *
+ * @return the port.
+ */
+ @JsonProperty("port")
+ public Port port() {
+ return this.port;
+ }
- /**
- * Get the queue ID.
- *
- * @return the queue ID.
- */
- @JsonProperty("queueId")
- public int queueId() {
- return this.queueId;
- }
+ /**
+ * Get the queue ID.
+ *
+ * @return the queue ID.
+ */
+ @JsonProperty("queueId")
+ public int queueId() {
+ return this.queueId;
+ }
- /**
- * Convert the action to a string.
- *
- * The string has the following form:
- * [port=XXX queueId=XXX]
- *
- * @return the action as a string.
- */
- @Override
- public String toString() {
- String ret = "[";
- ret += "port=" + port.toString();
- ret += " queueId=" + queueId;
- ret += "]";
+ /**
+ * Convert the action to a string.
+ * <p/>
+ * The string has the following form:
+ * [port=XXX queueId=XXX]
+ *
+ * @return the action as a string.
+ */
+ @Override
+ public String toString() {
+ String ret = "[";
+ ret += "port=" + port.toString();
+ ret += " queueId=" + queueId;
+ ret += "]";
- return ret;
- }
+ return ret;
+ }
- /**
- * Convert a string to an action.
- *
- * The string has the following form:
- * [port=XXX queueId=XXX]
- *
- * @param actionStr the action as a string.
- */
- public void fromString(String actionStr) {
- String[] parts = actionStr.split(" ");
- String decode = null;
+ /**
+ * Convert a string to an action.
+ * <p/>
+ * The string has the following form:
+ * [port=XXX queueId=XXX]
+ *
+ * @param actionStr the action as a string.
+ */
+ public void fromString(String actionStr) {
+ String[] parts = actionStr.split(" ");
+ String decode = null;
- // Decode the "port=XXX" part
- if (parts.length > 0)
- decode = parts[0];
- if (decode != null) {
- String[] tokens = decode.split("port=");
- if (tokens.length > 1 && tokens[1] != null) {
- try {
- Short valueShort = Short.valueOf(tokens[1]);
- port = new Port(valueShort);
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException("Invalid action string");
- }
- }
- } else {
- throw new IllegalArgumentException("Invalid action string");
- }
+ // Decode the "port=XXX" part
+ if (parts.length > 0)
+ decode = parts[0];
+ if (decode != null) {
+ String[] tokens = decode.split("port=");
+ if (tokens.length > 1 && tokens[1] != null) {
+ try {
+ Short valueShort = Short.valueOf(tokens[1]);
+ port = new Port(valueShort);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ }
+ } else {
+ throw new IllegalArgumentException("Invalid action string");
+ }
- // Decode the "queueId=XXX" part
- decode = null;
- if (parts.length > 1)
- decode = parts[1];
- if (decode != null) {
- decode = decode.replace("]", "");
- String[] tokens = decode.split("queueId=");
- if (tokens.length > 1 && tokens[1] != null) {
- try {
- queueId = Short.valueOf(tokens[1]);
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException("Invalid action string");
- }
- }
- } else {
- throw new IllegalArgumentException("Invalid action string");
- }
- }
+ // Decode the "queueId=XXX" part
+ decode = null;
+ if (parts.length > 1)
+ decode = parts[1];
+ if (decode != null) {
+ decode = decode.replace("]", "");
+ String[] tokens = decode.split("queueId=");
+ if (tokens.length > 1 && tokens[1] != null) {
+ try {
+ queueId = Short.valueOf(tokens[1]);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ }
+ } else {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ }
}
- private ActionValues actionType; // The action type
+ private ActionValues actionType; // The action type
//
// The actions.
@@ -1051,7 +1053,7 @@
* Default constructor.
*/
public FlowEntryAction() {
- actionType = ActionValues.ACTION_VENDOR; // XXX: Initial value
+ actionType = ActionValues.ACTION_VENDOR; // XXX: Initial value
}
/**
@@ -1060,80 +1062,80 @@
* @param other the object to copy from.
*/
public FlowEntryAction(FlowEntryAction other) {
- this.actionType = other.actionType;
+ this.actionType = other.actionType;
- //
- if (other.actionOutput != null)
- this.actionOutput = new ActionOutput(other.actionOutput);
- else
- this.actionOutput = null;
- //
- if (other.actionSetVlanId != null)
- this.actionSetVlanId = new ActionSetVlanId(other.actionSetVlanId);
- else
- this.actionSetVlanId = null;
- //
- if (other.actionSetVlanPriority != null)
- this.actionSetVlanPriority = new ActionSetVlanPriority(other.actionSetVlanPriority);
- else
- this.actionSetVlanPriority = null;
- //
- if (other.actionStripVlan != null)
- this.actionStripVlan = new ActionStripVlan(other.actionStripVlan);
- else
- this.actionStripVlan = null;
- //
- if (other.actionSetEthernetSrcAddr != null)
- this.actionSetEthernetSrcAddr = new ActionSetEthernetAddr(other.actionSetEthernetSrcAddr);
- else
- this.actionSetEthernetSrcAddr = null;
- //
- if (other.actionSetEthernetDstAddr != null)
- this.actionSetEthernetDstAddr = new ActionSetEthernetAddr(other.actionSetEthernetDstAddr);
- else
- this.actionSetEthernetDstAddr = null;
- //
- if (other.actionSetIPv4SrcAddr != null)
- this.actionSetIPv4SrcAddr = new ActionSetIPv4Addr(other.actionSetIPv4SrcAddr);
- else
- this.actionSetIPv4SrcAddr = null;
- //
- if (other.actionSetIPv4DstAddr != null)
- this.actionSetIPv4DstAddr = new ActionSetIPv4Addr(other.actionSetIPv4DstAddr);
- else
- this.actionSetIPv4DstAddr = null;
- //
- if (other.actionSetIpToS != null)
- this.actionSetIpToS = new ActionSetIpToS(other.actionSetIpToS);
- else
- this.actionSetIpToS = null;
- //
- if (other.actionSetTcpUdpSrcPort != null)
- this.actionSetTcpUdpSrcPort = new ActionSetTcpUdpPort(other.actionSetTcpUdpSrcPort);
- else
- this.actionSetTcpUdpSrcPort = null;
- //
- if (other.actionSetTcpUdpDstPort != null)
- this.actionSetTcpUdpDstPort = new ActionSetTcpUdpPort(other.actionSetTcpUdpDstPort);
- else
- this.actionSetTcpUdpDstPort = null;
- //
- if (other.actionEnqueue != null)
- this.actionEnqueue = new ActionEnqueue(other.actionEnqueue);
- else
- this.actionEnqueue = null;
+ //
+ if (other.actionOutput != null)
+ this.actionOutput = new ActionOutput(other.actionOutput);
+ else
+ this.actionOutput = null;
+ //
+ if (other.actionSetVlanId != null)
+ this.actionSetVlanId = new ActionSetVlanId(other.actionSetVlanId);
+ else
+ this.actionSetVlanId = null;
+ //
+ if (other.actionSetVlanPriority != null)
+ this.actionSetVlanPriority = new ActionSetVlanPriority(other.actionSetVlanPriority);
+ else
+ this.actionSetVlanPriority = null;
+ //
+ if (other.actionStripVlan != null)
+ this.actionStripVlan = new ActionStripVlan(other.actionStripVlan);
+ else
+ this.actionStripVlan = null;
+ //
+ if (other.actionSetEthernetSrcAddr != null)
+ this.actionSetEthernetSrcAddr = new ActionSetEthernetAddr(other.actionSetEthernetSrcAddr);
+ else
+ this.actionSetEthernetSrcAddr = null;
+ //
+ if (other.actionSetEthernetDstAddr != null)
+ this.actionSetEthernetDstAddr = new ActionSetEthernetAddr(other.actionSetEthernetDstAddr);
+ else
+ this.actionSetEthernetDstAddr = null;
+ //
+ if (other.actionSetIPv4SrcAddr != null)
+ this.actionSetIPv4SrcAddr = new ActionSetIPv4Addr(other.actionSetIPv4SrcAddr);
+ else
+ this.actionSetIPv4SrcAddr = null;
+ //
+ if (other.actionSetIPv4DstAddr != null)
+ this.actionSetIPv4DstAddr = new ActionSetIPv4Addr(other.actionSetIPv4DstAddr);
+ else
+ this.actionSetIPv4DstAddr = null;
+ //
+ if (other.actionSetIpToS != null)
+ this.actionSetIpToS = new ActionSetIpToS(other.actionSetIpToS);
+ else
+ this.actionSetIpToS = null;
+ //
+ if (other.actionSetTcpUdpSrcPort != null)
+ this.actionSetTcpUdpSrcPort = new ActionSetTcpUdpPort(other.actionSetTcpUdpSrcPort);
+ else
+ this.actionSetTcpUdpSrcPort = null;
+ //
+ if (other.actionSetTcpUdpDstPort != null)
+ this.actionSetTcpUdpDstPort = new ActionSetTcpUdpPort(other.actionSetTcpUdpDstPort);
+ else
+ this.actionSetTcpUdpDstPort = null;
+ //
+ if (other.actionEnqueue != null)
+ this.actionEnqueue = new ActionEnqueue(other.actionEnqueue);
+ else
+ this.actionEnqueue = null;
}
/**
* Constructor from a string.
- *
+ * <p/>
* The string has the following form:
- * [type=XXX action=XXX]
+ * [type=XXX action=XXX]
*
* @param actionStr the action as a string.
*/
public FlowEntryAction(String actionStr) {
- this.fromString(actionStr);
+ this.fromString(actionStr);
}
/**
@@ -1142,7 +1144,9 @@
* @return the action type.
*/
@JsonProperty("actionType")
- public ActionValues actionType() { return actionType; }
+ public ActionValues actionType() {
+ return actionType;
+ }
/**
* Get the output action.
@@ -1150,7 +1154,9 @@
* @return the output action.
*/
@JsonProperty("actionOutput")
- public ActionOutput actionOutput() { return actionOutput; }
+ public ActionOutput actionOutput() {
+ return actionOutput;
+ }
/**
* Set the output action on a port.
@@ -1159,8 +1165,8 @@
*/
@JsonProperty("actionOutput")
public void setActionOutput(ActionOutput action) {
- actionOutput = action;
- actionType = ActionValues.ACTION_OUTPUT;
+ actionOutput = action;
+ actionType = ActionValues.ACTION_OUTPUT;
}
/**
@@ -1169,8 +1175,8 @@
* @param port the output port to set.
*/
public void setActionOutput(Port port) {
- actionOutput = new ActionOutput(port);
- actionType = ActionValues.ACTION_OUTPUT;
+ actionOutput = new ActionOutput(port);
+ actionType = ActionValues.ACTION_OUTPUT;
}
/**
@@ -1179,9 +1185,9 @@
* @param maxLen the maximum length (in bytes) to send to controller.
*/
public void setActionOutputToController(short maxLen) {
- Port port = new Port(Port.PortValues.PORT_CONTROLLER);
- actionOutput = new ActionOutput(port, maxLen);
- actionType = ActionValues.ACTION_OUTPUT;
+ Port port = new Port(Port.PortValues.PORT_CONTROLLER);
+ actionOutput = new ActionOutput(port, maxLen);
+ actionType = ActionValues.ACTION_OUTPUT;
}
/**
@@ -1190,7 +1196,9 @@
* @return the action to set the VLAN ID.
*/
@JsonProperty("actionSetVlanId")
- public ActionSetVlanId actionSetVlanId() { return actionSetVlanId; }
+ public ActionSetVlanId actionSetVlanId() {
+ return actionSetVlanId;
+ }
/**
* Set the action to set the VLAN ID.
@@ -1199,8 +1207,8 @@
*/
@JsonProperty("actionSetVlanId")
public void setActionSetVlanId(ActionSetVlanId action) {
- actionSetVlanId = action;
- actionType = ActionValues.ACTION_SET_VLAN_VID;
+ actionSetVlanId = action;
+ actionType = ActionValues.ACTION_SET_VLAN_VID;
}
/**
@@ -1209,8 +1217,8 @@
* @param vlanId the VLAN ID to set.
*/
public void setActionSetVlanId(short vlanId) {
- actionSetVlanId = new ActionSetVlanId(vlanId);
- actionType = ActionValues.ACTION_SET_VLAN_VID;
+ actionSetVlanId = new ActionSetVlanId(vlanId);
+ actionType = ActionValues.ACTION_SET_VLAN_VID;
}
/**
@@ -1220,7 +1228,7 @@
*/
@JsonProperty("actionSetVlanPriority")
public ActionSetVlanPriority actionSetVlanPriority() {
- return actionSetVlanPriority;
+ return actionSetVlanPriority;
}
/**
@@ -1230,8 +1238,8 @@
*/
@JsonProperty("actionSetVlanPriority")
public void setActionSetVlanPriority(ActionSetVlanPriority action) {
- actionSetVlanPriority = action;
- actionType = ActionValues.ACTION_SET_VLAN_PCP;
+ actionSetVlanPriority = action;
+ actionType = ActionValues.ACTION_SET_VLAN_PCP;
}
/**
@@ -1240,8 +1248,8 @@
* @param vlanPriority the VLAN priority to set.
*/
public void setActionSetVlanPriority(byte vlanPriority) {
- actionSetVlanPriority = new ActionSetVlanPriority(vlanPriority);
- actionType = ActionValues.ACTION_SET_VLAN_PCP;
+ actionSetVlanPriority = new ActionSetVlanPriority(vlanPriority);
+ actionType = ActionValues.ACTION_SET_VLAN_PCP;
}
/**
@@ -1251,7 +1259,7 @@
*/
@JsonProperty("actionStripVlan")
public ActionStripVlan actionStripVlan() {
- return actionStripVlan;
+ return actionStripVlan;
}
/**
@@ -1261,8 +1269,8 @@
*/
@JsonProperty("actionStripVlan")
public void setActionStripVlan(ActionStripVlan action) {
- actionStripVlan = action;
- actionType = ActionValues.ACTION_STRIP_VLAN;
+ actionStripVlan = action;
+ actionType = ActionValues.ACTION_STRIP_VLAN;
}
/**
@@ -1271,8 +1279,8 @@
* @param stripVlan if true, strip the VLAN header.
*/
public void setActionStripVlan(boolean stripVlan) {
- actionStripVlan = new ActionStripVlan(stripVlan);
- actionType = ActionValues.ACTION_STRIP_VLAN;
+ actionStripVlan = new ActionStripVlan(stripVlan);
+ actionType = ActionValues.ACTION_STRIP_VLAN;
}
/**
@@ -1282,7 +1290,7 @@
*/
@JsonProperty("actionSetEthernetSrcAddr")
public ActionSetEthernetAddr actionSetEthernetSrcAddr() {
- return actionSetEthernetSrcAddr;
+ return actionSetEthernetSrcAddr;
}
/**
@@ -1292,8 +1300,8 @@
*/
@JsonProperty("actionSetEthernetSrcAddr")
public void setActionSetEthernetSrcAddr(ActionSetEthernetAddr action) {
- actionSetEthernetSrcAddr = action;
- actionType = ActionValues.ACTION_SET_DL_SRC;
+ actionSetEthernetSrcAddr = action;
+ actionType = ActionValues.ACTION_SET_DL_SRC;
}
/**
@@ -1302,8 +1310,8 @@
* @param addr the MAC address to set as the Ethernet source address.
*/
public void setActionSetEthernetSrcAddr(MACAddress addr) {
- actionSetEthernetSrcAddr = new ActionSetEthernetAddr(addr);
- actionType = ActionValues.ACTION_SET_DL_SRC;
+ actionSetEthernetSrcAddr = new ActionSetEthernetAddr(addr);
+ actionType = ActionValues.ACTION_SET_DL_SRC;
}
/**
@@ -1313,7 +1321,7 @@
*/
@JsonProperty("actionSetEthernetDstAddr")
public ActionSetEthernetAddr actionSetEthernetDstAddr() {
- return actionSetEthernetDstAddr;
+ return actionSetEthernetDstAddr;
}
/**
@@ -1323,8 +1331,8 @@
*/
@JsonProperty("actionSetEthernetDstAddr")
public void setActionSetEthernetDstAddr(ActionSetEthernetAddr action) {
- actionSetEthernetDstAddr = action;
- actionType = ActionValues.ACTION_SET_DL_DST;
+ actionSetEthernetDstAddr = action;
+ actionType = ActionValues.ACTION_SET_DL_DST;
}
/**
@@ -1333,8 +1341,8 @@
* @param addr the MAC address to set as the Ethernet destination address.
*/
public void setActionSetEthernetDstAddr(MACAddress addr) {
- actionSetEthernetDstAddr = new ActionSetEthernetAddr(addr);
- actionType = ActionValues.ACTION_SET_DL_DST;
+ actionSetEthernetDstAddr = new ActionSetEthernetAddr(addr);
+ actionType = ActionValues.ACTION_SET_DL_DST;
}
/**
@@ -1344,7 +1352,7 @@
*/
@JsonProperty("actionSetIPv4SrcAddr")
public ActionSetIPv4Addr actionSetIPv4SrcAddr() {
- return actionSetIPv4SrcAddr;
+ return actionSetIPv4SrcAddr;
}
/**
@@ -1354,8 +1362,8 @@
*/
@JsonProperty("actionSetIPv4SrcAddr")
public void setActionSetIPv4SrcAddr(ActionSetIPv4Addr action) {
- actionSetIPv4SrcAddr = action;
- actionType = ActionValues.ACTION_SET_NW_SRC;
+ actionSetIPv4SrcAddr = action;
+ actionType = ActionValues.ACTION_SET_NW_SRC;
}
/**
@@ -1364,8 +1372,8 @@
* @param addr the IPv4 address to set as the IPv4 source address.
*/
public void setActionSetIPv4SrcAddr(IPv4 addr) {
- actionSetIPv4SrcAddr = new ActionSetIPv4Addr(addr);
- actionType = ActionValues.ACTION_SET_NW_SRC;
+ actionSetIPv4SrcAddr = new ActionSetIPv4Addr(addr);
+ actionType = ActionValues.ACTION_SET_NW_SRC;
}
/**
@@ -1375,7 +1383,7 @@
*/
@JsonProperty("actionSetIPv4DstAddr")
public ActionSetIPv4Addr actionSetIPv4DstAddr() {
- return actionSetIPv4DstAddr;
+ return actionSetIPv4DstAddr;
}
/**
@@ -1385,8 +1393,8 @@
*/
@JsonProperty("actionSetIPv4DstAddr")
public void setActionSetIPv4DstAddr(ActionSetIPv4Addr action) {
- actionSetIPv4DstAddr = action;
- actionType = ActionValues.ACTION_SET_NW_DST;
+ actionSetIPv4DstAddr = action;
+ actionType = ActionValues.ACTION_SET_NW_DST;
}
/**
@@ -1395,8 +1403,8 @@
* @param addr the IPv4 address to set as the IPv4 destination address.
*/
public void setActionSetIPv4DstAddr(IPv4 addr) {
- actionSetIPv4DstAddr = new ActionSetIPv4Addr(addr);
- actionType = ActionValues.ACTION_SET_NW_DST;
+ actionSetIPv4DstAddr = new ActionSetIPv4Addr(addr);
+ actionType = ActionValues.ACTION_SET_NW_DST;
}
/**
@@ -1406,7 +1414,7 @@
*/
@JsonProperty("actionSetIpToS")
public ActionSetIpToS actionSetIpToS() {
- return actionSetIpToS;
+ return actionSetIpToS;
}
/**
@@ -1416,8 +1424,8 @@
*/
@JsonProperty("actionSetIpToS")
public void setActionSetIpToS(ActionSetIpToS action) {
- actionSetIpToS = action;
- actionType = ActionValues.ACTION_SET_NW_TOS;
+ actionSetIpToS = action;
+ actionType = ActionValues.ACTION_SET_NW_TOS;
}
/**
@@ -1426,8 +1434,8 @@
* @param ipToS the IP ToS (DSCP field, 6 bits) to set.
*/
public void setActionSetIpToS(byte ipToS) {
- actionSetIpToS = new ActionSetIpToS(ipToS);
- actionType = ActionValues.ACTION_SET_NW_TOS;
+ actionSetIpToS = new ActionSetIpToS(ipToS);
+ actionType = ActionValues.ACTION_SET_NW_TOS;
}
/**
@@ -1437,7 +1445,7 @@
*/
@JsonProperty("actionSetTcpUdpSrcPort")
public ActionSetTcpUdpPort actionSetTcpUdpSrcPort() {
- return actionSetTcpUdpSrcPort;
+ return actionSetTcpUdpSrcPort;
}
/**
@@ -1447,8 +1455,8 @@
*/
@JsonProperty("actionSetTcpUdpSrcPort")
public void setActionSetTcpUdpSrcPort(ActionSetTcpUdpPort action) {
- actionSetTcpUdpSrcPort = action;
- actionType = ActionValues.ACTION_SET_TP_SRC;
+ actionSetTcpUdpSrcPort = action;
+ actionType = ActionValues.ACTION_SET_TP_SRC;
}
/**
@@ -1457,8 +1465,8 @@
* @param port the TCP/UDP port to set as the TCP/UDP source port.
*/
public void setActionSetTcpUdpSrcPort(short port) {
- actionSetTcpUdpSrcPort = new ActionSetTcpUdpPort(port);
- actionType = ActionValues.ACTION_SET_TP_SRC;
+ actionSetTcpUdpSrcPort = new ActionSetTcpUdpPort(port);
+ actionType = ActionValues.ACTION_SET_TP_SRC;
}
/**
@@ -1468,7 +1476,7 @@
*/
@JsonProperty("actionSetTcpUdpDstPort")
public ActionSetTcpUdpPort actionSetTcpUdpDstPort() {
- return actionSetTcpUdpDstPort;
+ return actionSetTcpUdpDstPort;
}
/**
@@ -1478,8 +1486,8 @@
*/
@JsonProperty("actionSetTcpUdpDstPort")
public void setActionSetTcpUdpDstPort(ActionSetTcpUdpPort action) {
- actionSetTcpUdpDstPort = action;
- actionType = ActionValues.ACTION_SET_TP_DST;
+ actionSetTcpUdpDstPort = action;
+ actionType = ActionValues.ACTION_SET_TP_DST;
}
/**
@@ -1488,8 +1496,8 @@
* @param port the TCP/UDP port to set as the TCP/UDP destination port.
*/
public void setActionSetTcpUdpDstPort(short port) {
- actionSetTcpUdpDstPort = new ActionSetTcpUdpPort(port);
- actionType = ActionValues.ACTION_SET_TP_DST;
+ actionSetTcpUdpDstPort = new ActionSetTcpUdpPort(port);
+ actionType = ActionValues.ACTION_SET_TP_DST;
}
/**
@@ -1498,7 +1506,9 @@
* @return the action to output to queue on a port.
*/
@JsonProperty("actionEnqueue")
- public ActionEnqueue actionEnqueue() { return actionEnqueue; }
+ public ActionEnqueue actionEnqueue() {
+ return actionEnqueue;
+ }
/**
* Set the action to output to queue on a port.
@@ -1507,171 +1517,171 @@
*/
@JsonProperty("actionEnqueue")
public void setActionEnqueue(ActionEnqueue action) {
- actionEnqueue = action;
- actionType = ActionValues.ACTION_ENQUEUE;
+ actionEnqueue = action;
+ actionType = ActionValues.ACTION_ENQUEUE;
}
/**
* Set the action to output to queue on a port.
*
- * @param port the port to set.
+ * @param port the port to set.
* @param queueId the queue ID to set.
*/
public void setActionEnqueue(Port port, int queueId) {
- actionEnqueue = new ActionEnqueue(port, queueId);
- actionType = ActionValues.ACTION_ENQUEUE;
+ actionEnqueue = new ActionEnqueue(port, queueId);
+ actionType = ActionValues.ACTION_ENQUEUE;
}
/**
* Convert the action to a string.
- *
+ * <p/>
* The string has the following form:
- * [type=XXX action=XXX]
+ * [type=XXX action=XXX]
*
* @return the action as a string.
*/
@Override
public String toString() {
- String ret = "[";
- ret += "type=" + actionType;
- switch (actionType) {
- case ACTION_OUTPUT:
- ret += " action=" + actionOutput.toString();
- break;
- case ACTION_SET_VLAN_VID:
- ret += " action=" + actionSetVlanId.toString();
- break;
- case ACTION_SET_VLAN_PCP:
- ret += " action=" + actionSetVlanPriority.toString();
- break;
- case ACTION_STRIP_VLAN:
- ret += " action=" + actionStripVlan.toString();
- break;
- case ACTION_SET_DL_SRC:
- ret += " action=" + actionSetEthernetSrcAddr.toString();
- break;
- case ACTION_SET_DL_DST:
- ret += " action=" + actionSetEthernetDstAddr.toString();
- break;
- case ACTION_SET_NW_SRC:
- ret += " action=" + actionSetIPv4SrcAddr.toString();
- break;
- case ACTION_SET_NW_DST:
- ret += " action=" + actionSetIPv4DstAddr.toString();
- break;
- case ACTION_SET_NW_TOS:
- ret += " action=" + actionSetIpToS.toString();
- break;
- case ACTION_SET_TP_SRC:
- ret += " action=" + actionSetTcpUdpSrcPort.toString();
- break;
- case ACTION_SET_TP_DST:
- ret += " action=" + actionSetTcpUdpDstPort.toString();
- break;
- case ACTION_ENQUEUE:
- ret += " action=" + actionEnqueue.toString();
- break;
- case ACTION_VENDOR:
- ret += " action=VENDOR";
- break;
- }
- ret += "]";
+ String ret = "[";
+ ret += "type=" + actionType;
+ switch (actionType) {
+ case ACTION_OUTPUT:
+ ret += " action=" + actionOutput.toString();
+ break;
+ case ACTION_SET_VLAN_VID:
+ ret += " action=" + actionSetVlanId.toString();
+ break;
+ case ACTION_SET_VLAN_PCP:
+ ret += " action=" + actionSetVlanPriority.toString();
+ break;
+ case ACTION_STRIP_VLAN:
+ ret += " action=" + actionStripVlan.toString();
+ break;
+ case ACTION_SET_DL_SRC:
+ ret += " action=" + actionSetEthernetSrcAddr.toString();
+ break;
+ case ACTION_SET_DL_DST:
+ ret += " action=" + actionSetEthernetDstAddr.toString();
+ break;
+ case ACTION_SET_NW_SRC:
+ ret += " action=" + actionSetIPv4SrcAddr.toString();
+ break;
+ case ACTION_SET_NW_DST:
+ ret += " action=" + actionSetIPv4DstAddr.toString();
+ break;
+ case ACTION_SET_NW_TOS:
+ ret += " action=" + actionSetIpToS.toString();
+ break;
+ case ACTION_SET_TP_SRC:
+ ret += " action=" + actionSetTcpUdpSrcPort.toString();
+ break;
+ case ACTION_SET_TP_DST:
+ ret += " action=" + actionSetTcpUdpDstPort.toString();
+ break;
+ case ACTION_ENQUEUE:
+ ret += " action=" + actionEnqueue.toString();
+ break;
+ case ACTION_VENDOR:
+ ret += " action=VENDOR";
+ break;
+ }
+ ret += "]";
- return ret;
+ return ret;
}
/**
* Convert a string to an action.
- *
+ * <p/>
* The string has the following form:
- * [type=XXX action=XXX]
+ * [type=XXX action=XXX]
*
* @param actionStr the action as a string.
*/
public void fromString(String actionStr) {
- String[] parts = actionStr.split("type=");
- String decode = null;
+ String[] parts = actionStr.split("type=");
+ String decode = null;
- // Extract the string after the "type="
- if (parts.length > 1)
- decode = parts[1];
- if (decode == null)
- throw new IllegalArgumentException("Invalid action string");
+ // Extract the string after the "type="
+ if (parts.length > 1)
+ decode = parts[1];
+ if (decode == null)
+ throw new IllegalArgumentException("Invalid action string");
- // Remove the trailing ']'
- if ((decode.length() > 0) && (decode.charAt(decode.length() - 1) == ']')) {
- decode = decode.substring(0, decode.length() - 1);
- } else {
- throw new IllegalArgumentException("Invalid action string");
- }
+ // Remove the trailing ']'
+ if ((decode.length() > 0) && (decode.charAt(decode.length() - 1) == ']')) {
+ decode = decode.substring(0, decode.length() - 1);
+ } else {
+ throw new IllegalArgumentException("Invalid action string");
+ }
- // Extract the type value and the action value
- parts = decode.split(" action=");
+ // Extract the type value and the action value
+ parts = decode.split(" action=");
- // Decode the "type=XXX" payload
- if (parts.length > 0)
- decode = parts[0];
- if (decode != null) {
- try {
- actionType = Enum.valueOf(ActionValues.class, decode);
- } catch (IllegalArgumentException e) {
- throw new IllegalArgumentException("Invalid action string");
- }
- } else {
- throw new IllegalArgumentException("Invalid action string");
- }
+ // Decode the "type=XXX" payload
+ if (parts.length > 0)
+ decode = parts[0];
+ if (decode != null) {
+ try {
+ actionType = Enum.valueOf(ActionValues.class, decode);
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException("Invalid action string");
+ }
+ } else {
+ throw new IllegalArgumentException("Invalid action string");
+ }
- // Decode the "action=XXX" payload
- decode = null;
- if (parts.length > 1)
- decode = parts[1];
- if (decode == null)
- throw new IllegalArgumentException("Invalid action string");
- //
- try {
- switch (actionType) {
- case ACTION_OUTPUT:
- actionOutput = new ActionOutput(decode);
- break;
- case ACTION_SET_VLAN_VID:
- actionSetVlanId = new ActionSetVlanId(decode);
- break;
- case ACTION_SET_VLAN_PCP:
- actionSetVlanPriority = new ActionSetVlanPriority(decode);
- break;
- case ACTION_STRIP_VLAN:
- actionStripVlan = new ActionStripVlan(decode);
- break;
- case ACTION_SET_DL_SRC:
- actionSetEthernetSrcAddr = new ActionSetEthernetAddr(decode);
- break;
- case ACTION_SET_DL_DST:
- actionSetEthernetDstAddr = new ActionSetEthernetAddr(decode);
- break;
- case ACTION_SET_NW_SRC:
- actionSetIPv4SrcAddr = new ActionSetIPv4Addr(decode);
- break;
- case ACTION_SET_NW_DST:
- actionSetIPv4DstAddr = new ActionSetIPv4Addr(decode);
- break;
- case ACTION_SET_NW_TOS:
- actionSetIpToS = new ActionSetIpToS(decode);
- break;
- case ACTION_SET_TP_SRC:
- actionSetTcpUdpSrcPort = new ActionSetTcpUdpPort(decode);
- break;
- case ACTION_SET_TP_DST:
- actionSetTcpUdpDstPort = new ActionSetTcpUdpPort(decode);
- break;
- case ACTION_ENQUEUE:
- actionEnqueue = new ActionEnqueue(decode);
- break;
- case ACTION_VENDOR:
- // TODO: Handle it as appropriate
- break;
- }
- } catch (IllegalArgumentException e) {
- throw new IllegalArgumentException("Invalid action string");
- }
+ // Decode the "action=XXX" payload
+ decode = null;
+ if (parts.length > 1)
+ decode = parts[1];
+ if (decode == null)
+ throw new IllegalArgumentException("Invalid action string");
+ //
+ try {
+ switch (actionType) {
+ case ACTION_OUTPUT:
+ actionOutput = new ActionOutput(decode);
+ break;
+ case ACTION_SET_VLAN_VID:
+ actionSetVlanId = new ActionSetVlanId(decode);
+ break;
+ case ACTION_SET_VLAN_PCP:
+ actionSetVlanPriority = new ActionSetVlanPriority(decode);
+ break;
+ case ACTION_STRIP_VLAN:
+ actionStripVlan = new ActionStripVlan(decode);
+ break;
+ case ACTION_SET_DL_SRC:
+ actionSetEthernetSrcAddr = new ActionSetEthernetAddr(decode);
+ break;
+ case ACTION_SET_DL_DST:
+ actionSetEthernetDstAddr = new ActionSetEthernetAddr(decode);
+ break;
+ case ACTION_SET_NW_SRC:
+ actionSetIPv4SrcAddr = new ActionSetIPv4Addr(decode);
+ break;
+ case ACTION_SET_NW_DST:
+ actionSetIPv4DstAddr = new ActionSetIPv4Addr(decode);
+ break;
+ case ACTION_SET_NW_TOS:
+ actionSetIpToS = new ActionSetIpToS(decode);
+ break;
+ case ACTION_SET_TP_SRC:
+ actionSetTcpUdpSrcPort = new ActionSetTcpUdpPort(decode);
+ break;
+ case ACTION_SET_TP_DST:
+ actionSetTcpUdpDstPort = new ActionSetTcpUdpPort(decode);
+ break;
+ case ACTION_ENQUEUE:
+ actionEnqueue = new ActionEnqueue(decode);
+ break;
+ case ACTION_VENDOR:
+ // TODO: Handle it as appropriate
+ break;
+ }
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException("Invalid action string");
+ }
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/FlowEntryActions.java b/src/main/java/net/onrc/onos/core/util/FlowEntryActions.java
index 8839ceb..fc55932 100644
--- a/src/main/java/net/onrc/onos/core/util/FlowEntryActions.java
+++ b/src/main/java/net/onrc/onos/core/util/FlowEntryActions.java
@@ -7,29 +7,29 @@
/**
* The class representing multiple Flow Entry actions.
- *
+ * <p/>
* A set of Flow Entry actions need to be applied to each packet.
*/
public class FlowEntryActions {
- private ArrayList<FlowEntryAction> actions; // The Flow Entry Actions
+ private ArrayList<FlowEntryAction> actions; // The Flow Entry Actions
/**
* Default constructor.
*/
public FlowEntryActions() {
- actions = new ArrayList<FlowEntryAction>();
+ actions = new ArrayList<FlowEntryAction>();
}
/**
* Constructor from a string.
- *
+ * <p/>
* The string has the following form:
- * [[type=XXX action=XXX];[type=XXX action=XXX];...;]
+ * [[type=XXX action=XXX];[type=XXX action=XXX];...;]
*
* @param actionsStr the set of actions as a string.
*/
public FlowEntryActions(String actionsStr) {
- this.fromString(actionsStr);
+ this.fromString(actionsStr);
}
/**
@@ -38,12 +38,12 @@
* @param other the object to copy from.
*/
public FlowEntryActions(FlowEntryActions other) {
- actions = new ArrayList<FlowEntryAction>();
+ actions = new ArrayList<FlowEntryAction>();
- for (FlowEntryAction action : other.actions) {
- FlowEntryAction newAction = new FlowEntryAction(action);
- actions.add(newAction);
- }
+ for (FlowEntryAction action : other.actions) {
+ FlowEntryAction newAction = new FlowEntryAction(action);
+ actions.add(newAction);
+ }
}
/**
@@ -53,7 +53,7 @@
*/
@JsonProperty("actions")
public ArrayList<FlowEntryAction> actions() {
- return actions;
+ return actions;
}
/**
@@ -63,7 +63,7 @@
*/
@JsonProperty("actions")
public void setActions(ArrayList<FlowEntryAction> actions) {
- this.actions = actions;
+ this.actions = actions;
}
/**
@@ -72,7 +72,7 @@
* @param flowEntryAction the Flow Entry Action to add.
*/
public void addAction(FlowEntryAction flowEntryAction) {
- actions.add(flowEntryAction);
+ actions.add(flowEntryAction);
}
/**
@@ -82,67 +82,67 @@
*/
@JsonIgnore
public Boolean isEmpty() {
- return actions.isEmpty();
+ return actions.isEmpty();
}
/**
* Convert the set of actions to a string.
- *
+ * <p/>
* The string has the following form:
- * [[type=XXX action=XXX];[type=XXX action=XXX];...;]
+ * [[type=XXX action=XXX];[type=XXX action=XXX];...;]
*
* @return the set of actions as a string.
*/
@Override
public String toString() {
- String ret = "[";
- for (FlowEntryAction action : actions) {
- ret += action.toString() + ";";
- }
- ret += "]";
+ String ret = "[";
+ for (FlowEntryAction action : actions) {
+ ret += action.toString() + ";";
+ }
+ ret += "]";
- return ret;
+ return ret;
}
/**
* Convert a string to a set of actions.
- *
+ * <p/>
* The string has the following form:
- * [[type=XXX action=XXX];[type=XXX action=XXX];...;]
+ * [[type=XXX action=XXX];[type=XXX action=XXX];...;]
*
* @param actionsStr the set of actions as a string.
*/
public void fromString(String actionsStr) {
- String decode = actionsStr;
+ String decode = actionsStr;
- actions = new ArrayList<FlowEntryAction>();
+ actions = new ArrayList<FlowEntryAction>();
- if (decode.isEmpty())
- return; // Nothing to do
+ if (decode.isEmpty())
+ return; // Nothing to do
- // Remove the '[' and ']' in the beginning and the end of the string
- if ((decode.length() > 1) && (decode.charAt(0) == '[') &&
- (decode.charAt(decode.length() - 1) == ']')) {
- decode = decode.substring(1, decode.length() - 1);
- } else {
- throw new IllegalArgumentException("Invalid action string");
- }
+ // Remove the '[' and ']' in the beginning and the end of the string
+ if ((decode.length() > 1) && (decode.charAt(0) == '[') &&
+ (decode.charAt(decode.length() - 1) == ']')) {
+ decode = decode.substring(1, decode.length() - 1);
+ } else {
+ throw new IllegalArgumentException("Invalid action string");
+ }
- // Split the string, and decode each action
- String[] parts = decode.split(";");
- for (int i = 0; i < parts.length; i++) {
- decode = parts[i];
- if ((decode == null) || decode.isEmpty())
- continue;
- FlowEntryAction flowEntryAction = null;
- try {
- flowEntryAction = new FlowEntryAction(decode);
- } catch (IllegalArgumentException e) {
- // TODO: Ignore invalid actions for now
- continue;
- }
- if (flowEntryAction != null)
- actions.add(flowEntryAction);
- }
+ // Split the string, and decode each action
+ String[] parts = decode.split(";");
+ for (int i = 0; i < parts.length; i++) {
+ decode = parts[i];
+ if ((decode == null) || decode.isEmpty())
+ continue;
+ FlowEntryAction flowEntryAction = null;
+ try {
+ flowEntryAction = new FlowEntryAction(decode);
+ } catch (IllegalArgumentException e) {
+ // TODO: Ignore invalid actions for now
+ continue;
+ }
+ if (flowEntryAction != null)
+ actions.add(flowEntryAction);
+ }
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/FlowEntryErrorState.java b/src/main/java/net/onrc/onos/core/util/FlowEntryErrorState.java
index e1c5731..fa12055 100644
--- a/src/main/java/net/onrc/onos/core/util/FlowEntryErrorState.java
+++ b/src/main/java/net/onrc/onos/core/util/FlowEntryErrorState.java
@@ -6,15 +6,15 @@
* The class representing the Flow Entry error state.
*/
public class FlowEntryErrorState {
- private short type; // The error type (e.g., see OF-1.3.1 spec, pp. 95)
- private short code; // The error code (e.g., see OF-1.3.1 spec, pp. 95)
+ private short type; // The error type (e.g., see OF-1.3.1 spec, pp. 95)
+ private short code; // The error code (e.g., see OF-1.3.1 spec, pp. 95)
/**
* Default constructor.
*/
public FlowEntryErrorState() {
- this.type = 0;
- this.code = 0;
+ this.type = 0;
+ this.code = 0;
}
/**
@@ -24,8 +24,8 @@
* @param code the error code to use.
*/
public FlowEntryErrorState(short type, short code) {
- this.type = type;
- this.code = code;
+ this.type = type;
+ this.code = code;
}
/**
@@ -34,7 +34,9 @@
* @return the error type.
*/
@JsonProperty("type")
- public short type() { return type; }
+ public short type() {
+ return type;
+ }
/**
* Set the error type.
@@ -43,7 +45,7 @@
*/
@JsonProperty("type")
public void setType(short type) {
- this.type = type;
+ this.type = type;
}
/**
@@ -52,7 +54,9 @@
* @return the error code.
*/
@JsonProperty("code")
- public short code() { return code; }
+ public short code() {
+ return code;
+ }
/**
* Set the error code.
@@ -61,7 +65,7 @@
*/
@JsonProperty("code")
public void setCode(short code) {
- this.code = code;
+ this.code = code;
}
/**
@@ -71,13 +75,13 @@
* @param code the error code to use.
*/
public void setValue(short type, short code) {
- this.type = type;
- this.code = code;
+ this.type = type;
+ this.code = code;
}
/**
* Convert the error type and code to a string.
- *
+ * <p/>
* The string has the following form:
* [type=1 code=2]
*
@@ -85,7 +89,7 @@
*/
@Override
public String toString() {
- String ret = "[type=" + this.type + " code=" + code + "]";
- return ret;
+ String ret = "[type=" + this.type + " code=" + code + "]";
+ return ret;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/FlowEntryId.java b/src/main/java/net/onrc/onos/core/util/FlowEntryId.java
index e4dd32c..373962e 100644
--- a/src/main/java/net/onrc/onos/core/util/FlowEntryId.java
+++ b/src/main/java/net/onrc/onos/core/util/FlowEntryId.java
@@ -12,8 +12,8 @@
/**
* The class representing a Flow Entry ID.
*/
-@JsonDeserialize(using=FlowEntryIdDeserializer.class)
-@JsonSerialize(using=FlowEntryIdSerializer.class)
+@JsonDeserialize(using = FlowEntryIdDeserializer.class)
+@JsonSerialize(using = FlowEntryIdSerializer.class)
public class FlowEntryId {
private long value;
@@ -21,7 +21,7 @@
* Default constructor.
*/
public FlowEntryId() {
- this.value = -1;
+ this.value = -1;
}
/**
@@ -30,7 +30,7 @@
* @param value the value to use.
*/
public FlowEntryId(long value) {
- this.value = value;
+ this.value = value;
}
/**
@@ -39,17 +39,17 @@
* @param value the value to use.
*/
public FlowEntryId(String value) {
- //
- // Use the help of BigInteger to parse strings representing
- // large unsigned hex long values.
- //
- char c = 0;
- if (value.length() > 2)
- c = value.charAt(1);
- if ((c == 'x') || (c == 'X'))
- this.value = new BigInteger(value.substring(2), 16).longValue();
- else
- this.value = Long.decode(value);
+ //
+ // Use the help of BigInteger to parse strings representing
+ // large unsigned hex long values.
+ //
+ char c = 0;
+ if (value.length() > 2)
+ c = value.charAt(1);
+ if ((c == 'x') || (c == 'X'))
+ this.value = new BigInteger(value.substring(2), 16).longValue();
+ else
+ this.value = Long.decode(value);
}
/**
@@ -57,7 +57,9 @@
*
* @return the value of the Flow Entry ID.
*/
- public long value() { return value; }
+ public long value() {
+ return value;
+ }
/**
* Set the value of the Flow Entry ID.
@@ -65,7 +67,7 @@
* @param value the value to set.
*/
public void setValue(long value) {
- this.value = value;
+ this.value = value;
}
/**
@@ -75,30 +77,30 @@
*/
@JsonIgnore
public boolean isValid() {
- return (this.value() != -1);
+ return (this.value() != -1);
}
/**
- * Returns true of the object is another Flow Entry ID with
+ * Returns true of the object is another Flow Entry ID with
* the same value; otherwise, returns false.
- *
+ *
* @param Object to compare
*/
@Override
- public boolean equals(Object obj){
- if(obj != null && obj.getClass() == this.getClass()) {
- FlowEntryId entry = (FlowEntryId) obj;
- return this.value() == entry.value();
- }
- return false;
+ public boolean equals(Object obj) {
+ if (obj != null && obj.getClass() == this.getClass()) {
+ FlowEntryId entry = (FlowEntryId) obj;
+ return this.value() == entry.value();
+ }
+ return false;
}
-
+
/**
* Return the hash code of the Flow Entry ID
*/
@Override
public int hashCode() {
- return Long.valueOf(value).hashCode();
+ return Long.valueOf(value).hashCode();
}
/**
@@ -108,6 +110,6 @@
*/
@Override
public String toString() {
- return "0x" + Long.toHexString(this.value);
+ return "0x" + Long.toHexString(this.value);
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/FlowEntryMatch.java b/src/main/java/net/onrc/onos/core/util/FlowEntryMatch.java
index cc18071..ce6a202 100644
--- a/src/main/java/net/onrc/onos/core/util/FlowEntryMatch.java
+++ b/src/main/java/net/onrc/onos/core/util/FlowEntryMatch.java
@@ -6,7 +6,7 @@
/**
* The class representing the Flow Entry Matching filter.
- *
+ * <p/>
* The Flow Entry matching filter that is used to specify
* the network data that would be forwarded on the data path from
* the source to the destination. Examples: source or destination MAC address,
@@ -17,70 +17,74 @@
* A class for storing a value to match.
*/
public static class Field<T> {
- /**
- * Default constructor.
- */
- public Field() {
- this.enabled = false;
- }
+ /**
+ * Default constructor.
+ */
+ public Field() {
+ this.enabled = false;
+ }
- /**
- * Constructor for a given value to match.
- *
- * @param value the value to match.
- */
- public Field(T value) {
- this.value = value;
- this.enabled = true;
- }
+ /**
+ * Constructor for a given value to match.
+ *
+ * @param value the value to match.
+ */
+ public Field(T value) {
+ this.value = value;
+ this.enabled = true;
+ }
- /**
- * Get the value.
- *
- * @return the value.
- */
- public T value() { return this.value; }
+ /**
+ * Get the value.
+ *
+ * @return the value.
+ */
+ public T value() {
+ return this.value;
+ }
- /**
- * Enable the matching for a given value.
- *
- * @param value the value to set.
- */
- public void enableMatch(T value) {
- this.value = value;
- this.enabled = true;
- }
+ /**
+ * Enable the matching for a given value.
+ *
+ * @param value the value to set.
+ */
+ public void enableMatch(T value) {
+ this.value = value;
+ this.enabled = true;
+ }
- /**
- * Disable the matching.
- */
- public void disableMatch() {
- this.enabled = false;
- }
+ /**
+ * Disable the matching.
+ */
+ public void disableMatch() {
+ this.enabled = false;
+ }
- /**
- * Test whether matching is enabled.
- *
- * @return true if matching is enabled, otherwise false.
- */
- public boolean enabled() { return this.enabled; }
+ /**
+ * Test whether matching is enabled.
+ *
+ * @return true if matching is enabled, otherwise false.
+ */
+ public boolean enabled() {
+ return this.enabled;
+ }
- private T value; // The value to match
- private boolean enabled; // Set to true, if matching is enabled
+ private T value; // The value to match
+ private boolean enabled; // Set to true, if matching is enabled
}
- private Field<Port> inPort; // Matching input switch port
- private Field<MACAddress> srcMac; // Matching source MAC address
- private Field<MACAddress> dstMac; // Matching destination MAC address
+ private Field<Port> inPort; // Matching input switch port
+ private Field<MACAddress> srcMac; // Matching source MAC address
+ private Field<MACAddress> dstMac; // Matching destination MAC address
private Field<Short> ethernetFrameType; // Matching Ethernet frame type
- private Field<Short> vlanId; // Matching VLAN ID
- private Field<Byte> vlanPriority; // Matching VLAN priority
- private Field<IPv4Net> srcIPv4Net; // Matching source IPv4 prefix
- private Field<IPv4Net> dstIPv4Net; // Matching destination IPv4 prefix
- private Field<Byte> ipProto; // Matching IP protocol
- private Field<Byte> ipToS; // Matching IP ToS (DSCP field, 6 bits)
- private Field<Short> srcTcpUdpPort; // Matching source TCP/UDP port
- private Field<Short> dstTcpUdpPort; // Matching destination TCP/UDP port
+ private Field<Short> vlanId; // Matching VLAN ID
+ private Field<Byte> vlanPriority; // Matching VLAN priority
+ private Field<IPv4Net> srcIPv4Net; // Matching source IPv4 prefix
+ private Field<IPv4Net> dstIPv4Net; // Matching destination IPv4 prefix
+ private Field<Byte> ipProto; // Matching IP protocol
+ private Field<Byte> ipToS; // Matching IP ToS (DSCP field, 6 bits)
+ private Field<Short> srcTcpUdpPort; // Matching source TCP/UDP port
+ private Field<Short> dstTcpUdpPort; // Matching destination TCP/UDP port
/**
* Default constructor.
@@ -94,30 +98,30 @@
* @param other the object to copy from.
*/
public FlowEntryMatch(FlowEntryMatch other) {
- if ((other.inPort != null) && other.inPort.enabled())
- this.enableInPort(other.inPort.value());
- if ((other.srcMac != null) && other.srcMac.enabled())
- this.enableSrcMac(other.srcMac.value());
- if ((other.dstMac != null) && other.dstMac.enabled())
- this.enableDstMac(other.dstMac.value());
- if ((other.ethernetFrameType != null) && other.ethernetFrameType.enabled())
- this.enableEthernetFrameType(other.ethernetFrameType.value());
- if ((other.vlanId != null) && other.vlanId.enabled())
- this.enableVlanId(other.vlanId.value());
- if ((other.vlanPriority != null) && other.vlanPriority.enabled())
- this.enableVlanPriority(other.vlanPriority.value());
- if ((other.srcIPv4Net != null) && other.srcIPv4Net.enabled())
- this.enableSrcIPv4Net(other.srcIPv4Net.value());
- if ((other.dstIPv4Net != null) && other.dstIPv4Net.enabled())
- this.enableDstIPv4Net(other.dstIPv4Net.value());
- if ((other.ipProto != null) && other.ipProto.enabled())
- this.enableIpProto(other.ipProto.value());
- if ((other.ipToS != null) && other.ipToS.enabled())
- this.enableIpToS(other.ipToS.value());
- if ((other.srcTcpUdpPort != null) && other.srcTcpUdpPort.enabled())
- this.enableSrcTcpUdpPort(other.srcTcpUdpPort.value());
- if ((other.dstTcpUdpPort != null) && other.dstTcpUdpPort.enabled())
- this.enableDstTcpUdpPort(other.dstTcpUdpPort.value());
+ if ((other.inPort != null) && other.inPort.enabled())
+ this.enableInPort(other.inPort.value());
+ if ((other.srcMac != null) && other.srcMac.enabled())
+ this.enableSrcMac(other.srcMac.value());
+ if ((other.dstMac != null) && other.dstMac.enabled())
+ this.enableDstMac(other.dstMac.value());
+ if ((other.ethernetFrameType != null) && other.ethernetFrameType.enabled())
+ this.enableEthernetFrameType(other.ethernetFrameType.value());
+ if ((other.vlanId != null) && other.vlanId.enabled())
+ this.enableVlanId(other.vlanId.value());
+ if ((other.vlanPriority != null) && other.vlanPriority.enabled())
+ this.enableVlanPriority(other.vlanPriority.value());
+ if ((other.srcIPv4Net != null) && other.srcIPv4Net.enabled())
+ this.enableSrcIPv4Net(other.srcIPv4Net.value());
+ if ((other.dstIPv4Net != null) && other.dstIPv4Net.enabled())
+ this.enableDstIPv4Net(other.dstIPv4Net.value());
+ if ((other.ipProto != null) && other.ipProto.enabled())
+ this.enableIpProto(other.ipProto.value());
+ if ((other.ipToS != null) && other.ipToS.enabled())
+ this.enableIpToS(other.ipToS.value());
+ if ((other.srcTcpUdpPort != null) && other.srcTcpUdpPort.enabled())
+ this.enableSrcTcpUdpPort(other.srcTcpUdpPort.value());
+ if ((other.dstTcpUdpPort != null) && other.dstTcpUdpPort.enabled())
+ this.enableDstTcpUdpPort(other.dstTcpUdpPort.value());
}
/**
@@ -127,9 +131,9 @@
*/
@JsonProperty("inPort")
public Port inPort() {
- if (inPort != null)
- return inPort.value();
- return null;
+ if (inPort != null)
+ return inPort.value();
+ return null;
}
/**
@@ -139,14 +143,14 @@
*/
@JsonProperty("inPort")
public void enableInPort(Port inPort) {
- this.inPort = new Field<Port>(inPort);
+ this.inPort = new Field<Port>(inPort);
}
/**
* Disable the matching on input switch port.
*/
public void disableInPort() {
- this.inPort = null;
+ this.inPort = null;
}
/**
@@ -156,9 +160,9 @@
*/
@JsonProperty("matchInPort")
public boolean matchInPort() {
- if (inPort != null)
- return inPort.enabled();
- return false;
+ if (inPort != null)
+ return inPort.enabled();
+ return false;
}
/**
@@ -168,9 +172,9 @@
*/
@JsonProperty("srcMac")
public MACAddress srcMac() {
- if (srcMac != null)
- return srcMac.value();
- return null;
+ if (srcMac != null)
+ return srcMac.value();
+ return null;
}
/**
@@ -180,14 +184,14 @@
*/
@JsonProperty("srcMac")
public void enableSrcMac(MACAddress srcMac) {
- this.srcMac = new Field<MACAddress>(srcMac);
+ this.srcMac = new Field<MACAddress>(srcMac);
}
/**
* Disable the matching on source MAC address.
*/
public void disableSrcMac() {
- this.srcMac = null;
+ this.srcMac = null;
}
/**
@@ -197,9 +201,9 @@
*/
@JsonProperty("matchSrcMac")
public boolean matchSrcMac() {
- if (srcMac != null)
- return srcMac.enabled();
- return false;
+ if (srcMac != null)
+ return srcMac.enabled();
+ return false;
}
/**
@@ -209,9 +213,9 @@
*/
@JsonProperty("dstMac")
public MACAddress dstMac() {
- if (dstMac != null)
- return dstMac.value();
- return null;
+ if (dstMac != null)
+ return dstMac.value();
+ return null;
}
/**
@@ -221,14 +225,14 @@
*/
@JsonProperty("dstMac")
public void enableDstMac(MACAddress dstMac) {
- this.dstMac = new Field<MACAddress>(dstMac);
+ this.dstMac = new Field<MACAddress>(dstMac);
}
/**
* Disable the matching on destination MAC address.
*/
public void disableDstMac() {
- this.dstMac = null;
+ this.dstMac = null;
}
/**
@@ -238,9 +242,9 @@
*/
@JsonProperty("matchDstMac")
public boolean matchDstMac() {
- if (dstMac != null)
- return dstMac.enabled();
- return false;
+ if (dstMac != null)
+ return dstMac.enabled();
+ return false;
}
/**
@@ -250,27 +254,27 @@
*/
@JsonProperty("ethernetFrameType")
public Short ethernetFrameType() {
- if (ethernetFrameType != null)
- return ethernetFrameType.value();
- return null;
+ if (ethernetFrameType != null)
+ return ethernetFrameType.value();
+ return null;
}
/**
* Enable the matching on Ethernet frame type.
*
* @param ethernetFrameType the Ethernet frame type value to enable for
- * matching.
+ * matching.
*/
@JsonProperty("ethernetFrameType")
public void enableEthernetFrameType(Short ethernetFrameType) {
- this.ethernetFrameType = new Field<Short>(ethernetFrameType);
+ this.ethernetFrameType = new Field<Short>(ethernetFrameType);
}
/**
* Disable the matching on Ethernet frame type.
*/
public void disableEthernetFrameType() {
- this.ethernetFrameType = null;
+ this.ethernetFrameType = null;
}
/**
@@ -280,9 +284,9 @@
*/
@JsonProperty("matchEthernetFrameType")
public boolean matchEthernetFrameType() {
- if (ethernetFrameType != null)
- return ethernetFrameType.enabled();
- return false;
+ if (ethernetFrameType != null)
+ return ethernetFrameType.enabled();
+ return false;
}
/**
@@ -292,9 +296,9 @@
*/
@JsonProperty("vlanId")
public Short vlanId() {
- if (vlanId != null)
- return vlanId.value();
- return null;
+ if (vlanId != null)
+ return vlanId.value();
+ return null;
}
/**
@@ -304,14 +308,14 @@
*/
@JsonProperty("vlanId")
public void enableVlanId(Short vlanId) {
- this.vlanId = new Field<Short>(vlanId);
+ this.vlanId = new Field<Short>(vlanId);
}
/**
* Disable the matching on VLAN ID.
*/
public void disableVlanId() {
- this.vlanId = null;
+ this.vlanId = null;
}
/**
@@ -321,9 +325,9 @@
*/
@JsonProperty("matchVlanId")
public boolean matchVlanId() {
- if (vlanId != null)
- return vlanId.enabled();
- return false;
+ if (vlanId != null)
+ return vlanId.enabled();
+ return false;
}
/**
@@ -333,9 +337,9 @@
*/
@JsonProperty("vlanPriority")
public Byte vlanPriority() {
- if (vlanPriority != null)
- return vlanPriority.value();
- return null;
+ if (vlanPriority != null)
+ return vlanPriority.value();
+ return null;
}
/**
@@ -345,14 +349,14 @@
*/
@JsonProperty("vlanPriority")
public void enableVlanPriority(Byte vlanPriority) {
- this.vlanPriority = new Field<Byte>(vlanPriority);
+ this.vlanPriority = new Field<Byte>(vlanPriority);
}
/**
* Disable the matching on VLAN priority.
*/
public void disableVlanPriority() {
- this.vlanPriority = null;
+ this.vlanPriority = null;
}
/**
@@ -362,9 +366,9 @@
*/
@JsonProperty("matchVlanPriority")
public boolean matchVlanPriority() {
- if (vlanPriority != null)
- return vlanPriority.enabled();
- return false;
+ if (vlanPriority != null)
+ return vlanPriority.enabled();
+ return false;
}
/**
@@ -374,9 +378,9 @@
*/
@JsonProperty("srcIPv4Net")
public IPv4Net srcIPv4Net() {
- if (srcIPv4Net != null)
- return srcIPv4Net.value();
- return null;
+ if (srcIPv4Net != null)
+ return srcIPv4Net.value();
+ return null;
}
/**
@@ -386,14 +390,14 @@
*/
@JsonProperty("srcIPv4Net")
public void enableSrcIPv4Net(IPv4Net srcIPv4Net) {
- this.srcIPv4Net = new Field<IPv4Net>(srcIPv4Net);
+ this.srcIPv4Net = new Field<IPv4Net>(srcIPv4Net);
}
/**
* Disable the matching on source IPv4 prefix.
*/
public void disableSrcIPv4Net() {
- this.srcIPv4Net = null;
+ this.srcIPv4Net = null;
}
/**
@@ -403,9 +407,9 @@
*/
@JsonProperty("matchSrcIPv4Net")
public boolean matchSrcIPv4Net() {
- if (srcIPv4Net != null)
- return srcIPv4Net.enabled();
- return false;
+ if (srcIPv4Net != null)
+ return srcIPv4Net.enabled();
+ return false;
}
/**
@@ -415,27 +419,27 @@
*/
@JsonProperty("dstIPv4Net")
public IPv4Net dstIPv4Net() {
- if (dstIPv4Net != null)
- return dstIPv4Net.value();
- return null;
+ if (dstIPv4Net != null)
+ return dstIPv4Net.value();
+ return null;
}
/**
* Enable the matching on destination IPv4 prefix.
*
* @param dstIPv4Net the destination IPv4 prefix value to enable for
- * matching.
+ * matching.
*/
@JsonProperty("dstIPv4Net")
public void enableDstIPv4Net(IPv4Net dstIPv4Net) {
- this.dstIPv4Net = new Field<IPv4Net>(dstIPv4Net);
+ this.dstIPv4Net = new Field<IPv4Net>(dstIPv4Net);
}
/**
* Disable the matching on destination IPv4 prefix.
*/
public void disableDstIPv4Net() {
- this.dstIPv4Net = null;
+ this.dstIPv4Net = null;
}
/**
@@ -445,9 +449,9 @@
*/
@JsonProperty("matchDstIPv4Net")
public boolean matchDstIPv4Net() {
- if (dstIPv4Net != null)
- return dstIPv4Net.enabled();
- return false;
+ if (dstIPv4Net != null)
+ return dstIPv4Net.enabled();
+ return false;
}
/**
@@ -457,9 +461,9 @@
*/
@JsonProperty("ipProto")
public Byte ipProto() {
- if (ipProto != null)
- return ipProto.value();
- return null;
+ if (ipProto != null)
+ return ipProto.value();
+ return null;
}
/**
@@ -469,14 +473,14 @@
*/
@JsonProperty("ipProto")
public void enableIpProto(Byte ipProto) {
- this.ipProto = new Field<Byte>(ipProto);
+ this.ipProto = new Field<Byte>(ipProto);
}
/**
* Disable the matching on IP protocol.
*/
public void disableIpProto() {
- this.ipProto = null;
+ this.ipProto = null;
}
/**
@@ -486,9 +490,9 @@
*/
@JsonProperty("matchIpProto")
public boolean matchIpProto() {
- if (ipProto != null)
- return ipProto.enabled();
- return false;
+ if (ipProto != null)
+ return ipProto.enabled();
+ return false;
}
/**
@@ -498,9 +502,9 @@
*/
@JsonProperty("ipToS")
public Byte ipToS() {
- if (ipToS != null)
- return ipToS.value();
- return null;
+ if (ipToS != null)
+ return ipToS.value();
+ return null;
}
/**
@@ -510,14 +514,14 @@
*/
@JsonProperty("ipToS")
public void enableIpToS(Byte ipToS) {
- this.ipToS = new Field<Byte>(ipToS);
+ this.ipToS = new Field<Byte>(ipToS);
}
/**
* Disable the matching on IP ToS (DSCP field, 6 bits).
*/
public void disableIpToS() {
- this.ipToS = null;
+ this.ipToS = null;
}
/**
@@ -527,9 +531,9 @@
*/
@JsonProperty("matchIpToS")
public boolean matchIpToS() {
- if (ipToS != null)
- return ipToS.enabled();
- return false;
+ if (ipToS != null)
+ return ipToS.enabled();
+ return false;
}
/**
@@ -539,9 +543,9 @@
*/
@JsonProperty("srcTcpUdpPort")
public Short srcTcpUdpPort() {
- if (srcTcpUdpPort != null)
- return srcTcpUdpPort.value();
- return null;
+ if (srcTcpUdpPort != null)
+ return srcTcpUdpPort.value();
+ return null;
}
/**
@@ -551,14 +555,14 @@
*/
@JsonProperty("srcTcpUdpPort")
public void enableSrcTcpUdpPort(Short srcTcpUdpPort) {
- this.srcTcpUdpPort = new Field<Short>(srcTcpUdpPort);
+ this.srcTcpUdpPort = new Field<Short>(srcTcpUdpPort);
}
/**
* Disable the matching on source TCP/UDP port.
*/
public void disableSrcTcpUdpPort() {
- this.srcTcpUdpPort = null;
+ this.srcTcpUdpPort = null;
}
/**
@@ -568,9 +572,9 @@
*/
@JsonProperty("matchSrcTcpUdpPort")
public boolean matchSrcTcpUdpPort() {
- if (srcTcpUdpPort != null)
- return srcTcpUdpPort.enabled();
- return false;
+ if (srcTcpUdpPort != null)
+ return srcTcpUdpPort.enabled();
+ return false;
}
/**
@@ -580,27 +584,27 @@
*/
@JsonProperty("dstTcpUdpPort")
public Short dstTcpUdpPort() {
- if (dstTcpUdpPort != null)
- return dstTcpUdpPort.value();
- return null;
+ if (dstTcpUdpPort != null)
+ return dstTcpUdpPort.value();
+ return null;
}
/**
* Enable the matching on destination TCP/UDP port.
*
* @param dstTcpUdpPort the destination TCP/UDP port to enable for
- * matching.
+ * matching.
*/
@JsonProperty("dstTcpUdpPort")
public void enableDstTcpUdpPort(Short dstTcpUdpPort) {
- this.dstTcpUdpPort = new Field<Short>(dstTcpUdpPort);
+ this.dstTcpUdpPort = new Field<Short>(dstTcpUdpPort);
}
/**
* Disable the matching on destination TCP/UDP port.
*/
public void disableDstTcpUdpPort() {
- this.dstTcpUdpPort = null;
+ this.dstTcpUdpPort = null;
}
/**
@@ -610,102 +614,102 @@
*/
@JsonProperty("matchDstTcpUdpPort")
public boolean matchDstTcpUdpPort() {
- if (dstTcpUdpPort != null)
- return dstTcpUdpPort.enabled();
- return false;
+ if (dstTcpUdpPort != null)
+ return dstTcpUdpPort.enabled();
+ return false;
}
/**
* Convert the matching filter to a string.
- *
+ * <p/>
* The string has the following form:
- * [srcMac=XXX dstMac=XXX srcIPv4Net=XXX dstIPv4Net=XXX]
+ * [srcMac=XXX dstMac=XXX srcIPv4Net=XXX dstIPv4Net=XXX]
*
* @return the matching filter as a string.
*/
@Override
public String toString() {
- String ret = "[";
- boolean addSpace = false;
+ String ret = "[";
+ boolean addSpace = false;
- //
- // Conditionally add only those matching fields that are enabled
- //
- if (matchInPort()) {
- if (addSpace)
- ret += " ";
- addSpace = true;
- ret += "inPort=" + this.inPort().toString();
- }
- if (matchSrcMac()) {
- if (addSpace)
- ret += " ";
- addSpace = true;
- ret += "srcMac=" + this.srcMac().toString();
- }
- if (matchDstMac()) {
- if (addSpace)
- ret += " ";
- addSpace = true;
- ret += "dstMac=" + this.dstMac().toString();
- }
- if (matchEthernetFrameType()) {
- if (addSpace)
- ret += " ";
- addSpace = true;
- ret += "ethernetFrameType=" + this.ethernetFrameType().toString();
- }
- if (matchVlanId()) {
- if (addSpace)
- ret += " ";
- addSpace = true;
- ret += "vlanId=" + this.vlanId().toString();
- }
- if (matchVlanPriority()) {
- if (addSpace)
- ret += " ";
- addSpace = true;
- ret += "vlanPriority=" + this.vlanPriority().toString();
- }
- if (matchSrcIPv4Net()) {
- if (addSpace)
- ret += " ";
- addSpace = true;
- ret += "srcIPv4Net=" + this.srcIPv4Net().toString();
- }
- if (matchDstIPv4Net()) {
- if (addSpace)
- ret += " ";
- addSpace = true;
- ret += "dstIPv4Net=" + this.dstIPv4Net().toString();
- }
- if (matchIpProto()) {
- if (addSpace)
- ret += " ";
- addSpace = true;
- ret += "ipProto=" + this.ipProto().toString();
- }
- if (matchIpToS()) {
- if (addSpace)
- ret += " ";
- addSpace = true;
- ret += "ipToS=" + this.ipToS().toString();
- }
- if (matchSrcTcpUdpPort()) {
- if (addSpace)
- ret += " ";
- addSpace = true;
- ret += "srcTcpUdpPort=" + this.srcTcpUdpPort().toString();
- }
- if (matchDstTcpUdpPort()) {
- if (addSpace)
- ret += " ";
- addSpace = true;
- ret += "dstTcpUdpPort=" + this.dstTcpUdpPort().toString();
- }
+ //
+ // Conditionally add only those matching fields that are enabled
+ //
+ if (matchInPort()) {
+ if (addSpace)
+ ret += " ";
+ addSpace = true;
+ ret += "inPort=" + this.inPort().toString();
+ }
+ if (matchSrcMac()) {
+ if (addSpace)
+ ret += " ";
+ addSpace = true;
+ ret += "srcMac=" + this.srcMac().toString();
+ }
+ if (matchDstMac()) {
+ if (addSpace)
+ ret += " ";
+ addSpace = true;
+ ret += "dstMac=" + this.dstMac().toString();
+ }
+ if (matchEthernetFrameType()) {
+ if (addSpace)
+ ret += " ";
+ addSpace = true;
+ ret += "ethernetFrameType=" + this.ethernetFrameType().toString();
+ }
+ if (matchVlanId()) {
+ if (addSpace)
+ ret += " ";
+ addSpace = true;
+ ret += "vlanId=" + this.vlanId().toString();
+ }
+ if (matchVlanPriority()) {
+ if (addSpace)
+ ret += " ";
+ addSpace = true;
+ ret += "vlanPriority=" + this.vlanPriority().toString();
+ }
+ if (matchSrcIPv4Net()) {
+ if (addSpace)
+ ret += " ";
+ addSpace = true;
+ ret += "srcIPv4Net=" + this.srcIPv4Net().toString();
+ }
+ if (matchDstIPv4Net()) {
+ if (addSpace)
+ ret += " ";
+ addSpace = true;
+ ret += "dstIPv4Net=" + this.dstIPv4Net().toString();
+ }
+ if (matchIpProto()) {
+ if (addSpace)
+ ret += " ";
+ addSpace = true;
+ ret += "ipProto=" + this.ipProto().toString();
+ }
+ if (matchIpToS()) {
+ if (addSpace)
+ ret += " ";
+ addSpace = true;
+ ret += "ipToS=" + this.ipToS().toString();
+ }
+ if (matchSrcTcpUdpPort()) {
+ if (addSpace)
+ ret += " ";
+ addSpace = true;
+ ret += "srcTcpUdpPort=" + this.srcTcpUdpPort().toString();
+ }
+ if (matchDstTcpUdpPort()) {
+ if (addSpace)
+ ret += " ";
+ addSpace = true;
+ ret += "dstTcpUdpPort=" + this.dstTcpUdpPort().toString();
+ }
- ret += "]";
+ ret += "]";
- return ret;
+ return ret;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/FlowEntrySwitchState.java b/src/main/java/net/onrc/onos/core/util/FlowEntrySwitchState.java
index c5a79de..754755a 100644
--- a/src/main/java/net/onrc/onos/core/util/FlowEntrySwitchState.java
+++ b/src/main/java/net/onrc/onos/core/util/FlowEntrySwitchState.java
@@ -4,9 +4,9 @@
* The Flow Entry state as set by the controller.
*/
public enum FlowEntrySwitchState {
- FE_SWITCH_UNKNOWN, // Initialization value: state unknown
- FE_SWITCH_NOT_UPDATED, // Switch not updated with this entry
- FE_SWITCH_UPDATE_IN_PROGRESS, // Switch update in progress
- FE_SWITCH_UPDATED, // Switch updated with this entry
- FE_SWITCH_UPDATE_FAILED // Error updating the switch with this entry
+ FE_SWITCH_UNKNOWN, // Initialization value: state unknown
+ FE_SWITCH_NOT_UPDATED, // Switch not updated with this entry
+ FE_SWITCH_UPDATE_IN_PROGRESS, // Switch update in progress
+ FE_SWITCH_UPDATED, // Switch updated with this entry
+ FE_SWITCH_UPDATE_FAILED // Error updating the switch with this entry
}
diff --git a/src/main/java/net/onrc/onos/core/util/FlowEntryUserState.java b/src/main/java/net/onrc/onos/core/util/FlowEntryUserState.java
index 64d283a..8cad5d0 100644
--- a/src/main/java/net/onrc/onos/core/util/FlowEntryUserState.java
+++ b/src/main/java/net/onrc/onos/core/util/FlowEntryUserState.java
@@ -4,8 +4,8 @@
* The Flow Entry state as set by the user (via the ONOS API).
*/
public enum FlowEntryUserState {
- FE_USER_UNKNOWN, // Initialization value: state unknown
- FE_USER_ADD, // Flow entry that is added
- FE_USER_MODIFY, // Flow entry that is modified
- FE_USER_DELETE // Flow entry that is deleted
+ FE_USER_UNKNOWN, // Initialization value: state unknown
+ FE_USER_ADD, // Flow entry that is added
+ FE_USER_MODIFY, // Flow entry that is modified
+ FE_USER_DELETE // Flow entry that is deleted
}
diff --git a/src/main/java/net/onrc/onos/core/util/FlowId.java b/src/main/java/net/onrc/onos/core/util/FlowId.java
index a6ceed8..c5ee39d 100644
--- a/src/main/java/net/onrc/onos/core/util/FlowId.java
+++ b/src/main/java/net/onrc/onos/core/util/FlowId.java
@@ -12,8 +12,8 @@
/**
* The class representing a Flow ID.
*/
-@JsonDeserialize(using=FlowIdDeserializer.class)
-@JsonSerialize(using=FlowIdSerializer.class)
+@JsonDeserialize(using = FlowIdDeserializer.class)
+@JsonSerialize(using = FlowIdSerializer.class)
public class FlowId implements Comparable<FlowId> {
private long value;
@@ -21,7 +21,7 @@
* Default constructor.
*/
public FlowId() {
- this.value = -1;
+ this.value = -1;
}
/**
@@ -30,7 +30,7 @@
* @param value the value to use.
*/
public FlowId(long value) {
- this.value = value;
+ this.value = value;
}
/**
@@ -39,17 +39,17 @@
* @param value the value to use.
*/
public FlowId(String value) {
- //
- // Use the help of BigInteger to parse strings representing
- // large unsigned hex long values.
- //
- char c = 0;
- if (value.length() > 2)
- c = value.charAt(1);
- if ((c == 'x') || (c == 'X'))
- this.value = new BigInteger(value.substring(2), 16).longValue();
- else
- this.value = Long.decode(value);
+ //
+ // Use the help of BigInteger to parse strings representing
+ // large unsigned hex long values.
+ //
+ char c = 0;
+ if (value.length() > 2)
+ c = value.charAt(1);
+ if ((c == 'x') || (c == 'X'))
+ this.value = new BigInteger(value.substring(2), 16).longValue();
+ else
+ this.value = Long.decode(value);
}
/**
@@ -57,7 +57,9 @@
*
* @return the value of the Flow ID.
*/
- public long value() { return value; }
+ public long value() {
+ return value;
+ }
/**
* Set the value of the Flow ID.
@@ -65,7 +67,7 @@
* @param value the value to set.
*/
public void setValue(long value) {
- this.value = value;
+ this.value = value;
}
/**
@@ -75,7 +77,7 @@
*/
@JsonIgnore
public boolean isValid() {
- return (this.value() != -1);
+ return (this.value() != -1);
}
/**
@@ -85,18 +87,18 @@
*/
@Override
public String toString() {
- return "0x" + Long.toHexString(this.value);
+ return "0x" + Long.toHexString(this.value);
}
/**
* Compare two FlowId objects numerically using their Flow IDs.
*
* @return the value 0 if the Flow ID is equal to the argument's Flow ID;
- * a value less than 0 if the Flow ID is numerically less than the argument's Flow ID;
- * and a value greater than 0 if the Flow ID is numerically greater than the argument's Flow ID.
+ * a value less than 0 if the Flow ID is numerically less than the argument's Flow ID;
+ * and a value greater than 0 if the Flow ID is numerically greater than the argument's Flow ID.
*/
- @Override
- public int compareTo(FlowId o) {
- return Long.valueOf(this.value).compareTo(o.value());
- }
+ @Override
+ public int compareTo(FlowId o) {
+ return Long.valueOf(this.value).compareTo(o.value());
+ }
}
diff --git a/src/main/java/net/onrc/onos/core/util/FlowPath.java b/src/main/java/net/onrc/onos/core/util/FlowPath.java
index 2bb5ad3..fe51f08 100644
--- a/src/main/java/net/onrc/onos/core/util/FlowPath.java
+++ b/src/main/java/net/onrc/onos/core/util/FlowPath.java
@@ -9,32 +9,32 @@
* The class representing the Flow Path.
*/
public class FlowPath implements Comparable<FlowPath> {
- public static final int PRIORITY_DEFAULT = 32768; // Default Flow Priority
+ public static final int PRIORITY_DEFAULT = 32768; // Default Flow Priority
- private FlowId flowId; // The Flow ID
- private CallerId installerId; // The Caller ID of the path installer
- private FlowPathType flowPathType; // The Flow Path type
+ private FlowId flowId; // The Flow ID
+ private CallerId installerId; // The Caller ID of the path installer
+ private FlowPathType flowPathType; // The Flow Path type
private FlowPathUserState flowPathUserState; // The Flow Path User state
private FlowPathFlags flowPathFlags; // The Flow Path flags
- private int idleTimeout; // The Flow idle timeout
- private int hardTimeout; // The Flow hard timeout
- private int priority; // The Flow priority
- private DataPath dataPath; // The data path
+ private int idleTimeout; // The Flow idle timeout
+ private int hardTimeout; // The Flow hard timeout
+ private int priority; // The Flow priority
+ private DataPath dataPath; // The data path
private FlowEntryMatch flowEntryMatch; // Common Flow Entry Match for all
- // Flow Entries
+ // Flow Entries
private FlowEntryActions flowEntryActions; // The Flow Entry Actions for
- // the first Flow Entry
+ // the first Flow Entry
/**
* Default constructor.
*/
public FlowPath() {
- flowPathType = FlowPathType.FP_TYPE_UNKNOWN;
- flowPathUserState = FlowPathUserState.FP_USER_UNKNOWN;
- flowPathFlags = new FlowPathFlags();
- priority = FlowPath.PRIORITY_DEFAULT;
- dataPath = new DataPath();
- flowEntryActions = new FlowEntryActions();
+ flowPathType = FlowPathType.FP_TYPE_UNKNOWN;
+ flowPathUserState = FlowPathUserState.FP_USER_UNKNOWN;
+ flowPathFlags = new FlowPathFlags();
+ priority = FlowPath.PRIORITY_DEFAULT;
+ dataPath = new DataPath();
+ flowEntryActions = new FlowEntryActions();
}
/**
@@ -43,7 +43,9 @@
* @return the flow path Flow ID.
*/
@JsonProperty("flowId")
- public FlowId flowId() { return flowId; }
+ public FlowId flowId() {
+ return flowId;
+ }
/**
* Set the flow path Flow ID.
@@ -52,7 +54,7 @@
*/
@JsonProperty("flowId")
public void setFlowId(FlowId flowId) {
- this.flowId = flowId;
+ this.flowId = flowId;
}
/**
@@ -62,9 +64,9 @@
*/
@JsonIgnore
public boolean isValidFlowId() {
- if (this.flowId == null)
- return false;
- return (this.flowId.isValid());
+ if (this.flowId == null)
+ return false;
+ return (this.flowId.isValid());
}
/**
@@ -73,7 +75,9 @@
* @return the Caller ID of the flow path installer.
*/
@JsonProperty("installerId")
- public CallerId installerId() { return installerId; }
+ public CallerId installerId() {
+ return installerId;
+ }
/**
* Set the Caller ID of the flow path installer.
@@ -82,7 +86,7 @@
*/
@JsonProperty("installerId")
public void setInstallerId(CallerId installerId) {
- this.installerId = installerId;
+ this.installerId = installerId;
}
/**
@@ -91,7 +95,9 @@
* @return the flow path type.
*/
@JsonProperty("flowPathType")
- public FlowPathType flowPathType() { return flowPathType; }
+ public FlowPathType flowPathType() {
+ return flowPathType;
+ }
/**
* Set the flow path type.
@@ -100,7 +106,7 @@
*/
@JsonProperty("flowPathType")
public void setFlowPathType(FlowPathType flowPathType) {
- this.flowPathType = flowPathType;
+ this.flowPathType = flowPathType;
}
/**
@@ -109,7 +115,9 @@
* @return the flow path user state.
*/
@JsonProperty("flowPathUserState")
- public FlowPathUserState flowPathUserState() { return flowPathUserState; }
+ public FlowPathUserState flowPathUserState() {
+ return flowPathUserState;
+ }
/**
* Set the flow path user state.
@@ -118,7 +126,7 @@
*/
@JsonProperty("flowPathUserState")
public void setFlowPathUserState(FlowPathUserState flowPathUserState) {
- this.flowPathUserState = flowPathUserState;
+ this.flowPathUserState = flowPathUserState;
}
/**
@@ -127,7 +135,9 @@
* @return the flow path flags.
*/
@JsonProperty("flowPathFlags")
- public FlowPathFlags flowPathFlags() { return flowPathFlags; }
+ public FlowPathFlags flowPathFlags() {
+ return flowPathFlags;
+ }
/**
* Set the flow path flags.
@@ -136,23 +146,25 @@
*/
@JsonProperty("flowPathFlags")
public void setFlowPathFlags(FlowPathFlags flowPathFlags) {
- this.flowPathFlags = flowPathFlags;
+ this.flowPathFlags = flowPathFlags;
}
/**
* Get the flow idle timeout in seconds.
- *
+ * <p/>
* It should be an unsigned integer in the interval [0, 65535].
* If zero, the timeout is not set.
*
* @return the flow idle timeout.
*/
@JsonProperty("idleTimeout")
- public int idleTimeout() { return idleTimeout; }
+ public int idleTimeout() {
+ return idleTimeout;
+ }
/**
* Set the flow idle timeout in seconds.
- *
+ * <p/>
* It should be an unsigned integer in the interval [0, 65535].
* If zero, the timeout is not set.
*
@@ -160,23 +172,25 @@
*/
@JsonProperty("idleTimeout")
public void setIdleTimeout(int idleTimeout) {
- this.idleTimeout = 0xffff & idleTimeout;
+ this.idleTimeout = 0xffff & idleTimeout;
}
/**
* Get the flow hard timeout in seconds.
- *
+ * <p/>
* It should be an unsigned integer in the interval [0, 65535].
* If zero, the timeout is not set.
*
* @return the flow hard timeout.
*/
@JsonProperty("hardTimeout")
- public int hardTimeout() { return hardTimeout; }
+ public int hardTimeout() {
+ return hardTimeout;
+ }
/**
* Set the flow hard timeout.
- *
+ * <p/>
* It should be an unsigned integer in the interval [0, 65535].
* If zero, the timeout is not set.
*
@@ -184,29 +198,31 @@
*/
@JsonProperty("hardTimeout")
public void setHardTimeout(int hardTimeout) {
- this.hardTimeout = 0xffff & hardTimeout;
+ this.hardTimeout = 0xffff & hardTimeout;
}
/**
* Get the flow priority.
- *
+ * <p/>
* It should be an unsigned integer in the interval [0, 65535].
*
* @return the flow priority.
*/
@JsonProperty("priority")
- public int priority() { return priority; }
+ public int priority() {
+ return priority;
+ }
/**
* Set the flow priority.
- *
+ * <p/>
* It should be an unsigned integer in the interval [0, 65535].
*
* @param priority the flow priority to set.
*/
@JsonProperty("priority")
public void setPriority(int priority) {
- this.priority = 0xffff & priority;
+ this.priority = 0xffff & priority;
}
/**
@@ -215,7 +231,9 @@
* @return the flow path's data path.
*/
@JsonProperty("dataPath")
- public DataPath dataPath() { return dataPath; }
+ public DataPath dataPath() {
+ return dataPath;
+ }
/**
* Set the flow path's data path.
@@ -224,7 +242,7 @@
*/
@JsonProperty("dataPath")
public void setDataPath(DataPath dataPath) {
- this.dataPath = dataPath;
+ this.dataPath = dataPath;
}
/**
@@ -233,7 +251,7 @@
* @return the data path flow entries.
*/
public ArrayList<FlowEntry> flowEntries() {
- return this.dataPath.flowEntries();
+ return this.dataPath.flowEntries();
}
/**
@@ -242,17 +260,19 @@
* @return the flow path's match conditions common for all Flow Entries.
*/
@JsonProperty("flowEntryMatch")
- public FlowEntryMatch flowEntryMatch() { return flowEntryMatch; }
+ public FlowEntryMatch flowEntryMatch() {
+ return flowEntryMatch;
+ }
/**
* Set the flow path's match conditions common for all Flow Entries.
*
* @param flowEntryMatch the flow path's match conditions common for all
- * Flow Entries.
+ * Flow Entries.
*/
@JsonProperty("flowEntryMatch")
public void setFlowEntryMatch(FlowEntryMatch flowEntryMatch) {
- this.flowEntryMatch = flowEntryMatch;
+ this.flowEntryMatch = flowEntryMatch;
}
/**
@@ -262,55 +282,55 @@
*/
@JsonProperty("flowEntryActions")
public FlowEntryActions flowEntryActions() {
- return flowEntryActions;
+ return flowEntryActions;
}
/**
* Set the flow path's flow entry actions for the first Flow Entry.
*
* @param flowEntryActions the flow path's flow entry actions for the first
- * Flow Entry.
+ * Flow Entry.
*/
@JsonProperty("flowEntryActions")
public void setFlowEntryActions(FlowEntryActions flowEntryActions) {
- this.flowEntryActions = flowEntryActions;
+ this.flowEntryActions = flowEntryActions;
}
/**
* Convert the flow path to a string.
- *
+ * <p/>
* The string has the following form:
- * [flowId=XXX installerId=XXX flowPathType = XXX flowPathUserState = XXX
- * flowPathFlags=XXX idleTimeout=XXX hardTimeout=XXX priority=XXX
- * dataPath=XXX flowEntryMatch=XXX flowEntryActions=XXX]
+ * [flowId=XXX installerId=XXX flowPathType = XXX flowPathUserState = XXX
+ * flowPathFlags=XXX idleTimeout=XXX hardTimeout=XXX priority=XXX
+ * dataPath=XXX flowEntryMatch=XXX flowEntryActions=XXX]
*
* @return the flow path as a string.
*/
@Override
public String toString() {
- String ret = "[flowId=" + this.flowId.toString();
- ret += " installerId=" + this.installerId.toString();
- ret += " flowPathType=" + this.flowPathType;
- ret += " flowPathUserState=" + this.flowPathUserState;
- ret += " flowPathFlags=" + this.flowPathFlags.toString();
- ret += " idleTimeout=" + this.idleTimeout;
- ret += " hardTimeout=" + this.hardTimeout;
- ret += " priority=" + this.priority;
- if (dataPath != null)
- ret += " dataPath=" + this.dataPath.toString();
- if (flowEntryMatch != null)
- ret += " flowEntryMatch=" + this.flowEntryMatch.toString();
- if (flowEntryActions != null)
- ret += " flowEntryActions=" + this.flowEntryActions.toString();
- ret += "]";
- return ret;
+ String ret = "[flowId=" + this.flowId.toString();
+ ret += " installerId=" + this.installerId.toString();
+ ret += " flowPathType=" + this.flowPathType;
+ ret += " flowPathUserState=" + this.flowPathUserState;
+ ret += " flowPathFlags=" + this.flowPathFlags.toString();
+ ret += " idleTimeout=" + this.idleTimeout;
+ ret += " hardTimeout=" + this.hardTimeout;
+ ret += " priority=" + this.priority;
+ if (dataPath != null)
+ ret += " dataPath=" + this.dataPath.toString();
+ if (flowEntryMatch != null)
+ ret += " flowEntryMatch=" + this.flowEntryMatch.toString();
+ if (flowEntryActions != null)
+ ret += " flowEntryActions=" + this.flowEntryActions.toString();
+ ret += "]";
+ return ret;
}
-
+
/**
* CompareTo method to order flowPath by Id
*/
@Override
public int compareTo(FlowPath f) {
- return (int) (this.flowId.value() - f.flowId.value());
+ return (int) (this.flowId.value() - f.flowId.value());
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/FlowPathFlags.java b/src/main/java/net/onrc/onos/core/util/FlowPathFlags.java
index b52d888..e1e67c5 100644
--- a/src/main/java/net/onrc/onos/core/util/FlowPathFlags.java
+++ b/src/main/java/net/onrc/onos/core/util/FlowPathFlags.java
@@ -9,7 +9,7 @@
private long flags;
// Discard the first-hop Flow Entry
- public static final long DISCARD_FIRST_HOP_ENTRY = (1 << 0);
+ public static final long DISCARD_FIRST_HOP_ENTRY = (1 << 0);
// Keep only the first-hop Flow Entry
public static final long KEEP_ONLY_FIRST_HOP_ENTRY = (1 << 1);
@@ -18,7 +18,7 @@
* Default constructor.
*/
public FlowPathFlags() {
- this.flags = 0;
+ this.flags = 0;
}
/**
@@ -27,18 +27,19 @@
* @param flags the flags value to set.
*/
public FlowPathFlags(long flags) {
- this.flags = flags;
+ this.flags = flags;
}
/**
* Constructor for given flags as a string.
- *
+ * <p/>
* The string value should contain the name of each flags to set. E.g.:
- * "DISCARD_FIRST_HOP_ENTRY,KEEP_ONLY_FIRST_HOP_ENTRY"
+ * "DISCARD_FIRST_HOP_ENTRY,KEEP_ONLY_FIRST_HOP_ENTRY"
+ *
* @param flagsStr the string value of the flags to set.
*/
public FlowPathFlags(String flagsStr) {
- this.setFlagsStr(flagsStr);
+ this.setFlagsStr(flagsStr);
}
/**
@@ -47,7 +48,9 @@
* @return the flags.
*/
@JsonProperty("flags")
- public long flags() { return flags; }
+ public long flags() {
+ return flags;
+ }
/**
* Set the flags.
@@ -56,25 +59,26 @@
*/
@JsonProperty("flags")
public void setFlags(long flags) {
- this.flags = flags;
+ this.flags = flags;
}
/**
* Set the flags as a string.
- *
+ * <p/>
* The string value should contain the name of each flags to set. E.g.:
- * "DISCARD_FIRST_HOP_ENTRY,KEEP_ONLY_FIRST_HOP_ENTRY"
+ * "DISCARD_FIRST_HOP_ENTRY,KEEP_ONLY_FIRST_HOP_ENTRY"
+ *
* @param flagsStr the string value of the flags to set.
*/
@JsonProperty("flagsStr")
public void setFlagsStr(String flagsStr) {
- this.flags = 0L;
+ this.flags = 0L;
- // Test all flags
- if (flagsStr.contains("DISCARD_FIRST_HOP_ENTRY"))
- this.flags |= DISCARD_FIRST_HOP_ENTRY;
- if (flagsStr.contains("KEEP_ONLY_FIRST_HOP_ENTRY"))
- this.flags |= KEEP_ONLY_FIRST_HOP_ENTRY;
+ // Test all flags
+ if (flagsStr.contains("DISCARD_FIRST_HOP_ENTRY"))
+ this.flags |= DISCARD_FIRST_HOP_ENTRY;
+ if (flagsStr.contains("KEEP_ONLY_FIRST_HOP_ENTRY"))
+ this.flags |= KEEP_ONLY_FIRST_HOP_ENTRY;
}
/**
@@ -84,7 +88,7 @@
* otherwise false.
*/
public boolean isDiscardFirstHopEntry() {
- return ((flags & DISCARD_FIRST_HOP_ENTRY) != 0);
+ return ((flags & DISCARD_FIRST_HOP_ENTRY) != 0);
}
/**
@@ -94,36 +98,36 @@
* otherwise false.
*/
public boolean isKeepOnlyFirstHopEntry() {
- return ((flags & KEEP_ONLY_FIRST_HOP_ENTRY) != 0);
+ return ((flags & KEEP_ONLY_FIRST_HOP_ENTRY) != 0);
}
/**
* Convert the Flow Path Flags to a string.
- *
+ * <p/>
* The string has the following form:
- * [flags=DISCARD_FIRST_HOP_ENTRY,KEEP_ONLY_FIRST_HOP_ENTRY]
+ * [flags=DISCARD_FIRST_HOP_ENTRY,KEEP_ONLY_FIRST_HOP_ENTRY]
*
* @return the Flow Path flags as a string.
*/
@Override
public String toString() {
- String flagsStr = null;
- String ret = "[flags=";
+ String flagsStr = null;
+ String ret = "[flags=";
- // Test all flags
- if ((this.flags & DISCARD_FIRST_HOP_ENTRY) != 0) {
- flagsStr += "DISCARD_FIRST_HOP_ENTRY";
- }
- if ((this.flags & KEEP_ONLY_FIRST_HOP_ENTRY) != 0) {
- if (flagsStr != null)
- flagsStr += ",";
- flagsStr += "KEEP_ONLY_FIRST_HOP_ENTRY";
- }
- if (flagsStr != null)
- ret += flagsStr;
- ret += "]";
+ // Test all flags
+ if ((this.flags & DISCARD_FIRST_HOP_ENTRY) != 0) {
+ flagsStr += "DISCARD_FIRST_HOP_ENTRY";
+ }
+ if ((this.flags & KEEP_ONLY_FIRST_HOP_ENTRY) != 0) {
+ if (flagsStr != null)
+ flagsStr += ",";
+ flagsStr += "KEEP_ONLY_FIRST_HOP_ENTRY";
+ }
+ if (flagsStr != null)
+ ret += flagsStr;
+ ret += "]";
- return ret;
+ return ret;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/FlowPathType.java b/src/main/java/net/onrc/onos/core/util/FlowPathType.java
index 4b1214e..f18938d 100644
--- a/src/main/java/net/onrc/onos/core/util/FlowPathType.java
+++ b/src/main/java/net/onrc/onos/core/util/FlowPathType.java
@@ -4,7 +4,7 @@
* The Flow Path types.
*/
public enum FlowPathType {
- FP_TYPE_UNKNOWN, // Initialization value: state unknown
- FP_TYPE_SHORTEST_PATH, // Shortest path flow
- FP_TYPE_EXPLICIT_PATH // Flow path with explicit flow entries
+ FP_TYPE_UNKNOWN, // Initialization value: state unknown
+ FP_TYPE_SHORTEST_PATH, // Shortest path flow
+ FP_TYPE_EXPLICIT_PATH // Flow path with explicit flow entries
}
diff --git a/src/main/java/net/onrc/onos/core/util/FlowPathUserState.java b/src/main/java/net/onrc/onos/core/util/FlowPathUserState.java
index bc91c2a..4b637d1 100644
--- a/src/main/java/net/onrc/onos/core/util/FlowPathUserState.java
+++ b/src/main/java/net/onrc/onos/core/util/FlowPathUserState.java
@@ -4,8 +4,8 @@
* The Flow Path state as set by the user (via the ONOS API).
*/
public enum FlowPathUserState {
- FP_USER_UNKNOWN, // Initialization value: state unknown
- FP_USER_ADD, // Flow path that is added
- FP_USER_MODIFY, // Flow path that is modified
- FP_USER_DELETE // Flow path that is deleted
+ FP_USER_UNKNOWN, // Initialization value: state unknown
+ FP_USER_ADD, // Flow path that is added
+ FP_USER_MODIFY, // Flow path that is modified
+ FP_USER_DELETE // Flow path that is deleted
}
diff --git a/src/main/java/net/onrc/onos/core/util/IPv4.java b/src/main/java/net/onrc/onos/core/util/IPv4.java
index 86795aa..a7f3d24 100644
--- a/src/main/java/net/onrc/onos/core/util/IPv4.java
+++ b/src/main/java/net/onrc/onos/core/util/IPv4.java
@@ -9,8 +9,8 @@
/**
* The class representing an IPv4 address.
*/
-@JsonDeserialize(using=IPv4Deserializer.class)
-@JsonSerialize(using=IPv4Serializer.class)
+@JsonDeserialize(using = IPv4Deserializer.class)
+@JsonSerialize(using = IPv4Serializer.class)
public class IPv4 {
private int value;
@@ -18,7 +18,7 @@
* Default constructor.
*/
public IPv4() {
- this.value = 0;
+ this.value = 0;
}
/**
@@ -27,7 +27,7 @@
* @param other the object to copy from.
*/
public IPv4(IPv4 other) {
- this.value = other.value;
+ this.value = other.value;
}
/**
@@ -36,7 +36,7 @@
* @param value the value to use.
*/
public IPv4(int value) {
- this.value = value;
+ this.value = value;
}
/**
@@ -48,13 +48,13 @@
String[] splits = value.split("\\.");
if (splits.length != 4)
throw new IllegalArgumentException("Specified IPv4 address must contain four " +
- "numerical digits separated by '.'");
+ "numerical digits separated by '.'");
int result = 0;
for (int i = 0; i < 4; ++i) {
- result |= Integer.valueOf(splits[i]) << ((3-i)*8);
+ result |= Integer.valueOf(splits[i]) << ((3 - i) * 8);
}
- this.value = result;
+ this.value = result;
}
/**
@@ -62,7 +62,9 @@
*
* @return the value of the IPv4 address.
*/
- public int value() { return value; }
+ public int value() {
+ return value;
+ }
/**
* Set the value of the IPv4 address.
@@ -70,7 +72,7 @@
* @param value the value to set.
*/
public void setValue(int value) {
- this.value = value;
+ this.value = value;
}
/**
@@ -80,9 +82,9 @@
*/
@Override
public String toString() {
- return ((this.value >> 24) & 0xFF) + "." +
- ((this.value >> 16) & 0xFF) + "." +
- ((this.value >> 8) & 0xFF) + "." +
- (this.value & 0xFF);
+ return ((this.value >> 24) & 0xFF) + "." +
+ ((this.value >> 16) & 0xFF) + "." +
+ ((this.value >> 8) & 0xFF) + "." +
+ (this.value & 0xFF);
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/IPv4Net.java b/src/main/java/net/onrc/onos/core/util/IPv4Net.java
index 82f2fc6..3aa5a8b 100644
--- a/src/main/java/net/onrc/onos/core/util/IPv4Net.java
+++ b/src/main/java/net/onrc/onos/core/util/IPv4Net.java
@@ -9,17 +9,17 @@
/**
* The class representing an IPv4 network address.
*/
-@JsonDeserialize(using=IPv4NetDeserializer.class)
-@JsonSerialize(using=IPv4NetSerializer.class)
+@JsonDeserialize(using = IPv4NetDeserializer.class)
+@JsonSerialize(using = IPv4NetSerializer.class)
public class IPv4Net {
- private IPv4 address; // The IPv4 address
- private short prefixLen; // The prefix length
+ private IPv4 address; // The IPv4 address
+ private short prefixLen; // The prefix length
/**
* Default constructor.
*/
public IPv4Net() {
- this.prefixLen = 0;
+ this.prefixLen = 0;
}
/**
@@ -28,20 +28,20 @@
* @param other the object to copy from.
*/
public IPv4Net(IPv4Net other) {
- if (other.address != null)
- this.address = new IPv4(other.address);
- this.prefixLen = other.prefixLen;
+ if (other.address != null)
+ this.address = new IPv4(other.address);
+ this.prefixLen = other.prefixLen;
}
/**
* Constructor for a given address and prefix length.
*
- * @param address the address to use.
+ * @param address the address to use.
* @param prefixLen the prefix length to use.
*/
public IPv4Net(IPv4 address, short prefixLen) {
- this.address = address;
- this.prefixLen = prefixLen;
+ this.address = address;
+ this.prefixLen = prefixLen;
}
/**
@@ -50,13 +50,13 @@
* @param value the value to use.
*/
public IPv4Net(String value) {
- String[] splits = value.split("/");
- if (splits.length != 2) {
- throw new IllegalArgumentException("Specified IPv4Net address must contain an IPv4 " +
- "address and a prefix length separated by '/'");
- }
- this.address = new IPv4(splits[0]);
- this.prefixLen = Short.decode(splits[1]);
+ String[] splits = value.split("/");
+ if (splits.length != 2) {
+ throw new IllegalArgumentException("Specified IPv4Net address must contain an IPv4 " +
+ "address and a prefix length separated by '/'");
+ }
+ this.address = new IPv4(splits[0]);
+ this.prefixLen = Short.decode(splits[1]);
}
/**
@@ -64,7 +64,9 @@
*
* @return the address value of the IPv4Net address.
*/
- public IPv4 address() { return address; }
+ public IPv4 address() {
+ return address;
+ }
/**
* Set the address value of the IPv4Net address.
@@ -72,7 +74,7 @@
* @param address the address to use.
*/
public void setAddress(IPv4 address) {
- this.address = address;
+ this.address = address;
}
/**
@@ -80,7 +82,9 @@
*
* @return the prefix length value of the IPv4Net address.
*/
- public short prefixLen() { return prefixLen; }
+ public short prefixLen() {
+ return prefixLen;
+ }
/**
* Set the prefix length value of the IPv4Net address.
@@ -88,18 +92,18 @@
* @param prefixLen the prefix length to use.
*/
public void setPrefixLen(short prefixLen) {
- this.prefixLen = prefixLen;
+ this.prefixLen = prefixLen;
}
/**
* Set the value of the IPv4Net address.
*
- * @param address the address to use.
+ * @param address the address to use.
* @param prefixLen the prefix length to use.
*/
public void setValue(IPv4 address, short prefixLen) {
- this.address = address;
- this.prefixLen = prefixLen;
+ this.address = address;
+ this.prefixLen = prefixLen;
}
/**
@@ -109,6 +113,6 @@
*/
@Override
public String toString() {
- return this.address.toString() + "/" + this.prefixLen;
+ return this.address.toString() + "/" + this.prefixLen;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/IPv6.java b/src/main/java/net/onrc/onos/core/util/IPv6.java
index 1648723..38a86b5 100644
--- a/src/main/java/net/onrc/onos/core/util/IPv6.java
+++ b/src/main/java/net/onrc/onos/core/util/IPv6.java
@@ -10,18 +10,18 @@
/**
* The class representing an IPv6 address.
*/
-@JsonDeserialize(using=IPv6Deserializer.class)
-@JsonSerialize(using=IPv6Serializer.class)
+@JsonDeserialize(using = IPv6Deserializer.class)
+@JsonSerialize(using = IPv6Serializer.class)
public class IPv6 {
- private long valueHigh; // The higher (more significant) 64 bits
- private long valueLow; // The lower (less significant) 64 bits
+ private long valueHigh; // The higher (more significant) 64 bits
+ private long valueLow; // The lower (less significant) 64 bits
/**
* Default constructor.
*/
public IPv6() {
- this.valueHigh = 0;
- this.valueLow = 0;
+ this.valueHigh = 0;
+ this.valueLow = 0;
}
/**
@@ -30,19 +30,19 @@
* @param other the object to copy from.
*/
public IPv6(IPv6 other) {
- this.valueHigh = other.valueHigh;
- this.valueLow = other.valueLow;
+ this.valueHigh = other.valueHigh;
+ this.valueLow = other.valueLow;
}
/**
* Constructor from integer values.
*
* @param valueHigh the higher (more significant) 64 bits of the address.
- * @param valueLow the lower (less significant) 64 bits of the address.
+ * @param valueLow the lower (less significant) 64 bits of the address.
*/
public IPv6(long valueHigh, long valueLow) {
- this.valueHigh = valueHigh;
- this.valueLow = valueLow;
+ this.valueHigh = valueHigh;
+ this.valueLow = valueLow;
}
/**
@@ -51,9 +51,9 @@
* @param value the value to use.
*/
public IPv6(String value) {
- // TODO: Implement it!
- this.valueHigh = 0;
- this.valueLow = 0;
+ // TODO: Implement it!
+ this.valueHigh = 0;
+ this.valueLow = 0;
}
/**
@@ -62,7 +62,9 @@
* @return the value of the higher (more significant) 64 bits of the
* address.
*/
- public long valueHigh() { return valueHigh; }
+ public long valueHigh() {
+ return valueHigh;
+ }
/**
* Set the value of the higher (more significant) 64 bits of the address.
@@ -70,7 +72,7 @@
* @param valueHigh the higher (more significant) 64 bits of the address.
*/
public void setValueHigh(long valueHigh) {
- this.valueHigh = valueHigh;
+ this.valueHigh = valueHigh;
}
/**
@@ -79,7 +81,9 @@
* @return the value of the lower (less significant) 64 bits of the
* address.
*/
- public long valueLow() { return valueLow; }
+ public long valueLow() {
+ return valueLow;
+ }
/**
* Get the value of the lower (less significant) 64 bits of the address.
@@ -87,18 +91,18 @@
* @param valueLow the lower (less significant) 64 bits of the address.
*/
public void setValueLow(long valueLow) {
- this.valueLow = valueLow;
+ this.valueLow = valueLow;
}
/**
* Set the value of the IPv6 address.
*
* @param valueHigh the higher (more significant) 64 bits of the address.
- * @param valueLow the lower (less significant) 64 bits of the address.
+ * @param valueLow the lower (less significant) 64 bits of the address.
*/
public void setValue(long valueHigh, long valueLow) {
- this.valueHigh = valueHigh;
- this.valueLow = valueLow;
+ this.valueHigh = valueHigh;
+ this.valueLow = valueLow;
}
/**
@@ -108,7 +112,7 @@
*/
@Override
public String toString() {
- return HexString.toHexString(this.valueHigh) + ":" +
- HexString.toHexString(this.valueLow);
+ return HexString.toHexString(this.valueHigh) + ":" +
+ HexString.toHexString(this.valueLow);
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/IPv6Net.java b/src/main/java/net/onrc/onos/core/util/IPv6Net.java
index 486f8e8..1faa7c5 100644
--- a/src/main/java/net/onrc/onos/core/util/IPv6Net.java
+++ b/src/main/java/net/onrc/onos/core/util/IPv6Net.java
@@ -9,17 +9,17 @@
/**
* The class representing an IPv6 network address.
*/
-@JsonDeserialize(using=IPv6NetDeserializer.class)
-@JsonSerialize(using=IPv6NetSerializer.class)
+@JsonDeserialize(using = IPv6NetDeserializer.class)
+@JsonSerialize(using = IPv6NetSerializer.class)
public class IPv6Net {
- private IPv6 address; // The IPv6 address
- private short prefixLen; // The prefix length
+ private IPv6 address; // The IPv6 address
+ private short prefixLen; // The prefix length
/**
* Default constructor.
*/
public IPv6Net() {
- this.prefixLen = 0;
+ this.prefixLen = 0;
}
/**
@@ -28,20 +28,20 @@
* @param other the object to copy from.
*/
public IPv6Net(IPv6Net other) {
- if (other.address != null)
- this.address = new IPv6(other.address);
- this.prefixLen = other.prefixLen;
+ if (other.address != null)
+ this.address = new IPv6(other.address);
+ this.prefixLen = other.prefixLen;
}
/**
* Constructor for a given address and prefix length.
*
- * @param address the address to use.
+ * @param address the address to use.
* @param prefixLen the prefix length to use.
*/
public IPv6Net(IPv6 address, short prefixLen) {
- this.address = address;
- this.prefixLen = prefixLen;
+ this.address = address;
+ this.prefixLen = prefixLen;
}
/**
@@ -50,13 +50,13 @@
* @param value the value to use.
*/
public IPv6Net(String value) {
- String[] splits = value.split("/");
- if (splits.length != 2) {
- throw new IllegalArgumentException("Specified IPv6Net address must contain an IPv6 " +
- "address and a prefix length separated by '/'");
- }
- this.address = new IPv6(splits[0]);
- this.prefixLen = Short.decode(splits[1]);
+ String[] splits = value.split("/");
+ if (splits.length != 2) {
+ throw new IllegalArgumentException("Specified IPv6Net address must contain an IPv6 " +
+ "address and a prefix length separated by '/'");
+ }
+ this.address = new IPv6(splits[0]);
+ this.prefixLen = Short.decode(splits[1]);
}
/**
@@ -64,7 +64,9 @@
*
* @return the address value of the IPv6Net address.
*/
- public IPv6 address() { return address; }
+ public IPv6 address() {
+ return address;
+ }
/**
* Set the address value of the IPv6Net address.
@@ -72,7 +74,7 @@
* @param address the address to use.
*/
public void setAddress(IPv6 address) {
- this.address = address;
+ this.address = address;
}
/**
@@ -80,7 +82,9 @@
*
* @return the prefix length value of the IPv6Net address.
*/
- public short prefixLen() { return prefixLen; }
+ public short prefixLen() {
+ return prefixLen;
+ }
/**
* Set the prefix length value of the IPv6Net address.
@@ -88,18 +92,18 @@
* @param prefixLen the prefix length to use.
*/
public void setPrefixLen(short prefixLen) {
- this.prefixLen = prefixLen;
+ this.prefixLen = prefixLen;
}
/**
* Set the value of the IPv6Net address.
*
- * @param address the address to use.
+ * @param address the address to use.
* @param prefixLen the prefix length to use.
*/
public void setValue(IPv6 address, short prefixLen) {
- this.address = address;
- this.prefixLen = prefixLen;
+ this.address = address;
+ this.prefixLen = prefixLen;
}
/**
@@ -109,6 +113,6 @@
*/
@Override
public String toString() {
- return this.address.toString() + "/" + this.prefixLen;
+ return this.address.toString() + "/" + this.prefixLen;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/Pair.java b/src/main/java/net/onrc/onos/core/util/Pair.java
index 36a76bb..abf9fed 100644
--- a/src/main/java/net/onrc/onos/core/util/Pair.java
+++ b/src/main/java/net/onrc/onos/core/util/Pair.java
@@ -4,22 +4,22 @@
* A generic class representing a pair of two values.
*/
public class Pair<F, S> {
- public F first; // The first value in the pair
- public S second; // The second value in the pair
+ public F first; // The first value in the pair
+ public S second; // The second value in the pair
/**
* Constructor for a pair of two values.
*
- * @param first the first value in the pair.
+ * @param first the first value in the pair.
* @param second the second value in the pair.
*/
public Pair(F first, S second) {
- this.first = first;
- this.second = second;
+ this.first = first;
+ this.second = second;
}
@Override
public String toString() {
- return String.format("<%s, %s>", first, second);
+ return String.format("<%s, %s>", first, second);
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/PerformanceMonitor.java b/src/main/java/net/onrc/onos/core/util/PerformanceMonitor.java
index dd5e36f..b6cdd94 100644
--- a/src/main/java/net/onrc/onos/core/util/PerformanceMonitor.java
+++ b/src/main/java/net/onrc/onos/core/util/PerformanceMonitor.java
@@ -15,17 +15,18 @@
private final static Logger log = LoggerFactory.getLogger(PerformanceMonitor.class);
// experiment name -> PerformanceMonitor
- private static final ConcurrentHashMap<String,PerformanceMonitor> perfMons = new ConcurrentHashMap<>();
+ private static final ConcurrentHashMap<String, PerformanceMonitor> perfMons = new ConcurrentHashMap<>();
+
public static PerformanceMonitor experiment(String name) {
- PerformanceMonitor pm = perfMons.get(name);
- if (pm == null) {
- pm = new PerformanceMonitor();
- PerformanceMonitor existing = perfMons.putIfAbsent(name, pm);
- if (existing != null) {
- pm = existing;
- }
- }
- return pm;
+ PerformanceMonitor pm = perfMons.get(name);
+ if (pm == null) {
+ pm = new PerformanceMonitor();
+ PerformanceMonitor existing = perfMons.putIfAbsent(name, pm);
+ if (existing != null) {
+ pm = existing;
+ }
+ }
+ return pm;
}
// tag -> Measurements
@@ -36,111 +37,111 @@
/**
* Start a performance measurement, identified by a tag
- *
+ * <p/>
* Note: Only a single measurement can use the same tag at a time.
* ..... not true anymore.
*
* @param tag for performance measurement
*/
public Measurement startStep(String tag) {
- long start = System.nanoTime();
- if(start < experimentStart) {
- experimentStart = start;
- }
- Queue<Measurement> list = map.get(tag);
- if(list == null) {
- list = new ConcurrentLinkedQueue<Measurement>();
- Queue<Measurement> existing_list = map.putIfAbsent(tag, list);
- if (existing_list != null) {
- // someone concurrently added, using theirs
- list = existing_list;
- }
- }
- Measurement m = new Measurement();
- list.add(m);
- m.start();
- overhead += System.nanoTime() - start;
- return m;
+ long start = System.nanoTime();
+ if (start < experimentStart) {
+ experimentStart = start;
+ }
+ Queue<Measurement> list = map.get(tag);
+ if (list == null) {
+ list = new ConcurrentLinkedQueue<Measurement>();
+ Queue<Measurement> existing_list = map.putIfAbsent(tag, list);
+ if (existing_list != null) {
+ // someone concurrently added, using theirs
+ list = existing_list;
+ }
+ }
+ Measurement m = new Measurement();
+ list.add(m);
+ m.start();
+ overhead += System.nanoTime() - start;
+ return m;
}
/**
* Stop a performance measurement.
- *
+ * <p/>
* You must have already started a measurement with tag.
*
* @param tag for performance measurement
*/
public void stopStep(String tag) {
- long time = System.nanoTime();
- Queue<Measurement> list = map.get(tag);
- if(list == null || list.size() == 0) {
- log.error("Tag {} does not exist", tag);
- }
- list.peek().stop(time);
- if(list.size() > 1) {
- log.error("Tag {} has multiple measurements", tag);
- }
- overhead += System.nanoTime() - time;
+ long time = System.nanoTime();
+ Queue<Measurement> list = map.get(tag);
+ if (list == null || list.size() == 0) {
+ log.error("Tag {} does not exist", tag);
+ }
+ list.peek().stop(time);
+ if (list.size() > 1) {
+ log.error("Tag {} has multiple measurements", tag);
+ }
+ overhead += System.nanoTime() - time;
}
/**
* Clear all performance measurements.
*/
public void reset() {
- map.clear();
- overhead = 0;
- experimentStart = Long.MAX_VALUE;
+ map.clear();
+ overhead = 0;
+ experimentStart = Long.MAX_VALUE;
}
/**
* Write all performance measurements to the log
*/
public void reportAll() {
- String result = "Performance Results: (avg/start/stop/count)\n";
- if(map.size() == 0) {
- result += "No Measurements";
- log.error(result);
- return;
- }
- long experimentEnd = -1;
- for(Entry<String, Queue<Measurement>> e : map.entrySet()) {
- String key = e.getKey();
- Queue<Measurement> list = e.getValue();
- long total = 0, count = 0;
- long start = Long.MAX_VALUE, stop = -1;
- for(Measurement m : list) {
- if(m.stop < 0) {
- continue; // measurement has not been stopped
- }
- // Collect overall start and end times
- if(m.start < start) {
- start = m.start;
- }
- if(m.stop > stop) {
- stop = m.stop;
- if(stop > experimentEnd) {
- experimentEnd = stop;
- }
- }
- // Collect statistics for average
- total += m.elapsed();
- count++;
- }
- double avg = (double) total / count;
- // Normalize start/stop
- start -= experimentStart;
- stop -= experimentStart;
- result += key + '=' +
- (avg / normalization) + '/' +
- (start / normalization) + '/' +
- (stop / normalization) + '/' +
- count + '\n';
- }
- double overheadMs = overhead / normalization;
- double experimentElapsed = (experimentEnd - experimentStart) / normalization;
- result += "TotalTime:" + experimentElapsed + "/Overhead:" + overheadMs;
- log.error(result);
-// log.error("Performance Results: {} with measurement overhead: {} ms", map, overheadMilli);
+ String result = "Performance Results: (avg/start/stop/count)\n";
+ if (map.size() == 0) {
+ result += "No Measurements";
+ log.error(result);
+ return;
+ }
+ long experimentEnd = -1;
+ for (Entry<String, Queue<Measurement>> e : map.entrySet()) {
+ String key = e.getKey();
+ Queue<Measurement> list = e.getValue();
+ long total = 0, count = 0;
+ long start = Long.MAX_VALUE, stop = -1;
+ for (Measurement m : list) {
+ if (m.stop < 0) {
+ continue; // measurement has not been stopped
+ }
+ // Collect overall start and end times
+ if (m.start < start) {
+ start = m.start;
+ }
+ if (m.stop > stop) {
+ stop = m.stop;
+ if (stop > experimentEnd) {
+ experimentEnd = stop;
+ }
+ }
+ // Collect statistics for average
+ total += m.elapsed();
+ count++;
+ }
+ double avg = (double) total / count;
+ // Normalize start/stop
+ start -= experimentStart;
+ stop -= experimentStart;
+ result += key + '=' +
+ (avg / normalization) + '/' +
+ (start / normalization) + '/' +
+ (stop / normalization) + '/' +
+ count + '\n';
+ }
+ double overheadMs = overhead / normalization;
+ double experimentElapsed = (experimentEnd - experimentStart) / normalization;
+ result += "TotalTime:" + experimentElapsed + "/Overhead:" + overheadMs;
+ log.error(result);
+// log.error("Performance Results: {} with measurement overhead: {} ms", map, overheadMilli);
}
/**
@@ -149,79 +150,79 @@
* @param tag the tag name.
*/
public void reportStep(String tag) {
- Queue<Measurement> list = map.get(tag);
- if(list == null) {
- return; //TODO
- }
- //TODO: fix this;
- Measurement m = list.peek();
- if (m != null) {
- log.error("Performance Result: tag = {} start = {} stop = {} elapsed = {}",
- tag, m.start, m.stop, m.toString());
- } else {
- log.error("Performance Result: unknown tag {}", tag);
- }
+ Queue<Measurement> list = map.get(tag);
+ if (list == null) {
+ return; //TODO
+ }
+ //TODO: fix this;
+ Measurement m = list.peek();
+ if (m != null) {
+ log.error("Performance Result: tag = {} start = {} stop = {} elapsed = {}",
+ tag, m.start, m.stop, m.toString());
+ } else {
+ log.error("Performance Result: unknown tag {}", tag);
+ }
}
/**
* A single performance measurement
*/
public static class Measurement {
- long start;
- long stop = -1;
+ long start;
+ long stop = -1;
- /**
- * Start the measurement
- */
- public void start() {
- if(start <= 0) {
- start = System.nanoTime();
- }
- }
+ /**
+ * Start the measurement
+ */
+ public void start() {
+ if (start <= 0) {
+ start = System.nanoTime();
+ }
+ }
- /**
- * Stop the measurement
- */
- public void stop() {
- long now = System.nanoTime();
- stop(now);
- }
+ /**
+ * Stop the measurement
+ */
+ public void stop() {
+ long now = System.nanoTime();
+ stop(now);
+ }
- /**
- * Stop the measurement at a specific time
- * @param time to stop
- */
- public void stop(long time){
- if(stop <= 0) {
- stop = time;
- }
- }
+ /**
+ * Stop the measurement at a specific time
+ *
+ * @param time to stop
+ */
+ public void stop(long time) {
+ if (stop <= 0) {
+ stop = time;
+ }
+ }
- /**
- * Compute the elapsed time of the measurement in nanoseconds
- *
- * @return the measurement time in nanoseconds, or -1 if the measurement is stil running.
- */
- public long elapsed() {
- if(stop <= 0) {
- return -1;
- }
- else {
- return stop - start;
- }
- }
+ /**
+ * Compute the elapsed time of the measurement in nanoseconds
+ *
+ * @return the measurement time in nanoseconds, or -1 if the measurement is stil running.
+ */
+ public long elapsed() {
+ if (stop <= 0) {
+ return -1;
+ } else {
+ return stop - start;
+ }
+ }
- /**
- * Returns the number of milliseconds for the measurement as a String.
- */
- @Override
- public String toString() {
- double milli = elapsed() / normalization;
- double startMs = start / normalization;
- double stopMs = stop / normalization;
+ /**
+ * Returns the number of milliseconds for the measurement as a String.
+ */
+ @Override
+ public String toString() {
+ double milli = elapsed() / normalization;
+ double startMs = start / normalization;
+ double stopMs = stop / normalization;
- return milli + "ms/" + startMs + '/' + stopMs;
- }
+ return milli + "ms/" + startMs + '/' + stopMs;
+ }
}
@Deprecated
@@ -229,64 +230,87 @@
@Deprecated
public static Measurement start(String tag) {
- return theInstance.startStep(tag);
+ return theInstance.startStep(tag);
}
@Deprecated
public static void stop(String tag) {
- theInstance.stopStep(tag);;
+ theInstance.stopStep(tag);
+ ;
}
@Deprecated
public static void clear() {
- theInstance.reset();;
+ theInstance.reset();
+ ;
}
@Deprecated
public static void report() {
- theInstance.reportAll();;
+ theInstance.reportAll();
+ ;
}
@Deprecated
public static void report(String tag) {
- theInstance.reportStep(tag);
+ theInstance.reportStep(tag);
}
- public static void main(String args[]){
- // test the measurement overhead
- String tag;
- for(int i = 0; i < 2; i++){
- tag = "foo foo foo";
- Measurement m;
- m = start(tag); System.out.println(tag); m.stop();
- m = start(tag); System.out.println(tag); m.stop();
- m = start(tag); System.out.println(tag); m.stop();
- m = start(tag); System.out.println(tag); m.stop();
- tag = "bar";
- start(tag); stop(tag);
- tag = "baz";
- start(tag); stop(tag);
- report();
- clear();
- }
- for(int i = 0; i < 100; i++){
- tag = "a";
- start(tag); stop(tag);
- start(tag); stop(tag);
+ public static void main(String args[]) {
+ // test the measurement overhead
+ String tag;
+ for (int i = 0; i < 2; i++) {
+ tag = "foo foo foo";
+ Measurement m;
+ m = start(tag);
+ System.out.println(tag);
+ m.stop();
+ m = start(tag);
+ System.out.println(tag);
+ m.stop();
+ m = start(tag);
+ System.out.println(tag);
+ m.stop();
+ m = start(tag);
+ System.out.println(tag);
+ m.stop();
+ tag = "bar";
+ start(tag);
+ stop(tag);
+ tag = "baz";
+ start(tag);
+ stop(tag);
+ report();
+ clear();
+ }
+ for (int i = 0; i < 100; i++) {
+ tag = "a";
+ start(tag);
+ stop(tag);
+ start(tag);
+ stop(tag);
- start(tag); stop(tag);
- start(tag); stop(tag);
- start(tag); stop(tag);
- start(tag); stop(tag);
- start(tag); stop(tag);
- start(tag); stop(tag);
+ start(tag);
+ stop(tag);
+ start(tag);
+ stop(tag);
+ start(tag);
+ stop(tag);
+ start(tag);
+ stop(tag);
+ start(tag);
+ stop(tag);
+ start(tag);
+ stop(tag);
- tag = "b";
- start(tag); stop(tag);
- tag = "c";
- start(tag); stop(tag);
- report();
- clear();
- }
+ tag = "b";
+ start(tag);
+ stop(tag);
+ tag = "c";
+ start(tag);
+ stop(tag);
+ report();
+ clear();
+ }
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/Port.java b/src/main/java/net/onrc/onos/core/util/Port.java
index 722c802..77d983b 100644
--- a/src/main/java/net/onrc/onos/core/util/Port.java
+++ b/src/main/java/net/onrc/onos/core/util/Port.java
@@ -9,63 +9,65 @@
public class Port {
/**
* Special port values.
- *
+ * <p/>
* Those values are taken as-is from the OpenFlow-v1.0.0 specification
* (pp 18-19).
*/
public enum PortValues {
- /* Maximum number of physical switch ports. */
- PORT_MAX ((short)0xff00),
+ /* Maximum number of physical switch ports. */
+ PORT_MAX((short) 0xff00),
- /* Fake output "ports". */
+ /* Fake output "ports". */
- /* Send the packet out the input port. This
- virtual port must be explicitly used
- in order to send back out of the input
- port. */
- PORT_IN_PORT ((short)0xfff8),
+ /* Send the packet out the input port. This
+ virtual port must be explicitly used
+ in order to send back out of the input
+ port. */
+ PORT_IN_PORT((short) 0xfff8),
- /* Perform actions in flow table.
- NB: This can only be the destination
- port for packet-out messages. */
- PORT_TABLE ((short)0xfff9),
+ /* Perform actions in flow table.
+ NB: This can only be the destination
+ port for packet-out messages. */
+ PORT_TABLE((short) 0xfff9),
- /* Process with normal L2/L3 switching. */
- PORT_NORMAL ((short)0xfffa),
+ /* Process with normal L2/L3 switching. */
+ PORT_NORMAL((short) 0xfffa),
- /* All physical ports except input port and
- those disabled by STP. */
- PORT_FLOOD ((short)0xfffb),
+ /* All physical ports except input port and
+ those disabled by STP. */
+ PORT_FLOOD((short) 0xfffb),
- /* All physical ports except input port. */
- PORT_ALL ((short)0xfffc),
+ /* All physical ports except input port. */
+ PORT_ALL((short) 0xfffc),
- /* Send to controller. */
- PORT_CONTROLLER ((short)0xfffd),
+ /* Send to controller. */
+ PORT_CONTROLLER((short) 0xfffd),
- /* Local openflow "port". */
- PORT_LOCAL ((short)0xfffe),
+ /* Local openflow "port". */
+ PORT_LOCAL((short) 0xfffe),
- /* Not associated with a physical port. */
- PORT_NONE ((short)0xffff);
+ /* Not associated with a physical port. */
+ PORT_NONE((short) 0xffff);
- private final short value; // The value
+ private final short value; // The value
- /**
- * Constructor for a given value.
- *
- * @param value the value to use for the initialization.
- */
- private PortValues(short value) {
- this.value = value;
- }
+ /**
+ * Constructor for a given value.
+ *
+ * @param value the value to use for the initialization.
+ */
+ private PortValues(short value) {
+ this.value = value;
+ }
- /**
- * Get the value as a short integer.
- *
- * @return the value as a short integer.
- */
- private short value() { return this.value; }
+ /**
+ * Get the value as a short integer.
+ *
+ * @return the value as a short integer.
+ */
+ private short value() {
+ return this.value;
+ }
}
private short value;
@@ -74,7 +76,7 @@
* Default constructor.
*/
public Port() {
- this.value = 0;
+ this.value = 0;
}
/**
@@ -83,7 +85,7 @@
* @param other the object to copy from.
*/
public Port(Port other) {
- this.value = other.value();
+ this.value = other.value();
}
/**
@@ -92,7 +94,7 @@
* @param value the value to use.
*/
public Port(short value) {
- this.value = value;
+ this.value = value;
}
/**
@@ -101,7 +103,7 @@
* @param value the value to use.
*/
public Port(PortValues value) {
- this.value = value.value();
+ this.value = value.value();
}
/**
@@ -110,7 +112,9 @@
* @return the value of the port.
*/
@JsonProperty("value")
- public short value() { return value; }
+ public short value() {
+ return value;
+ }
/**
* Set the value of the port.
@@ -119,7 +123,7 @@
*/
@JsonProperty("value")
public void setValue(short value) {
- this.value = value;
+ this.value = value;
}
/**
@@ -129,25 +133,25 @@
*/
@Override
public String toString() {
- return Short.toString(this.value);
+ return Short.toString(this.value);
}
-
+
@Override
public boolean equals(Object other) {
- if (!(other instanceof Port)) {
- return false;
- }
+ if (!(other instanceof Port)) {
+ return false;
+ }
- Port otherPort = (Port) other;
+ Port otherPort = (Port) other;
- return value == otherPort.value;
+ return value == otherPort.value;
}
@Override
public int hashCode() {
- int hash = 17;
- hash += 31 * hash + (int)value;
- return hash;
+ int hash = 17;
+ hash += 31 * hash + (int) value;
+ return hash;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/Switch.java b/src/main/java/net/onrc/onos/core/util/Switch.java
index e3c525f..d1a463c 100644
--- a/src/main/java/net/onrc/onos/core/util/Switch.java
+++ b/src/main/java/net/onrc/onos/core/util/Switch.java
@@ -11,44 +11,44 @@
* The Switch state.
*/
public enum SwitchState {
- INACTIVE,
- ACTIVE,
+ INACTIVE,
+ ACTIVE,
}
- private Dpid dpid; // The DPID of the switch
- private SwitchState state; // The state of the switch
+ private Dpid dpid; // The DPID of the switch
+ private SwitchState state; // The state of the switch
/**
* Default constructor.
- *
+ * <p/>
* NOTE: The default state for the switch is INACTIVE.
*/
public Switch() {
- this.dpid = new Dpid();
- this.state = SwitchState.INACTIVE;
+ this.dpid = new Dpid();
+ this.state = SwitchState.INACTIVE;
}
/**
* Constructor for a given DPID.
- *
+ * <p/>
* NOTE: The state for the switch with a given DPID is ACTIVE.
*
* @param dpid the DPID to use.
*/
public Switch(Dpid dpid) {
- this.dpid = dpid;
- this.state = SwitchState.ACTIVE;
+ this.dpid = dpid;
+ this.state = SwitchState.ACTIVE;
}
/**
* Constructor for a given DPID and Switch State.
*
- * @param dpid the DPID to use.
+ * @param dpid the DPID to use.
* @param state the Switch State to use.
*/
public Switch(Dpid dpid, SwitchState state) {
- this.dpid = dpid;
- this.state = state;
+ this.dpid = dpid;
+ this.state = state;
}
/**
@@ -57,7 +57,9 @@
* @return the DPID.
*/
@JsonProperty("dpid")
- public Dpid dpid() { return dpid; }
+ public Dpid dpid() {
+ return dpid;
+ }
/**
* Set the DPID.
@@ -66,7 +68,7 @@
*/
@JsonProperty("dpid")
public void setDpid(Dpid dpid) {
- this.dpid = dpid;
+ this.dpid = dpid;
}
/**
@@ -75,7 +77,9 @@
* @return the state.
*/
@JsonProperty("state")
- public SwitchState state() { return state; }
+ public SwitchState state() {
+ return state;
+ }
/**
* Set the state.
@@ -84,33 +88,33 @@
*/
@JsonProperty("state")
public void setState(SwitchState state) {
- this.state = state;
+ this.state = state;
}
/**
* Set the Switch State to ACTIVE.
*/
public void setStateActive() {
- this.state = SwitchState.ACTIVE;
+ this.state = SwitchState.ACTIVE;
}
/**
* Set the Switch State to INACTIVE.
*/
public void setStateInactive() {
- this.state = SwitchState.INACTIVE;
+ this.state = SwitchState.INACTIVE;
}
/**
* Convert the Switch value to a string.
- *
+ * <p/>
* The string has the following form:
- * dpid/state
+ * dpid/state
*
* @return the Switch value as a string.
*/
@Override
public String toString() {
- return this.dpid.toString() + "/" + this.state.toString();
+ return this.dpid.toString() + "/" + this.state.toString();
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/SwitchPort.java b/src/main/java/net/onrc/onos/core/util/SwitchPort.java
index edc8905..eb72b72 100644
--- a/src/main/java/net/onrc/onos/core/util/SwitchPort.java
+++ b/src/main/java/net/onrc/onos/core/util/SwitchPort.java
@@ -6,8 +6,8 @@
* The class representing a Switch-Port.
*/
public class SwitchPort {
- private Dpid dpid; // The DPID of the switch
- private Port port; // The port of the switch
+ private Dpid dpid; // The DPID of the switch
+ private Port port; // The port of the switch
/**
* Default constructor.
@@ -22,8 +22,8 @@
* @param port the port to use.
*/
public SwitchPort(Dpid dpid, Port port) {
- this.dpid = dpid;
- this.port = port;
+ this.dpid = dpid;
+ this.port = port;
}
/**
@@ -32,7 +32,9 @@
* @return the DPID value of the Switch-Port.
*/
@JsonProperty("dpid")
- public Dpid dpid() { return dpid; }
+ public Dpid dpid() {
+ return dpid;
+ }
/**
* Set the DPID value of the Switch-Port.
@@ -41,7 +43,7 @@
*/
@JsonProperty("dpid")
public void setDpid(Dpid dpid) {
- this.dpid = dpid;
+ this.dpid = dpid;
}
/**
@@ -50,7 +52,9 @@
* @return the port value of the Switch-Port.
*/
@JsonProperty("port")
- public Port port() { return port; }
+ public Port port() {
+ return port;
+ }
/**
* Set the port value of the Switch-Port.
@@ -59,7 +63,7 @@
*/
@JsonProperty("port")
public void setPort(Port port) {
- this.port = port;
+ this.port = port;
}
/**
@@ -69,41 +73,41 @@
* @param port the port to use.
*/
public void setValue(Dpid dpid, Port port) {
- this.dpid = dpid;
- this.port = port;
+ this.dpid = dpid;
+ this.port = port;
}
/**
* Convert the Switch-Port value to a string.
- *
+ * <p/>
* The string has the following form:
- * 01:02:03:04:05:06:07:08/1234
+ * 01:02:03:04:05:06:07:08/1234
*
* @return the Switch-Port value as a string.
*/
@Override
public String toString() {
- return this.dpid.toString() + "/" + this.port;
+ return this.dpid.toString() + "/" + this.port;
}
-
+
@Override
public boolean equals(Object other) {
- if (!(other instanceof SwitchPort)) {
- return false;
- }
+ if (!(other instanceof SwitchPort)) {
+ return false;
+ }
- SwitchPort otherSwitchPort = (SwitchPort) other;
+ SwitchPort otherSwitchPort = (SwitchPort) other;
- return (dpid.equals(otherSwitchPort.dpid) &&
- port.equals(otherSwitchPort.port));
+ return (dpid.equals(otherSwitchPort.dpid) &&
+ port.equals(otherSwitchPort.port));
}
@Override
public int hashCode() {
- int hash = 17;
- hash += 31 * hash + dpid.hashCode();
- hash += 31 * hash + port.hashCode();
- return hash;
+ int hash = 17;
+ hash += 31 * hash + dpid.hashCode();
+ hash += 31 * hash + port.hashCode();
+ return hash;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/DpidDeserializer.java b/src/main/java/net/onrc/onos/core/util/serializers/DpidDeserializer.java
index 7a8c570..955f0ff 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/DpidDeserializer.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/DpidDeserializer.java
@@ -21,20 +21,20 @@
@Override
public Dpid deserialize(JsonParser jp,
- DeserializationContext ctxt)
- throws IOException, JsonProcessingException {
+ DeserializationContext ctxt)
+ throws IOException, JsonProcessingException {
- Dpid dpid = null;
+ Dpid dpid = null;
- jp.nextToken(); // Move to JsonToken.START_OBJECT
- while (jp.nextToken() != JsonToken.END_OBJECT) {
- String fieldname = jp.getCurrentName();
- if ("value".equals(fieldname)) {
- String value = jp.getText();
- log.debug("Fieldname: {} Value: {}", fieldname, value);
- dpid = new Dpid(value);
- }
- }
- return dpid;
+ jp.nextToken(); // Move to JsonToken.START_OBJECT
+ while (jp.nextToken() != JsonToken.END_OBJECT) {
+ String fieldname = jp.getCurrentName();
+ if ("value".equals(fieldname)) {
+ String value = jp.getText();
+ log.debug("Fieldname: {} Value: {}", fieldname, value);
+ dpid = new Dpid(value);
+ }
+ }
+ return dpid;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/DpidSerializer.java b/src/main/java/net/onrc/onos/core/util/serializers/DpidSerializer.java
index 4e784f2..68766f9 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/DpidSerializer.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/DpidSerializer.java
@@ -16,10 +16,10 @@
@Override
public void serialize(Dpid dpid, JsonGenerator jGen,
- SerializerProvider serializer)
- throws IOException, JsonProcessingException {
- jGen.writeStartObject();
- jGen.writeStringField("value", dpid.toString());
- jGen.writeEndObject();
+ SerializerProvider serializer)
+ throws IOException, JsonProcessingException {
+ jGen.writeStartObject();
+ jGen.writeStringField("value", dpid.toString());
+ jGen.writeEndObject();
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/FlowEntryIdDeserializer.java b/src/main/java/net/onrc/onos/core/util/serializers/FlowEntryIdDeserializer.java
index 712daa8..de13574 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/FlowEntryIdDeserializer.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/FlowEntryIdDeserializer.java
@@ -21,20 +21,20 @@
@Override
public FlowEntryId deserialize(JsonParser jp,
- DeserializationContext ctxt)
- throws IOException, JsonProcessingException {
+ DeserializationContext ctxt)
+ throws IOException, JsonProcessingException {
- FlowEntryId flowEntryId = null;
+ FlowEntryId flowEntryId = null;
- jp.nextToken(); // Move to JsonToken.START_OBJECT
- while (jp.nextToken() != JsonToken.END_OBJECT) {
- String fieldname = jp.getCurrentName();
- if ("value".equals(fieldname)) {
- String value = jp.getText();
- log.debug("Fieldname: " + fieldname + " Value: " + value);
- flowEntryId = new FlowEntryId(value);
- }
- }
- return flowEntryId;
+ jp.nextToken(); // Move to JsonToken.START_OBJECT
+ while (jp.nextToken() != JsonToken.END_OBJECT) {
+ String fieldname = jp.getCurrentName();
+ if ("value".equals(fieldname)) {
+ String value = jp.getText();
+ log.debug("Fieldname: " + fieldname + " Value: " + value);
+ flowEntryId = new FlowEntryId(value);
+ }
+ }
+ return flowEntryId;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/FlowEntryIdSerializer.java b/src/main/java/net/onrc/onos/core/util/serializers/FlowEntryIdSerializer.java
index 3911a4c..bc91f46 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/FlowEntryIdSerializer.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/FlowEntryIdSerializer.java
@@ -16,8 +16,8 @@
@Override
public void serialize(FlowEntryId flowEntryId, JsonGenerator jGen,
- SerializerProvider serializer)
- throws IOException, JsonProcessingException {
- jGen.writeString(flowEntryId.toString());
+ SerializerProvider serializer)
+ throws IOException, JsonProcessingException {
+ jGen.writeString(flowEntryId.toString());
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/FlowIdDeserializer.java b/src/main/java/net/onrc/onos/core/util/serializers/FlowIdDeserializer.java
index d1b91a8..12c5cbd 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/FlowIdDeserializer.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/FlowIdDeserializer.java
@@ -21,20 +21,20 @@
@Override
public FlowId deserialize(JsonParser jp,
- DeserializationContext ctxt)
- throws IOException, JsonProcessingException {
+ DeserializationContext ctxt)
+ throws IOException, JsonProcessingException {
- FlowId flowId = null;
+ FlowId flowId = null;
- jp.nextToken(); // Move to JsonToken.START_OBJECT
- while (jp.nextToken() != JsonToken.END_OBJECT) {
- String fieldname = jp.getCurrentName();
- if ("value".equals(fieldname)) {
- String value = jp.getText();
- log.debug("Fieldname: {} Value: {}", fieldname, value);
- flowId = new FlowId(value);
- }
- }
- return flowId;
+ jp.nextToken(); // Move to JsonToken.START_OBJECT
+ while (jp.nextToken() != JsonToken.END_OBJECT) {
+ String fieldname = jp.getCurrentName();
+ if ("value".equals(fieldname)) {
+ String value = jp.getText();
+ log.debug("Fieldname: {} Value: {}", fieldname, value);
+ flowId = new FlowId(value);
+ }
+ }
+ return flowId;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/FlowIdSerializer.java b/src/main/java/net/onrc/onos/core/util/serializers/FlowIdSerializer.java
index b0d020e..37a3e45 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/FlowIdSerializer.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/FlowIdSerializer.java
@@ -16,10 +16,10 @@
@Override
public void serialize(FlowId flowId, JsonGenerator jGen,
- SerializerProvider serializer)
- throws IOException, JsonProcessingException {
- jGen.writeStartObject();
- jGen.writeStringField("value", flowId.toString());
- jGen.writeEndObject();
+ SerializerProvider serializer)
+ throws IOException, JsonProcessingException {
+ jGen.writeStartObject();
+ jGen.writeStringField("value", flowId.toString());
+ jGen.writeEndObject();
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/IPv4Deserializer.java b/src/main/java/net/onrc/onos/core/util/serializers/IPv4Deserializer.java
index 2992bfd..f58f746 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/IPv4Deserializer.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/IPv4Deserializer.java
@@ -21,20 +21,20 @@
@Override
public IPv4 deserialize(JsonParser jp,
- DeserializationContext ctxt)
- throws IOException, JsonProcessingException {
+ DeserializationContext ctxt)
+ throws IOException, JsonProcessingException {
- IPv4 ipv4 = null;
+ IPv4 ipv4 = null;
- jp.nextToken(); // Move to JsonToken.START_OBJECT
- while (jp.nextToken() != JsonToken.END_OBJECT) {
- String fieldname = jp.getCurrentName();
- if ("value".equals(fieldname)) {
- String value = jp.getText();
- log.debug("Fieldname: {} Value: {}", fieldname, value);
- ipv4 = new IPv4(value);
- }
- }
- return ipv4;
+ jp.nextToken(); // Move to JsonToken.START_OBJECT
+ while (jp.nextToken() != JsonToken.END_OBJECT) {
+ String fieldname = jp.getCurrentName();
+ if ("value".equals(fieldname)) {
+ String value = jp.getText();
+ log.debug("Fieldname: {} Value: {}", fieldname, value);
+ ipv4 = new IPv4(value);
+ }
+ }
+ return ipv4;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/IPv4NetDeserializer.java b/src/main/java/net/onrc/onos/core/util/serializers/IPv4NetDeserializer.java
index 68f74c4..da68668 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/IPv4NetDeserializer.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/IPv4NetDeserializer.java
@@ -21,20 +21,20 @@
@Override
public IPv4Net deserialize(JsonParser jp,
- DeserializationContext ctxt)
- throws IOException, JsonProcessingException {
+ DeserializationContext ctxt)
+ throws IOException, JsonProcessingException {
- IPv4Net ipv4Net = null;
+ IPv4Net ipv4Net = null;
- jp.nextToken(); // Move to JsonToken.START_OBJECT
- while (jp.nextToken() != JsonToken.END_OBJECT) {
- String fieldname = jp.getCurrentName();
- if ("value".equals(fieldname)) {
- String value = jp.getText();
- log.debug("Fieldname: {} Value: {}", fieldname, value);
- ipv4Net = new IPv4Net(value);
- }
- }
- return ipv4Net;
+ jp.nextToken(); // Move to JsonToken.START_OBJECT
+ while (jp.nextToken() != JsonToken.END_OBJECT) {
+ String fieldname = jp.getCurrentName();
+ if ("value".equals(fieldname)) {
+ String value = jp.getText();
+ log.debug("Fieldname: {} Value: {}", fieldname, value);
+ ipv4Net = new IPv4Net(value);
+ }
+ }
+ return ipv4Net;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/IPv4NetSerializer.java b/src/main/java/net/onrc/onos/core/util/serializers/IPv4NetSerializer.java
index 697f846..f44aeb3 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/IPv4NetSerializer.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/IPv4NetSerializer.java
@@ -16,10 +16,10 @@
@Override
public void serialize(IPv4Net ipv4Net, JsonGenerator jGen,
- SerializerProvider serializer)
- throws IOException, JsonProcessingException {
- jGen.writeStartObject();
- jGen.writeStringField("value", ipv4Net.toString());
- jGen.writeEndObject();
+ SerializerProvider serializer)
+ throws IOException, JsonProcessingException {
+ jGen.writeStartObject();
+ jGen.writeStringField("value", ipv4Net.toString());
+ jGen.writeEndObject();
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/IPv4Serializer.java b/src/main/java/net/onrc/onos/core/util/serializers/IPv4Serializer.java
index 773fd1d..37a5564 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/IPv4Serializer.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/IPv4Serializer.java
@@ -16,10 +16,10 @@
@Override
public void serialize(IPv4 ipv4, JsonGenerator jGen,
- SerializerProvider serializer)
- throws IOException, JsonProcessingException {
- jGen.writeStartObject();
- jGen.writeStringField("value", ipv4.toString());
- jGen.writeEndObject();
+ SerializerProvider serializer)
+ throws IOException, JsonProcessingException {
+ jGen.writeStartObject();
+ jGen.writeStringField("value", ipv4.toString());
+ jGen.writeEndObject();
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/IPv6Deserializer.java b/src/main/java/net/onrc/onos/core/util/serializers/IPv6Deserializer.java
index 6627d2a..3b9673a 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/IPv6Deserializer.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/IPv6Deserializer.java
@@ -21,20 +21,20 @@
@Override
public IPv6 deserialize(JsonParser jp,
- DeserializationContext ctxt)
- throws IOException, JsonProcessingException {
+ DeserializationContext ctxt)
+ throws IOException, JsonProcessingException {
- IPv6 ipv6 = null;
+ IPv6 ipv6 = null;
- jp.nextToken(); // Move to JsonToken.START_OBJECT
- while (jp.nextToken() != JsonToken.END_OBJECT) {
- String fieldname = jp.getCurrentName();
- if ("value".equals(fieldname)) {
- String value = jp.getText();
- log.debug("Fieldname: {} Value: {}", fieldname, value);
- ipv6 = new IPv6(value);
- }
- }
- return ipv6;
+ jp.nextToken(); // Move to JsonToken.START_OBJECT
+ while (jp.nextToken() != JsonToken.END_OBJECT) {
+ String fieldname = jp.getCurrentName();
+ if ("value".equals(fieldname)) {
+ String value = jp.getText();
+ log.debug("Fieldname: {} Value: {}", fieldname, value);
+ ipv6 = new IPv6(value);
+ }
+ }
+ return ipv6;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/IPv6NetDeserializer.java b/src/main/java/net/onrc/onos/core/util/serializers/IPv6NetDeserializer.java
index 08b8018..2b80984 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/IPv6NetDeserializer.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/IPv6NetDeserializer.java
@@ -21,20 +21,20 @@
@Override
public IPv6Net deserialize(JsonParser jp,
- DeserializationContext ctxt)
- throws IOException, JsonProcessingException {
+ DeserializationContext ctxt)
+ throws IOException, JsonProcessingException {
- IPv6Net ipv6Net = null;
+ IPv6Net ipv6Net = null;
- jp.nextToken(); // Move to JsonToken.START_OBJECT
- while (jp.nextToken() != JsonToken.END_OBJECT) {
- String fieldname = jp.getCurrentName();
- if ("value".equals(fieldname)) {
- String value = jp.getText();
- log.debug("Fieldname: {} Value: {}", fieldname, value);
- ipv6Net = new IPv6Net(value);
- }
- }
- return ipv6Net;
+ jp.nextToken(); // Move to JsonToken.START_OBJECT
+ while (jp.nextToken() != JsonToken.END_OBJECT) {
+ String fieldname = jp.getCurrentName();
+ if ("value".equals(fieldname)) {
+ String value = jp.getText();
+ log.debug("Fieldname: {} Value: {}", fieldname, value);
+ ipv6Net = new IPv6Net(value);
+ }
+ }
+ return ipv6Net;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/IPv6NetSerializer.java b/src/main/java/net/onrc/onos/core/util/serializers/IPv6NetSerializer.java
index 99bd654..690b17f 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/IPv6NetSerializer.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/IPv6NetSerializer.java
@@ -16,10 +16,10 @@
@Override
public void serialize(IPv6Net ipv6Net, JsonGenerator jGen,
- SerializerProvider serializer)
- throws IOException, JsonProcessingException {
- jGen.writeStartObject();
- jGen.writeStringField("value", ipv6Net.toString());
- jGen.writeEndObject();
+ SerializerProvider serializer)
+ throws IOException, JsonProcessingException {
+ jGen.writeStartObject();
+ jGen.writeStringField("value", ipv6Net.toString());
+ jGen.writeEndObject();
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/IPv6Serializer.java b/src/main/java/net/onrc/onos/core/util/serializers/IPv6Serializer.java
index b165658..ed39fee 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/IPv6Serializer.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/IPv6Serializer.java
@@ -16,10 +16,10 @@
@Override
public void serialize(IPv6 ipv6, JsonGenerator jGen,
- SerializerProvider serializer)
- throws IOException, JsonProcessingException {
- jGen.writeStartObject();
- jGen.writeStringField("value", ipv6.toString());
- jGen.writeEndObject();
+ SerializerProvider serializer)
+ throws IOException, JsonProcessingException {
+ jGen.writeStartObject();
+ jGen.writeStringField("value", ipv6.toString());
+ jGen.writeEndObject();
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/KryoFactory.java b/src/main/java/net/onrc/onos/core/util/serializers/KryoFactory.java
index 3590f67..e78be58 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/KryoFactory.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/KryoFactory.java
@@ -62,7 +62,7 @@
/**
* Default constructor.
- *
+ * <p/>
* Preallocates {@code DEFAULT_PREALLOCATIONS} Kryo instances.
*/
public KryoFactory() {
@@ -89,7 +89,7 @@
* @return the created Kryo object.
*/
public Kryo newKryo() {
- return newDeleteKryo(null);
+ return newDeleteKryo(null);
}
/**
@@ -98,34 +98,34 @@
* @param deleteKryo the object to delete.
*/
public void deleteKryo(Kryo deleteKryo) {
- newDeleteKryo(deleteKryo);
+ newDeleteKryo(deleteKryo);
}
/**
* Create or delete a Kryo object.
*
* @param deleteKryo if null, then allocate and return a new object,
- * otherwise delete the provided object.
+ * otherwise delete the provided object.
* @return a new Kryo object if needed, otherwise null.
*/
synchronized private Kryo newDeleteKryo(Kryo deleteKryo) {
- if (deleteKryo != null) {
- // Delete an entry by moving it back to the buffer
- kryoList.add(deleteKryo);
- return null;
- } else {
- Kryo kryo = null;
- if (kryoList.isEmpty()) {
- // Preallocate
- for (int i = 0; i < 100; i++) {
- kryo = newKryoImpl();
- kryoList.add(kryo);
- }
- }
+ if (deleteKryo != null) {
+ // Delete an entry by moving it back to the buffer
+ kryoList.add(deleteKryo);
+ return null;
+ } else {
+ Kryo kryo = null;
+ if (kryoList.isEmpty()) {
+ // Preallocate
+ for (int i = 0; i < 100; i++) {
+ kryo = newKryoImpl();
+ kryoList.add(kryo);
+ }
+ }
- kryo = kryoList.remove(kryoList.size() - 1);
- return kryo;
- }
+ kryo = kryoList.remove(kryoList.size() - 1);
+ return kryo;
+ }
}
/**
@@ -134,91 +134,91 @@
* @return the created Kryo object.
*/
private Kryo newKryoImpl() {
- Kryo kryo = new Kryo();
- kryo.setRegistrationRequired(true);
- //
- // WARNING: Order of register() calls affects serialized bytes.
- // - Do no insert new entry in the middle, always add to the end.
- // - Do not simply remove existing entry
- //
+ Kryo kryo = new Kryo();
+ kryo.setRegistrationRequired(true);
+ //
+ // WARNING: Order of register() calls affects serialized bytes.
+ // - Do no insert new entry in the middle, always add to the end.
+ // - Do not simply remove existing entry
+ //
- // kryo.setReferences(false);
- //
- kryo.register(ArrayList.class);
+ // kryo.setReferences(false);
+ //
+ kryo.register(ArrayList.class);
- // FlowPath and related classes
- kryo.register(CallerId.class);
- kryo.register(DataPath.class);
- kryo.register(DataPathEndpoints.class);
- kryo.register(Dpid.class);
- kryo.register(FlowEntryAction.class);
- kryo.register(FlowEntryAction.ActionEnqueue.class);
- kryo.register(FlowEntryAction.ActionOutput.class);
- kryo.register(FlowEntryAction.ActionSetEthernetAddr.class);
- kryo.register(FlowEntryAction.ActionSetIpToS.class);
- kryo.register(FlowEntryAction.ActionSetIPv4Addr.class);
- kryo.register(FlowEntryAction.ActionSetTcpUdpPort.class);
- kryo.register(FlowEntryAction.ActionSetVlanId.class);
- kryo.register(FlowEntryAction.ActionSetVlanPriority.class);
- kryo.register(FlowEntryAction.ActionStripVlan.class);
- kryo.register(FlowEntryAction.ActionValues.class);
- kryo.register(FlowEntryActions.class);
- kryo.register(FlowEntryErrorState.class);
- kryo.register(FlowEntryId.class);
- kryo.register(FlowEntry.class);
- kryo.register(FlowEntryMatch.class);
- kryo.register(FlowEntryMatch.Field.class);
- kryo.register(FlowEntrySwitchState.class);
- kryo.register(FlowEntryUserState.class);
- kryo.register(FlowId.class);
- kryo.register(FlowPath.class);
- kryo.register(FlowPathFlags.class);
- kryo.register(FlowPathType.class);
- kryo.register(FlowPathUserState.class);
- kryo.register(IPv4.class);
- kryo.register(IPv4Net.class);
- kryo.register(IPv6.class);
- kryo.register(IPv6Net.class);
- kryo.register(byte[].class);
- kryo.register(MACAddress.class);
- kryo.register(Port.class);
- kryo.register(Switch.class);
- // kryo.register(SwitchPort.class);
+ // FlowPath and related classes
+ kryo.register(CallerId.class);
+ kryo.register(DataPath.class);
+ kryo.register(DataPathEndpoints.class);
+ kryo.register(Dpid.class);
+ kryo.register(FlowEntryAction.class);
+ kryo.register(FlowEntryAction.ActionEnqueue.class);
+ kryo.register(FlowEntryAction.ActionOutput.class);
+ kryo.register(FlowEntryAction.ActionSetEthernetAddr.class);
+ kryo.register(FlowEntryAction.ActionSetIpToS.class);
+ kryo.register(FlowEntryAction.ActionSetIPv4Addr.class);
+ kryo.register(FlowEntryAction.ActionSetTcpUdpPort.class);
+ kryo.register(FlowEntryAction.ActionSetVlanId.class);
+ kryo.register(FlowEntryAction.ActionSetVlanPriority.class);
+ kryo.register(FlowEntryAction.ActionStripVlan.class);
+ kryo.register(FlowEntryAction.ActionValues.class);
+ kryo.register(FlowEntryActions.class);
+ kryo.register(FlowEntryErrorState.class);
+ kryo.register(FlowEntryId.class);
+ kryo.register(FlowEntry.class);
+ kryo.register(FlowEntryMatch.class);
+ kryo.register(FlowEntryMatch.Field.class);
+ kryo.register(FlowEntrySwitchState.class);
+ kryo.register(FlowEntryUserState.class);
+ kryo.register(FlowId.class);
+ kryo.register(FlowPath.class);
+ kryo.register(FlowPathFlags.class);
+ kryo.register(FlowPathType.class);
+ kryo.register(FlowPathUserState.class);
+ kryo.register(IPv4.class);
+ kryo.register(IPv4Net.class);
+ kryo.register(IPv6.class);
+ kryo.register(IPv6Net.class);
+ kryo.register(byte[].class);
+ kryo.register(MACAddress.class);
+ kryo.register(Port.class);
+ kryo.register(Switch.class);
+ // kryo.register(SwitchPort.class);
- // New data model-related classes
- kryo.register(DeviceEvent.class);
- kryo.register(InetAddress.class);
- kryo.register(LinkEvent.class);
- kryo.register(PortEvent.class);
- kryo.register(PortEvent.SwitchPort.class);
- kryo.register(SwitchEvent.class);
- kryo.register(TopologyEvent.class);
+ // New data model-related classes
+ kryo.register(DeviceEvent.class);
+ kryo.register(InetAddress.class);
+ kryo.register(LinkEvent.class);
+ kryo.register(PortEvent.class);
+ kryo.register(PortEvent.SwitchPort.class);
+ kryo.register(SwitchEvent.class);
+ kryo.register(TopologyEvent.class);
- // Intent-related classes
- kryo.register(Path.class);
- kryo.register(Intent.class);
- kryo.register(Intent.IntentState.class);
- kryo.register(PathIntent.class);
- kryo.register(ShortestPathIntent.class);
- kryo.register(ConstrainedShortestPathIntent.class);
- kryo.register(ErrorIntent.class);
- kryo.register(ErrorIntent.ErrorType.class);
- kryo.register(IntentOperation.class);
- kryo.register(IntentOperation.Operator.class);
- kryo.register(IntentOperationList.class);
- kryo.register(IntentStateList.class);
+ // Intent-related classes
+ kryo.register(Path.class);
+ kryo.register(Intent.class);
+ kryo.register(Intent.IntentState.class);
+ kryo.register(PathIntent.class);
+ kryo.register(ShortestPathIntent.class);
+ kryo.register(ConstrainedShortestPathIntent.class);
+ kryo.register(ErrorIntent.class);
+ kryo.register(ErrorIntent.ErrorType.class);
+ kryo.register(IntentOperation.class);
+ kryo.register(IntentOperation.Operator.class);
+ kryo.register(IntentOperationList.class);
+ kryo.register(IntentStateList.class);
- // Device-related classes
- kryo.register(HashSet.class);
- kryo.register(Inet4Address.class);
- kryo.register(OnosDevice.class);
- kryo.register(Date.class);
+ // Device-related classes
+ kryo.register(HashSet.class);
+ kryo.register(Inet4Address.class);
+ kryo.register(OnosDevice.class);
+ kryo.register(Date.class);
- // ProxyArp-related classes
- kryo.register(BroadcastPacketOutNotification.class);
- kryo.register(SinglePacketOutNotification.class);
- kryo.register(ArpReplyNotification.class);
+ // ProxyArp-related classes
+ kryo.register(BroadcastPacketOutNotification.class);
+ kryo.register(SinglePacketOutNotification.class);
+ kryo.register(ArpReplyNotification.class);
- return kryo;
+ return kryo;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/MACAddressDeserializer.java b/src/main/java/net/onrc/onos/core/util/serializers/MACAddressDeserializer.java
index 4ed31a5..45bc336 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/MACAddressDeserializer.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/MACAddressDeserializer.java
@@ -21,20 +21,20 @@
@Override
public MACAddress deserialize(JsonParser jp,
- DeserializationContext ctxt)
- throws IOException, JsonProcessingException {
+ DeserializationContext ctxt)
+ throws IOException, JsonProcessingException {
- MACAddress mac = null;
+ MACAddress mac = null;
- jp.nextToken(); // Move to JsonToken.START_OBJECT
- while (jp.nextToken() != JsonToken.END_OBJECT) {
- String fieldname = jp.getCurrentName();
- if ("value".equals(fieldname)) {
- String value = jp.getText();
- log.debug("Fieldname: {} Value: {}", fieldname, value);
- mac = MACAddress.valueOf(value);
- }
- }
- return mac;
+ jp.nextToken(); // Move to JsonToken.START_OBJECT
+ while (jp.nextToken() != JsonToken.END_OBJECT) {
+ String fieldname = jp.getCurrentName();
+ if ("value".equals(fieldname)) {
+ String value = jp.getText();
+ log.debug("Fieldname: {} Value: {}", fieldname, value);
+ mac = MACAddress.valueOf(value);
+ }
+ }
+ return mac;
}
}
diff --git a/src/main/java/net/onrc/onos/core/util/serializers/MACAddressSerializer.java b/src/main/java/net/onrc/onos/core/util/serializers/MACAddressSerializer.java
index e57a777..f56ac0a 100644
--- a/src/main/java/net/onrc/onos/core/util/serializers/MACAddressSerializer.java
+++ b/src/main/java/net/onrc/onos/core/util/serializers/MACAddressSerializer.java
@@ -16,10 +16,10 @@
@Override
public void serialize(MACAddress mac, JsonGenerator jGen,
- SerializerProvider serializer)
- throws IOException, JsonProcessingException {
- jGen.writeStartObject();
- jGen.writeStringField("value", mac.toString());
- jGen.writeEndObject();
+ SerializerProvider serializer)
+ throws IOException, JsonProcessingException {
+ jGen.writeStartObject();
+ jGen.writeStringField("value", mac.toString());
+ jGen.writeEndObject();
}
}