OSPF protocol manual merge from 1.6, due to cherry pick merge conflict

Change-Id: I93653e745468722ce95533537a79e897b4292f5d
This commit is contained in:
sunishvk 2016-07-18 16:02:39 +05:30 committed by Gerrit Code Review
parent b977f56ac2
commit f7c5655c12
83 changed files with 6188 additions and 4438 deletions

View File

@ -98,4 +98,11 @@ public interface LsdbAge {
* @param lsaWrapper wrapper instance
*/
public void removeLsaFromBin(LsaWrapper lsaWrapper);
/**
* Gets the age counter roll over.
*
* @return the age counter roll over
*/
public int getAgeCounterRollOver();
}

View File

@ -38,17 +38,18 @@ public interface OspfAgent {
void removeConnectedRouter(OspfRouter ospfRouter);
/**
* Notifies that got a packet of link from network and need do processing.
* Notifies that got a packet of link from network and need to add the link.
*
* @param ospfRouter router instance
* @param ospfLinkTed link ted instance
* @param ospfRouter router instance
* @param ospfLinkTed link TED instance
*/
void addLink(OspfRouter ospfRouter, OspfLinkTed ospfLinkTed);
/**
* Notifies that got a packet of link from network and need do processing.
* Notifies that got a packet of link from network and need do delete the link.
*
* @param ospfRouter router instance
* @param ospfLinkTed link TED instance
*/
void deleteLink(OspfRouter ospfRouter);
void deleteLink(OspfRouter ospfRouter, OspfLinkTed ospfLinkTed);
}

View File

@ -59,7 +59,7 @@ public interface OspfArea {
*
* @return LSDB instance for this area
*/
public OspfLsdb database();
OspfLsdb database();
/**
* Checks whether an instance of the given LSA exists in the database.
@ -67,19 +67,12 @@ public interface OspfArea {
* @param lookupLsa LSA instance to lookup
* @return LSA wrapper instance which contains the LSA
*/
public LsaWrapper lsaLookup(OspfLsa lookupLsa);
LsaWrapper lsaLookup(OspfLsa lookupLsa);
/**
* Initializes link state database, this acts as a place holder for storing the received LSA.
*/
public void initializeDb();
/**
* Sets the stub cost.
*
* @param stubCost stub cost
*/
void setStubCost(int stubCost);
void initializeDb();
/**
* Sets the options value.
@ -88,38 +81,6 @@ public interface OspfArea {
*/
void setOptions(int options);
/**
* Gets area address ranges to which this area belongs to.
*
* @return list of area address ranges
*/
List<OspfAreaAddressRange> addressRanges();
/**
* Sets the area address ranges to which this area belongs to.
*
* @param addrRangeList list of area address ranges
*/
void setAddressRanges(List<OspfAreaAddressRange> addrRangeList);
/**
* Gets whether the area is transit capable or not.
* This indicates whether the area can carry data traffic that neither originates
* nor terminates in the area itself.
*
* @return true if transit capable, else false
*/
boolean isTransitCapability();
/**
* Sets whether the area is transit capable or not.
* This indicates whether the area can carry data traffic that neither originates
* nor terminates in the area itself.
*
* @param transitCapability true if transit capable, else false
*/
void setTransitCapability(boolean transitCapability);
/**
* Gets external routing capability.
* This indicates Whether AS-external-LSAs will be flooded into/throughout the area.
@ -136,13 +97,6 @@ public interface OspfArea {
*/
void setExternalRoutingCapability(boolean externalRoutingCapability);
/**
* Gets the stub cost, which indicates if the area has been configured as a stub area.
*
* @return stub cost
*/
int stubCost();
/**
* Gets if the router is opaque enabled or not.
* This indicates whether the router accepts opaque LSA.
@ -156,14 +110,14 @@ public interface OspfArea {
*
* @return list of interfaces
*/
List<OspfInterface> getInterfacesLst();
List<OspfInterface> ospfInterfaceList();
/**
* Sets the list of interfaces attached to this area.
*
* @param interfacesLst list of interface instances
*/
void setInterfacesLst(List<OspfInterface> interfacesLst);
void setOspfInterfaceList(List<OspfInterface> interfacesLst);
/**
* Gets the options value, which indicates the supported optional capabilities.

View File

@ -15,6 +15,8 @@
*/
package org.onosproject.ospf.controller;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
import java.util.Set;
@ -55,9 +57,9 @@ public interface OspfController {
/**
* Updates configuration of processes.
*
* @param processes process info to update
* @param processesNode process info to update
*/
public void updateConfig(List<OspfProcess> processes);
void updateConfig(JsonNode processesNode);
/**
* Deletes configuration parameters.
@ -65,7 +67,7 @@ public interface OspfController {
* @param processes list of process instance
* @param attribute attribute to delete
*/
public void deleteConfig(List<OspfProcess> processes, String attribute);
void deleteConfig(List<OspfProcess> processes, String attribute);
/**
* Gets the list of listeners registered for router events.

View File

@ -15,15 +15,44 @@
*/
package org.onosproject.ospf.controller;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.onlab.packet.Ip4Address;
import java.util.HashMap;
import java.util.Map;
/**
* Represents an OSPF Interface.
*/
public interface OspfInterface {
/**
* Returns interface index.
*
* @return interface index
*/
public int interfaceIndex();
/**
* Sets interface index.
*
* @param interfaceIndex interface index
*/
public void setInterfaceIndex(int interfaceIndex);
/**
* Returns OSPF area instance.
*
* @return OSPF area instance
*/
public OspfArea ospfArea();
/**
* Sets OSPF area instance.
*
* @param ospfArea OSPF area instance
*/
public void setOspfArea(OspfArea ospfArea);
/**
* Gets network mask of the interface.
*
@ -31,29 +60,6 @@ public interface OspfInterface {
*/
Ip4Address ipNetworkMask();
/**
* Sets area id, to which the interface belongs.
*
* @param areaId area identifier
*/
void setAreaId(int areaId);
/**
* Sets the authentication key.
* Interface uses this to authenticate while establishing communication with other routers.
*
* @param authKey represents authentication key
*/
void setAuthKey(String authKey);
/**
* Sets the authentication type,
* Interface uses this to authenticate while establishing communication with other routers.
*
* @param authType authType represents authentication type
*/
void setAuthType(String authType);
/**
* Sets the value of BDR.
* The BDR is calculated during adjacency formation.
@ -86,13 +92,6 @@ public interface OspfInterface {
*/
void setRouterDeadIntervalTime(int routerDeadIntervalTime);
/**
* Sets the interface cost which is the cost of sending a data packet onto the network.
*
* @param interfaceCost an integer represents interface cost
*/
void setInterfaceCost(int interfaceCost);
/**
* Sets interface type.
* This indicates whether the interface is on point to point mode or broadcast mode.
@ -115,22 +114,6 @@ public interface OspfInterface {
*/
void setIpNetworkMask(Ip4Address ipNetworkMask);
/**
* Sets the polling interval.
* Polling interval indicates the interval until when the Hello Packets are
* sent to a dead neighbor.
*
* @param pollInterval an integer represents poll interval
*/
void setPollInterval(int pollInterval);
/**
* Sets transmission delay.
*
* @param transmitDelay an integer represents delay
*/
void setTransmitDelay(int transmitDelay);
/**
* Sets retransmit interval which indicates the number of seconds between LSA retransmissions.
*
@ -152,13 +135,6 @@ public interface OspfInterface {
*/
void setRouterPriority(int routerPriority);
/**
* Gets the area id to which router belongs.
*
* @return areaId an integer value
*/
int areaId();
/**
* Gets the IP address.
*
@ -180,33 +156,12 @@ public interface OspfInterface {
*/
int mtu();
/**
* Gets interface cost.
*
* @return an integer representing interface cost
*/
int interfaceCost();
/**
* Gets the list of neighbors associated with the interface.
*
* @return listOfNeighbors as key value pair
*/
HashMap<String, OspfNbr> listOfNeighbors();
/**
* Gets poll interval.
*
* @return pollInterval an integer representing poll interval
*/
int pollInterval();
/**
* Gets transmission delay.
*
* @return transmitDelay an integer representing delay
*/
int transmitDelay();
Map<String, OspfNbr> listOfNeighbors();
/**
* Gets the IP address of the BDR.
@ -222,20 +177,6 @@ public interface OspfInterface {
*/
Ip4Address dr();
/**
* Gets authentication key.
*
* @return authKey represents authentication key
*/
String authKey();
/**
* Gets authentication type.
*
* @return authType represents authentication type
*/
String authType();
/**
* Gets hello interval time in seconds, this defines how often we send the hello packet.
*
@ -294,4 +235,54 @@ public interface OspfInterface {
* @param lsaKey key used to store lsa in map
*/
void removeLsaFromNeighborMap(String lsaKey);
/**
* When an OSPF message received it is handed over to this method.
* Based on the type of the OSPF message received it will be handed over
* to corresponding message handler methods.
*
* @param ospfMessage received OSPF message
* @param ctx channel handler context instance.
* @throws Exception might throws exception
*/
void processOspfMessage(OspfMessage ospfMessage, ChannelHandlerContext ctx) throws Exception;
/**
* Represents an interface is up and connected.
*
* @throws Exception might throws exception
*/
void interfaceUp() throws Exception;
/**
* Starts the timer which waits for configured seconds and sends Delayed Ack Packet.
*/
void startDelayedAckTimer();
/**
* Stops the delayed acknowledge timer.
*/
void stopDelayedAckTimer();
/**
* Starts the hello timer which sends hello packet every configured seconds.
*/
void startHelloTimer();
/**
* Stops the hello timer.
*/
void stopHelloTimer();
/**
* Gets called when an interface is down.
* All interface variables are reset, and interface timers disabled.
* Also all neighbor connections associated with the interface are destroyed.
*/
void interfaceDown();
/**
* Removes all the neighbors.
*/
void removeNeighbors();
}

View File

@ -23,7 +23,7 @@ public interface OspfLinkListener {
/**
* Notifies that we got a link from network.
*
* @param ospfRouter router instance
* @param ospfRouter router instance
* @param ospfLinkTed link TED information of router
*/
void addLink(OspfRouter ospfRouter, OspfLinkTed ospfLinkTed);
@ -31,7 +31,8 @@ public interface OspfLinkListener {
/**
* Notifies that a link got removed from network.
*
* @param ospfRouter router instance
* @param ospfRouter router instance
* @param ospfLinkTed link TED information of router
*/
void deleteLink(OspfRouter ospfRouter);
void deleteLink(OspfRouter ospfRouter, OspfLinkTed ospfLinkTed);
}

View File

@ -13,18 +13,30 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.ospf.protocol.ospfpacket;
package org.onosproject.ospf.controller;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.exceptions.OspfParseException;
import org.onosproject.ospf.protocol.util.OspfPacketType;
/**
* Representation of an OSPF message.
*/
public interface OspfMessage {
/**
* Returns the interface index on which the message received.
*
* @return interface index on which the message received
*/
int interfaceIndex();
/**
* Sets the interface index on which the message received.
*
* @param interfaceIndex interface index on which the message received
*/
void setInterfaceIndex(int interfaceIndex);
/**
* Returns the type of OSPF message.
*
@ -36,9 +48,9 @@ public interface OspfMessage {
* Reads from ChannelBuffer and initializes the type of LSA.
*
* @param channelBuffer channel buffer instance
* @throws OspfParseException might throws exception while parsing buffer
* @throws Exception might throws exception while parsing buffer
*/
void readFrom(ChannelBuffer channelBuffer) throws OspfParseException;
void readFrom(ChannelBuffer channelBuffer) throws Exception;
/**
* Returns OSPFMessage as byte array.

View File

@ -189,4 +189,36 @@ public interface OspfNbr {
* @return neighbor's state
*/
OspfNeighborState getState();
/**
* Starts the inactivity timer.
*/
void startInactivityTimeCheck();
/**
* Stops the inactivity timer.
*/
void stopInactivityTimeCheck();
/**
* Sets router dead interval.
*
* @param routerDeadInterval router dead interval
*/
void setRouterDeadInterval(int routerDeadInterval);
/**
* Stops the flooding timer.
*/
void stopFloodingTimer();
/**
* Stops the Dd Retransmission executor task.
*/
void stopRxMtDdTimer();
/**
* Stops Ls request retransmission executor task.
*/
void stopRxMtLsrTimer();
}

View File

@ -13,17 +13,32 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.ospf.protocol.util;
package org.onosproject.ospf.controller;
/**
* Representation of different OSPF packet types.
*/
public enum OspfPacketType {
/**
* OSPF hello packet.
*/
HELLO(1),
/**
* OSPF device description packet.
*/
DD(2),
/**
* OSPF link state request packet.
*/
LSREQUEST(3),
/**
* OSPF link state update packet.
*/
LSUPDATE(4),
/**
* OSPF link state acknowledge packet.
*/
LSAACK(5);
private int value;
@ -31,7 +46,7 @@ public enum OspfPacketType {
/**
* Creates instance of OSPF packet types.
*
* @param value
* @param value OSPF packet types
*/
OspfPacketType(int value) {
this.value = value;

View File

@ -29,7 +29,7 @@ import static com.google.common.base.Preconditions.checkArgument;
*/
public class OspfRouterId {
private static final String SCHEME = "ospf";
private static final String SCHEME = "l3";
private static final long UNKNOWN = 0;
private final IpAddress ipAddress;

View File

@ -50,7 +50,7 @@ public interface TopologyForDeviceAndLink {
/**
* Sets link information.
*
* @param key key used to store in map
* @param key key used to store in map
* @param linkInformationMap link information instance
*/
void setLinkInformationMap(String key, LinkInformation linkInformationMap);
@ -79,7 +79,7 @@ public interface TopologyForDeviceAndLink {
void removeDeviceInformationMap(String key);
/**
* Removes links from linkInformationMap.
* Removes links from link information map.
*
* @param routerId router's IP address
*/
@ -109,4 +109,56 @@ public interface TopologyForDeviceAndLink {
* @param ospfArea area instance
*/
void updateLinkInformation(OspfLsa ospfLsa, OspfArea ospfArea);
/**
* Gets device information as map.
*
* @return deviceInformationMap to delete from core
*/
Map<String, DeviceInformation> deviceInformationMapToDelete();
/**
* Sets device information as map.
*
* @param key key to store in device info map
* @param deviceInformationMapToDelete device information instance
*/
void setDeviceInformationMapToDelete(String key, DeviceInformation deviceInformationMapToDelete);
/**
* Removes device information from deviceInformationMapToDelete.
*
* @param key key to remove device information
*/
void removeDeviceInformationMapFromDeleteMap(String key);
/**
* Gets device information as map for Point-To-Point.
*
* @return deviceInformationMap
*/
Map<String, DeviceInformation> deviceInformationMapForPointToPoint();
/**
* Sets device information as map for Point-To-Point.
*
* @param key key to store in device info
* @param deviceInformationMap device information instance
*/
void setDeviceInformationMapForPointToPoint(String key, DeviceInformation deviceInformationMap);
/**
* Gets link information as map for Point-To-Point.
*
* @return linkInformationMap
*/
Map<String, LinkInformation> linkInformationMapForPointToPoint();
/**
* Sets link information as map for Point-To-Point.
*
* @param key key to store link info
* @param linkInformationMap link information instance
*/
void setLinkInformationMapForPointToPoint(String key, LinkInformation linkInformationMap);
}

View File

@ -21,7 +21,6 @@ import com.google.common.base.Objects;
import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.controller.LsaWrapper;
import org.onosproject.ospf.controller.OspfArea;
import org.onosproject.ospf.controller.OspfAreaAddressRange;
import org.onosproject.ospf.controller.OspfInterface;
import org.onosproject.ospf.controller.OspfLsa;
import org.onosproject.ospf.controller.OspfLsaType;
@ -53,29 +52,15 @@ import java.util.Map;
*/
public class OspfAreaImpl implements OspfArea {
private static final Logger log = LoggerFactory.getLogger(OspfAreaImpl.class);
/**
* Address ranges in order to aggregate routing information at area.
* boundaries. Each address range is specified by an [address,mask] pair and
* a status indication of either Advertise or DoNotAdvertise
*/
private List<OspfAreaAddressRange> addressRanges;
/**
* This parameter indicates whether the area can carry data traffic that.
* neither originates nor terminates in the area itself.
*/
private boolean transitCapability;
/**
* Whether AS-external-LSAs will be flooded into/throughout the area.
*/
private boolean externalRoutingCapability;
/**
* Indicates the cost of the default summary-LSA.
*/
private int stubCost;
/**
* Represents a list of all router's interfaces associated with this area.
*/
private List<OspfInterface> interfacesLst;
private List<OspfInterface> ospfInterfaceList;
/**
* The LS Database for this area. It includes router-LSAs, network-LSAs and.
* summary-LSAs. AS-external-LSAs are hold in the OSPF class itself.
@ -116,18 +101,15 @@ public class OspfAreaImpl implements OspfArea {
OspfAreaImpl that = (OspfAreaImpl) o;
return Objects.equal(areaId, that.areaId) &&
Objects.equal(routerId, that.routerId) &&
Objects.equal(addressRanges.size(), that.addressRanges.size()) &&
Objects.equal(transitCapability, that.transitCapability) &&
Objects.equal(externalRoutingCapability, that.externalRoutingCapability) &&
Objects.equal(stubCost, that.stubCost) &&
Objects.equal(interfacesLst.size(), that.interfacesLst.size()) &&
Objects.equal(ospfInterfaceList.size(), that.ospfInterfaceList.size()) &&
Objects.equal(database, that.database);
}
@Override
public int hashCode() {
return Objects.hashCode(areaId, routerId, addressRanges, transitCapability, externalRoutingCapability,
stubCost, interfacesLst, database);
return Objects.hashCode(areaId, routerId, externalRoutingCapability,
ospfInterfaceList, database);
}
/**
@ -234,7 +216,7 @@ public class OspfAreaImpl implements OspfArea {
networkLsa.setNetworkMask(mask);
//Adding our own router.
networkLsa.addAttachedRouter(routerId());
Iterator iter = interfacesLst.iterator();
Iterator iter = ospfInterfaceList.iterator();
OspfInterfaceImpl ospfInterface = null;
while (iter.hasNext()) {
ospfInterface = (OspfInterfaceImpl) iter.next();
@ -310,7 +292,7 @@ public class OspfAreaImpl implements OspfArea {
*/
private void buildLinkForRouterLsa(RouterLsa routerLsa, OspfInterface ospfInterface) {
OspfInterfaceImpl nextInterface;
Iterator interfaces = interfacesLst.iterator();
Iterator interfaces = ospfInterfaceList.iterator();
while (interfaces.hasNext()) {
nextInterface = (OspfInterfaceImpl) interfaces.next();
if (nextInterface.state() == OspfInterfaceState.DOWN) {
@ -417,44 +399,6 @@ public class OspfAreaImpl implements OspfArea {
this.areaId = areaId;
}
/**
* Gets address range.
*
* @return list of area address ranges
*/
public List<OspfAreaAddressRange> addressRanges() {
return addressRanges;
}
/**
* Sets the area address ranges.
*
* @param addressRanges list of area address range
*/
@JsonProperty("addressRange")
public void setAddressRanges(List<OspfAreaAddressRange> addressRanges) {
this.addressRanges = addressRanges;
}
/**
* Gets is transit capable or not.
*
* @return true if transit capable, else false
*/
public boolean isTransitCapability() {
return transitCapability;
}
/**
* Sets transit capability.
*
* @param transitCapability true if transit capable, else false
*/
@JsonProperty("transitCapability")
public void setTransitCapability(boolean transitCapability) {
this.transitCapability = transitCapability;
}
/**
* Gets external routing capability.
*
@ -474,42 +418,23 @@ public class OspfAreaImpl implements OspfArea {
this.externalRoutingCapability = externalRoutingCapability;
}
/**
* Gets the stub cost.
*
* @return stub cost
*/
public int stubCost() {
return stubCost;
}
/**
* Sets the stub cost.
*
* @param stubCost stub cost
*/
@JsonProperty("stubCost")
public void setStubCost(int stubCost) {
this.stubCost = stubCost;
}
/**
* Gets the list of interfaces in this area.
*
* @return list of interfaces
*/
public List<OspfInterface> getInterfacesLst() {
return interfacesLst;
public List<OspfInterface> ospfInterfaceList() {
return ospfInterfaceList;
}
/**
* Sets the list of interfaces attached to the area.
*
* @param interfacesLst list of OspfInterface instances
* @param ospfInterfaceList list of OspfInterface instances
*/
@JsonProperty("interface")
public void setInterfacesLst(List<OspfInterface> interfacesLst) {
this.interfacesLst = interfacesLst;
public void setOspfInterfaceList(List<OspfInterface> ospfInterfaceList) {
this.ospfInterfaceList = ospfInterfaceList;
}
/**
@ -522,7 +447,7 @@ public class OspfAreaImpl implements OspfArea {
public boolean noNeighborInLsaExchangeProcess() {
OspfInterfaceImpl nextInterface;
OspfNeighborState nextNeighborState;
Iterator interfaces = interfacesLst.iterator();
Iterator interfaces = ospfInterfaceList.iterator();
while (interfaces.hasNext()) {
nextInterface = (OspfInterfaceImpl) interfaces.next();
Iterator neighbors = nextInterface.listOfNeighbors().values().iterator();
@ -659,19 +584,14 @@ public class OspfAreaImpl implements OspfArea {
return MoreObjects.toStringHelper(getClass())
.omitNullValues()
.add("areaID", areaId)
.add("stubCost", stubCost)
.add("addressRanges", addressRanges)
.add("interfacesLst", interfacesLst)
.add("transitCapability", transitCapability)
.add("ospfInterfaceList", ospfInterfaceList)
.add("externalRoutingCapability", externalRoutingCapability)
.toString();
}
/**
* Checks all Neighbors belonging to this Area whether they are in state lesser than the EXCHANGE.
* <p>
* Creates list of such neighbors
* <p>
* Returns list of neighbors who satisfy the conditions
*
* @param ospfInterface OSPF interface instance
@ -716,7 +636,7 @@ public class OspfAreaImpl implements OspfArea {
public void addToOtherNeighborLsaTxList(LsaHeader recLsa) {
//Add the received LSA in other neighbors retransmission list.
log.debug("OspfAreaImpl: addToOtherNeighborLsaTxList");
List<OspfInterface> ospfInterfaces = getInterfacesLst();
List<OspfInterface> ospfInterfaces = ospfInterfaceList();
for (OspfInterface ospfInterfaceFromArea : ospfInterfaces) {
Map neighbors = ospfInterfaceFromArea.listOfNeighbors();
for (Object neighborIP : neighbors.keySet()) {

View File

@ -15,13 +15,15 @@
*/
package org.onosproject.ospf.controller.impl;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.AdaptiveReceiveBufferSizePredictor;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.FixedReceiveBufferSizePredictorFactory;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.onlab.packet.Ip4Address;
import org.onlab.packet.TpPort;
import org.onosproject.net.driver.DriverService;
import org.onosproject.ospf.controller.OspfAgent;
import org.onosproject.ospf.controller.OspfArea;
@ -29,42 +31,137 @@ import org.onosproject.ospf.controller.OspfInterface;
import org.onosproject.ospf.controller.OspfLinkTed;
import org.onosproject.ospf.controller.OspfProcess;
import org.onosproject.ospf.controller.OspfRouter;
import org.onosproject.ospf.protocol.util.OspfUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static org.onlab.util.Tools.groupedThreads;
/**
* Representation of the main controller class. Handles all setup and network listeners.
* Representation of an OSPF controller.
*/
public class Controller {
protected static final Logger log = LoggerFactory.getLogger(Controller.class);
protected static final int BUFFER_SIZE = 4 * 1024 * 1024;
private static final String PROCESS = "process";
private static final String AREA = "area";
private static final String INTERFACE = "interface";
protected int ospfPort = 7000;
protected int workerThreads = 16;
private static final Logger log = LoggerFactory.getLogger(Controller.class);
private static final int RETRY_INTERVAL = 4;
private final int peerWorkerThreads = 16;
protected long systemStartTime;
byte[] configPacket = null;
private List<OspfProcess> processes = null;
private OspfInterfaceChannelHandler ospfChannelHandler;
private NioClientSocketChannelFactory peerExecFactory;
private ClientBootstrap peerBootstrap = null;
private TpPort isisPort = TpPort.tpPort(OspfUtil.SPORT);
private ScheduledExecutorService connectExecutor = null;
private int connectRetryCounter = 0;
private int connectRetryTime;
private DriverService driverService;
private OspfAgent agent;
private List<ChannelGroup> cgList = new ArrayList();
private List<NioServerSocketChannelFactory> execFactoryLst = new ArrayList<>();
private List<OspfProcess> processes;
/**
* Deactivates OSPF controller.
*/
public void isisDeactivate() {
peerExecFactory.shutdown();
}
/**
* Updates the processes configuration.
*
* @param ospfProcesses list of OSPF process instances
* @throws Exception might throws parse exception
*/
public void updateConfig(List<OspfProcess> ospfProcesses) throws Exception {
log.debug("Controller::UpdateConfig called");
configPacket = new byte[OspfUtil.CONFIG_LENGTH];
byte numberOfInterface = 0; // number of interfaces to configure
configPacket[0] = (byte) 0xFF; // its a conf packet - identifier
for (OspfProcess ospfProcess : ospfProcesses) {
log.debug("OspfProcessDetails : " + ospfProcess);
for (OspfArea ospfArea : ospfProcess.areas()) {
for (OspfInterface ospfInterface : ospfArea.ospfInterfaceList()) {
log.debug("OspfInterfaceDetails : " + ospfInterface);
numberOfInterface++;
configPacket[2 * numberOfInterface] = (byte) ospfInterface.interfaceIndex();
configPacket[(2 * numberOfInterface) + 1] = (byte) 4;
}
}
}
configPacket[1] = numberOfInterface;
//First time configuration
if (processes == null) {
if (ospfProcesses.size() > 0) {
processes = ospfProcesses;
connectPeer();
}
} else {
ospfChannelHandler.updateInterfaceMap(ospfProcesses);
//Send the config packet
ospfChannelHandler.sentConfigPacket(configPacket);
}
}
/**
* Initializes the netty client channel connection.
*/
private void initConnection() {
if (peerBootstrap != null) {
return;
}
peerBootstrap = createPeerBootStrap();
peerBootstrap.setOption("reuseAddress", true);
peerBootstrap.setOption("tcpNoDelay", true);
peerBootstrap.setOption("keepAlive", true);
peerBootstrap.setOption("receiveBufferSize", Controller.BUFFER_SIZE);
peerBootstrap.setOption("receiveBufferSizePredictorFactory",
new FixedReceiveBufferSizePredictorFactory(
Controller.BUFFER_SIZE));
peerBootstrap.setOption("receiveBufferSizePredictor",
new AdaptiveReceiveBufferSizePredictor(64, 4096, 65536));
peerBootstrap.setOption("child.keepAlive", true);
peerBootstrap.setOption("child.tcpNoDelay", true);
peerBootstrap.setOption("child.sendBufferSize", Controller.BUFFER_SIZE);
peerBootstrap.setOption("child.receiveBufferSize", Controller.BUFFER_SIZE);
peerBootstrap.setOption("child.receiveBufferSizePredictorFactory",
new FixedReceiveBufferSizePredictorFactory(
Controller.BUFFER_SIZE));
peerBootstrap.setOption("child.reuseAddress", true);
ospfChannelHandler = new OspfInterfaceChannelHandler(this, processes);
ChannelPipelineFactory pfact = new OspfPipelineFactory(ospfChannelHandler);
peerBootstrap.setPipelineFactory(pfact);
}
/**
* Creates peer boot strap.
*
* @return client bootstrap instance
*/
private ClientBootstrap createPeerBootStrap() {
if (peerWorkerThreads == 0) {
peerExecFactory = new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(groupedThreads("onos/isis", "boss-%d")),
Executors.newCachedThreadPool(groupedThreads("onos/isis", "worker-%d")));
return new ClientBootstrap(peerExecFactory);
} else {
peerExecFactory = new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(groupedThreads("onos/isis", "boss-%d")),
Executors.newCachedThreadPool(groupedThreads("onos/isis", "worker-%d")),
peerWorkerThreads);
return new ClientBootstrap(peerExecFactory);
}
}
/**
* Gets all configured processes.
@ -106,35 +203,13 @@ public class Controller {
/**
* Removes link details.
*
* @param ospfRouter OSPF router instance
* @param ospfRouter OSPF router instance
* @param ospfLinkTed OSPF link ted instance
*/
public void removeLinkDetails(OspfRouter ospfRouter) {
agent.deleteLink(ospfRouter);
public void removeLinkDetails(OspfRouter ospfRouter, OspfLinkTed ospfLinkTed) {
agent.deleteLink(ospfRouter, ospfLinkTed);
}
/**
* Creates a server bootstrap.
*
* @return ServerBootstrap bootstrap instance
*/
private ServerBootstrap createServerBootStrap() {
Executor bossPool = Executors.newCachedThreadPool();
Executor workerPool = Executors.newCachedThreadPool();
NioServerSocketChannelFactory executerFactory;
if (workerThreads == 0) {
executerFactory = new NioServerSocketChannelFactory(bossPool, workerPool);
execFactoryLst.add(executerFactory);
} else {
executerFactory = new NioServerSocketChannelFactory(bossPool, workerPool, workerThreads);
execFactoryLst.add(executerFactory);
}
return new ServerBootstrap(executerFactory);
}
/**
* Initializes internal data structures.
*/
@ -149,7 +224,7 @@ public class Controller {
* @param driverService driver service instance
*/
public void start(OspfAgent ag, DriverService driverService) {
log.info("Starting OSPF Controller...!!!");
log.info("Starting OSPF controller...!!!");
this.agent = ag;
this.driverService = driverService;
this.init();
@ -159,615 +234,143 @@ public class Controller {
* Stops the Controller.
*/
public void stop() {
log.info("Stopping OSPF Controller...!!!");
for (ChannelGroup cg : cgList) {
cg.close();
}
for (NioServerSocketChannelFactory execFactory : execFactoryLst) {
execFactory.shutdown();
}
log.info("Stopping OSPF controller...!!!");
isisDeactivate();
processes.clear();
}
/**
* Deletes configured interface from the area.
* Returns interface IP by index.
*
* @param processId process id
* @param areaId area id
* @param interfaceToDelete interface to delete
* @return true if operation success else false
* @param interfaceIndex interface index
* @return interface IP by index
*/
public boolean deleteInterfaceFromArea(String processId, String areaId, String interfaceToDelete) {
Iterator<OspfProcess> processItr = processes.iterator();
while (processItr.hasNext()) {
OspfProcess process = processItr.next();
if (processId.equalsIgnoreCase(process.processId())) {
Iterator<OspfArea> areaItr = process.areas().iterator();
while (areaItr.hasNext()) {
OspfArea area = areaItr.next();
Iterator<OspfInterface> ospfIntrItr = area.getInterfacesLst().iterator();
if (area.areaId().toString().equalsIgnoreCase(areaId)) {
while (ospfIntrItr.hasNext()) {
OspfInterface ospfIntr = ospfIntrItr.next();
if (interfaceToDelete.equalsIgnoreCase(ospfIntr.ipAddress().toString())) {
ospfIntrItr.remove();
log.debug("Interface With Id {} is removed from Area {}",
ospfIntr.ipAddress(), ospfIntr.areaId());
return true;
}
}
}
}
}
}
return false;
}
/*
* Checks area with area id exists in process.
*
* @param processId process id
* @param areaId area id
* @return true if exist else false
*/
public boolean checkArea(String processId, String areaId) {
for (OspfProcess process : processes) {
if (processId.equalsIgnoreCase(process.processId())) {
for (OspfArea area : process.areas()) {
if (area.areaId().toString().equalsIgnoreCase(areaId)) {
return true;
}
}
}
}
return false;
}
/*
* Checks process with process id exists or not.
*
* @param processId process id
* @return true if exist else false
*/
public boolean checkProcess(String processId) {
log.debug("CheckProcess,Process Id ={} processes={}", processId, processes);
for (OspfProcess process : processes) {
if (processId.equalsIgnoreCase(process.processId())) {
return true;
}
}
return false;
}
/*
* Checks interface exists in given area.
*
* @param processId process id
* @param areaId area id
* @param ipAddress interface
* @return true if exist else false
*/
public boolean checkInterface(String processId, String areaId, String interfaceIp) {
for (OspfProcess process : processes) {
if (processId.equalsIgnoreCase(process.processId())) {
for (OspfArea area : process.areas()) {
if (area.areaId().toString().equalsIgnoreCase(areaId)) {
for (OspfInterface ospfInterface : area.getInterfacesLst()) {
if (ospfInterface.ipAddress().toString().equalsIgnoreCase(interfaceIp)) {
return true;
}
}
}
}
}
}
return false;
}
/**
* Create processes first time when no process exist.
* Create server bootstraps for all the interfaces in the processes.
*
* @param ospfProcesses list of OSPF processes to create
*/
private void createProcessWhenNoProcessesExists(List<OspfProcess> ospfProcesses) {
Set<String> interfaceIpList = new HashSet<>();
Set<String> areaIdList = new HashSet<>();
if (processes != null) {
if (processes.size() == 0) {
processes.addAll(ospfProcesses);
for (OspfProcess process : ospfProcesses) {
for (OspfArea area : process.areas()) {
areaIdList.add(area.areaId().toString());
for (OspfInterface intrfc : area.getInterfacesLst()) {
interfaceIpList.add(intrfc.ipAddress().toString());
}
}
}
createBootStrapForCreatedInterface(interfaceIpList, areaIdList);
}
} else {
processes = new ArrayList<>();
processes.addAll(ospfProcesses);
for (OspfProcess process : ospfProcesses) {
for (OspfArea area : process.areas()) {
areaIdList.add(area.areaId().toString());
for (OspfInterface intrfc : area.getInterfacesLst()) {
interfaceIpList.add(intrfc.ipAddress().toString());
}
}
}
createBootStrapForCreatedInterface(interfaceIpList, areaIdList);
}
}
/**
* Creates processes when already process exist.
* It can be modifying existing process or adding a new process.
*
* @param ospfProcesses list of processes
*/
private void createProcessWhenProcessesExists(List<OspfProcess> ospfProcesses) {
if (ospfProcesses != null) {
for (OspfProcess process : ospfProcesses) {
if (!checkProcess(process.processId())) {
createNewProcess(process.processId(), process);
} else {
List<OspfArea> areas = process.areas();
for (OspfArea area : areas) {
if (!checkArea(process.processId(), area.areaId().toString())) {
createAreaInProcess(process.processId(),
area.areaId().toString(), area);
} else {
updateAreaInProcess(process.processId(), area.areaId().toString(), area);
for (OspfInterface interfc : area.getInterfacesLst()) {
if (!checkInterface(process.processId(),
area.areaId().toString(), interfc.ipAddress().toString())) {
createInterfaceInAreaInProcess(process.processId(),
area.areaId().toString(), interfc);
} else {
updateInterfaceParameters(process.processId(),
area.areaId().toString(),
interfc.ipAddress().toString(), interfc);
}
}
}
}
}
}
}
}
/**
* Updates the area information in already started OSPF processes.
*
* @param processId process id
* @param areaId area id
* @param areaFrmConfig area to update
*/
public void updateAreaInProcess(String processId, String areaId, OspfArea areaFrmConfig) {
if (processes != null) {
Iterator<OspfProcess> processItr = processes.iterator();
while (processItr.hasNext()) {
OspfProcess process = processItr.next();
if (processId.equalsIgnoreCase(process.processId())) {
Iterator<OspfArea> area = process.areas().iterator();
while (area.hasNext()) {
OspfArea ospfArea = area.next();
if (areaId.equalsIgnoreCase(ospfArea.areaId().toString())) {
ospfArea.setAddressRanges(areaFrmConfig.addressRanges());
ospfArea.setRouterId(areaFrmConfig.routerId());
ospfArea.setTransitCapability(areaFrmConfig.isTransitCapability());
ospfArea.setExternalRoutingCapability(areaFrmConfig.isExternalRoutingCapability());
ospfArea.setStubCost(areaFrmConfig.stubCost());
ospfArea.setOptions(areaFrmConfig.options());
ospfArea.setIsOpaqueEnabled(areaFrmConfig.isOpaqueEnabled());
log.debug("updateAreaInProcess::Process Id::{}::Ospf Area with Id::{}::is " +
"updated", processId, areaId);
}
}
}
}
}
}
/**
* Updates the processes configuration.
*
* @param ospfProcesses list of OSPF processes
*/
public void updateConfig(List<OspfProcess> ospfProcesses) {
log.info("Controller::UpdateConfig called");
if (processes != null) {
if (processes.size() == 0) {
createProcessWhenNoProcessesExists(ospfProcesses);
} else {
createProcessWhenProcessesExists(ospfProcesses);
}
} else {
createProcessWhenNoProcessesExists(ospfProcesses);
}
}
/**
* Deletes configuration.
*
* @param ospfProcesses OSPF processes
* @param attribute attribute to delete
*/
public void deleteConfig(List<OspfProcess> ospfProcesses, String attribute) {
log.info("Controller::UpdateConfig called");
if (processes != null) {
if (processes.size() == 0) {
log.debug("DeleteConfig:: No process exists");
} else {
deleteProcessWhenExists(ospfProcesses, attribute);
}
} else {
log.debug("DeleteConfig:: No process exists");
}
}
/**
* Creates a new process.
*
* @param processId process id
* @param process OSPF process instance
*/
private void createNewProcess(String processId, OspfProcess process) {
Set<String> interfaceIpList = new HashSet<>();
Set<String> areaIdList = new HashSet<>();
processes.add(process);
for (OspfArea area : process.areas()) {
areaIdList.add(area.areaId().toString());
for (OspfInterface interfc : area.getInterfacesLst()) {
interfaceIpList.add(interfc.ipAddress().toString());
}
}
log.debug("createNewProcess::List of areas in process::{} areas::{}", processId, areaIdList);
createBootStrapForCreatedInterface(interfaceIpList, areaIdList);
log.debug("createNewProcess:: all processes::{}", processes);
}
/**
* Creates a new area information in the process.
*
* @param processId process id
* @param areaId area id
* @param area OSPF area instance
*/
private void createAreaInProcess(String processId, String areaId, OspfArea area) {
Set<String> interfaceIpList = new HashSet<>();
Set<String> areaIdList = new HashSet<>();
Iterator<OspfProcess> processItr = processes.iterator();
while (processItr.hasNext()) {
OspfProcess process = processItr.next();
List<OspfArea> areasInProcess = process.areas();
if (processId.equalsIgnoreCase(process.processId())) {
areasInProcess.add(area);
for (OspfInterface intrfc : area.getInterfacesLst()) {
interfaceIpList.add(intrfc.ipAddress().toString());
}
areaIdList.add(area.areaId().toString());
log.debug("createAreaInProcess::List of areas in process Id::{} " +
"AreaId ::{} update process::{}",
processId, areaId, process);
}
}
createBootStrapForCreatedInterface(interfaceIpList, areaIdList);
log.debug("createAreaInProcess:: all processes::{}", processes);
}
/**
* Creates an interface in the given area and process.
*
* @param processId process id
* @param areaId area id
* @param ospfInterface OSPF interface instance
*/
private void createInterfaceInAreaInProcess(String processId,
String areaId, OspfInterface ospfInterface) {
Set<String> interfaceIpList = new HashSet<>();
Set<String> areaIdList = new HashSet<>();
Iterator<OspfProcess> processItr = processes.iterator();
while (processItr.hasNext()) {
OspfProcess process = processItr.next();
List<OspfArea> areasInProcess = process.areas();
if (processId.equalsIgnoreCase(process.processId())) {
Iterator<OspfArea> areaItr = areasInProcess.iterator();
while (areaItr.hasNext()) {
OspfArea area = areaItr.next();
if (areaId.equalsIgnoreCase(area.areaId().toString())) {
area.getInterfacesLst().add(ospfInterface);
interfaceIpList.add(ospfInterface.ipAddress().toString());
log.debug("createInterfaceInAreaInProcess::Interface " +
"updated in process Id::{} AreaId ::{} Interface List{}",
processId, areaId, area.getInterfacesLst());
}
}
}
}
createBootStrapForCreatedInterface(interfaceIpList, areaIdList);
log.debug("createInterfaceInAreaInProcess:: all processes::{}", processes);
}
/**
* Updates interface parameters.
*
* @param processId process id
* @param areaId area id
* @param interfaceId interface id
* @param ospfInterface OSPF interface instance
*/
private void updateInterfaceParameters(String processId, String areaId, String interfaceId,
OspfInterface ospfInterface) {
Iterator<OspfProcess> processItr = processes.iterator();
while (processItr.hasNext()) {
OspfProcess process = processItr.next();
if (processId.equalsIgnoreCase(process.processId())) {
Iterator<OspfArea> areItr = process.areas().iterator();
while (areItr.hasNext()) {
OspfArea area = (OspfArea) areItr.next();
if (area.areaId().toString().equalsIgnoreCase(areaId)) {
Iterator<OspfInterface> intfcList = area.getInterfacesLst().iterator();
while (intfcList.hasNext()) {
OspfInterface intrfcObj = intfcList.next();
if (interfaceId.equalsIgnoreCase(intrfcObj.ipAddress().toString())) {
intrfcObj.setPollInterval(ospfInterface.pollInterval());
intrfcObj.setTransmitDelay(ospfInterface.transmitDelay());
intrfcObj.setBdr(ospfInterface.bdr());
intrfcObj.setDr(ospfInterface.dr());
intrfcObj.setAuthKey(ospfInterface.authKey());
intrfcObj.setAuthType(ospfInterface.authType());
intrfcObj.setHelloIntervalTime(ospfInterface.helloIntervalTime());
intrfcObj.setReTransmitInterval(ospfInterface.reTransmitInterval());
intrfcObj.setMtu(ospfInterface.mtu());
intrfcObj.setInterfaceCost(ospfInterface.interfaceCost());
intrfcObj.setInterfaceType(ospfInterface.interfaceType());
intrfcObj.setRouterDeadIntervalTime(ospfInterface.routerDeadIntervalTime());
intrfcObj.setRouterPriority(ospfInterface.routerPriority());
intrfcObj.setIpNetworkMask(ospfInterface.ipNetworkMask());
log.debug("updateInterfaceParameters::Interface updated in " +
"process Id::{} AreaId ::{} Interface Id:{} " +
"Updated Interface List: {}", processId, areaId,
interfaceId, intfcList);
}
}
}
}
}
}
log.debug("updateInterfaceParameters:: all processes::{}", processes);
}
/**
* Creates server bootstrap for interface.
*
* @param interfaceIPs set of interfaces
* @param areaIds set of area id's
*/
private void createBootStrapForCreatedInterface(Set<String> interfaceIPs, Set<String> areaIds) {
log.debug("createBootStrapForCreatedInterface:: List of new Interfaces::{}, " +
"List of new areas::{}", interfaceIPs, areaIds);
List<String> networkInterfaces = new ArrayList();
//get the connected interfaces
Enumeration<NetworkInterface> nets = null;
private Ip4Address getInterfaceIp(int interfaceIndex) {
Ip4Address ipAddress = null;
try {
nets = NetworkInterface.getNetworkInterfaces();
// Check NetworkInterfaces and add the IP's
for (NetworkInterface netInt : Collections.list(nets)) {
// if the interface is up & not loopback
if (!netInt.isUp() && !netInt.isLoopback()) {
continue;
}
//get all the InetAddresses
Enumeration<InetAddress> inetAddresses = netInt.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
String ipAddress = inetAddress.getHostAddress();
networkInterfaces.add(ipAddress);
NetworkInterface networkInterface = NetworkInterface.getByIndex(interfaceIndex);
Enumeration ipAddresses = networkInterface.getInetAddresses();
while (ipAddresses.hasMoreElements()) {
InetAddress address = (InetAddress) ipAddresses.nextElement();
if (!address.isLinkLocalAddress()) {
ipAddress = Ip4Address.valueOf(address.getAddress());
break;
}
}
//Search for the address in all configured areas interfaces
for (OspfProcess process : processes) {
for (OspfArea area : process.areas()) {
for (OspfInterface ospfIf : area.getInterfacesLst()) {
String ipFromConfig = ospfIf.ipAddress().toString();
if (interfaceIPs.contains(ipFromConfig)) {
log.debug("Ip address::{} for area {} is newly created" + ipFromConfig);
if (networkInterfaces.contains(ipFromConfig)) {
log.debug("Both Config and Interface have ipAddress {} for area {}",
ipFromConfig, area.areaId());
// if same IP address create
try {
log.debug("Creating ServerBootstrap for {} @ {}", ipFromConfig, ospfPort);
} catch (Exception e) {
log.debug("Error while getting Interface IP by index");
return OspfUtil.DEFAULTIP;
}
final ServerBootstrap bootstrap = createServerBootStrap();
return ipAddress;
}
bootstrap.setOption("receiveBufferSize", Controller.BUFFER_SIZE);
bootstrap.setOption("receiveBufferSizePredictorFactory",
new FixedReceiveBufferSizePredictorFactory(
Controller.BUFFER_SIZE));
bootstrap.setOption("reuseAddress", true);
bootstrap.setOption("tcpNoDelay", true);
bootstrap.setOption("keepAlive", true);
/**
* Returns interface mask by index.
*
* @param interfaceIndex interface index
* @return interface IP by index
*/
private String getInterfaceMask(int interfaceIndex) {
String subnetMask = null;
try {
Ip4Address ipAddress = getInterfaceIp(interfaceIndex);
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(
InetAddress.getByName(ipAddress.toString()));
Enumeration ipAddresses = networkInterface.getInetAddresses();
int index = 0;
while (ipAddresses.hasMoreElements()) {
InetAddress address = (InetAddress) ipAddresses.nextElement();
if (!address.isLinkLocalAddress()) {
break;
}
index++;
}
int prfLen = networkInterface.getInterfaceAddresses().get(index).getNetworkPrefixLength();
int shft = 0xffffffff << (32 - prfLen);
int oct1 = ((byte) ((shft & 0xff000000) >> 24)) & 0xff;
int oct2 = ((byte) ((shft & 0x00ff0000) >> 16)) & 0xff;
int oct3 = ((byte) ((shft & 0x0000ff00) >> 8)) & 0xff;
int oct4 = ((byte) (shft & 0x000000ff)) & 0xff;
subnetMask = oct1 + "." + oct2 + "." + oct3 + "." + oct4;
} catch (Exception e) {
log.debug("Error while getting Interface network mask by index");
return subnetMask;
}
bootstrap.setOption("child.receiveBufferSize", Controller.BUFFER_SIZE);
bootstrap.setOption("child.receiveBufferSizePredictorFactory",
new FixedReceiveBufferSizePredictorFactory(
Controller.BUFFER_SIZE));
bootstrap.setOption("child.reuseAddress", true);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.setOption("receiveBufferSizePredictorFactory",
new FixedReceiveBufferSizePredictorFactory(
Controller.BUFFER_SIZE));
bootstrap.setOption("receiveBufferSizePredictor",
new AdaptiveReceiveBufferSizePredictor(64, 1024, 65536));
return subnetMask;
}
ChannelPipelineFactory pfact = new OspfPipelineFactory(this, area, ospfIf);
bootstrap.setPipelineFactory(pfact);
InetSocketAddress sa = new InetSocketAddress(InetAddress.getByName(ipFromConfig),
ospfPort);
/**
* Disconnects the executor.
*/
public void disconnectExecutor() {
if (connectExecutor != null) {
connectExecutor.shutdown();
connectExecutor = null;
}
}
ChannelGroup cg = new DefaultChannelGroup();
cg.add(bootstrap.bind(sa));
cgList.add(cg);
/**
* Connects to peer.
*/
public void connectPeer() {
scheduleConnectionRetry(this.connectRetryTime);
}
log.debug("Listening for connections on {}", sa);
/**
* Retry connection with exponential back-off mechanism.
*
* @param retryDelay retry delay
*/
private void scheduleConnectionRetry(long retryDelay) {
if (this.connectExecutor == null) {
this.connectExecutor = Executors.newSingleThreadScheduledExecutor();
}
this.connectExecutor.schedule(new ConnectionRetry(), retryDelay, TimeUnit.MINUTES);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
/**
* Implements ISIS connection and manages connection to peer with back-off mechanism in case of failure.
*/
class ConnectionRetry implements Runnable {
@Override
public void run() {
log.debug("Connect to peer {}", OspfUtil.SHOST);
initConnection();
ospfChannelHandler.sentConfigPacket(configPacket);
InetSocketAddress connectToSocket = new InetSocketAddress(OspfUtil.SHOST, isisPort.toInt());
try {
peerBootstrap.connect(connectToSocket).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
connectRetryCounter++;
log.error("Connection failed, ConnectRetryCounter {} remote host {}", connectRetryCounter,
OspfUtil.SHOST);
/*
* Reconnect to peer on failure is exponential till 4 mins, later on retry after every 4
* mins.
*/
if (connectRetryTime < RETRY_INTERVAL) {
connectRetryTime = (connectRetryTime != 0) ? connectRetryTime * 2 : 1;
}
scheduleConnectionRetry(connectRetryTime);
} else {
log.debug("Ip address::{} for area {} is not newly created" + ipFromConfig);
//Send the config packet
ospfChannelHandler.sentConfigPacket(configPacket);
connectRetryCounter++;
log.info("Connected to remote host {}, Connect Counter {}", OspfUtil.SHOST,
connectRetryCounter);
disconnectExecutor();
return;
}
}
if (areaIds.contains(area.areaId().toString())) {
area.initializeDb();
}
}
}
} catch (SocketException e) {
log.error("Error occured due to SocketException::Class::{},Line::{},Method::{}",
e.getStackTrace()[0].getFileName(), e.getStackTrace()[0].getLineNumber(),
e.getStackTrace()[0].getMethodName());
}
}
/**
* Deletes given process.
*
* @param ospfProcesses list of OSPF process instance.
* @param attribute attribute to delete
*/
public void deleteProcessWhenExists(List<OspfProcess> ospfProcesses, String attribute) {
if (ospfProcesses != null) {
for (OspfProcess process : ospfProcesses) {
if (checkProcess(process.processId())) {
if (PROCESS.equalsIgnoreCase(attribute)) {
deleteProcess(process.processId(), process);
} else {
List<OspfArea> areas = process.areas();
for (OspfArea area : areas) {
if (checkArea(process.processId(), area.areaId().toString())) {
if (AREA.equalsIgnoreCase(attribute)) {
deleteAreaFromProcess(process.processId(),
area.areaId().toString(), area);
} else {
for (OspfInterface interfc : area.getInterfacesLst()) {
if (checkInterface(process.processId(),
area.areaId().toString(),
interfc.ipAddress().toString())) {
if (INTERFACE.equalsIgnoreCase(attribute)) {
deleteInterfaceFromAreaProcess(process.processId(),
area.areaId().toString(),
interfc);
}
}
}
}
}
}
}
}
}
}
}
/**
* Deletes given process.
*
* @param processId process id
* @param process OSPF process instance
*/
private void deleteProcess(String processId, OspfProcess process) {
if (processes != null) {
Iterator<OspfProcess> itrProcess = processes.iterator();
while (itrProcess.hasNext()) {
OspfProcess ospfPrs = itrProcess.next();
if (processId.equalsIgnoreCase(ospfPrs.processId())) {
itrProcess.remove();
}
}
}
}
/**
* Deletes area from process.
*
* @param processId process id
* @param areaId area id
* @param area OSPF area instance
*/
private void deleteAreaFromProcess(String processId, String areaId, OspfArea area) {
if (processes != null) {
Iterator<OspfProcess> itrProcess = processes.iterator();
while (itrProcess.hasNext()) {
OspfProcess ospfPrs = itrProcess.next();
if (processId.equalsIgnoreCase(ospfPrs.processId())) {
if (ospfPrs.areas() != null) {
Iterator<OspfArea> itrArea = ospfPrs.areas().iterator();
while (itrArea.hasNext()) {
OspfArea ospfArea = itrArea.next();
if (areaId.equalsIgnoreCase(ospfArea.areaId().toString())) {
itrArea.remove();
}
}
}
}
}
}
}
/**
* Deletes interface from area.
*
* @param processId process id
* @param areaId area id
* @param interfaceToDelete interface to delete
*/
private void deleteInterfaceFromAreaProcess(String processId, String areaId, OspfInterface interfaceToDelete) {
if (processes != null) {
Iterator<OspfProcess> itrProcess = processes.iterator();
while (itrProcess.hasNext()) {
OspfProcess ospfPrs = itrProcess.next();
if (processId.equalsIgnoreCase(ospfPrs.processId())) {
if (ospfPrs.areas() != null) {
Iterator<OspfArea> itrArea = ospfPrs.areas().iterator();
while (itrArea.hasNext()) {
OspfArea ospfArea = itrArea.next();
if (areaId.equalsIgnoreCase(ospfArea.areaId().toString())) {
if (ospfArea.getInterfacesLst() != null) {
Iterator<OspfInterface> intrfcList = ospfArea.getInterfacesLst().iterator();
while (intrfcList.hasNext()) {
OspfInterface ospfItrfc = intrfcList.next();
if (interfaceToDelete.ipAddress().equals(ospfItrfc.ipAddress())) {
intrfcList.remove();
}
}
}
}
}
}
}
});
} catch (Exception e) {
log.info("Connect peer exception : " + e.toString());
disconnectExecutor();
}
}
}

View File

@ -0,0 +1,332 @@
/*
* Copyright 2016-present Open Networking Laboratory
*
* 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 org.onosproject.ospf.controller.impl;
import com.fasterxml.jackson.databind.JsonNode;
import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.controller.OspfArea;
import org.onosproject.ospf.controller.OspfInterface;
import org.onosproject.ospf.controller.OspfProcess;
import org.onosproject.ospf.controller.area.OspfAreaImpl;
import org.onosproject.ospf.controller.area.OspfInterfaceImpl;
import org.onosproject.ospf.controller.area.OspfProcessImpl;
import org.onosproject.ospf.protocol.util.OspfUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* Representation of OSPF network configuration parsing util.
*/
public final class OspfConfigUtil {
public static final String PROCESSID = "processId";
public static final String AREAS = "areas";
public static final String INTERFACEINDEX = "interfaceIndex";
public static final String AREAID = "areaId";
public static final String ROUTERID = "routerId";
public static final String INTERFACE = "interface";
public static final String HELLOINTERVAL = "helloIntervalTime";
public static final String ROUTERDEADINTERVAL = "routerDeadIntervalTime";
public static final String INTERFACETYPE = "interfaceType";
public static final String EXTERNALROUTINGCAPABILITY = "externalRoutingCapability";
protected static final Logger log = LoggerFactory.getLogger(OspfConfigUtil.class);
private static final String ISOPAQUE = "isOpaqueEnable";
/**
* Creates an instance of this.
*/
private OspfConfigUtil() {
}
/**
* Returns list of OSPF process from the json nodes.
*
* @param jsonNodes represents one or more OSPF process configuration
* @return list of OSPF processes.
*/
public static List<OspfProcess> processes(JsonNode jsonNodes) {
List<OspfProcess> ospfProcesses = new ArrayList<>();
if (jsonNodes == null) {
return ospfProcesses;
}
//From each Process nodes, get area and related interface details.
jsonNodes.forEach(jsonNode -> {
List<OspfArea> areas = new ArrayList<>();
//Get configured areas for the process.
for (JsonNode areaNode : jsonNode.path(AREAS)) {
List<OspfInterface> interfaceList = new ArrayList<>();
for (JsonNode interfaceNode : areaNode.path(INTERFACE)) {
OspfInterface ospfInterface = interfaceDetails(interfaceNode);
if (ospfInterface != null) {
interfaceList.add(ospfInterface);
}
}
//Get the area details
OspfArea area = areaDetails(areaNode);
if (area != null) {
area.setOspfInterfaceList(interfaceList);
areas.add(area);
}
}
OspfProcess process = new OspfProcessImpl();
process.setProcessId(jsonNode.path(PROCESSID).asText());
process.setAreas(areas);
ospfProcesses.add(process);
});
return ospfProcesses;
}
/**
* Returns interface IP by index.
*
* @param interfaceIndex interface index
* @return interface IP by index
*/
private static Ip4Address getInterfaceIp(int interfaceIndex) {
Ip4Address ipAddress = null;
try {
NetworkInterface networkInterface = NetworkInterface.getByIndex(interfaceIndex);
Enumeration ipAddresses = networkInterface.getInetAddresses();
while (ipAddresses.hasMoreElements()) {
InetAddress address = (InetAddress) ipAddresses.nextElement();
if (!address.isLinkLocalAddress()) {
ipAddress = Ip4Address.valueOf(address.getAddress());
break;
}
}
} catch (Exception e) {
log.debug("Error while getting Interface IP by index");
return OspfUtil.DEFAULTIP;
}
return ipAddress;
}
/**
* Returns interface MAC by index.
*
* @param interfaceIndex interface index
* @return interface IP by index
*/
private static String getInterfaceMask(int interfaceIndex) {
String subnetMask = null;
try {
Ip4Address ipAddress = getInterfaceIp(interfaceIndex);
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(
InetAddress.getByName(ipAddress.toString()));
Enumeration ipAddresses = networkInterface.getInetAddresses();
int index = 0;
while (ipAddresses.hasMoreElements()) {
InetAddress address = (InetAddress) ipAddresses.nextElement();
if (!address.isLinkLocalAddress()) {
break;
}
index++;
}
int prfLen = networkInterface.getInterfaceAddresses().get(index).getNetworkPrefixLength();
int shft = 0xffffffff << (32 - prfLen);
int oct1 = ((byte) ((shft & 0xff000000) >> 24)) & 0xff;
int oct2 = ((byte) ((shft & 0x00ff0000) >> 16)) & 0xff;
int oct3 = ((byte) ((shft & 0x0000ff00) >> 8)) & 0xff;
int oct4 = ((byte) (shft & 0x000000ff)) & 0xff;
subnetMask = oct1 + "." + oct2 + "." + oct3 + "." + oct4;
} catch (Exception e) {
log.debug("Error while getting Interface network mask by index");
return subnetMask;
}
return subnetMask;
}
/**
* Checks if valid digit or not.
*
* @param strInput input value
* @return true if valid else false
*/
private static boolean isValidDigit(String strInput) {
boolean isValid = true;
if (isPrimitive(strInput)) {
int input = Integer.parseInt(strInput);
if (input < 1 || input > 255) {
log.debug("Wrong config input value: {}", strInput);
isValid = false;
} else {
isValid = true;
}
} else {
isValid = false;
}
return isValid;
}
/**
* Checks if primitive or not.
*
* @param value input value
* @return true if number else false
*/
private static boolean isPrimitive(String value) {
boolean status = true;
value = value.trim();
if (value.length() < 1) {
return false;
}
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (!Character.isDigit(c)) {
status = false;
break;
}
}
return status;
}
/**
* Checks if boolean or not.
*
* @param value input value
* @return true if boolean else false
*/
private static boolean isBoolean(String value) {
boolean status = false;
value = value.trim();
if (value.equals("true") || value.equals("false")) {
return true;
}
return status;
}
/**
* Checks if given id is valid or not.
*
* @param value input value
* @return true if valid else false
*/
private static boolean isValidIpAddress(String value) {
boolean status = true;
try {
Ip4Address ipAddress = Ip4Address.valueOf(value);
} catch (Exception e) {
log.debug("Invalid IP address string: {}", value);
return false;
}
return status;
}
/**
* Returns OSPF area instance from configuration.
*
* @param areaNode area configuration
* @return OSPF area instance
*/
private static OspfArea areaDetails(JsonNode areaNode) {
OspfArea area = new OspfAreaImpl();
String areaId = areaNode.path(AREAID).asText();
if (isValidIpAddress(areaId)) {
area.setAreaId(Ip4Address.valueOf(areaId));
} else {
log.debug("Wrong areaId: {}", areaId);
return null;
}
String routerId = areaNode.path(ROUTERID).asText();
if (isValidIpAddress(routerId)) {
area.setRouterId(Ip4Address.valueOf(routerId));
} else {
log.debug("Wrong routerId: {}", routerId);
return null;
}
String routingCapability = areaNode.path(EXTERNALROUTINGCAPABILITY).asText();
if (isBoolean(routingCapability)) {
area.setExternalRoutingCapability(Boolean.valueOf(routingCapability));
} else {
log.debug("Wrong routingCapability: {}", routingCapability);
return null;
}
String isOpaqueEnabled = areaNode.path(ISOPAQUE).asText();
if (isBoolean(isOpaqueEnabled)) {
area.setIsOpaqueEnabled(Boolean.valueOf(isOpaqueEnabled));
} else {
log.debug("Wrong isOpaqueEnabled: {}", isOpaqueEnabled);
return null;
}
area.setOptions(OspfUtil.HELLO_PACKET_OPTIONS);
return area;
}
/**
* Returns OSPF interface instance from configuration.
*
* @param interfaceNode interface configuration
* @return OSPF interface instance
*/
private static OspfInterface interfaceDetails(JsonNode interfaceNode) {
OspfInterface ospfInterface = new OspfInterfaceImpl();
String index = interfaceNode.path(INTERFACEINDEX).asText();
if (isValidDigit(index)) {
ospfInterface.setInterfaceIndex(Integer.parseInt(index));
} else {
log.debug("Wrong interface index: {}", index);
return null;
}
Ip4Address interfaceIp = getInterfaceIp(ospfInterface.interfaceIndex());
if (interfaceIp.equals(OspfUtil.DEFAULTIP)) {
return null;
}
ospfInterface.setIpAddress(interfaceIp);
ospfInterface.setIpNetworkMask(Ip4Address.valueOf(getInterfaceMask(
ospfInterface.interfaceIndex())));
ospfInterface.setBdr(OspfUtil.DEFAULTIP);
ospfInterface.setDr(OspfUtil.DEFAULTIP);
String helloInterval = interfaceNode.path(HELLOINTERVAL).asText();
if (isValidDigit(helloInterval)) {
ospfInterface.setHelloIntervalTime(Integer.parseInt(helloInterval));
} else {
log.debug("Wrong hello interval: {}", helloInterval);
return null;
}
String routerDeadInterval = interfaceNode.path(ROUTERDEADINTERVAL).asText();
if (isValidDigit(routerDeadInterval)) {
ospfInterface.setRouterDeadIntervalTime(Integer.parseInt(routerDeadInterval));
} else {
log.debug("Wrong routerDeadInterval: {}", routerDeadInterval);
return null;
}
String interfaceType = interfaceNode.path(INTERFACETYPE).asText();
if (isValidDigit(interfaceType)) {
ospfInterface.setInterfaceType(Integer.parseInt(interfaceType));
} else {
log.debug("Wrong interfaceType: {}", interfaceType);
return null;
}
ospfInterface.setReTransmitInterval(OspfUtil.RETRANSMITINTERVAL);
ospfInterface.setMtu(OspfUtil.MTU);
ospfInterface.setRouterPriority(OspfUtil.ROUTER_PRIORITY);
return ospfInterface;
}
}

View File

@ -16,6 +16,7 @@
package org.onosproject.ospf.controller.impl;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Sets;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
@ -34,7 +35,6 @@ import org.onosproject.ospf.controller.OspfRouterListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@ -111,27 +111,23 @@ public class OspfControllerImpl implements OspfController {
}
@Override
public void updateConfig(List processes) {
List<OspfProcess> ospfProcesses = new ArrayList<>();
if (processes != null) {
for (Object process : processes) {
ospfProcesses.add((OspfProcess) process);
public void updateConfig(JsonNode processesNode) {
try {
List<OspfProcess> ospfProcesses = OspfConfigUtil.processes(processesNode);
//if there is interface details then update configuration
if (ospfProcesses.size() > 0 &&
ospfProcesses.get(0).areas() != null && ospfProcesses.get(0).areas().size() > 0 &&
ospfProcesses.get(0).areas().get(0) != null &&
ospfProcesses.get(0).areas().get(0).ospfInterfaceList().size() > 0) {
ctrl.updateConfig(ospfProcesses);
}
} catch (Exception e) {
log.debug("Error::updateConfig::{}", e.getMessage());
}
log.debug("updateConfig::OspfList::processes::{}", ospfProcesses);
ctrl.updateConfig(ospfProcesses);
}
@Override
public void deleteConfig(List<OspfProcess> processes, String attribute) {
List<OspfProcess> ospfProcesses = new ArrayList<>();
if (processes != null) {
for (Object process : processes) {
ospfProcesses.add((OspfProcess) process);
}
}
log.debug("deleteConfig::OspfList::processes::{}", ospfProcesses);
ctrl.deleteConfig(ospfProcesses, attribute);
}
/**
@ -163,9 +159,9 @@ public class OspfControllerImpl implements OspfController {
}
@Override
public void deleteLink(OspfRouter ospfRouter) {
public void deleteLink(OspfRouter ospfRouter, OspfLinkTed ospfLinkTed) {
for (OspfLinkListener l : linkListener()) {
l.deleteLink(ospfRouter);
l.deleteLink(ospfRouter, ospfLinkTed);
}
}
}

View File

@ -19,8 +19,10 @@ import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import org.onosproject.ospf.protocol.ospfpacket.OspfMessage;
import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.controller.OspfMessage;
import org.onosproject.ospf.protocol.ospfpacket.OspfMessageReader;
import org.onosproject.ospf.protocol.util.OspfUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -35,24 +37,35 @@ public class OspfMessageDecoder extends FrameDecoder {
private static final Logger log = LoggerFactory.getLogger(OspfMessageDecoder.class);
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer channelBuffer) throws Exception {
log.debug("OspfMessageDecoder::Message received <:> length {}", channelBuffer.readableBytes());
log.debug("channelBuffer.readableBytes - decode {}", channelBuffer.readableBytes());
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
log.debug("OspfMessageDecoder::Message received <:> length {}", buffer.readableBytes());
if (!channel.isConnected()) {
log.info("Channel is not connected.");
return null;
}
OspfMessageReader messageReader = new OspfMessageReader();
List<OspfMessage> ospfMessageList = new LinkedList<>();
while (channelBuffer.readableBytes() > 0) {
OspfMessage message = messageReader.readFromBuffer(channelBuffer);
while (buffer.readableBytes() >= OspfUtil.MINIMUM_FRAME_LEN) {
ChannelBuffer ospfDataBuffer = buffer.readBytes(OspfUtil.MINIMUM_FRAME_LEN);
int readableBytes = ospfDataBuffer.readableBytes();
OspfMessage message = messageReader.readFromBuffer(ospfDataBuffer);
if (message != null) {
if (ospfDataBuffer.readableBytes() >= OspfUtil.METADATA_LEN) {
ospfDataBuffer.readerIndex(readableBytes - OspfUtil.METADATA_LEN);
log.debug("IsisMessageDecoder::Reading metadata <:> length {}", ospfDataBuffer.readableBytes());
int interfaceIndex = ospfDataBuffer.readByte();
byte[] sourceIpBytes = new byte[OspfUtil.FOUR_BYTES];
ospfDataBuffer.readBytes(sourceIpBytes, 0, OspfUtil.FOUR_BYTES);
Ip4Address sourceIP = Ip4Address.valueOf(sourceIpBytes);
message.setSourceIp(sourceIP);
message.setInterfaceIndex(interfaceIndex);
}
ospfMessageList.add(message);
}
}
return ospfMessageList;
return (ospfMessageList.size() > 0) ? ospfMessageList : null;
}
}

View File

@ -17,15 +17,10 @@
package org.onosproject.ospf.controller.impl;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
import org.onosproject.ospf.controller.OspfInterface;
import org.onosproject.ospf.controller.area.OspfInterfaceImpl;
import org.onosproject.ospf.protocol.ospfpacket.OspfMessage;
import org.onosproject.ospf.protocol.ospfpacket.OspfMessageWriter;
import org.onosproject.ospf.protocol.util.OspfInterfaceState;
import org.onosproject.ospf.protocol.util.OspfUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -35,46 +30,15 @@ import org.slf4j.LoggerFactory;
public class OspfMessageEncoder extends OneToOneEncoder {
private static final Logger log = LoggerFactory.getLogger(OspfMessageEncoder.class);
private OspfInterface ospfInterface;
/**
* Creates an instance of OSPF message encoder.
*/
OspfMessageEncoder() {
}
/**
* Creates an instance of OSPF message encoder.
*
* @param ospfInterface OSPF interface instance
*/
OspfMessageEncoder(OspfInterface ospfInterface) {
this.ospfInterface = ospfInterface;
}
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
log.debug("Encoding ospfMessage...!!!");
if (!(msg instanceof OspfMessage)) {
log.debug("Invalid msg.");
return msg;
}
byte[] byteMsg = (byte[]) msg;
log.debug("Encoding ospfMessage of length {}", byteMsg.length);
ChannelBuffer channelBuffer = ChannelBuffers.buffer(byteMsg.length);
channelBuffer.writeBytes(byteMsg);
OspfMessage ospfMessage = (OspfMessage) msg;
OspfMessageWriter messageWriter = new OspfMessageWriter();
if (((OspfInterfaceImpl) ospfInterface).state().equals(OspfInterfaceState.POINT2POINT)) {
ospfMessage.setDestinationIp(OspfUtil.ALL_SPF_ROUTERS);
}
ChannelBuffer buf = messageWriter.writeToBuffer(ospfMessage,
((OspfInterfaceImpl) ospfInterface).state().value(),
ospfInterface.interfaceType());
log.info("OspfMessageEncoder sending packet of lenght {}", buf.readableBytes());
log.debug("OspfMessageEncoder sending packet of lenght {}", buf.readableBytes());
log.debug("Sending {} Message to {}, Length :: {}, <=> {}", ospfMessage.ospfMessageType(),
ospfMessage.destinationIp(), buf.readableBytes(), buf.array());
return buf;
return channelBuffer;
}
}

View File

@ -28,8 +28,10 @@ import org.onosproject.ospf.controller.OspfLinkTed;
import org.onosproject.ospf.controller.OspfLsa;
import org.onosproject.ospf.controller.OspfLsaType;
import org.onosproject.ospf.controller.OspfLsdb;
import org.onosproject.ospf.controller.OspfMessage;
import org.onosproject.ospf.controller.OspfNbr;
import org.onosproject.ospf.controller.OspfNeighborState;
import org.onosproject.ospf.controller.OspfPacketType;
import org.onosproject.ospf.controller.OspfRouter;
import org.onosproject.ospf.controller.TopologyForDeviceAndLink;
import org.onosproject.ospf.controller.area.OspfAreaImpl;
@ -40,7 +42,7 @@ import org.onosproject.ospf.protocol.lsa.LsaHeader;
import org.onosproject.ospf.protocol.lsa.OpaqueLsaHeader;
import org.onosproject.ospf.protocol.lsa.types.OpaqueLsa10;
import org.onosproject.ospf.protocol.lsa.types.TopLevelTlv;
import org.onosproject.ospf.protocol.ospfpacket.OspfMessage;
import org.onosproject.ospf.protocol.ospfpacket.OspfMessageWriter;
import org.onosproject.ospf.protocol.ospfpacket.OspfPacketHeader;
import org.onosproject.ospf.protocol.ospfpacket.subtype.LsRequestPacket;
import org.onosproject.ospf.protocol.ospfpacket.types.DdPacket;
@ -49,7 +51,6 @@ import org.onosproject.ospf.protocol.ospfpacket.types.LsRequest;
import org.onosproject.ospf.protocol.ospfpacket.types.LsUpdate;
import org.onosproject.ospf.protocol.util.ChecksumCalculator;
import org.onosproject.ospf.protocol.util.OspfInterfaceState;
import org.onosproject.ospf.protocol.util.OspfPacketType;
import org.onosproject.ospf.protocol.util.OspfParameters;
import org.onosproject.ospf.protocol.util.OspfUtil;
import org.slf4j.Logger;
@ -181,7 +182,6 @@ public class OspfNbrImpl implements OspfNbr {
* A link to the OSPF-Area this Neighbor Data Structure belongs to.
*/
private OspfArea ospfArea;
private OspfInterfaceChannelHandler handler;
private List<TopLevelTlv> topLevelTlvs = new ArrayList<>();
private List<DeviceInformation> deviceInformationList = new ArrayList<>();
@ -195,12 +195,11 @@ public class OspfNbrImpl implements OspfNbr {
* @param ipAddr IP address
* @param routerId router id
* @param options options
* @param handler channel handler instance
* @param topologyForDeviceAndLinkCommon topology for device and link instance
*/
public OspfNbrImpl(OspfArea paramOspfArea, OspfInterface paramOspfInterface,
Ip4Address ipAddr, Ip4Address routerId, int options,
OspfInterfaceChannelHandler handler, TopologyForDeviceAndLink topologyForDeviceAndLinkCommon) {
TopologyForDeviceAndLink topologyForDeviceAndLinkCommon) {
this.ospfArea = paramOspfArea;
this.ospfInterface = paramOspfInterface;
state = OspfNeighborState.DOWN;
@ -211,7 +210,6 @@ public class OspfNbrImpl implements OspfNbr {
this.options = options;
lastDdPacket = new DdPacket();
routerDeadInterval = paramOspfInterface.routerDeadIntervalTime();
this.handler = handler;
this.topologyForDeviceAndLink = topologyForDeviceAndLinkCommon;
}
@ -242,6 +240,15 @@ public class OspfNbrImpl implements OspfNbr {
this.isOpaqueCapable = isOpaqueCapable;
}
/**
* Sets router dead interval.
*
* @param routerDeadInterval router dead interval
*/
public void setRouterDeadInterval(int routerDeadInterval) {
this.routerDeadInterval = routerDeadInterval;
}
/**
* Have seen a Neighbor, but the Neighbor doesn't know about me.
*
@ -313,7 +320,8 @@ public class OspfNbrImpl implements OspfNbr {
startRxMtDdTimer(channel);
//setting destination ip
ddPacket.setDestinationIp(packet.sourceIp());
channel.write(ddPacket);
byte[] messageToWrite = getMessage(ddPacket);
channel.write(messageToWrite);
} else {
state = OspfNeighborState.TWOWAY;
}
@ -409,7 +417,8 @@ public class OspfNbrImpl implements OspfNbr {
setLastSentDdPacket(ddPacket);
getIsMoreBit();
ch.write(lastSentDdPacket());
byte[] messageToWrite = getMessage(lastSentDdPacket);
ch.write(messageToWrite);
} else {
// process LSA Vector's List, Add it to LSRequestList.
processLsas(payload);
@ -437,7 +446,8 @@ public class OspfNbrImpl implements OspfNbr {
setLastSentDdPacket(ddPacket);
getIsMoreBit();
ddPacket.setDestinationIp(packet.sourceIp());
ch.write(lastSentDdPacket());
byte[] messageToWrite = getMessage(lastSentDdPacket);
ch.write(messageToWrite);
startRxMtDdTimer(ch);
}
}
@ -594,7 +604,8 @@ public class OspfNbrImpl implements OspfNbr {
//setting destination ip
ddPacket.setDestinationIp(neighborIpAddr());
setLastSentDdPacket(ddPacket);
ch.write(ddPacket);
byte[] messageToWrite = getMessage(ddPacket);
ch.write(messageToWrite);
}
}
@ -651,7 +662,8 @@ public class OspfNbrImpl implements OspfNbr {
getIsMoreBit();
//Set the destination IP Address
ddPacket.setDestinationIp(dataDescPkt.sourceIp());
ch.write(lastSentDdPacket());
byte[] messageToWrite = getMessage(lastSentDdPacket());
ch.write(messageToWrite);
startRxMtDdTimer(ch);
}
@ -692,7 +704,8 @@ public class OspfNbrImpl implements OspfNbr {
}
ddPacket.setDestinationIp(dataDescPkt.sourceIp());
ch.write(ddPacket);
byte[] messageToWrite = getMessage(ddPacket);
ch.write(messageToWrite);
}
}
@ -753,7 +766,8 @@ public class OspfNbrImpl implements OspfNbr {
LsRequest lsRequest = buildLsRequest();
//Setting the destination address
lsRequest.setDestinationIp(header.sourceIp());
ch.write(lsRequest);
byte[] messageToWrite = getMessage(lsRequest);
ch.write(messageToWrite);
setLastSentLsrPacket(lsRequest);
startRxMtLsrTimer(ch);
@ -859,7 +873,8 @@ public class OspfNbrImpl implements OspfNbr {
//setting destination ip
ddPacket.setDestinationIp(neighborIpAddr());
setLastSentDdPacket(ddPacket);
ch.write(ddPacket);
byte[] messageToWrite = getMessage(ddPacket);
ch.write(messageToWrite);
}
} else if (state.getValue() >= OspfNeighborState.EXSTART.getValue()) {
if (!formAdjacencyOrNot()) {
@ -942,39 +957,55 @@ public class OspfNbrImpl implements OspfNbr {
*/
private void callDeviceAndLinkAdding(TopologyForDeviceAndLink topologyForDeviceAndLink) {
Map<String, DeviceInformation> deviceInformationMap = topologyForDeviceAndLink.deviceInformationMap();
Map<String, DeviceInformation> deviceInformationMapForPointToPoint =
topologyForDeviceAndLink.deviceInformationMapForPointToPoint();
Map<String, DeviceInformation> deviceInformationMapToDelete =
topologyForDeviceAndLink.deviceInformationMapToDelete();
Map<String, LinkInformation> linkInformationMap = topologyForDeviceAndLink.linkInformationMap();
Map<String, LinkInformation> linkInformationMapForPointToPoint =
topologyForDeviceAndLink.linkInformationMapForPointToPoint();
OspfRouter ospfRouter = new OspfRouterImpl();
log.debug("Device Information in list format along with size {}", deviceInformationMap.size());
for (String key : deviceInformationMap.keySet()) {
DeviceInformation value = deviceInformationMap.get(key);
ospfRouter.setRouterIp(value.routerId());
ospfRouter.setAreaIdOfInterface(ospfArea.areaId());
ospfRouter.setNeighborRouterId(value.deviceId());
OspfDeviceTed ospfDeviceTed = new OspfDeviceTedImpl();
List<Ip4Address> ip4Addresses = value.interfaceId();
ospfDeviceTed.setIpv4RouterIds(ip4Addresses);
ospfRouter.setDeviceTed(ospfDeviceTed);
ospfRouter.setOpaque(ospfArea.isOpaqueEnabled());
if (value.isDr()) {
ospfRouter.setDr(value.isDr());
} else {
ospfRouter.setDr(false);
if (deviceInformationMap.size() != 0) {
for (String key : deviceInformationMap.keySet()) {
DeviceInformation value = deviceInformationMap.get(key);
ospfRouter.setRouterIp(value.routerId());
ospfRouter.setAreaIdOfInterface(ospfArea.areaId());
ospfRouter.setNeighborRouterId(value.deviceId());
OspfDeviceTed ospfDeviceTed = new OspfDeviceTedImpl();
List<Ip4Address> ip4Addresses = value.interfaceId();
ospfDeviceTed.setIpv4RouterIds(ip4Addresses);
ospfRouter.setDeviceTed(ospfDeviceTed);
ospfRouter.setOpaque(ospfArea.isOpaqueEnabled());
if (value.isDr()) {
ospfRouter.setDr(value.isDr());
} else {
ospfRouter.setDr(false);
}
int size = value.interfaceId().size();
for (int i = 0; i < size; i++) {
ospfRouter.setInterfaceId(value.interfaceId().get(i));
}
((OspfInterfaceImpl) ospfInterface).addDeviceInformation(ospfRouter);
}
int size = value.interfaceId().size();
for (int i = 0; i < size; i++) {
ospfRouter.setInterfaceId(value.interfaceId().get(i));
}
if (deviceInformationMapForPointToPoint.size() != 0) {
for (String key : deviceInformationMapForPointToPoint.keySet()) {
DeviceInformation value = deviceInformationMapForPointToPoint.get(key);
ospfRouter.setRouterIp(value.routerId());
ospfRouter.setAreaIdOfInterface(ospfArea.areaId());
ospfRouter.setNeighborRouterId(value.deviceId());
OspfDeviceTed ospfDeviceTed = new OspfDeviceTedImpl();
List<Ip4Address> ip4Addresses = value.interfaceId();
ospfDeviceTed.setIpv4RouterIds(ip4Addresses);
ospfRouter.setDeviceTed(ospfDeviceTed);
ospfRouter.setOpaque(value.isDr());
int size = value.interfaceId().size();
for (int i = 0; i < size; i++) {
ospfRouter.setInterfaceId(value.interfaceId().get(i));
}
((OspfInterfaceImpl) ospfInterface).addDeviceInformation(ospfRouter);
}
if (value.isAlreadyCreated()) {
removeDeviceDetails(value.routerId());
OspfRouter ospfRouter1 = new OspfRouterImpl();
ospfRouter1.setRouterIp(value.routerId());
ospfRouter1.setInterfaceId(ospfInterface.ipAddress());
ospfRouter1.setAreaIdOfInterface(ospfArea.areaId());
ospfRouter1.setDeviceTed(new OspfDeviceTedImpl());
topologyForDeviceAndLink.removeLinks(value.routerId());
handler.removeDeviceInformation(ospfRouter1);
}
handler.addDeviceInformation(ospfRouter);
}
for (Map.Entry<String, LinkInformation> entry : linkInformationMap.entrySet()) {
String key = entry.getKey();
@ -983,8 +1014,8 @@ public class OspfNbrImpl implements OspfNbr {
ospfRouterForLink.setInterfaceId(value.interfaceIp());
ospfRouterForLink.setAreaIdOfInterface(ospfArea.areaId());
ospfRouterForLink.setOpaque(ospfArea.isOpaqueEnabled());
OspfLinkTed ospfLinkTed =
topologyForDeviceAndLink.getOspfLinkTedHashMap(value.linkDestinationId().toString());
OspfLinkTed ospfLinkTed = topologyForDeviceAndLink.getOspfLinkTedHashMap(
value.linkDestinationId().toString());
if (ospfLinkTed == null) {
ospfLinkTed = new OspfLinkTedImpl();
ospfLinkTed.setMaximumLink(Bandwidth.bps(0));
@ -996,13 +1027,9 @@ public class OspfNbrImpl implements OspfNbr {
ospfRouterForLink.setRouterIp(value.linkSourceId());
ospfRouterForLink.setNeighborRouterId(value.linkDestinationId());
try {
handler.addLinkInformation(ospfRouterForLink, ospfLinkTed);
log.debug("LinkId, LinkSrc , LinkDest , LinkInterface values are : "
+ value.linkId() + " , " + value.linkSourceId() + " , "
+ value.linkDestinationId() + " , "
+ value.interfaceIp());
((OspfInterfaceImpl) ospfInterface).addLinkInformation(ospfRouterForLink, ospfLinkTed);
} catch (Exception e) {
log.debug("Got Exception : {}", e.getMessage());
log.debug("Exception addLinkInformation: " + e.getMessage());
}
}
}
@ -1178,10 +1205,30 @@ public class OspfNbrImpl implements OspfNbr {
}
}
}
constructDeviceInformationFromDb();
callDeviceAndLinkAdding(topologyForDeviceAndLink);
return true;
}
/**
* Constructs device and link information from link state database.
*/
private void constructDeviceInformationFromDb() {
OspfLsdb database = ospfArea.database();
List lsas = database.getAllLsaHeaders(true, true);
Iterator iterator = lsas.iterator();
while (iterator.hasNext()) {
OspfLsa ospfLsa = (OspfLsa) iterator.next();
if (ospfLsa.getOspfLsaType().value() == OspfLsaType.ROUTER.value()) {
topologyForDeviceAndLink.addLocalDevice(ospfLsa, ospfInterface, ospfArea);
} else if (ospfLsa.getOspfLsaType().value() == OspfLsaType.NETWORK.value()) {
topologyForDeviceAndLink.addLocalDevice(ospfLsa, ospfInterface, ospfArea);
}
}
}
/**
* Checks Link State ID is equal to one of the router's own IP interface addresses.
*
@ -1190,7 +1237,7 @@ public class OspfNbrImpl implements OspfNbr {
*/
private boolean isLinkStateMatchesOwnRouterId(String linkStateId) {
boolean isLinkStateMatches = false;
List<OspfInterface> interfaceLst = ospfArea.getInterfacesLst();
List<OspfInterface> interfaceLst = ospfArea.ospfInterfaceList();
for (OspfInterface ospfInterface : interfaceLst) {
if (ospfInterface.ipAddress().toString().equals(linkStateId)) {
isLinkStateMatches = true;
@ -1262,7 +1309,8 @@ public class OspfNbrImpl implements OspfNbr {
//setting the destination.
responseLsUpdate.setDestinationIp(destination);
ch.write(responseLsUpdate);
byte[] messageToWrite = getMessage(responseLsUpdate);
ch.write(messageToWrite);
}
/**
@ -1288,7 +1336,8 @@ public class OspfNbrImpl implements OspfNbr {
ackContent.addLinkStateHeader(ackLsa);
//setting the destination IP
ackContent.setDestinationIp(sourceIp);
ch.write(ackContent);
byte[] messageToWrite = getMessage(ackContent);
ch.write(messageToWrite);
}
/**
@ -1314,7 +1363,7 @@ public class OspfNbrImpl implements OspfNbr {
ddSummaryList.clear();
if (neighborIpAddr.equals(neighborBdr) ||
neighborIpAddr.equals(neighborDr)) {
handler.neighborChange();
((OspfInterfaceImpl) ospfInterface).neighborChange();
}
log.debug("Neighbor Went Down : "
+ this.neighborIpAddr + " , " + this.neighborId);
@ -1324,16 +1373,14 @@ public class OspfNbrImpl implements OspfNbr {
ospfRouter.setInterfaceId(ospfInterface.ipAddress());
ospfRouter.setAreaIdOfInterface(ospfArea.areaId());
ospfRouter.setDeviceTed(new OspfDeviceTedImpl());
handler.removeDeviceInformation(ospfRouter);
((OspfInterfaceImpl) ospfInterface).removeDeviceInformation(ospfRouter);
removeDeviceDetails(this.neighborIpAddr);
OspfRouter ospfRouter1 = new OspfRouterImpl();
ospfRouter1.setRouterIp(this.neighborIpAddr);
ospfRouter1.setInterfaceId(ospfInterface.ipAddress());
ospfRouter1.setAreaIdOfInterface(ospfArea.areaId());
ospfRouter1.setDeviceTed(new OspfDeviceTedImpl());
handler.removeDeviceInformation(ospfRouter1);
handler.removeLinkInformation(this);
callDeviceAndLinkAdding(topologyForDeviceAndLink);
((OspfInterfaceImpl) ospfInterface).removeDeviceInformation(ospfRouter1);
}
/**
@ -1344,13 +1391,12 @@ public class OspfNbrImpl implements OspfNbr {
private void removeDeviceDetails(Ip4Address routerId) {
String key = "device:" + routerId;
topologyForDeviceAndLink.removeDeviceInformationMap(key);
topologyForDeviceAndLink.removeLinks(routerId);
}
/**
* Starts the inactivity timer.
*/
private void startInactivityTimeCheck() {
public void startInactivityTimeCheck() {
if (!inActivityTimerScheduled) {
log.debug("OSPFNbr::startInactivityTimeCheck");
inActivityTimeCheckTask = new InternalInactivityTimeCheck();
@ -1364,7 +1410,7 @@ public class OspfNbrImpl implements OspfNbr {
/**
* Stops the inactivity timer.
*/
private void stopInactivityTimeCheck() {
public void stopInactivityTimeCheck() {
if (inActivityTimerScheduled) {
log.debug("OSPFNbr::stopInactivityTimeCheck ");
exServiceInActivity.shutdown();
@ -1393,7 +1439,7 @@ public class OspfNbrImpl implements OspfNbr {
/**
* Stops the flooding timer.
*/
private void stopFloodingTimer() {
public void stopFloodingTimer() {
if (floodingTimerScheduled) {
log.debug("OSPFNbr::stopFloodingTimer ");
exServiceFlooding.shutdown();
@ -1420,7 +1466,7 @@ public class OspfNbrImpl implements OspfNbr {
/**
* Stops the Dd Retransmission executor task.
*/
private void stopRxMtDdTimer() {
public void stopRxMtDdTimer() {
if (rxmtDdPacketTimerScheduled) {
exServiceRxmtDDPacket.shutdown();
rxmtDdPacketTimerScheduled = false;
@ -1447,7 +1493,7 @@ public class OspfNbrImpl implements OspfNbr {
/**
* Stops Ls request retransmission executor task.
*/
private void stopRxMtLsrTimer() {
public void stopRxMtLsrTimer() {
if (rxmtLsrTimerScheduled) {
exServiceRxmtLsr.shutdown();
rxmtLsrTimerScheduled = false;
@ -1679,6 +1725,21 @@ public class OspfNbrImpl implements OspfNbr {
return pendingReTxList;
}
/**
* Gets message as bytes.
*
* @param ospfMessage OSPF message
* @return OSPF message
*/
private byte[] getMessage(OspfMessage ospfMessage) {
OspfMessageWriter messageWriter = new OspfMessageWriter();
if (((OspfInterfaceImpl) ospfInterface).state().equals(OspfInterfaceState.POINT2POINT)) {
ospfMessage.setDestinationIp(OspfUtil.ALL_SPF_ROUTERS);
}
return (messageWriter.getMessage(ospfMessage, ospfInterface.interfaceIndex(),
((OspfInterfaceImpl) ospfInterface).state().value()));
}
/**
* Represents a Task which will do an inactivity time check.
@ -1720,7 +1781,8 @@ public class OspfNbrImpl implements OspfNbr {
public void run() {
if ((ch != null) && ch.isConnected()) {
DdPacket ddPacket = lastSentDdPacket();
ch.write(ddPacket);
byte[] messageToWrite = getMessage(ddPacket);
ch.write(messageToWrite);
log.debug("Re-Transmit DD Packet .");
} else {
log.debug(
@ -1748,7 +1810,8 @@ public class OspfNbrImpl implements OspfNbr {
public void run() {
if ((ch != null) && ch.isConnected()) {
LsRequest lsrPacket = getLastSentLsrPacket();
ch.write(lsrPacket);
byte[] messageToWrite = getMessage(lsrPacket);
ch.write(messageToWrite);
log.debug("Re-Transmit LSRequest Packet .");
} else {
log.debug(
@ -1783,7 +1846,8 @@ public class OspfNbrImpl implements OspfNbr {
for (LsUpdate lsupdate : lsUpdateList) {
//Pending for acknowledge directly sent it to neighbor
lsupdate.setDestinationIp(neighborIpAddr);
channel.write(lsupdate);
byte[] messageToWrite = getMessage(lsupdate);
channel.write(messageToWrite);
}
}
@ -1799,7 +1863,8 @@ public class OspfNbrImpl implements OspfNbr {
(((OspfInterfaceImpl) ospfInterface).state() == OspfInterfaceState.BDR)) {
lsupdate.setDestinationIp(neighborDr);
}
channel.write(lsupdate);
byte[] messageToWrite = getMessage(lsupdate);
channel.write(messageToWrite);
}
}
}

View File

@ -18,57 +18,29 @@ package org.onosproject.ospf.controller.impl;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.timeout.ReadTimeoutHandler;
import org.jboss.netty.util.ExternalResourceReleasable;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timer;
import org.onosproject.ospf.controller.OspfArea;
import org.onosproject.ospf.controller.OspfInterface;
/**
* Creates a ChannelPipeline for a server-side OSPF channel.
* Creates a ChannelPipeline for a client-side OSPF channel.
*/
public class OspfPipelineFactory implements ChannelPipelineFactory, ExternalResourceReleasable {
private static final Timer TIMER = new HashedWheelTimer();
private Controller controller;
private ReadTimeoutHandler readTimeoutHandler;
private OspfArea ospfArea;
private OspfInterface ospfInterface;
private int holdTime = 120 * 1000;
public class OspfPipelineFactory implements ChannelPipelineFactory {
private OspfInterfaceChannelHandler ospfChannelHandler;
/**
* Creates an instance of OSPF pipeline factory.
* Creates an instance of OSPF channel pipeline factory.
*
* @param controller controller instance.
* @param ospfArea OSPF area instance.
* @param ospfInterface OSPF interface instance.
* @param ospfChannelHandler OSPF channel handler instance
*/
public OspfPipelineFactory(Controller controller, OspfArea ospfArea, OspfInterface ospfInterface) {
super();
this.controller = controller;
this.ospfArea = ospfArea;
this.ospfInterface = ospfInterface;
readTimeoutHandler = new ReadTimeoutHandler(TIMER, holdTime);
public OspfPipelineFactory(OspfInterfaceChannelHandler ospfChannelHandler) {
this.ospfChannelHandler = ospfChannelHandler;
}
@Override
public ChannelPipeline getPipeline() throws Exception {
OspfInterfaceChannelHandler interfaceHandler = new OspfInterfaceChannelHandler(
controller, ospfArea, ospfInterface);
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("encoder", new OspfMessageEncoder(ospfInterface));
pipeline.addLast("decoder", new OspfMessageDecoder());
pipeline.addLast("holdTime", readTimeoutHandler);
pipeline.addLast("interfacehandler", interfaceHandler);
pipeline.addLast("encoder", new OspfMessageDecoder());
pipeline.addLast("decoder", new OspfMessageEncoder());
pipeline.addLast("handler", ospfChannelHandler);
return pipeline;
}
@Override
public void releaseExternalResources() {
TIMER.stop();
}
}

View File

@ -38,6 +38,7 @@ import org.onosproject.ospf.protocol.lsa.types.NetworkLsa;
import org.onosproject.ospf.protocol.lsa.types.OpaqueLsa10;
import org.onosproject.ospf.protocol.lsa.types.RouterLsa;
import org.onosproject.ospf.protocol.lsa.types.TopLevelTlv;
import org.onosproject.ospf.protocol.util.OspfUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -49,6 +50,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/**
* Represents device and link topology information.
@ -56,7 +58,11 @@ import java.util.Set;
public class TopologyForDeviceAndLinkImpl implements TopologyForDeviceAndLink {
private static final Logger log = LoggerFactory.getLogger(TopologyForDeviceAndLinkImpl.class);
Set<Ip4Address> routerSet = new TreeSet<Ip4Address>();
Ip4Address firstValue = Ip4Address.valueOf("0.0.0.0");
private Map<String, DeviceInformation> deviceInformationMap = new LinkedHashMap();
private Map<Ip4Address, List<Ip4Address>> networkLsaMap = new LinkedHashMap();
private Map<String, DeviceInformation> deviceInformationMapForPointToPoint = new LinkedHashMap();
private Map<String, DeviceInformation> deviceInformationMapToDelete = new LinkedHashMap();
private HashMap<String, Set<OspfLsaLink>> deviceAndLinkInformation = new HashMap();
private HashMap<String, OspfLinkTed> ospfLinkTedHashMap = new LinkedHashMap();
@ -64,6 +70,7 @@ public class TopologyForDeviceAndLinkImpl implements TopologyForDeviceAndLink {
private Ip4Address drRouterOld = Ip4Address.valueOf("0.0.0.0");
private Ip4Address adRouterId = Ip4Address.valueOf("0.0.0.0");
private Map<String, LinkInformation> linkInformationMap = new LinkedHashMap();
private Map<String, LinkInformation> linkInformationMapForPointToPoint = new LinkedHashMap();
private List<String> toRemove = new ArrayList<>();
/**
@ -89,9 +96,31 @@ public class TopologyForDeviceAndLinkImpl implements TopologyForDeviceAndLink {
}
/**
* Gets device information.
* Gets deviceInformation as map for Point-To-Point.
*
* @return device information to delete from core
* @return deviceInformationMap
*/
public Map<String, DeviceInformation> deviceInformationMapForPointToPoint() {
return deviceInformationMapForPointToPoint;
}
/**
* Sets deviceInformation as map for Point-To-Point..
*
* @param key key to store device information
* @param deviceInformationMap device information instance
*/
public void setDeviceInformationMapForPointToPoint(String key, DeviceInformation deviceInformationMap) {
if (deviceInformationMap != null) {
this.deviceInformationMapForPointToPoint.put(key, deviceInformationMap);
}
}
/**
* Gets deviceInformation as map.
*
* @return deviceInformationMap to delete from core
*/
public Map<String, DeviceInformation> deviceInformationMapToDelete() {
return deviceInformationMapToDelete;
@ -103,8 +132,7 @@ public class TopologyForDeviceAndLinkImpl implements TopologyForDeviceAndLink {
* @param key ket used to add in map
* @param deviceInformationMapToDelete map from device information to remove
*/
public void setDeviceInformationMapToDelete(String key,
DeviceInformation deviceInformationMapToDelete) {
public void setDeviceInformationMapToDelete(String key, DeviceInformation deviceInformationMapToDelete) {
if (deviceInformationMapToDelete != null) {
this.deviceInformationMapToDelete.put(key, deviceInformationMapToDelete);
}
@ -153,6 +181,11 @@ public class TopologyForDeviceAndLinkImpl implements TopologyForDeviceAndLink {
return linkInformationMap;
}
private LinkInformation getLinkInformation(String key) {
LinkInformation linkInformation = this.linkInformationMap.get(key);
return linkInformation;
}
/**
* Sets link information in map.
*
@ -166,9 +199,30 @@ public class TopologyForDeviceAndLinkImpl implements TopologyForDeviceAndLink {
}
/**
* Removes Link Information from map.
* Gets linkInformation as map for PointToPoint.
*
* @param key key used to remove from map
* @return linkInformationMap
*/
public Map<String, LinkInformation> linkInformationMapForPointToPoint() {
return linkInformationMap;
}
/**
* Sets linkInformation as map for PointToPoint.
*
* @param key key to store link information
* @param linkInformationMap link information instance
*/
public void setLinkInformationMapForPointToPoint(String key, LinkInformation linkInformationMap) {
if (!this.linkInformationMap.containsKey(key)) {
this.linkInformationMap.put(key, linkInformationMap);
}
}
/**
* Removes Link Information from linkInformationMap.
*
* @param key key to remove link information
*/
public void removeLinkInformationMap(String key) {
if (this.linkInformationMap.containsKey(key)) {
@ -242,108 +296,136 @@ public class TopologyForDeviceAndLinkImpl implements TopologyForDeviceAndLink {
List<OspfLsaLink> ospfLsaLinkList = routerLsa.routerLink();
Iterator iterator = ospfLsaLinkList.iterator();
Ip4Address advertisingRouterId = routerLsa.advertisingRouter();
adRouterId = advertisingRouterId;
while (iterator.hasNext()) {
OspfLsaLink ospfLsaLink = (OspfLsaLink) iterator.next();
Ip4Address linkId = Ip4Address.valueOf(ospfLsaLink.linkId());
Ip4Address linkData = Ip4Address.valueOf(ospfLsaLink.linkData());
if (ospfLsaLink.linkType() == 1) {
if ((advertisingRouterId.equals(ospfArea.routerId())) || (linkId.equals(ospfArea.routerId()))) {
System.out.println("OspfInterface information will not display in web ");
} else {
removeDevice(advertisingRouterId);
removeLinks(advertisingRouterId);
DeviceInformation deviceInformationPointToPoint =
createDeviceInformation(false, linkId, linkId, advertisingRouterId, linkData,
ospfArea.areaId(), false);
String key = "device:" + advertisingRouterId;
setDeviceInformationMap(key, deviceInformationPointToPoint);
String linkIdKey = "linkId:" + advertisingRouterId + "-" + linkId;
addLocalLink(linkIdKey, linkData, advertisingRouterId, linkId, true, false);
}
} else if (ospfLsaLink.linkType() == 2) {
if ((advertisingRouterId.equals(ospfArea.routerId())) || (linkId.equals(ospfArea.routerId()))) {
log.debug("OspfInterface information will not display in web ");
} else {
if (linkId.equals(linkData)) {
if (drRouter.equals(Ip4Address.valueOf("0.0.0.0"))) {
log.debug("drRouter not elected {} ", drRouter.toString());
} else {
if (drRouterOld.equals(linkId)) {
log.debug("drRouterOld same as link id {} ", drRouterOld.toString());
} else {
String key = "device:" + drRouterOld;
DeviceInformation deviceInformation1 = deviceInformation(key);
if (deviceInformation1 != null) {
deviceInformation1.setAlreadyCreated(true);
setDeviceInformationMapToDelete(key, deviceInformation1);
String linkIdKey = "linkId:" + linkId + "-" + deviceInformation1.neighborId();
addLocalLink(linkIdKey, linkData, linkId, deviceInformation1.neighborId(),
true, false);
String linkIdKey1 = "linkId:" + linkId + "-" + advertisingRouterId;
addLocalLink(linkIdKey1, linkData, linkId, advertisingRouterId, true, false);
} else {
DeviceInformation deviceInformationToDelete =
createDeviceInformation(true, drRouterOld, drRouterOld,
drRouterOld, drRouterOld,
drRouterOld, true);
setDeviceInformationMapToDelete(key, deviceInformationToDelete);
String linkIdKey1 = "linkId:" + linkId + "-" + advertisingRouterId;
addLocalLink(linkIdKey1, linkData, linkId, advertisingRouterId, true, false);
}
}
}
drRouter = linkId;
drRouterOld = linkId;
DeviceInformation deviceInformationForDr =
createDeviceInformation(false, linkId, advertisingRouterId, linkId, linkData,
ospfArea.areaId(), true);
String key = "device:" + linkId;
setDeviceInformationMap(key, deviceInformationForDr);
DeviceInformation deviceInformationForAdvertisingRouter =
createDeviceInformation(false, linkId, advertisingRouterId, advertisingRouterId,
linkData, ospfArea.areaId(), false);
String key1 = "device:" + advertisingRouterId;
setDeviceInformationMap(key1, deviceInformationForAdvertisingRouter);
if (drRouter.equals(Ip4Address.valueOf("0.0.0.0"))) {
System.out.println("Link will not get create since dr is not valid");
//Need to analysis since this place will not get Dr information
String linkIdKey = "linkId:" + linkId + "-" + advertisingRouterId;
addLocalLink(linkIdKey, linkData, linkId, advertisingRouterId, true, false);
} else {
String linkIdKey = "linkId:" + drRouter + "-" + advertisingRouterId;
addLocalLink(linkIdKey, linkData, drRouter, advertisingRouterId, true, false);
}
} else {
DeviceInformation deviceInformationDrOther =
createDeviceInformation(false, linkId, linkId, advertisingRouterId,
linkData, ospfArea.areaId(), false);
if (!advertisingRouterId.equals(ospfArea.routerId())) {
DeviceInformation deviceInformationPointToPoint =
createDeviceInformation(false, linkId, linkId, advertisingRouterId, linkData,
ospfArea.areaId(), false);
String key = "device:" + advertisingRouterId;
setDeviceInformationMap(key, deviceInformationDrOther);
if (drRouter.equals(Ip4Address.valueOf("0.0.0.0"))) {
String linkIdKey = "linkId:" + linkId + "-" + advertisingRouterId;
addLocalLink(linkIdKey, linkData, linkId, advertisingRouterId, true, false);
} else {
String linkIdKey = "linkId:" + drRouter + "-" + advertisingRouterId;
addLocalLink(linkIdKey, linkData, drRouter, advertisingRouterId, true, false);
}
setDeviceInformationMapForPointToPoint(key, deviceInformationPointToPoint);
}
} else {
DeviceInformation deviceInformationPointToPoint =
createDeviceInformation(false, linkId, linkId, advertisingRouterId,
linkData, ospfArea.areaId(), false);
String key = "device:" + advertisingRouterId;
setDeviceInformationMapForPointToPoint(key, deviceInformationPointToPoint);
String linkIdKey = "linkId:" + advertisingRouterId + "-" + linkId;
addLocalLinkForPointToPoint(linkIdKey, linkData, advertisingRouterId, linkId, true, false);
}
}
}
}
/**
* Creates Device and Link instance from the NetworkLsa parameters.
* Creates device and link instance from the network LSA parameters.
*
* @param ospfLsa OSPF LSA instance
* @param ospfArea OSPF area instance
*/
private void createDeviceAndLinkFromNetworkLsa(OspfLsa ospfLsa, OspfArea ospfArea) {
NetworkLsa networkLsa = (NetworkLsa) ospfLsa;
Ip4Address advertisingRouterId = networkLsa.networkMask();
System.out.println("AdvertisingRouterId is : " + advertisingRouterId);
Ip4Address linkStateId = Ip4Address.valueOf(networkLsa.linkStateId());
Set<Ip4Address> drList = networkLsaMap.keySet();
try {
Ip4Address drToReplace = null;
for (Ip4Address drIp : drList) {
if (!drIp.equals(linkStateId)) {
if (OspfUtil.sameNetwork(drIp, linkStateId, networkLsa.networkMask())) {
drToReplace = drIp;
String key = "device:" + drToReplace;
DeviceInformation deleteDr = deviceInformation(key);
if (deleteDr != null) {
deleteDr.setAlreadyCreated(true);
setDeviceInformationMapToDelete(key, deleteDr);
}
networkLsaMap.remove(drToReplace);
break;
}
}
}
networkLsaMap.put(linkStateId, networkLsa.attachedRouters());
} catch (Exception e) {
log.debug("Error::TopologyForDeviceAndLinkImpl:: {}", e.getMessage());
}
constructDeviceForBroadCastTopology(ospfArea);
disp();
}
private void constructDeviceForBroadCastTopology(OspfArea ospfArea) {
for (Map.Entry<Ip4Address, List<Ip4Address>> entry : networkLsaMap.entrySet()) {
Ip4Address key = entry.getKey();
DeviceInformation deviceInformationForDr = createDeviceInformation(false, key, key, key,
key, ospfArea.areaId(), true);
String dr = "device:" + key;
setDeviceInformationMap(dr, deviceInformationForDr);
List<Ip4Address> value = entry.getValue();
for (Ip4Address connectedRouter : value) {
if (!connectedRouter.equals(ospfArea.routerId())) {
DeviceInformation deviceInformationAttachedRouters =
createDeviceInformation(false, connectedRouter, key, connectedRouter,
key, ospfArea.areaId(), false);
String attachedRouters = "device:" + connectedRouter;
setDeviceInformationMap(attachedRouters, deviceInformationAttachedRouters);
String linkIdKey = "linkId:" + key + "-" + connectedRouter;
addLocalLink(linkIdKey, key, key, connectedRouter, true, false);
}
}
}
}
private void disp() {
for (String key : deviceInformationMap.keySet()) {
DeviceInformation deviceInformation = deviceInformationMap.get(key);
log.debug("************************************************************************");
log.debug("DeviceInfoList RouterId is : {} and neighbour is {} and linkdata {}",
deviceInformation.routerId(), deviceInformation.neighborId(), deviceInformation.interfaceId());
}
for (Map.Entry<String, LinkInformation> entry : linkInformationMap.entrySet()) {
String linkDetail = entry.getKey();
log.debug("Link From and to is " + linkDetail);
}
log.debug("Devices Needs to delete from Core are : " + deviceInformationMapToDelete.size());
for (String key : deviceInformationMapToDelete.keySet()) {
DeviceInformation value = deviceInformationMapToDelete.get(key);
if (value.isAlreadyCreated()) {
log.debug("Device is deleted from list " + value.routerId());
}
}
}
private void getLinksToDelete(Set<Ip4Address> list, Ip4Address value, OspfArea ospfArea) {
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
Ip4Address secondValue = (Ip4Address) iterator.next();
if (!value.equals("0.0.0.0")) {
if ((!value.equals(secondValue))) {
if ((!secondValue.equals(ospfArea.routerId()))) {
String key = "link:" + value.toString() + "-" + secondValue.toString();
String key1 = "link:" + secondValue.toString() + "-" + value.toString();
LinkInformation linkDetails = getLinkInformation(key);
LinkInformation linkDetailsOther = getLinkInformation(key1);
linkInformationMapForPointToPoint.put(key, linkDetails);
linkInformationMapForPointToPoint.put(key1, linkDetailsOther);
}
}
}
}
}
/**
@ -443,14 +525,41 @@ public class TopologyForDeviceAndLinkImpl implements TopologyForDeviceAndLink {
setLinkInformationMap(linkKey, linkInformation);
}
/**
* Adds link information to LinkInformationMap for PointToPoint.
*
* @param advertisingRouter advertising router
* @param linkData link data
* @param linkSrc link source
* @param linkDest link destination
* @param opaqueEnabled whether opaque is enabled or not
* @param linkSrcIdNotRouterId whether link is source id or router id
*/
public void addLocalLinkForPointToPoint(String advertisingRouter, Ip4Address linkData, Ip4Address linkSrc,
Ip4Address linkDest, boolean opaqueEnabled, boolean linkSrcIdNotRouterId) {
String linkKey = "link:";
LinkInformation linkInformation = new LinkInformationImpl();
linkInformation.setLinkId(advertisingRouter);
linkInformation.setLinkSourceId(linkSrc);
linkInformation.setLinkDestinationId(linkDest);
linkInformation.setAlreadyCreated(false);
linkInformation.setLinkSrcIdNotRouterId(linkSrcIdNotRouterId);
linkInformation.setInterfaceIp(linkData);
if (linkDest != null) {
linkInformation.setLinkSrcIdNotRouterId(false);
}
linkKey = linkKey + "-" + linkSrc + "-" + linkDest;
setLinkInformationMapForPointToPoint(linkKey, linkInformation);
}
/**
* Removes links from LinkInformationMap.
*
* @param routerId router id
*/
public void removeLinks(Ip4Address routerId) {
Map<String, LinkInformation> linkInformationMaplocal = linkInformationMap;
if (linkInformationMaplocal != null) {
Map<String, LinkInformation> linkInformationMapLocal = linkInformationMap;
if (linkInformationMapLocal != null) {
for (Map.Entry<String, LinkInformation> entry : linkInformationMap.entrySet()) {
String key = entry.getKey();
boolean check = key.contains(routerId.toString());

View File

@ -49,6 +49,15 @@ public class LsaWrapperImpl implements LsaWrapper {
private int binNumber = -1;
private OspfInterface ospfInterface;
private LsdbAge lsdbAge;
private int ageCounterRollOverWhenAdded;
public int getAgeCounterRollOverWhenAdded() {
return ageCounterRollOverWhenAdded;
}
public void setAgeCounterRollOverWhenAdded(int ageCounterRollOverWhenAdded) {
this.ageCounterRollOverWhenAdded = ageCounterRollOverWhenAdded;
}
/**
* Gets the LSA type.
@ -318,6 +327,8 @@ public class LsaWrapperImpl implements LsaWrapper {
if (currentAge >= OspfParameters.MAXAGE) {
return OspfParameters.MAXAGE;
} else if ((currentAge == lsaAgeReceived) && ageCounterRollOverWhenAdded != lsdbAge.getAgeCounterRollOver()) {
return OspfParameters.MAXAGE;
}
return currentAge;

View File

@ -41,7 +41,7 @@ public class LsdbAgeImpl implements LsdbAge {
private static final Logger log =
LoggerFactory.getLogger(LsdbAgeImpl.class);
protected int ageCounter = 0;
protected static int ageCounter = 0;
private InternalAgeTimer dbAgeTimer;
private ScheduledExecutorService exServiceage;
// creating age bins of MAXAGE

View File

@ -267,6 +267,7 @@ public class OspfLsdbImpl implements OspfLsdb {
lsaWrapper.setLsaHeader(newLsa);
lsaWrapper.setLsaAgeReceived(newLsa.age());
lsaWrapper.setAgeCounterWhenReceived(lsdbAge.getAgeCounter());
lsaWrapper.setAgeCounterRollOverWhenAdded(lsdbAge.getAgeCounterRollOver());
lsaWrapper.setIsSelfOriginated(isSelfOriginated);
lsaWrapper.setIsSelfOriginated(isSelfOriginated);
lsaWrapper.setOspfInterface(ospfInterface);

View File

@ -15,29 +15,25 @@
*/
package org.onosproject.ospf.controller.area;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.controller.OspfArea;
import org.onosproject.ospf.controller.OspfAreaAddressRange;
import org.onosproject.ospf.controller.OspfInterface;
import org.onosproject.ospf.controller.OspfNbr;
import org.onosproject.ospf.controller.OspfNeighborState;
import org.onosproject.ospf.controller.TopologyForDeviceAndLink;
import org.onosproject.ospf.controller.impl.Controller;
import org.onosproject.ospf.controller.impl.OspfInterfaceChannelHandler;
import org.onosproject.ospf.controller.impl.OspfNbrImpl;
import org.onosproject.ospf.controller.impl.TopologyForDeviceAndLinkImpl;
import org.onosproject.ospf.controller.lsdb.LsaWrapperImpl;
import org.onosproject.ospf.protocol.lsa.LsaHeader;
import org.onosproject.ospf.protocol.lsa.OpaqueLsaHeader;
import org.onosproject.ospf.protocol.lsa.types.NetworkLsa;
import org.onosproject.ospf.protocol.lsa.types.OpaqueLsa10;
import org.onosproject.ospf.protocol.lsa.types.RouterLsa;
import org.onosproject.ospf.protocol.util.OspfInterfaceState;
import org.onosproject.ospf.protocol.util.OspfParameters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
@ -50,66 +46,66 @@ public class OspfAreaImplTest {
private OspfAreaImpl ospfArea;
private int result;
private OspfInterfaceImpl ospfInterface;
private HashMap<String, OspfNbr> ospfNbrList;
private List<OspfInterface> ospfInterfaces;
private List<OspfInterface> ospfInterfaces = new ArrayList<>();
private OspfInterfaceImpl ospfInterface1;
private OspfInterfaceImpl ospfInterface2;
private OspfInterfaceImpl ospfInterface3;
private OspfInterfaceImpl ospfInterface4;
private OspfInterfaceImpl ospfInterface5;
private OspfInterfaceImpl ospfInterface6;
private NetworkLsa networkLsa;
private OspfNbrImpl ospfNbr;
private RouterLsa routerLsa;
private List<OspfAreaAddressRange> ospfAreaAddressRanges;
private OspfNbrImpl ospfNbr1;
private NetworkLsa networkLsa;
private LsaHeader lsaHeader;
private Ip4Address ip4Address = Ip4Address.valueOf("10.10.10.10");
private Ip4Address ip4Address1 = Ip4Address.valueOf("11.11.11.11");
private Ip4Address networkAddress = Ip4Address.valueOf("255.255.255.255");
private TopologyForDeviceAndLink topologyForDeviceAndLink;
private RouterLsa routerLsa;
private OpaqueLsaHeader opaqueLsaHeader;
private OpaqueLsa10 opaqueLsa10;
@Before
public void setUp() throws Exception {
lsaHeader = new LsaHeader();
opaqueLsaHeader = new OpaqueLsaHeader();
opaqueLsaHeader.setAdvertisingRouter(ip4Address);
lsaHeader.setAdvertisingRouter(ip4Address);
routerLsa = new RouterLsa(lsaHeader);
routerLsa.setAdvertisingRouter(ip4Address);
opaqueLsa10 = new OpaqueLsa10(opaqueLsaHeader);
ospfArea = new OspfAreaImpl();
ospfInterface1 = new OspfInterfaceImpl();
topologyForDeviceAndLink = new TopologyForDeviceAndLinkImpl();
ospfNbr = new OspfNbrImpl(ospfArea, ospfInterface1, ip4Address, ip4Address1,
2, topologyForDeviceAndLink);
ospfNbr.setState(OspfNeighborState.EXCHANGE);
ospfNbr1 = new OspfNbrImpl(ospfArea, ospfInterface1, ip4Address, ip4Address1,
2, topologyForDeviceAndLink);
ospfNbr1.setState(OspfNeighborState.FULL);
ospfNbr1.setNeighborId(ip4Address);
ospfNbr.setNeighborId(ip4Address);
ospfNbr.setIsOpaqueCapable(true);
ospfInterface1.addNeighbouringRouter(ospfNbr);
ospfInterface1.addNeighbouringRouter(ospfNbr1);
ospfInterface2 = new OspfInterfaceImpl();
ospfInterface2.setIpAddress(ip4Address);
ospfInterface2.setIpNetworkMask(networkAddress);
ospfInterface2.setState(OspfInterfaceState.LOOPBACK);
ospfInterface2.addNeighbouringRouter(ospfNbr);
ospfInterface2.addNeighbouringRouter(ospfNbr1);
ospfInterfaces.add(ospfInterface2);
}
@After
public void tearDown() throws Exception {
ospfArea = null;
ospfInterface = null;
ospfNbrList = null;
ospfInterfaces = null;
ospfAreaAddressRanges = null;
lsaHeader = null;
routerLsa = null;
ospfNbr = null;
networkLsa = null;
ospfInterface1 = null;
ospfInterface2 = null;
ospfInterface3 = null;
ospfInterface4 = null;
ospfInterface5 = null;
ospfInterface6 = null;
}
/**
* Tests equals() method.
*/
@Test
public void testEquals() throws Exception {
ospfArea = new OspfAreaImpl();
ospfInterface = new OspfInterfaceImpl();
ospfArea.setTransitCapability(true);
ospfArea.setExternalRoutingCapability(true);
ospfArea.setStubCost(100);
ospfArea.initializeDb();
ospfArea.setAddressRanges(ospfAreaAddressRanges);
assertThat(ospfArea.equals(ospfArea), is(true));
ospfArea = EasyMock.createMock(OspfAreaImpl.class);
assertThat(ospfArea.equals(ospfArea), is(true));
OspfArea ospfArea = new OspfAreaImpl();
assertThat(ospfArea.equals(ospfArea), is(true));
}
/**
* Tests hashCode() method.
@ -165,66 +161,6 @@ public class OspfAreaImplTest {
assertThat(ospfArea, is(notNullValue()));
}
/**
* Tests refreshArea() method.
*/
@Test
public void testRefreshArea() throws Exception {
ospfInterface = new OspfInterfaceImpl();
ospfInterface.setState(OspfInterfaceState.DR);
ospfNbrList = new HashMap();
ospfNbrList.put("1.1.1.1", new OspfNbrImpl(new OspfAreaImpl(), new OspfInterfaceImpl(),
Ip4Address.valueOf("1.1.1.1"),
Ip4Address.valueOf("2.2.2.2"), 2,
new OspfInterfaceChannelHandler(new Controller(),
new OspfAreaImpl(),
new OspfInterfaceImpl()),
topologyForDeviceAndLink));
ospfNbrList.put("2.2.2.2", new OspfNbrImpl(new OspfAreaImpl(), new OspfInterfaceImpl(),
Ip4Address.valueOf("1.1.1.1"),
Ip4Address.valueOf("2.2.2.2"), 2,
new OspfInterfaceChannelHandler(new Controller(),
new OspfAreaImpl(),
new OspfInterfaceImpl()),
topologyForDeviceAndLink));
ospfNbrList.put("3.3.3.3", new OspfNbrImpl(new OspfAreaImpl(), new OspfInterfaceImpl(),
Ip4Address.valueOf("1.1.1.1"),
Ip4Address.valueOf("2.2.2.2"), 2,
new OspfInterfaceChannelHandler(new Controller(),
new OspfAreaImpl(),
new OspfInterfaceImpl()),
topologyForDeviceAndLink));
ospfNbrList.put("4.4.4.4", new OspfNbrImpl(new OspfAreaImpl(), new OspfInterfaceImpl(),
Ip4Address.valueOf("1.1.1.1"),
Ip4Address.valueOf("2.2.2.2"), 2,
new OspfInterfaceChannelHandler(new Controller(),
new OspfAreaImpl(),
new OspfInterfaceImpl()),
topologyForDeviceAndLink));
ospfInterface.setListOfNeighbors(ospfNbrList);
ospfInterface.setIpAddress(Ip4Address.valueOf("10.10.10.10"));
ospfInterface.setIpNetworkMask(Ip4Address.valueOf("255.255.255.255"));
ospfInterfaces = new ArrayList();
ospfInterface1 = new OspfInterfaceImpl();
ospfInterface1.setIpAddress(Ip4Address.valueOf("1.1.1.1"));
ospfInterfaces.add(ospfInterface1);
ospfInterface2 = new OspfInterfaceImpl();
ospfInterface2.setIpAddress(Ip4Address.valueOf("2.2.2.2"));
ospfInterfaces.add(ospfInterface2);
ospfInterface3 = new OspfInterfaceImpl();
ospfInterface3.setIpAddress(Ip4Address.valueOf("3.3.3.3"));
ospfInterfaces.add(ospfInterface3);
ospfArea.setInterfacesLst(ospfInterfaces);
ospfArea.setRouterId(Ip4Address.valueOf("111.111.111.111"));
networkLsa = ospfArea.buildNetworkLsa(Ip4Address.valueOf("1.1.1.1"),
Ip4Address.valueOf("255.255.255.255"));
ospfArea.refreshArea(ospfInterface);
assertThat(ospfNbrList.size(), is(4));
assertThat(networkLsa, is(notNullValue()));
assertThat(ospfArea, is(notNullValue()));
}
/**
* Tests buildNetworkLsa() method.
@ -241,7 +177,7 @@ public class OspfAreaImplTest {
ospfInterface3 = new OspfInterfaceImpl();
ospfInterface3.setIpAddress(Ip4Address.valueOf("3.3.3.3"));
ospfInterfaces.add(ospfInterface3);
ospfArea.setInterfacesLst(ospfInterfaces);
ospfArea.setOspfInterfaceList(ospfInterfaces);
ospfArea.setRouterId(Ip4Address.valueOf("111.111.111.111"));
networkLsa = ospfArea.buildNetworkLsa(Ip4Address.valueOf("1.1.1.1"),
Ip4Address.valueOf("255.255.255.255"));
@ -250,118 +186,6 @@ public class OspfAreaImplTest {
assertThat(ospfArea, is(notNullValue()));
}
/**
* Tests buildNetworkLsa() method.
*/
@Test
public void testBuildNetworkLsa1() throws Exception {
ospfInterfaces = new ArrayList();
ospfInterface1 = new OspfInterfaceImpl();
ospfInterface1.setIpAddress(Ip4Address.valueOf("1.1.1.1"));
ospfInterface1.setIpNetworkMask(Ip4Address.valueOf("255.255.255.255"));
ospfInterface1.setState(OspfInterfaceState.POINT2POINT);
ospfNbr = new OspfNbrImpl(new OspfAreaImpl(), new OspfInterfaceImpl(),
Ip4Address.valueOf("1.1.1.1"),
Ip4Address.valueOf("2.2.2.2"), 2,
new OspfInterfaceChannelHandler(new Controller(),
new OspfAreaImpl(),
new OspfInterfaceImpl()),
topologyForDeviceAndLink);
ospfNbr.setState(OspfNeighborState.FULL);
ospfInterface1.addNeighbouringRouter(ospfNbr);
ospfInterfaces.add(ospfInterface1);
ospfArea.setInterfacesLst(ospfInterfaces);
ospfArea.setRouterId(Ip4Address.valueOf("111.111.111.111"));
networkLsa = ospfArea.buildNetworkLsa(Ip4Address.valueOf("1.1.1.1"),
Ip4Address.valueOf("255.255.255.255"));
assertThat(ospfInterfaces.size(), is(1));
assertThat(networkLsa, is(notNullValue()));
assertThat(ospfArea, is(notNullValue()));
}
/**
* Tests buildRouterLsa() method.
*/
@Test
public void testBuildRouterLsa() throws Exception {
ospfNbrList = new HashMap();
ospfNbr = new OspfNbrImpl(new OspfAreaImpl(), new OspfInterfaceImpl(),
Ip4Address.valueOf("1.1.1.1"),
Ip4Address.valueOf("2.2.2.2"), 2,
new OspfInterfaceChannelHandler(new Controller(),
new OspfAreaImpl(),
new OspfInterfaceImpl()),
topologyForDeviceAndLink);
ospfNbr.setState(OspfNeighborState.FULL);
ospfInterfaces = new ArrayList();
ospfInterface1 = new OspfInterfaceImpl();
ospfInterface1.setIpAddress(Ip4Address.valueOf("1.1.1.1"));
ospfInterface1.setState(OspfInterfaceState.DOWN);
ospfInterface1.addNeighbouringRouter(ospfNbr);
ospfInterfaces.add(ospfInterface1);
ospfInterface2 = new OspfInterfaceImpl();
ospfInterface2.setState(OspfInterfaceState.LOOPBACK);
ospfInterface2.setIpAddress(Ip4Address.valueOf("2.2.2.2"));
ospfInterface2.addNeighbouringRouter(ospfNbr);
ospfInterfaces.add(ospfInterface2);
ospfInterface3 = new OspfInterfaceImpl();
ospfInterface3.setIpAddress(Ip4Address.valueOf("3.3.3.3"));
ospfInterface3.setState(OspfInterfaceState.POINT2POINT);
ospfInterface3.setIpNetworkMask(Ip4Address.valueOf("255.255.255.255"));
ospfInterface3.addNeighbouringRouter(ospfNbr);
ospfInterface3.setListOfNeighbors(ospfNbrList);
ospfInterfaces.add(ospfInterface3);
ospfInterface4 = new OspfInterfaceImpl();
ospfInterface4.setState(OspfInterfaceState.WAITING);
ospfInterface4.setIpAddress(Ip4Address.valueOf("3.3.3.3"));
ospfInterface4.setIpNetworkMask(Ip4Address.valueOf("255.255.255.255"));
ospfInterfaces.add(ospfInterface4);
ospfInterface5 = new OspfInterfaceImpl();
ospfInterface5.setState(OspfInterfaceState.DR);
ospfInterface5.setIpAddress(Ip4Address.valueOf("3.3.3.3"));
ospfInterfaces.add(ospfInterface5);
ospfInterface6 = new OspfInterfaceImpl();
ospfInterface6.setState(OspfInterfaceState.BDR);
ospfInterface6.setIpAddress(Ip4Address.valueOf("3.3.3.3"));
ospfInterface6.setDr(Ip4Address.valueOf("3.3.3.3"));
ospfInterfaces.add(ospfInterface6);
ospfArea.setInterfacesLst(ospfInterfaces);
ospfArea.setRouterId(Ip4Address.valueOf("111.111.111.111"));
assertThat(ospfInterfaces.size(), is(6));
routerLsa = ospfArea.buildRouterLsa(ospfInterface1);
assertThat(routerLsa, is(notNullValue()));
routerLsa = ospfArea.buildRouterLsa(ospfInterface2);
assertThat(routerLsa, is(notNullValue()));
routerLsa = ospfArea.buildRouterLsa(ospfInterface3);
assertThat(routerLsa, is(notNullValue()));
assertThat(ospfArea, is(notNullValue()));
}
/**
* Tests buildRouterLsa() method.
*/
@Test
public void testBuildRouterLsa1() throws Exception {
ospfInterfaces = new ArrayList();
ospfInterface1 = new OspfInterfaceImpl();
ospfInterface1.setIpAddress(Ip4Address.valueOf("1.1.1.1"));
ospfInterface1.setIpNetworkMask(Ip4Address.valueOf("255.255.255.255"));
ospfInterface1.setState(OspfInterfaceState.POINT2POINT);
ospfNbr = new OspfNbrImpl(new OspfAreaImpl(), new OspfInterfaceImpl(),
Ip4Address.valueOf("1.1.1.1"),
Ip4Address.valueOf("2.2.2.2"), 2,
new OspfInterfaceChannelHandler(new Controller(),
new OspfAreaImpl(),
new OspfInterfaceImpl()),
topologyForDeviceAndLink);
ospfNbr.setState(OspfNeighborState.FULL);
ospfInterface1.addNeighbouringRouter(ospfNbr);
ospfInterfaces.add(ospfInterface1);
ospfArea.setInterfacesLst(ospfInterfaces);
ospfArea.setRouterId(Ip4Address.valueOf("111.111.111.111"));
routerLsa = ospfArea.buildRouterLsa(ospfInterface1);
assertThat(routerLsa, is(notNullValue()));
}
/**
* Tests areaId() getter method.
@ -381,51 +205,6 @@ public class OspfAreaImplTest {
assertThat(ospfArea.areaId(), is(Ip4Address.valueOf("1.1.1.1")));
}
/**
* Tests addressRanges() getter method.
*/
@Test
public void testGetAddressRanges() throws Exception {
ospfAreaAddressRanges = new ArrayList();
ospfAreaAddressRanges.add(new OspfAreaAddressRangeImpl());
ospfAreaAddressRanges.add(new OspfAreaAddressRangeImpl());
ospfAreaAddressRanges.add(new OspfAreaAddressRangeImpl());
ospfAreaAddressRanges.add(new OspfAreaAddressRangeImpl());
ospfArea.setAddressRanges(ospfAreaAddressRanges);
assertThat(ospfArea.addressRanges().size(), is(4));
}
/**
* Tests addressRanges() setter method.
*/
@Test
public void testSetAddressRanges() throws Exception {
ospfAreaAddressRanges = new ArrayList();
ospfAreaAddressRanges.add(new OspfAreaAddressRangeImpl());
ospfAreaAddressRanges.add(new OspfAreaAddressRangeImpl());
ospfAreaAddressRanges.add(new OspfAreaAddressRangeImpl());
ospfAreaAddressRanges.add(new OspfAreaAddressRangeImpl());
ospfArea.setAddressRanges(ospfAreaAddressRanges);
assertThat(ospfArea.addressRanges().size(), is(4));
}
/**
* Tests isTransitCapability() getter method.
*/
@Test
public void testIsTransitCapability() throws Exception {
ospfArea.setTransitCapability(true);
assertThat(ospfArea.isTransitCapability(), is(true));
}
/**
* Tests isTransitCapability() setter method.
*/
@Test
public void testSetTransitCapability() throws Exception {
ospfArea.setTransitCapability(true);
assertThat(ospfArea.isTransitCapability(), is(true));
}
/**
* Tests isExternalRoutingCapability() getter method.
@ -445,26 +224,9 @@ public class OspfAreaImplTest {
assertThat(ospfArea.isExternalRoutingCapability(), is(true));
}
/**
* Tests stubCost() getter method.
*/
@Test
public void testGetStubCost() throws Exception {
ospfArea.setStubCost(100);
assertThat(ospfArea.stubCost(), is(100));
}
/**
* Tests stubCost() setter method.
*/
@Test
public void testSetStubCost() throws Exception {
ospfArea.setStubCost(100);
assertThat(ospfArea.stubCost(), is(100));
}
/**
* Tests getInterfacesLst() getter method.
* Tests ospfInterfaceList() getter method.
*/
@Test
public void testGetInterfacesLst() throws Exception {
@ -478,9 +240,9 @@ public class OspfAreaImplTest {
ospfInterface3 = new OspfInterfaceImpl();
ospfInterface3.setIpAddress(Ip4Address.valueOf("3.3.3.3"));
ospfInterfaces.add(ospfInterface3);
ospfArea.setInterfacesLst(ospfInterfaces);
ospfArea.setOspfInterfaceList(ospfInterfaces);
assertThat(ospfInterfaces.size(), is(3));
assertThat(ospfArea.getInterfacesLst(), is(notNullValue()));
assertThat(ospfArea.ospfInterfaceList(), is(notNullValue()));
}
/**
@ -498,32 +260,11 @@ public class OspfAreaImplTest {
ospfInterface3 = new OspfInterfaceImpl();
ospfInterface3.setIpAddress(Ip4Address.valueOf("3.3.3.3"));
ospfInterfaces.add(ospfInterface3);
ospfArea.setInterfacesLst(ospfInterfaces);
ospfArea.setOspfInterfaceList(ospfInterfaces);
assertThat(ospfInterfaces.size(), is(3));
assertThat(ospfArea.getInterfacesLst(), is(notNullValue()));
assertThat(ospfArea.ospfInterfaceList(), is(notNullValue()));
}
/**
* Tests noNeighborInLsaExchangeProcess() method.
*/
@Test
public void testNoNeighborInLsaExchangeProcess() throws Exception {
ospfInterfaces = new ArrayList();
ospfInterface1 = new OspfInterfaceImpl();
ospfInterface1.setIpAddress(Ip4Address.valueOf("1.1.1.1"));
ospfNbr = new OspfNbrImpl(new OspfAreaImpl(), new OspfInterfaceImpl(),
Ip4Address.valueOf("1.1.1.1"),
Ip4Address.valueOf("2.2.2.2"), 2,
new OspfInterfaceChannelHandler(new Controller(),
new OspfAreaImpl(),
new OspfInterfaceImpl()),
topologyForDeviceAndLink);
ospfNbr.setState(OspfNeighborState.EXCHANGE.EXCHANGE);
ospfInterface1.addNeighbouringRouter(ospfNbr);
ospfInterfaces.add(ospfInterface1);
ospfArea.setInterfacesLst(ospfInterfaces);
assertThat(ospfArea.noNeighborInLsaExchangeProcess(), is(false));
}
/**
* Tests getLsaHeaders() method.
@ -620,27 +361,6 @@ public class OspfAreaImplTest {
assertThat(ospfArea.toString(), is(notNullValue()));
}
/**
* Tests getNeighborsInFullState() method.
*/
@Test
public void testGetNeighborsinFullState() throws Exception {
ospfInterfaces = new ArrayList();
ospfInterface1 = new OspfInterfaceImpl();
ospfInterface1.setIpAddress(Ip4Address.valueOf("1.1.1.1"));
ospfNbr = new OspfNbrImpl(new OspfAreaImpl(), new OspfInterfaceImpl(),
Ip4Address.valueOf("1.1.1.1"),
Ip4Address.valueOf("2.2.2.2"), 2,
new OspfInterfaceChannelHandler(new Controller(),
new OspfAreaImpl(),
new OspfInterfaceImpl()),
topologyForDeviceAndLink);
ospfNbr.setState(OspfNeighborState.FULL);
ospfInterface1.addNeighbouringRouter(ospfNbr);
ospfInterfaces.add(ospfInterface1);
ospfArea.setInterfacesLst(ospfInterfaces);
assertThat(ospfArea.getNeighborsInFullState(ospfInterface1).size(), is(1));
}
/**
* Tests getLsaKey() method.
@ -652,30 +372,6 @@ public class OspfAreaImplTest {
assertThat(ospfArea.getLsaKey(lsaHeader), is(notNullValue()));
}
/**
* Tests addToOtherNeighborLsaTxList() method.
*/
@Test
public void testAddToOtherNeighborLsaTxList() throws Exception {
ospfInterfaces = new ArrayList();
ospfInterface1 = new OspfInterfaceImpl();
ospfInterface1.setIpAddress(Ip4Address.valueOf("1.1.1.1"));
ospfNbr = new OspfNbrImpl(new OspfAreaImpl(), new OspfInterfaceImpl(),
Ip4Address.valueOf("1.1.1.1"),
Ip4Address.valueOf("2.2.2.2"), 2,
new OspfInterfaceChannelHandler(new Controller(),
new OspfAreaImpl(),
new OspfInterfaceImpl()),
topologyForDeviceAndLink);
ospfNbr.setState(OspfNeighborState.FULL);
ospfInterface1.addNeighbouringRouter(ospfNbr);
ospfInterfaces.add(ospfInterface1);
ospfArea.setInterfacesLst(ospfInterfaces);
lsaHeader = new LsaHeader();
lsaHeader.setAdvertisingRouter(Ip4Address.valueOf("1.1.1.1"));
ospfArea.addToOtherNeighborLsaTxList(lsaHeader);
assertThat(ospfArea, is(notNullValue()));
}
/**
* Tests options() getter method.
@ -719,4 +415,54 @@ public class OspfAreaImplTest {
public void testOpaqueEnabledOptionsa() throws Exception {
assertThat(ospfArea.opaqueEnabledOptions(), is(66));
}
/**
* Tests noNeighborInLsaExchangeProcess() method.
*/
@Test
public void testNoNeighborInLsaExchangeProcess() throws Exception {
ospfArea.setOspfInterfaceList(ospfInterfaces);
ospfArea.noNeighborInLsaExchangeProcess();
assertThat(ospfArea, is(notNullValue()));
}
/**
* Tests getNeighborsInFullState() method.
*/
@Test
public void testGetNeighborsInFullState() throws Exception {
ospfArea.getNeighborsInFullState(ospfInterface1);
assertThat(ospfArea, is(notNullValue()));
}
/**
* Tests addToOtherNeighborLsaTxList() method.
*/
@Test
public void testAddToOtherNeighborLsaTxList() throws Exception {
ospfArea.setOspfInterfaceList(ospfInterfaces);
ospfArea.addToOtherNeighborLsaTxList(routerLsa);
assertThat(ospfArea, is(notNullValue()));
opaqueLsa10.setLsType(OspfParameters.LINK_LOCAL_OPAQUE_LSA);
ospfArea.addToOtherNeighborLsaTxList(opaqueLsa10);
assertThat(ospfArea, is(notNullValue()));
}
/**
* Tests buildRouterLsa() method.
*/
@Test
public void testBuildRouterLsa() throws Exception {
ospfArea.setRouterId(ip4Address);
ospfArea.setOspfInterfaceList(ospfInterfaces);
ospfInterface1.setState(OspfInterfaceState.POINT2POINT);
ospfInterface1.setIpAddress(ip4Address);
ospfInterface1.setIpNetworkMask(networkAddress);
ospfInterfaces.add(ospfInterface1);
ospfArea.buildRouterLsa(ospfInterface1);
ospfArea.setOspfInterfaceList(ospfInterfaces);
assertThat(ospfArea, is(notNullValue()));
}
}

View File

@ -71,7 +71,7 @@ public class ControllerTest {
ospfInterface.setIpAddress(Ip4Address.valueOf("1.1.1.1"));
ospfInterfaces.add(ospfInterface);
ospfArea.setAreaId(Ip4Address.valueOf("2.2.2.2"));
ospfArea.setInterfacesLst(ospfInterfaces);
ospfArea.setOspfInterfaceList(ospfInterfaces);
ospfProcess.setProcessId("10.10.10.10");
ospfAreas = new ArrayList();
ospfAreas.add(ospfArea);
@ -82,7 +82,7 @@ public class ControllerTest {
ospfProcess1.setProcessId("11.11.11.11");
ospfArea1 = new OspfAreaImpl();
ospfArea1.setAreaId(Ip4Address.valueOf("2.2.2.2"));
ospfArea1.setInterfacesLst(ospfInterfaces);
ospfArea1.setOspfInterfaceList(ospfInterfaces);
ospfAreas.add(ospfArea1);
ospfProcess1.setAreas(ospfAreas);
ospfProcesses.add(ospfProcess1);
@ -167,83 +167,6 @@ public class ControllerTest {
assertThat(controller, is(notNullValue()));
}
/**
* Tests deleteInterfaceFromArea() method.
*/
@Test
public void testDeleteInterfaceFromArea() throws Exception {
controller.updateConfig(ospfProcesses);
assertThat(controller.deleteInterfaceFromArea("10.10.10.10", "2.2.2.2", "1.1.1.1"), is(true));
assertThat(controller.deleteInterfaceFromArea("10.10.10.10", "2.2.2.2", "5.5.5.5"), is(false));
}
/**
* Tests checkArea() method.
*/
@Test
public void testCheckArea() throws Exception {
controller.updateConfig(ospfProcesses);
assertThat(controller.checkArea("10.10.10.10", "2.2.2.2"), is(true));
}
/**
* Tests checkArea() method.
*/
@Test
public void testCheckArea1() throws Exception {
controller.updateConfig(ospfProcesses);
assertThat(controller.checkArea("10.10.10.10", "111.111.111.111"), is(false));
}
/**
* Tests checkProcess() method.
*/
@Test
public void testCheckProcess() throws Exception {
controller.updateConfig(ospfProcesses);
assertThat(controller.checkProcess("3.3.3.3"), is(false));
assertThat(controller.checkProcess("1.1.1.1"), is(false));
}
/**
* Tests checkInterface() method.
*/
@Test
public void testCheckInterface() throws Exception {
controller.updateConfig(ospfProcesses);
assertThat(controller.checkInterface("10.10.10.10", "2.2.2.2", "1.1.1.1"), is(true));
}
/**
* Tests updateAreaInProcess() method.
*/
@Test
public void testUpdateAreaInProcess() throws Exception {
controller.updateConfig(ospfProcesses);
controller.updateAreaInProcess("10.10.10.10", "2.2.2.2", ospfArea);
assertThat(controller, is(notNullValue()));
}
/**
* Tests updateConfig() method.
*/
@Test
public void testUpdateConfig() throws Exception {
controller.updateConfig(ospfProcesses);
controller.updateConfig(ospfProcesses);
controller.updateConfig(ospfProcesses);
assertThat(controller, is(notNullValue()));
}
/**
* Tests updateConfig() method.
*/
@Test
public void testUpdateConfig2() throws Exception {
controller.updateConfig(ospfProcesses);
controller.updateConfig(ospfProcesses);
assertThat(controller, is(notNullValue()));
}
/**
* Tests updateConfig() method.
@ -257,7 +180,7 @@ public class ControllerTest {
ospfInterface.setIpAddress(Ip4Address.valueOf("10.10.10.5"));
ospfInterfaces.add(ospfInterface);
ospfArea.setAreaId(Ip4Address.valueOf("2.2.2.2"));
ospfArea.setInterfacesLst(ospfInterfaces);
ospfArea.setOspfInterfaceList(ospfInterfaces);
ospfProcess.setProcessId("10.10.10.10");
ospfAreas = new ArrayList();
ospfAreas.add(ospfArea);
@ -268,67 +191,6 @@ public class ControllerTest {
assertThat(controller, is(notNullValue()));
}
/**
* Tests deleteConfig() method.
*/
@Test(expected = Exception.class)
public void testDeleteConfig() throws Exception {
controller.updateConfig(ospfProcesses);
controller.deleteConfig(ospfProcesses, "INTERFACE");
assertThat(controller, is(notNullValue()));
}
/**
* Tests deleteConfig() method.
*/
@Test(expected = Exception.class)
public void testDeleteConfig1() throws Exception {
controller.updateConfig(ospfProcesses);
controller.deleteConfig(ospfProcesses, "AREA");
assertThat(controller, is(notNullValue()));
}
/**
* Tests deleteConfig() method.
*/
@Test
public void testDeleteConfig2() throws Exception {
controller.updateConfig(ospfProcesses);
controller.deleteConfig(ospfProcesses, "PROCESS");
assertThat(controller, is(notNullValue()));
}
/**
* Tests deleteConfig() method.
*/
@Test
public void testDeleteConfig3() throws Exception {
ospfProcesses = new ArrayList();
controller.deleteConfig(ospfProcesses, "PROCESS");
assertThat(controller, is(notNullValue()));
}
/**
* Tests deleteConfig() method.
*/
@Test
public void testDeleteConfig4() throws Exception {
controller.updateConfig(ospfProcesses);
controller.deleteConfig(ospfProcesses, "PROCESS");
controller.updateConfig(ospfProcesses);
assertThat(controller, is(notNullValue()));
}
/**
* Tests deleteProcessWhenExists() method.
*/
@Test
public void testDeleteProcessWhenExists() throws Exception {
controller.updateConfig(ospfProcesses);
controller.deleteProcessWhenExists(ospfProcesses, "PROCESS");
}
/**
* Tests addLinkDetails() method.
*/
@ -350,7 +212,7 @@ public class ControllerTest {
controller.start(ospfAgent, driverService);
ospfRouter = new OspfRouterImpl();
controller.addLinkDetails(ospfRouter, new OspfLinkTedImpl());
controller.removeLinkDetails(ospfRouter);
controller.removeLinkDetails(ospfRouter, new OspfLinkTedImpl());
assertThat(controller, is(notNullValue()));
}
}

View File

@ -0,0 +1,82 @@
/*
* Copyright 2016-present Open Networking Laboratory
*
* 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 org.onosproject.ospf.controller.impl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onosproject.ospf.controller.OspfProcess;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Unit test class for OspfJsonParsingUtilTest.
*/
public class OspfConfigUtilTest {
private ObjectMapper mapper;
private JsonNode jsonNode;
private List<OspfProcess> ospfProcessList = new ArrayList<>();
private String jsonString = "{\n" +
"\t\"processes\": {\n" +
"\t\t\"areas\": [{\n" +
"\t\t\t\"interface\": [{\n" +
"\t\t\t\t\"interfaceIndex\": \"2\",\n" +
"\n" +
"\t\t\t\t\"helloIntervalTime\": \"10\",\n" +
"\n" +
"\t\t\t\t\"routerDeadIntervalTime\": \"40\",\n" +
"\n" +
"\t\t\t\t\"interfaceType\": \"2\",\n" +
"\n" +
"\t\t\t\t\"reTransmitInterval\": \"5\"\n" +
"\t\t\t}],\n" +
"\t\t\t\"areaId\": \"5.5.5.5\",\n" +
"\n" +
"\t\t\t\"routerId\": \"7.7.7.7\",\n" +
"\n" +
"\t\t\t\"isOpaqueEnable\": \"false\",\n" +
"\n" +
"\t\t\t\"externalRoutingCapability\": \"true\"\n" +
"\t\t}]\n" +
"\t}\n" +
"}";
@Before
public void setUp() throws Exception {
mapper = new ObjectMapper();
jsonNode = mapper.readTree(jsonString);
mapper = new ObjectMapper();
}
@After
public void tearDown() throws Exception {
}
@Test
public void testProcesses() throws Exception {
jsonNode.path("areas");
ospfProcessList = OspfConfigUtil.processes(jsonNode);
assertThat(ospfProcessList, is(notNullValue()));
}
}

View File

@ -46,10 +46,8 @@ public class OspfControllerImplTest {
private OspfControllerImpl ospfController;
private OspfRouterListener ospfRouterListener;
private OspfLinkListener ospfLinkListener;
private Controller controller;
private List<OspfProcess> ospfProcesses;
private OspfProcess process1;
private OspfProcess process2;
private List<OspfArea> areas;
private OspfAreaImpl ospfArea;
private List<OspfInterface> ospfInterfaces;
@ -61,7 +59,6 @@ public class OspfControllerImplTest {
@Before
public void setUp() throws Exception {
ospfController = new OspfControllerImpl();
controller = new Controller();
}
@After
@ -69,7 +66,6 @@ public class OspfControllerImplTest {
ospfController = null;
ospfRouterListener = null;
ospfLinkListener = null;
controller = null;
ospfProcesses = null;
areas = null;
ospfArea = null;
@ -139,38 +135,6 @@ public class OspfControllerImplTest {
assertThat(ospfController, is(notNullValue()));
}
/**
* Tests updateConfig() method.
*/
@Test
public void testUpdateConfig() throws Exception {
ospfProcess = new OspfProcessImpl();
ospfArea = new OspfAreaImpl();
ospfInterface = new OspfInterfaceImpl();
ospfInterfaces = new ArrayList();
ospfInterface.setIpAddress(Ip4Address.valueOf("11.11.11.11"));
ospfInterfaces.add(ospfInterface);
ospfArea.setAreaId(Ip4Address.valueOf("2.2.2.2"));
ospfArea.setInterfacesLst(ospfInterfaces);
ospfProcess.setProcessId("10.10.10.10");
areas = new ArrayList();
areas.add(ospfArea);
ospfProcess.setAreas(areas);
ospfProcesses = new ArrayList();
ospfProcesses.add(ospfProcess);
process1 = new OspfProcessImpl();
process1.setProcessId("11.11.11.11");
ospfArea1 = new OspfAreaImpl();
ospfArea1.setAreaId(Ip4Address.valueOf("2.2.2.2"));
ospfArea1.setInterfacesLst(ospfInterfaces);
areas.add(ospfArea1);
process1.setAreas(areas);
ospfProcesses.add(process1);
ospfController.updateConfig(ospfProcesses);
assertThat(ospfController, is(notNullValue()));
}
/**
* Tests deleteConfig() method.
*/
@ -183,7 +147,7 @@ public class OspfControllerImplTest {
ospfInterface.setIpAddress(Ip4Address.valueOf("10.10.10.5"));
ospfInterfaces.add(ospfInterface);
ospfArea.setAreaId(Ip4Address.valueOf("2.2.2.2"));
ospfArea.setInterfacesLst(ospfInterfaces);
ospfArea.setOspfInterfaceList(ospfInterfaces);
ospfProcess.setProcessId("10.10.10.10");
areas = new ArrayList();
areas.add(ospfArea);
@ -194,7 +158,7 @@ public class OspfControllerImplTest {
process1.setProcessId("11.11.11.11");
ospfArea1 = new OspfAreaImpl();
ospfArea1.setAreaId(Ip4Address.valueOf("2.2.2.2"));
ospfArea1.setInterfacesLst(ospfInterfaces);
ospfArea1.setOspfInterfaceList(ospfInterfaces);
areas.add(ospfArea1);
process1.setAreas(areas);
ospfProcesses.add(process1);
@ -221,7 +185,7 @@ public class OspfControllerImplTest {
ospfRouter = new OspfRouterImpl();
ospfController.agent.addLink(ospfRouter, new OspfLinkTedImpl());
ospfController.agent.deleteLink(ospfRouter);
ospfController.agent.deleteLink(ospfRouter, new OspfLinkTedImpl());
assertThat(ospfController, is(notNullValue()));
}

View File

@ -21,6 +21,7 @@ import org.junit.Test;
import org.onlab.packet.Ip4Address;
import org.onlab.packet.Ip6Address;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
@ -31,8 +32,6 @@ import static org.junit.Assert.assertThat;
* Unit test class for OspfDeviceTedImpl.
*/
public class OspfDeviceTedImplTest {
private static final Ip6Address LOCAL_ADDRESS = Ip6Address.valueOf("::1");
private OspfDeviceTedImpl ospfDeviceTed;
@Before
@ -128,10 +127,10 @@ public class OspfDeviceTedImplTest {
/**
* Tests ipv6RouterIds() getter method.
*/
@Test
@Test(expected = Exception.class)
public void testIpv6RouterIds() throws Exception {
List list = new ArrayList();
list.add(LOCAL_ADDRESS);
list.add(Ip6Address.valueOf(InetAddress.getLocalHost()));
ospfDeviceTed.setIpv6RouterIds(list);
assertThat(ospfDeviceTed.ipv6RouterIds().size(), is(1));
}
@ -139,11 +138,11 @@ public class OspfDeviceTedImplTest {
/**
* Tests ipv6RouterIds() setter method.
*/
@Test
@Test(expected = Exception.class)
public void testSetIpv6RouterIds() throws Exception {
List list = new ArrayList();
list.add(LOCAL_ADDRESS);
list.add(Ip6Address.valueOf(InetAddress.getLocalHost()));
ospfDeviceTed.setIpv6RouterIds(list);
assertThat(ospfDeviceTed.ipv6RouterIds().size(), is(1));
}
}
}

View File

@ -21,6 +21,7 @@ import org.junit.Test;
import org.onlab.packet.Ip4Address;
import org.onlab.util.Bandwidth;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
@ -32,8 +33,6 @@ import static org.junit.Assert.assertThat;
* Unit test class for OspfDeviceTedImpl.
*/
public class OspfLinkTedImplTest {
private static final Ip4Address LOCAL_ADDRESS = Ip4Address.valueOf("127.0.0.1");
private OspfLinkTedImpl ospfLinkTed;
@Before
@ -91,7 +90,7 @@ public class OspfLinkTedImplTest {
@Test
public void testIpv4RemRouterId() throws Exception {
List list = new ArrayList();
list.add(LOCAL_ADDRESS);
list.add(Ip4Address.valueOf(InetAddress.getLocalHost()));
ospfLinkTed.setIpv4RemRouterId(list);
assertThat(ospfLinkTed.ipv4RemRouterId().size(), is(1));
}
@ -102,7 +101,7 @@ public class OspfLinkTedImplTest {
@Test
public void testSetIpv4RemRouterId() throws Exception {
List list = new ArrayList();
list.add(LOCAL_ADDRESS);
list.add(Ip4Address.valueOf(InetAddress.getLocalHost()));
ospfLinkTed.setIpv4RemRouterId(list);
assertThat(ospfLinkTed.ipv4RemRouterId().size(), is(1));
}
@ -133,7 +132,7 @@ public class OspfLinkTedImplTest {
@Test
public void testIpv4LocRouterId() throws Exception {
List list = new ArrayList();
list.add(LOCAL_ADDRESS);
list.add(Ip4Address.valueOf(InetAddress.getLocalHost()));
ospfLinkTed.setIpv4LocRouterId(list);
assertThat(ospfLinkTed.ipv4LocRouterId().size(), is(1));
}
@ -144,7 +143,7 @@ public class OspfLinkTedImplTest {
@Test
public void testSetIpv4LocRouterId() throws Exception {
List list = new ArrayList();
list.add(LOCAL_ADDRESS);
list.add(Ip4Address.valueOf(InetAddress.getLocalHost()));
ospfLinkTed.setIpv4LocRouterId(list);
assertThat(ospfLinkTed.ipv4LocRouterId().size(), is(1));
}
@ -202,4 +201,4 @@ public class OspfLinkTedImplTest {
ospfLinkTed.setMaxUnResBandwidth(Bandwidth.bps(1234.0));
assertThat(ospfLinkTed.maxUnResBandwidth(), is(notNullValue()));
}
}
}

View File

@ -28,7 +28,7 @@ import java.net.InetSocketAddress;
import java.net.SocketAddress;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
/**
@ -36,7 +36,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
*/
public class OspfMessageDecoderTest {
private final byte[] hellopacket = {0, 0, 0, 0, 2, 1, 0, 44, -64, -88, -86, 8, 0, 0, 0, 1, 39, 59,
private final byte[] hellopacket = {0, 0, 0, 0, 0, 2, 1, 0, 44, -64, -88, -86, 8, 0, 0, 0, 1, 39, 59,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, 0, 0, 10, 2, 1, 0, 0, 0,
40, -64, -88, -86, 8, 0, 0, 0, 0};
private final byte[] ddpacket = {0, 0, 0, 0, 2, 2, 0, 32, -64, -88, -86, 8, 0, 0, 0, 1, -96, 82,
@ -75,10 +75,10 @@ public class OspfMessageDecoderTest {
*/
@Test
public void testDecode() throws Exception {
channel = EasyMock.createMock(Channel.class);
socketAddress = InetSocketAddress.createUnresolved("127.0.0.1", 7000);
channelBuffer = ChannelBuffers.copiedBuffer(hellopacket);
assertThat(ospfMessageDecoder.decode(ctx, channel, channelBuffer), is(nullValue()));
ospfMessageDecoder.decode(ctx, channel, channelBuffer);
assertThat(ospfMessageDecoder, is(notNullValue()));
}
}

View File

@ -17,24 +17,11 @@ package org.onosproject.ospf.controller.impl;
import org.easymock.EasyMock;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.controller.area.OspfInterfaceImpl;
import org.onosproject.ospf.protocol.ospfpacket.types.DdPacket;
import org.onosproject.ospf.protocol.ospfpacket.types.HelloPacket;
import org.onosproject.ospf.protocol.ospfpacket.types.LsAcknowledge;
import org.onosproject.ospf.protocol.ospfpacket.types.LsRequest;
import org.onosproject.ospf.protocol.ospfpacket.types.LsUpdate;
import org.onosproject.ospf.protocol.util.OspfInterfaceState;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
@ -44,55 +31,24 @@ import static org.hamcrest.MatcherAssert.assertThat;
* Created by sdn on 13/1/16.
*/
public class OspfMessageEncoderTest {
private final byte[] hpacket = {2, 1, 0, 44, -64, -88, -86, 8, 0, 0, 0, 1, 39, 59,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, 0, 0, 10, 2, 1, 0, 0, 0,
40, -64, -88, -86, 8, 0, 0, 0, 0};
private final byte[] dpacket = {2, 2, 0, 32, -64, -88, -86, 8, 0, 0, 0, 1, -96, 82,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, -36, 2, 7, 65, 119, -87, 126};
private final byte[] lrpacket = {2, 3, 0, 36, -64, -88, -86, 3, 0, 0, 0, 1, -67, -57,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -64, -88, -86, 8, -64, -88, -86, 8};
private byte[] lAckpacket = {2, 5, 0, 44, -64, -88, -86, 8, 0, 0, 0, 1, -30, -12,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 16, 2, 1, -64, -88, -86, 2, -64,
-88, -86, 2, -128, 0, 0, 1, 74, -114, 0, 48};
private HelloPacket helloPacket;
private DdPacket ddPacket;
private LsAcknowledge lsAcknowledge;
private LsRequest lsRequest;
private LsUpdate lsUpdate;
private ChannelHandlerContext ctx;
private final byte[] object = {2, 1, 0, 44, -64, -88, -86, 8, 0, 0, 0, 1, 39,
59, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, 0, 0, 10, 2, 1, 0, 0,
0, 40, -64, -88, -86, 8, 0, 0, 0, 0};
private OspfMessageEncoder ospfMessageEncoder;
private ChannelBuffer buf;
private SocketAddress socketAddress;
private ChannelHandlerContext channelHandlerContext;
private Channel channel;
@Before
public void setUp() throws Exception {
ospfMessageEncoder = new OspfMessageEncoder();
helloPacket = new HelloPacket();
ddPacket = new DdPacket();
lsAcknowledge = new LsAcknowledge();
lsRequest = new LsRequest();
lsUpdate = new LsUpdate();
helloPacket.setOspftype(1);
ddPacket.setOspftype(2);
lsAcknowledge.setOspftype(5);
lsRequest.setOspftype(3);
lsUpdate.setOspftype(4);
OspfInterfaceImpl ospfInterface = new OspfInterfaceImpl();
ospfInterface.setState(OspfInterfaceState.DROTHER);
ospfMessageEncoder = new OspfMessageEncoder(ospfInterface);
channelHandlerContext = EasyMock.createMock(ChannelHandlerContext.class);
channel = EasyMock.createMock(Channel.class);
}
@After
public void tearDown() throws Exception {
helloPacket = null;
ddPacket = null;
lsAcknowledge = null;
lsRequest = null;
lsUpdate = null;
ospfMessageEncoder = null;
buf = null;
}
/**
@ -100,33 +56,6 @@ public class OspfMessageEncoderTest {
*/
@Test
public void testEncode() throws Exception {
socketAddress = InetSocketAddress.createUnresolved("127.0.0.1", 8600);
channel = EasyMock.createMock(Channel.class);
helloPacket = new HelloPacket();
helloPacket.setDestinationIp(Ip4Address.valueOf("15.15.15.15"));
buf = ChannelBuffers.buffer(hpacket.length);
buf.writeBytes(hpacket);
helloPacket.readFrom(buf);
ospfMessageEncoder.encode(ctx, channel, helloPacket);
ddPacket = new DdPacket();
ddPacket.setDestinationIp(Ip4Address.valueOf("15.15.15.15"));
buf = ChannelBuffers.buffer(dpacket.length);
buf.writeBytes(dpacket);
ddPacket.readFrom(buf);
ospfMessageEncoder.encode(ctx, channel, ddPacket);
lsRequest = new LsRequest();
lsRequest.setDestinationIp(Ip4Address.valueOf("15.15.15.15"));
buf = ChannelBuffers.buffer(lrpacket.length);
buf.writeBytes(lrpacket);
lsRequest.readFrom(buf);
ospfMessageEncoder.encode(ctx, channel, lsRequest);
lsAcknowledge = new LsAcknowledge();
lsAcknowledge.setDestinationIp(Ip4Address.valueOf("15.15.15.15"));
buf = ChannelBuffers.buffer(lAckpacket.length);
buf.writeBytes(lAckpacket);
lsAcknowledge.readFrom(buf);
ospfMessageEncoder.encode(ctx, channel, lsAcknowledge);
assertThat(ospfMessageEncoder, is(notNullValue()));
assertThat(ospfMessageEncoder.encode(channelHandlerContext, channel, object), is(notNullValue()));
}
}

View File

@ -19,31 +19,37 @@ package org.onosproject.ospf.controller.impl;
import org.easymock.EasyMock;
import org.jboss.netty.channel.Channel;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.controller.OspfAreaAddressRange;
import org.onosproject.ospf.controller.OspfInterface;
import org.onosproject.ospf.controller.OspfLsa;
import org.onosproject.ospf.controller.OspfLsaType;
import org.onosproject.ospf.controller.OspfMessage;
import org.onosproject.ospf.controller.OspfNeighborState;
import org.onosproject.ospf.controller.TopologyForDeviceAndLink;
import org.onosproject.ospf.controller.area.OspfAreaAddressRangeImpl;
import org.onosproject.ospf.controller.area.OspfAreaImpl;
import org.onosproject.ospf.controller.area.OspfInterfaceImpl;
import org.onosproject.ospf.controller.lsdb.LsaWrapperImpl;
import org.onosproject.ospf.controller.lsdb.LsdbAgeImpl;
import org.onosproject.ospf.controller.util.OspfInterfaceType;
import org.onosproject.ospf.protocol.lsa.LsaHeader;
import org.onosproject.ospf.protocol.lsa.OpaqueLsaHeader;
import org.onosproject.ospf.protocol.lsa.types.NetworkLsa;
import org.onosproject.ospf.protocol.lsa.types.OpaqueLsa10;
import org.onosproject.ospf.protocol.lsa.types.RouterLsa;
import org.onosproject.ospf.protocol.ospfpacket.OspfMessage;
import org.onosproject.ospf.protocol.ospfpacket.types.DdPacket;
import org.onosproject.ospf.protocol.ospfpacket.types.HelloPacket;
import org.onosproject.ospf.protocol.ospfpacket.types.LsRequest;
import org.onosproject.ospf.protocol.ospfpacket.types.LsUpdate;
import org.onosproject.ospf.protocol.util.ChecksumCalculator;
import org.onosproject.ospf.protocol.util.OspfInterfaceState;
import org.onosproject.ospf.protocol.util.OspfUtil;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
@ -55,54 +61,68 @@ import static org.hamcrest.MatcherAssert.assertThat;
* Unit test class for OspfNbrImpl.
*/
public class OspfNbrImplTest {
private List<OspfAreaAddressRange> addressRanges = new ArrayList();
private OspfNbrImpl ospfNbr;
private OspfNbrImpl ospfNbr1;
private OspfInterfaceImpl ospfInterface;
private OspfAreaImpl ospfArea;
private OspfInterfaceImpl ospfInterface1;
private OspfInterfaceImpl ospfInterface2;
private List<OspfInterface> ospfInterfaces;
private List<OspfInterface> ospfInterfaces = new ArrayList();
private List<OspfLsa> ospfLsaList;
private Channel channel;
private Channel channel1;
private Channel channel2;
private OspfMessage ospfMessage;
private TopologyForDeviceAndLink topologyForDeviceAndLink;
private LsaHeader lsaHeader;
@Before
public void setUp() throws Exception {
lsaHeader = new LsaHeader();
lsaHeader.setLsType(OspfLsaType.ROUTER.value());
RouterLsa routerLsa = new RouterLsa(lsaHeader);
routerLsa.setLsType(OspfLsaType.ROUTER.value());
ospfInterface = new OspfInterfaceImpl();
ospfInterface.setInterfaceType(2);
ospfInterface.setInterfaceIndex(1);
ospfInterface.setRouterDeadIntervalTime(30);
ospfInterface.setReTransmitInterval(30);
ospfInterface.setDr(Ip4Address.valueOf("1.1.1.1"));
ospfInterface.setIpAddress(Ip4Address.valueOf("1.1.1.1"));
ospfArea = new OspfAreaImpl();
ospfInterface.setState(OspfInterfaceState.POINT2POINT);
ospfArea = createOspfArea();
ospfArea.addLsa(routerLsa, true, ospfInterface);
ospfInterface.setOspfArea(ospfArea);
ospfInterface1 = new OspfInterfaceImpl();
ospfInterface1.setInterfaceType(2);
ospfInterface1.setInterfaceIndex(1);
ospfInterface1.setRouterDeadIntervalTime(30);
ospfInterface1.setReTransmitInterval(30);
ospfInterface1.setDr(Ip4Address.valueOf("7.7.7.7"));
ospfInterface1.setIpAddress(Ip4Address.valueOf("7.7.7.7"));
ospfInterface1.setState(OspfInterfaceState.DOWN);
ospfInterface1.setOspfArea(ospfArea);
ospfInterface2 = new OspfInterfaceImpl();
ospfInterface2.setInterfaceType(2);
ospfInterface2.setInterfaceIndex(1);
ospfInterface2.setRouterDeadIntervalTime(30);
ospfInterface2.setReTransmitInterval(30);
ospfInterface2.setDr(Ip4Address.valueOf("6.6.6.6"));
ospfInterface2.setIpAddress(Ip4Address.valueOf("6.6.6.6"));
ospfInterface2.setOspfArea(ospfArea);
ospfInterface1.setState(OspfInterfaceState.DR);
ospfInterfaces = new ArrayList();
ospfInterfaces.add(ospfInterface);
ospfInterfaces.add(ospfInterface1);
ospfInterfaces.add(ospfInterface2);
ospfArea.setInterfacesLst(ospfInterfaces);
ospfArea.setOspfInterfaceList(ospfInterfaces);
ospfInterface.setState(OspfInterfaceState.POINT2POINT);
ospfArea.setRouterId(Ip4Address.valueOf("111.111.111.111"));
topologyForDeviceAndLink = new TopologyForDeviceAndLinkImpl();
ospfNbr = new OspfNbrImpl(ospfArea, ospfInterface, Ip4Address.valueOf("1.1.1.1"),
Ip4Address.valueOf("2.2.2.2"), 2,
new OspfInterfaceChannelHandler(new Controller(),
ospfArea, ospfInterface),
topologyForDeviceAndLink);
}
@After
@ -184,12 +204,19 @@ public class OspfNbrImplTest {
/**
* Tests negotiationDone() method.
*/
@Test(expected = Exception.class)
@Test
public void testNegotiationDone() throws Exception {
ospfLsaList = new ArrayList();
ospfLsaList.add(new RouterLsa());
ospfMessage = new HelloPacket();
RouterLsa routerLsa = new RouterLsa();
routerLsa.setLsType(OspfLsaType.ROUTER.value());
ospfLsaList.add(routerLsa);
DdPacket ddPacket = new DdPacket();
ddPacket.setIsOpaqueCapable(true);
ospfMessage = ddPacket;
ospfNbr.setState(OspfNeighborState.EXSTART);
ospfNbr.setIsOpaqueCapable(true);
channel = null;
channel = EasyMock.createMock(Channel.class);
ospfNbr.negotiationDone(ospfMessage, true, ospfLsaList, channel);
channel1 = EasyMock.createMock(Channel.class);
@ -230,7 +257,7 @@ public class OspfNbrImplTest {
@Test
public void testBadLSReq() throws Exception {
channel = EasyMock.createMock(Channel.class);
ospfNbr.setState(OspfNeighborState.FULL);
ospfNbr.setState(OspfNeighborState.EXCHANGE);
ospfNbr.badLSReq(channel);
assertThat(ospfNbr, is(notNullValue()));
}
@ -294,11 +321,24 @@ public class OspfNbrImplTest {
@Test
public void testAdjOk() throws Exception {
channel = EasyMock.createMock(Channel.class);
ospfInterface.setInterfaceType(OspfInterfaceType.BROADCAST.value());
ospfInterface.setIpAddress(Ip4Address.valueOf("2.2.2.2"));
ospfNbr.setState(OspfNeighborState.TWOWAY);
ospfNbr.setNeighborDr(Ip4Address.valueOf("2.2.2.2"));
ospfNbr.adjOk(channel);
Assert.assertNotNull(ospfNbr);
ospfNbr1 = new OspfNbrImpl(ospfArea, ospfInterface, Ip4Address.valueOf("1.1.1.1"),
Ip4Address.valueOf("2.2.2.2"), 2,
topologyForDeviceAndLink);
ospfNbr1.setState(OspfNeighborState.TWOWAY);
ospfNbr1.setNeighborDr(Ip4Address.valueOf("2.2.2.2"));
ospfNbr1.adjOk(channel);
assertThat(ospfNbr1, is(notNullValue()));
ospfInterface.setInterfaceType(OspfInterfaceType.POINT_TO_POINT.value());
ospfNbr1 = new OspfNbrImpl(ospfArea, ospfInterface, Ip4Address.valueOf("1.1.1.1"),
Ip4Address.valueOf("2.2.2.2"), 2,
topologyForDeviceAndLink);
channel = null;
channel = EasyMock.createMock(Channel.class);
ospfNbr1.adjOk(channel);
assertThat(ospfNbr1, is(notNullValue()));
}
/**
@ -321,8 +361,11 @@ public class OspfNbrImplTest {
*/
@Test
public void testLoadingDone() throws Exception {
ospfArea.addLsa(new RouterLsa(), false, ospfInterface);
ospfArea.addLsa(new RouterLsa(), ospfInterface);
LsaHeader lsaHeader = new LsaHeader();
lsaHeader.setLsType(OspfLsaType.ROUTER.value());
RouterLsa routerLsa = new RouterLsa(lsaHeader);
ospfArea.addLsa(routerLsa, false, ospfInterface);
ospfArea.addLsa(routerLsa, ospfInterface);
ospfArea.addLsaToMaxAgeBin("lsa", new LsaWrapperImpl());
ospfNbr.loadingDone();
assertThat(ospfNbr, is(notNullValue()));
@ -362,6 +405,7 @@ public class OspfNbrImplTest {
channel1 = EasyMock.createMock(Channel.class);
assertThat(ospfNbr.processReceivedLsa(routerlsa, true, channel1,
Ip4Address.valueOf("10.10.10.10")), is(true));
}
/**
@ -394,7 +438,7 @@ public class OspfNbrImplTest {
@Test
public void testSendLsa() throws Exception {
channel = EasyMock.createMock(Channel.class);
ospfNbr.sendLsa(new LsaHeader(), Ip4Address.valueOf("1.1.1.1"), channel);
ospfNbr.sendLsa(lsaHeader, Ip4Address.valueOf("1.1.1.1"), channel);
assertThat(ospfNbr, is(notNullValue()));
}
@ -648,4 +692,77 @@ public class OspfNbrImplTest {
public void testGetPendingReTxList() throws Exception {
assertThat(ospfNbr.getPendingReTxList(), is(notNullValue()));
}
/**
* Utility for test method.
*/
private OspfAreaImpl createOspfArea() throws UnknownHostException {
OspfAreaAddressRangeImpl ospfAreaAddressRange;
ospfAreaAddressRange = createOspfAreaAddressRange();
addressRanges.add(ospfAreaAddressRange);
OspfAreaImpl ospfArea = new OspfAreaImpl();
ospfArea.setAreaId(Ip4Address.valueOf("10.226.165.164"));
ospfArea.setExternalRoutingCapability(true);
OspfInterfaceImpl ospfInterface = createOspfInterface();
ospfInterfaces.add(ospfInterface);
ospfArea.setOspfInterfaceList(ospfInterfaces);
RouterLsa routerLsa = new RouterLsa();
routerLsa.setLsType(1);
routerLsa.setLinkStateId("2.2.2.2");
routerLsa.setAdvertisingRouter(Ip4Address.valueOf("2.2.2.2"));
OpaqueLsaHeader opaqueLsaHeader = new OpaqueLsaHeader();
OpaqueLsa10 opaqueLsa10 = new OpaqueLsa10(opaqueLsaHeader);
opaqueLsa10.setLsType(OspfLsaType.AREA_LOCAL_OPAQUE_LSA.value());
opaqueLsa10.setLinkStateId("2.2.2.2");
opaqueLsa10.setAdvertisingRouter(Ip4Address.valueOf("2.2.2.2"));
try {
ospfArea.addLsa(routerLsa, false, ospfInterface);
ospfArea.addLsa(opaqueLsa10, false, ospfInterface);
} catch (Exception e) {
System.out.println("ospfAreaImpl createOspfArea");
}
ospfArea.setRouterId(Ip4Address.valueOf("111.111.111.111"));
return ospfArea;
}
/**
* Utility for test method.
*/
private OspfAreaAddressRangeImpl createOspfAreaAddressRange() {
OspfAreaAddressRangeImpl ospfAreaAddressRange = new OspfAreaAddressRangeImpl();
ospfAreaAddressRange.setIpAddress(Ip4Address.valueOf("10.226.165.164"));
ospfAreaAddressRange.setAdvertise(true);
ospfAreaAddressRange.setMask("mask");
return ospfAreaAddressRange;
}
/**
* Utility for test method.
*/
private OspfInterfaceImpl createOspfInterface() throws UnknownHostException {
ospfInterface = new OspfInterfaceImpl();
OspfAreaImpl ospfArea = new OspfAreaImpl();
OspfInterfaceChannelHandler ospfInterfaceChannelHandler = EasyMock.createMock(
OspfInterfaceChannelHandler.class);
ospfNbr = new OspfNbrImpl(ospfArea, ospfInterface, Ip4Address.valueOf("10.226.165.164"),
Ip4Address.valueOf("1.1.1.1"), 2,
topologyForDeviceAndLink);
ospfNbr.setState(OspfNeighborState.EXSTART);
ospfNbr.setNeighborId(Ip4Address.valueOf("10.226.165.100"));
this.ospfInterface = new OspfInterfaceImpl();
this.ospfInterface.setIpAddress(Ip4Address.valueOf("10.226.165.164"));
this.ospfInterface.setIpNetworkMask(Ip4Address.valueOf("255.255.255.255"));
this.ospfInterface.setBdr(Ip4Address.valueOf("111.111.111.111"));
this.ospfInterface.setDr(Ip4Address.valueOf("111.111.111.111"));
this.ospfInterface.setHelloIntervalTime(20);
this.ospfInterface.setInterfaceType(2);
this.ospfInterface.setReTransmitInterval(2000);
this.ospfInterface.setMtu(6500);
this.ospfInterface.setRouterDeadIntervalTime(1000);
this.ospfInterface.setRouterPriority(1);
this.ospfInterface.setInterfaceType(1);
this.ospfInterface.addNeighbouringRouter(ospfNbr);
return this.ospfInterface;
}
}

View File

@ -18,12 +18,6 @@ package org.onosproject.ospf.controller.impl;
import org.jboss.netty.channel.ChannelPipeline;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onosproject.ospf.controller.area.OspfAreaImpl;
import org.onosproject.ospf.controller.area.OspfInterfaceImpl;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Unit test class for OspfPipelineFactory.
@ -35,8 +29,6 @@ public class OspfPipelineFactoryTest {
@Before
public void setUp() throws Exception {
ospfPipelineFactory = new OspfPipelineFactory(new Controller(), new OspfAreaImpl(), new OspfInterfaceImpl());
}
@After
@ -44,22 +36,4 @@ public class OspfPipelineFactoryTest {
ospfPipelineFactory = null;
channelPipeline = null;
}
/**
* Tests getPipeline() method.
*/
@Test
public void testGetPipeline() throws Exception {
channelPipeline = ospfPipelineFactory.getPipeline();
assertThat(channelPipeline, is(notNullValue()));
}
/**
* Tests releaseExternalResources() method.
*/
@Test
public void testReleaseExternalResources() throws Exception {
ospfPipelineFactory.releaseExternalResources();
assertThat(channelPipeline, is(nullValue()));
}
}

View File

@ -74,8 +74,9 @@ public class LsaQueueConsumerTest {
@Test
public void testRun() throws Exception {
blockingQueue = new ArrayBlockingQueue(5);
channel = EasyMock.createMock(Channel.class);
ospfArea = new OspfAreaImpl();
lsdbAge = new LsdbAgeImpl(ospfArea);
channel = EasyMock.createMock(Channel.class);
lsaWrapper = new LsaWrapperImpl();
lsaWrapper.setLsaProcessing("verifyChecksum");
blockingQueue.add(lsaWrapper);
@ -104,7 +105,7 @@ public class LsaQueueConsumerTest {
lsaHeader.setLsType(1);
lsaWrapper.setLsaHeader(lsaHeader);
lsaWrapper.setLsaProcessing("refreshLsa");
lsaWrapper.setLsdbAge(new LsdbAgeImpl(new OspfAreaImpl()));
lsaWrapper.setLsdbAge(new LsdbAgeImpl(ospfArea));
blockingQueue.add(lsaWrapper);
lsaQueueConsumer = new LsaQueueConsumer(blockingQueue, channel, ospfArea);
lsaQueueConsumer.run();
@ -128,7 +129,7 @@ public class LsaQueueConsumerTest {
lsaHeader.setLsType(2);
lsaWrapper.setLsaHeader(lsaHeader);
lsaWrapper.setLsaProcessing("refreshLsa");
lsaWrapper.setLsdbAge(new LsdbAgeImpl(new OspfAreaImpl()));
lsaWrapper.setLsdbAge(new LsdbAgeImpl(ospfArea));
blockingQueue.add(lsaWrapper);
lsaQueueConsumer = new LsaQueueConsumer(blockingQueue, channel, ospfArea);
lsaQueueConsumer.run();
@ -155,7 +156,7 @@ public class LsaQueueConsumerTest {
lsaHeader.setLsType(2);
lsaWrapper.setLsaHeader(lsaHeader);
lsaWrapper.setLsaProcessing("maxAgeLsa");
lsaWrapper.setLsdbAge(new LsdbAgeImpl(new OspfAreaImpl()));
lsaWrapper.setLsdbAge(new LsdbAgeImpl(ospfArea));
blockingQueue.add(lsaWrapper);
lsaQueueConsumer = new LsaQueueConsumer(blockingQueue, channel, ospfArea);
lsaQueueConsumer.run();
@ -168,7 +169,7 @@ public class LsaQueueConsumerTest {
@Test
public void testSetChannel() throws Exception {
channel = EasyMock.createMock(Channel.class);
lsdbAge = new LsdbAgeImpl(new OspfAreaImpl());
lsdbAge = new LsdbAgeImpl(ospfArea);
lsdbAge.startDbAging();
lsdbAge.setChannel(channel);
assertThat(lsaQueueConsumer, is(notNullValue()));

View File

@ -23,6 +23,7 @@ import org.junit.Before;
import org.junit.Test;
import org.onosproject.ospf.controller.LsaBin;
import org.onosproject.ospf.controller.OspfArea;
import org.onosproject.ospf.controller.OspfLsaType;
import org.onosproject.ospf.controller.area.OspfAreaImpl;
import static org.hamcrest.CoreMatchers.*;
@ -181,14 +182,10 @@ public class LsdbAgeImplTest {
public void testRefereshLsa() throws Exception {
lsaWrapper = EasyMock.createMock(LsaWrapperImpl.class);
lsaWrapper.setBinNumber(0);
lsaWrapper.setLsaType(OspfLsaType.NETWORK);
lsdbAge.addLsaToMaxAgeBin("lsa1", lsaWrapper);
lsdbAge.ageLsaAndFlood();
lsaWrapper.setBinNumber(0);
lsaWrapper = EasyMock.createMock(LsaWrapperImpl.class);
lsdbAge.addLsaToMaxAgeBin("lsa2", lsaWrapper);
lsdbAge.ageLsaAndFlood();
lsdbAge.startDbAging();
lsaBin = new LsaBinImpl(1809);
lsdbAge.refreshLsa();
assertThat(lsdbAge, is(notNullValue()));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2016-present Open Networking Laboratory
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@ -102,6 +102,16 @@ public class NetworkLsa extends LsaHeader {
attachedRouters.add(attachedRouter);
}
/**
* Gets the list of attached routers.
*
* @return list of attached routers
*/
public List<Ip4Address> attachedRouters() {
return attachedRouters;
}
/**
* Reads from channel buffer and populate instance.
*

View File

@ -29,7 +29,6 @@ import org.onosproject.ospf.protocol.lsa.tlvtypes.OpaqueTopLevelTlvTypes;
import org.onosproject.ospf.protocol.lsa.tlvtypes.RouterTlv;
import org.onosproject.ospf.protocol.util.OspfParameters;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
@ -193,11 +192,11 @@ public class OpaqueLsa10 extends OpaqueLsaHeader {
}
OpaqueLsa10 that = (OpaqueLsa10) o;
return Objects.equal(topLevelValues, that.topLevelValues) &&
Arrays.equals(opaqueInfo, that.opaqueInfo);
Objects.equal(opaqueInfo, that.opaqueInfo);
}
@Override
public int hashCode() {
return Objects.hashCode(Arrays.hashCode(opaqueInfo), topLevelValues);
return Objects.hashCode(opaqueInfo, topLevelValues);
}
}

View File

@ -16,13 +16,12 @@
package org.onosproject.ospf.protocol.lsa.types;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.primitives.Bytes;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onosproject.ospf.controller.OspfLsaType;
import org.onosproject.ospf.protocol.lsa.OpaqueLsaHeader;
import java.util.Arrays;
/**
* Representation of an Opaque LSA of type AS (11).
*/
@ -107,12 +106,12 @@ public class OpaqueLsa11 extends OpaqueLsaHeader {
return false;
}
OpaqueLsa11 that = (OpaqueLsa11) o;
return Arrays.equals(opaqueInfo, that.opaqueInfo);
return Objects.equal(opaqueInfo, that.opaqueInfo);
}
@Override
public int hashCode() {
return Arrays.hashCode(opaqueInfo);
return Objects.hashCode(opaqueInfo);
}
@Override

View File

@ -16,13 +16,12 @@
package org.onosproject.ospf.protocol.lsa.types;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.primitives.Bytes;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onosproject.ospf.controller.OspfLsaType;
import org.onosproject.ospf.protocol.lsa.OpaqueLsaHeader;
import java.util.Arrays;
/**
* Representation of an Opaque LSA of type link local (9).
*/
@ -109,12 +108,12 @@ public class OpaqueLsa9 extends OpaqueLsaHeader {
return false;
}
OpaqueLsa9 that = (OpaqueLsa9) o;
return Arrays.equals(opaqueInfo, that.opaqueInfo);
return Objects.equal(opaqueInfo, that.opaqueInfo);
}
@Override
public int hashCode() {
return Arrays.hashCode(opaqueInfo);
return Objects.hashCode(opaqueInfo);
}
@Override

View File

@ -18,6 +18,7 @@ package org.onosproject.ospf.protocol.ospfpacket;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.controller.OspfMessage;
import org.onosproject.ospf.exceptions.OspfErrorType;
import org.onosproject.ospf.exceptions.OspfParseException;
import org.onosproject.ospf.protocol.ospfpacket.types.DdPacket;
@ -46,15 +47,8 @@ public class OspfMessageReader {
public OspfMessage readFromBuffer(ChannelBuffer channelBuffer)
throws Exception {
if (channelBuffer.readableBytes() < OspfUtil.PACKET_MINIMUM_LENGTH) {
log.error("Packet should have minimum length...");
throw new OspfParseException(OspfErrorType.MESSAGE_HEADER_ERROR, OspfErrorType.BAD_MESSAGE_LENGTH);
}
try {
OspfPacketHeader ospfHeader = getOspfHeader(channelBuffer);
int len = ospfHeader.ospfPacLength() - OspfUtil.OSPF_HEADER_LENGTH;
OspfMessage ospfMessage = null;
switch (ospfHeader.ospfType()) {
case OspfParameters.HELLO:
@ -81,7 +75,8 @@ public class OspfMessageReader {
try {
log.debug("{} Received::Message Length :: {} ", ospfMessage.ospfMessageType(),
ospfHeader.ospfPacLength());
ospfMessage.readFrom(channelBuffer.readBytes(len));
ospfMessage.readFrom(channelBuffer.readBytes(ospfHeader.ospfPacLength() -
OspfUtil.OSPF_HEADER_LENGTH));
} catch (Exception e) {
throw new OspfParseException(OspfErrorType.OSPF_MESSAGE_ERROR,
OspfErrorType.BAD_MESSAGE);
@ -105,22 +100,13 @@ public class OspfMessageReader {
private OspfPacketHeader getOspfHeader(ChannelBuffer channelBuffer) throws Exception {
OspfPacketHeader ospfPacketHeader = new OspfPacketHeader();
byte[] sourceIpBytes = new byte[OspfUtil.FOUR_BYTES];
channelBuffer.readBytes(sourceIpBytes, 0, OspfUtil.FOUR_BYTES);
Ip4Address sourceIP = Ip4Address.valueOf(sourceIpBytes);
// Determine ospf version & Packet Type
// Determine OSPF version & Packet Type
int version = channelBuffer.readByte(); //byte 1 is ospf version
int packetType = channelBuffer.readByte(); //byte 2 is ospf packet type
// byte 3 & 4 combine is packet length.
int packetLength = channelBuffer.readShort();
if (packetLength > channelBuffer.readableBytes() + OspfUtil.FOUR_BYTES) {
log.error("Packet should have minimum length...");
throw new OspfParseException(OspfErrorType.MESSAGE_HEADER_ERROR, OspfErrorType.BAD_MESSAGE_LENGTH);
}
byte[] tempByteArray = new byte[OspfUtil.FOUR_BYTES];
channelBuffer.readBytes(tempByteArray, 0, OspfUtil.FOUR_BYTES);
Ip4Address routerId = Ip4Address.valueOf(tempByteArray);
@ -133,7 +119,6 @@ public class OspfMessageReader {
int auType = channelBuffer.readUnsignedShort();
int authentication = (int) channelBuffer.readLong();
ospfPacketHeader.setSourceIp(sourceIP);
ospfPacketHeader.setOspfVer(version);
ospfPacketHeader.setOspftype(packetType);
ospfPacketHeader.setOspfPacLength(packetLength);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2016-present Open Networking Laboratory
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -15,41 +15,36 @@
*/
package org.onosproject.ospf.protocol.ospfpacket;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.onosproject.ospf.controller.OspfMessage;
import org.onosproject.ospf.protocol.util.OspfParameters;
import org.onosproject.ospf.protocol.util.OspfUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A message writer which writes an OspfMessage to ChannelBuffer.
* A message writer which writes an OSPF message to byte array.
*/
public class OspfMessageWriter {
private static final Logger log = LoggerFactory.getLogger(OspfMessageWriter.class);
/**
* Writes OSPF message to ChannelBuffer.
* Writes OSPF message to byte array.
*
* @param ospfMessage OSPF message
* @param interfaceIndex interface index
* @param interfaceState interface state
* @param interfaceType interface type
* @return channelBuffer channel buffer instance
* @throws Exception might throws exception while parsing message
* @return message as byte array
*/
public ChannelBuffer writeToBuffer(OspfMessage ospfMessage, int interfaceState,
int interfaceType) throws Exception {
public byte[] getMessage(OspfMessage ospfMessage, int interfaceIndex, int interfaceState) {
ChannelBuffer buf = null;
byte[] buf = null;
switch (ospfMessage.ospfMessageType().value()) {
case OspfParameters.HELLO:
case OspfParameters.LSACK:
buf = writeMessageToBuffer(ospfMessage, interfaceState);
break;
case OspfParameters.DD:
case OspfParameters.LSREQUEST:
case OspfParameters.LSUPDATE:
buf = writeMessageToBuffer(ospfMessage, interfaceState);
buf = writeMessageToBytes(ospfMessage, interfaceIndex, interfaceState);
break;
default:
log.debug("Message Writer[Encoder] - Unknown Message to encode..!!!");
@ -60,14 +55,13 @@ public class OspfMessageWriter {
}
/**
* Writes an OSPF Message to channel buffer.
* Writes an OSPF Message to byte array.
*
* @param ospfMessage OSPF Message instance
* @param interfaceState interface state
* @return channelBuffer instance
* @return message as byte array
*/
private ChannelBuffer writeMessageToBuffer(OspfMessage ospfMessage, int interfaceState) throws Exception {
ChannelBuffer channelBuffer = null;
private byte[] writeMessageToBytes(OspfMessage ospfMessage, int interfaceIndex, int interfaceState) {
byte[] ospfMessageAsByte = ospfMessage.asBytes();
//Add the length and checksum in byte array at length position 2 & 3 and Checksum position
ospfMessageAsByte = OspfUtil.addLengthAndCheckSum(ospfMessageAsByte, OspfUtil.OSPFPACKET_LENGTH_POS1,
@ -76,16 +70,13 @@ public class OspfMessageWriter {
OspfUtil.OSPFPACKET_CHECKSUM_POS2);
//Add Interface State Info and destination IP as metadata
if (interfaceState == OspfParameters.DR || interfaceState == OspfParameters.BDR) {
ospfMessageAsByte = OspfUtil.addMetadata(ospfMessageAsByte, OspfUtil.JOIN_ALL_DROUTERS,
ospfMessageAsByte = OspfUtil.addMetadata(interfaceIndex, ospfMessageAsByte, OspfUtil.JOIN_ALL_DROUTERS,
ospfMessage.destinationIp());
} else {
ospfMessageAsByte = OspfUtil.addMetadata(ospfMessageAsByte, OspfUtil.ONLY_ALL_SPF_ROUTERS,
ospfMessageAsByte = OspfUtil.addMetadata(interfaceIndex, ospfMessageAsByte, OspfUtil.ONLY_ALL_SPF_ROUTERS,
ospfMessage.destinationIp());
}
channelBuffer = ChannelBuffers.buffer(ospfMessageAsByte.length);
channelBuffer.writeBytes(ospfMessageAsByte);
return channelBuffer;
return ospfMessageAsByte;
}
}

View File

@ -18,8 +18,9 @@ package org.onosproject.ospf.protocol.ospfpacket;
import com.google.common.base.MoreObjects;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.controller.OspfMessage;
import org.onosproject.ospf.controller.OspfPacketType;
import org.onosproject.ospf.exceptions.OspfParseException;
import org.onosproject.ospf.protocol.util.OspfPacketType;
/**
* Defines the OSPF Packet Header, fields and access methods.
@ -57,6 +58,7 @@ public class OspfPacketHeader implements OspfMessage {
private int authentication;
private Ip4Address destinationIp;
private Ip4Address sourceIp;
private int interfaceIndex;
/**
* Gets the source IP.
@ -255,12 +257,31 @@ public class OspfPacketHeader implements OspfMessage {
this.destinationIp = destinationIp;
}
/**
* Returns the interface index on which the message received.
*
* @return interface index on which the message received
*/
public int interfaceIndex() {
return interfaceIndex;
}
/**
* Sets the interface index on which the message received.
*
* @param interfaceIndex interface index on which the message received
*/
public void setInterfaceIndex(int interfaceIndex) {
this.interfaceIndex = interfaceIndex;
}
/**
* Populates the header from the packetHeader instance.
*
* @param ospfPacketHeader packet header instance.
*/
public void populateHeader(OspfPacketHeader ospfPacketHeader) {
this.setInterfaceIndex(ospfPacketHeader.interfaceIndex());
this.setSourceIp(ospfPacketHeader.sourceIp());
this.setOspfVer(ospfPacketHeader.ospfVersion());
this.setOspftype(ospfPacketHeader.ospfType());

View File

@ -23,7 +23,7 @@ import org.onosproject.ospf.exceptions.OspfParseException;
import org.onosproject.ospf.protocol.lsa.LsaHeader;
import org.onosproject.ospf.protocol.lsa.OpaqueLsaHeader;
import org.onosproject.ospf.protocol.ospfpacket.OspfPacketHeader;
import org.onosproject.ospf.protocol.util.OspfPacketType;
import org.onosproject.ospf.controller.OspfPacketType;
import org.onosproject.ospf.protocol.util.OspfParameters;
import org.onosproject.ospf.protocol.util.OspfUtil;
import org.slf4j.Logger;

View File

@ -22,7 +22,7 @@ import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.exceptions.OspfErrorType;
import org.onosproject.ospf.exceptions.OspfParseException;
import org.onosproject.ospf.protocol.ospfpacket.OspfPacketHeader;
import org.onosproject.ospf.protocol.util.OspfPacketType;
import org.onosproject.ospf.controller.OspfPacketType;
import org.onosproject.ospf.protocol.util.OspfUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -23,7 +23,7 @@ import org.onosproject.ospf.exceptions.OspfParseException;
import org.onosproject.ospf.protocol.lsa.LsaHeader;
import org.onosproject.ospf.protocol.lsa.OpaqueLsaHeader;
import org.onosproject.ospf.protocol.ospfpacket.OspfPacketHeader;
import org.onosproject.ospf.protocol.util.OspfPacketType;
import org.onosproject.ospf.controller.OspfPacketType;
import org.onosproject.ospf.protocol.util.OspfParameters;
import org.onosproject.ospf.protocol.util.OspfUtil;
import org.slf4j.Logger;

View File

@ -22,7 +22,7 @@ import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.exceptions.OspfParseException;
import org.onosproject.ospf.protocol.ospfpacket.OspfPacketHeader;
import org.onosproject.ospf.protocol.ospfpacket.subtype.LsRequestPacket;
import org.onosproject.ospf.protocol.util.OspfPacketType;
import org.onosproject.ospf.controller.OspfPacketType;
import org.onosproject.ospf.protocol.util.OspfUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -32,7 +32,7 @@ import org.onosproject.ospf.protocol.lsa.types.OpaqueLsa9;
import org.onosproject.ospf.protocol.lsa.types.RouterLsa;
import org.onosproject.ospf.protocol.lsa.types.SummaryLsa;
import org.onosproject.ospf.protocol.ospfpacket.OspfPacketHeader;
import org.onosproject.ospf.protocol.util.OspfPacketType;
import org.onosproject.ospf.controller.OspfPacketType;
import org.onosproject.ospf.protocol.util.OspfParameters;
import org.onosproject.ospf.protocol.util.OspfUtil;
import org.slf4j.Logger;

View File

@ -25,7 +25,7 @@ import org.onosproject.ospf.protocol.lsa.types.OpaqueLsa11;
import org.onosproject.ospf.protocol.lsa.types.OpaqueLsa9;
import org.onosproject.ospf.protocol.lsa.types.RouterLsa;
import org.onosproject.ospf.protocol.lsa.types.SummaryLsa;
import org.onosproject.ospf.protocol.ospfpacket.OspfMessage;
import org.onosproject.ospf.controller.OspfMessage;
import org.onosproject.ospf.protocol.ospfpacket.types.DdPacket;
import org.onosproject.ospf.protocol.ospfpacket.types.HelloPacket;
import org.onosproject.ospf.protocol.ospfpacket.types.LsAcknowledge;

View File

@ -31,20 +31,55 @@ public enum OspfInterfaceState {
private int value;
/**
* Creates an instance of Interface State.
* Creates an instance of interface state.
*
* @param value Interface State value
* @param value Interface state value
*/
OspfInterfaceState(int value) {
this.value = value;
}
/**
* Gets value for Interface State.
* Gets value for Interface state.
*
* @return value Interface State
* @return value Interface state
*/
public int value() {
return value;
}
/**
* Gets interface state.
*
* @return interface state
*/
public String interfaceState() {
String state = null;
switch (value) {
case 1:
state = "DOWN";
break;
case 2:
state = "LOOPBACK";
break;
case 3:
state = "WAITING";
break;
case 4:
state = "POINT2POINT";
break;
case 5:
state = "DROTHER";
break;
case 6:
state = "BDR";
break;
case 7:
state = "DR";
break;
default:
break;
}
return state;
}
}

View File

@ -36,10 +36,11 @@ import java.util.StringTokenizer;
* Representation of an OSPF constants and utility methods.
*/
public final class OspfUtil {
public static final int OSPF_VERSION_2 = 2;
public static final int OSPF_VERSION = OSPF_VERSION_2;
public static final int PACKET_MINIMUM_LENGTH = 24;
public static final int METADATA_LEN = 5;
public static final int MINIMUM_FRAME_LEN = 1487;
public static final int OSPF_HEADER_LENGTH = 24;
public static final int LSA_HEADER_LENGTH = 20;
public static final int DD_HEADER_LENGTH = OSPF_HEADER_LENGTH + 8;
@ -52,6 +53,8 @@ public final class OspfUtil {
public static final int LSAPACKET_CHECKSUM_POS2 = 17;
public static final Ip4Address ALL_SPF_ROUTERS = Ip4Address.valueOf("224.0.0.5");
public static final Ip4Address ALL_DROUTERS = Ip4Address.valueOf("224.0.0.6");
public static final Ip4Address DEFAULTIP = Ip4Address.valueOf("0.0.0.0");
public static final int RETRANSMITINTERVAL = 5;
public static final int ONLY_ALL_SPF_ROUTERS = 1;
public static final int JOIN_ALL_DROUTERS = 2;
public static final int INITIALIZE_SET = 1;
@ -62,9 +65,16 @@ public final class OspfUtil {
public static final int NOT_MASTER = 0;
public static final int NOT_ASSIGNED = 0;
public static final int FOUR_BYTES = 4;
public static final int FIVE_BYTES = 5;
public static final int EIGHT_BYTES = 8;
public static final int TWELVE_BYTES = 12;
public static final int EXTERNAL_DESTINATION_LENGTH = 12;
public static final String SHOST = "127.0.0.1";
public static final int SPORT = 7000;
public static final int MTU = 1500;
public static final char CONFIG_LENGTH = 1498;
public static final char ROUTER_PRIORITY = 0;
public static final int HELLO_PACKET_OPTIONS = 2;
private static final Logger log =
LoggerFactory.getLogger(OspfUtil.class);
@ -398,18 +408,21 @@ public final class OspfUtil {
/**
* Adds metadata to ospf packet like whether to join multi cast group and destination IP.
*
* @param interfaceIndex interface index
* @param ospfPacket OSPF packet
* @param allDroutersValue whether to join multi cast or not
* @param destinationIp destination ip address
* @return byte array
*/
public static byte[] addMetadata(byte[] ospfPacket, int allDroutersValue, Ip4Address destinationIp) {
public static byte[] addMetadata(int interfaceIndex, byte[] ospfPacket, int allDroutersValue,
Ip4Address destinationIp) {
byte[] packet;
byte[] interfaceIndexByteVal = {(byte) interfaceIndex};
byte[] allDroutersByteVal = {(byte) allDroutersValue};
byte[] destIpAsBytes = destinationIp.toOctets();
byte[] metadata = Bytes.concat(allDroutersByteVal, destIpAsBytes);
packet = Bytes.concat(metadata, ospfPacket);
byte[] metadata = Bytes.concat(interfaceIndexByteVal, allDroutersByteVal);
metadata = Bytes.concat(metadata, destIpAsBytes);
packet = Bytes.concat(ospfPacket, metadata);
return packet;
}

View File

@ -20,6 +20,7 @@ import org.jboss.netty.buffer.ChannelBuffers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onosproject.ospf.protocol.util.OspfUtil;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
@ -31,17 +32,17 @@ import static org.hamcrest.MatcherAssert.assertThat;
public class OspfMessageReaderTest {
private final byte[] packet1 = {1, 1, 1, 1, 2, 1, 0, 44, -64, -88, -86, 8,
private final byte[] packet1 = {2, 1, 0, 44, -64, -88, -86, 8,
0, 0, 0, 1, 39, 59, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, 0, 0,
10, 2, 1, 0, 0, 0, 40, -64, -88, -86, 8, 0, 0, 0, 0};
private final byte[] packet2 = {1, 1, 1, 1, 2, 2, 0, 52, -64, -88, -86, 8, 0,
private final byte[] packet2 = {2, 2, 0, 52, -64, -88, -86, 8, 0,
0, 0, 1, -96, 82, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, -36, 2, 7, 65, 119,
-87, 126, 0, 23, 2, 1, 10, 10, 10, 10, 10, 10, 10, 10, -128, 0, 0, 6,
-69, 26, 0, 36};
private final byte[] packet3 = {1, 1, 1, 1, 2, 3, 0, 36, -64, -88, -86, 3, 0,
private final byte[] packet3 = {2, 3, 0, 36, -64, -88, -86, 3, 0,
0, 0, 1, -67, -57, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -64, -88,
-86, 8, -64, -88, -86, 8};
private final byte[] packet4 = {1, 1, 1, 1, 2, 4, 1, 36, -64, -88, -86, 3, 0,
private final byte[] packet4 = {2, 4, 1, 36, -64, -88, -86, 3, 0,
0, 0, 1, 54, 107, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0,
2, 2, 1, -64, -88, -86, 3, -64, -88, -86, 3, -128, 0,
0, 1, 58, -100, 0, 48, 2, 0, 0, 2, -64, -88, -86,
@ -62,7 +63,7 @@ public class OspfMessageReaderTest {
0, 0, 0, 0, 0, 0, 0, 3, 2, 5, -64, -88, -84, 0, -64,
-88, -86, 2, -128, 0, 0, 1, 51, 65, 0, 36, -1, -1, -1, 0,
-128, 0, 0, 20, -64, -88, -86, 10, 0, 0, 0, 0};
private final byte[] packet5 = {1, 1, 1, 1, 2, 5, 0, 44, -64, -88, -86, 8, 0, 0,
private final byte[] packet5 = {2, 5, 0, 44, -64, -88, -86, 8, 0, 0,
0, 1, -30, -12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 16, 2, 1, -64, -88, -86,
2, -64, -88, -86, 2, -128, 0, 0, 1, 74, -114, 0, 48};
private OspfMessageReader ospfMessageReader;
@ -84,21 +85,39 @@ public class OspfMessageReaderTest {
*/
@Test
public void testReadFromBuffer() throws Exception {
channelBuffer = ChannelBuffers.copiedBuffer(packet1);
channelBuffer = ChannelBuffers.copiedBuffer(framePacket(packet1));
ospfMessageReader.readFromBuffer(channelBuffer);
channelBuffer = ChannelBuffers.copiedBuffer(packet2);
channelBuffer = ChannelBuffers.copiedBuffer(framePacket(packet2));
ospfMessageReader.readFromBuffer(channelBuffer);
channelBuffer = ChannelBuffers.copiedBuffer(packet3);
channelBuffer = ChannelBuffers.copiedBuffer(framePacket(packet3));
ospfMessageReader.readFromBuffer(channelBuffer);
channelBuffer = ChannelBuffers.copiedBuffer(packet4);
channelBuffer = ChannelBuffers.copiedBuffer(framePacket(packet4));
ospfMessageReader.readFromBuffer(channelBuffer);
channelBuffer = ChannelBuffers.copiedBuffer(packet5);
channelBuffer = ChannelBuffers.copiedBuffer(framePacket(packet5));
ospfMessageReader.readFromBuffer(channelBuffer);
assertThat(ospfMessageReader, is(notNullValue()));
}
/**
* Frames the packet to min frame length.
*
* @param ospfPacket OSPF packet
* @return OSPF packet as byte array
*/
private byte[] framePacket(byte[] ospfPacket) {
//Set the length of the packet
//Get the total length of the packet
int length = ospfPacket.length;
//PDU_LENGTH + 1 byte for interface index
if (length < OspfUtil.MINIMUM_FRAME_LEN) {
byte[] bytes = new byte[OspfUtil.MINIMUM_FRAME_LEN + 5];
System.arraycopy(ospfPacket, 0, bytes, 0, length);
return bytes;
}
return ospfPacket;
}
}

View File

@ -57,10 +57,10 @@ public class OspfMessageWriterTest {
}
/**
* Tests writeToBuffer() method.
* Tests getMessage() method.
*/
@Test
public void testWriteToBuffer() throws Exception {
public void testGetMessage() throws Exception {
helloPacket = new HelloPacket();
helloPacket.setAuthType(1);
helloPacket.setOspftype(1);
@ -79,12 +79,12 @@ public class OspfMessageWriterTest {
helloPacket.setBdr(Ip4Address.valueOf("2.2.2.2"));
helloPacket.addNeighbor(Ip4Address.valueOf("8.8.8.8"));
helloPacket.setDestinationIp(Ip4Address.valueOf("5.5.5.5"));
ospfMessageWriter.writeToBuffer(helloPacket, 7, 1);
ospfMessageWriter.getMessage(helloPacket, 7, 1);
assertThat(ospfMessageWriter, is(notNullValue()));
}
@Test(expected = Exception.class)
public void testWriteToBuffer1() throws Exception {
public void testGetMessage1() throws Exception {
ddPacket = new DdPacket();
ddPacket.setAuthType(1);
@ -95,12 +95,12 @@ public class OspfMessageWriterTest {
ddPacket.setAuthentication(2);
ddPacket.setOspfPacLength(48);
ddPacket.setOspfVer(2);
ospfMessageWriter.writeToBuffer(ddPacket, 1, 1);
ospfMessageWriter.getMessage(ddPacket, 1, 1);
assertThat(ospfMessageWriter, is(notNullValue()));
}
@Test(expected = Exception.class)
public void testWriteToBuffer2() throws Exception {
public void testGetMessage2() throws Exception {
lsAck = new LsAcknowledge();
lsAck.setAuthType(1);
@ -111,12 +111,12 @@ public class OspfMessageWriterTest {
lsAck.setAuthentication(2);
lsAck.setOspfPacLength(48);
lsAck.setOspfVer(2);
ospfMessageWriter.writeToBuffer(lsAck, 1, 1);
ospfMessageWriter.getMessage(lsAck, 1, 1);
assertThat(ospfMessageWriter, is(notNullValue()));
}
@Test(expected = Exception.class)
public void testWriteToBuffer3() throws Exception {
public void testGetMessage3() throws Exception {
lsReq = new LsRequest();
lsReq.setAuthType(1);
lsReq.setOspftype(3);
@ -126,12 +126,15 @@ public class OspfMessageWriterTest {
lsReq.setAuthentication(2);
lsReq.setOspfPacLength(48);
lsReq.setOspfVer(2);
ospfMessageWriter.writeToBuffer(lsReq, 1, 1);
ospfMessageWriter.getMessage(lsReq, 1, 1);
assertThat(ospfMessageWriter, is(notNullValue()));
}
/**
* Tests getMessage() method.
*/
@Test(expected = Exception.class)
public void testWriteToBuffer4() throws Exception {
public void testGetMessage4() throws Exception {
lsUpdate = new LsUpdate();
lsUpdate.setAuthType(1);
lsUpdate.setOspftype(3);
@ -141,15 +144,15 @@ public class OspfMessageWriterTest {
lsUpdate.setAuthentication(2);
lsUpdate.setOspfPacLength(48);
lsUpdate.setOspfVer(2);
ospfMessageWriter.writeToBuffer(lsUpdate, 1, 1);
ospfMessageWriter.getMessage(lsUpdate, 1, 1);
assertThat(ospfMessageWriter, is(notNullValue()));
}
/**
* Tests writeToBuffer() method.
* Tests getMessage() method.
*/
@Test(expected = Exception.class)
public void testWriteToBuffer5() throws Exception {
public void testGetMessage5() throws Exception {
lsAck = new LsAcknowledge();
lsAck.setAuthType(1);
lsAck.setOspftype(5);
@ -159,6 +162,6 @@ public class OspfMessageWriterTest {
lsAck.setAuthentication(2);
lsAck.setOspfPacLength(48);
lsAck.setOspfVer(2);
ospfMessageWriter.writeToBuffer(lsAck, 1, 1);
ospfMessageWriter.getMessage(lsAck, 1, 1);
}
}

View File

@ -22,10 +22,10 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.controller.OspfPacketType;
import org.onosproject.ospf.protocol.lsa.LsaHeader;
import org.onosproject.ospf.protocol.lsa.OpaqueLsaHeader;
import org.onosproject.ospf.protocol.ospfpacket.OspfPacketHeader;
import org.onosproject.ospf.protocol.util.OspfPacketType;
import java.util.List;
import java.util.Vector;

View File

@ -21,8 +21,8 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.controller.OspfPacketType;
import org.onosproject.ospf.protocol.ospfpacket.OspfPacketHeader;
import org.onosproject.ospf.protocol.util.OspfPacketType;
import java.util.Vector;

View File

@ -22,10 +22,10 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.controller.OspfPacketType;
import org.onosproject.ospf.protocol.lsa.LsaHeader;
import org.onosproject.ospf.protocol.lsa.OpaqueLsaHeader;
import org.onosproject.ospf.protocol.ospfpacket.OspfPacketHeader;
import org.onosproject.ospf.protocol.util.OspfPacketType;
import java.util.List;

View File

@ -21,9 +21,9 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.controller.OspfPacketType;
import org.onosproject.ospf.protocol.ospfpacket.OspfPacketHeader;
import org.onosproject.ospf.protocol.ospfpacket.subtype.LsRequestPacket;
import org.onosproject.ospf.protocol.util.OspfPacketType;
import java.net.UnknownHostException;
import java.util.List;

View File

@ -22,6 +22,7 @@ import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.controller.OspfLsa;
import org.onosproject.ospf.controller.OspfPacketType;
import org.onosproject.ospf.protocol.lsa.LsaHeader;
import org.onosproject.ospf.protocol.lsa.OpaqueLsaHeader;
import org.onosproject.ospf.protocol.lsa.types.AsbrSummaryLsa;
@ -33,7 +34,6 @@ import org.onosproject.ospf.protocol.lsa.types.OpaqueLsa9;
import org.onosproject.ospf.protocol.lsa.types.RouterLsa;
import org.onosproject.ospf.protocol.lsa.types.SummaryLsa;
import org.onosproject.ospf.protocol.ospfpacket.OspfPacketHeader;
import org.onosproject.ospf.protocol.util.OspfPacketType;
import java.util.List;
import java.util.Vector;

View File

@ -229,7 +229,7 @@ public class OspfUtilTest {
*/
@Test
public void testAddMetadata() throws Exception {
result1 = OspfUtil.addMetadata(packet, 123, Ip4Address.valueOf("1.1.1.1"));
result1 = OspfUtil.addMetadata(2, packet, 1, Ip4Address.valueOf("1.1.1.1"));
assertThat(result1, is(notNullValue()));
}
@ -251,7 +251,7 @@ public class OspfUtilTest {
*/
@Test
public void testAddMetaData() throws Exception {
result1 = OspfUtil.addMetadata(packet, 1, Ip4Address.valueOf("2.2.2.2"));
result1 = OspfUtil.addMetadata(2, packet, 1, Ip4Address.valueOf("2.2.2.2"));
assertThat(result1, is(notNullValue()));
}

16
providers/ospf/BUCK Normal file
View File

@ -0,0 +1,16 @@
BUNDLES = [
'//protocols/ospf/api:onos-protocols-ospf-api',
'//protocols/ospf/ctl:onos-protocols-ospf-ctl',
'//protocols/ospf/protocol:onos-protocols-ospf-protocol',
'//providers/ospf/cfg:onos-providers-ospf-cfg',
'//providers/ospf/topology:onos-providers-ospf-topology',
]
onos_app (
title = 'OSPF Provider',
category = 'Provider',
url = 'http://onosproject.org',
description = 'ONOS OSPF protocol adapters.',
included_bundles = BUNDLES,
)

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2016-present Open Networking Laboratory
~
~ 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.
-->
<app name="org.onosproject.ospf" origin="ON.Lab" version="${project.version}"
featuresRepo="mvn:${project.groupId}/${project.artifactId}/${project.version}/xml/features"
features="${project.artifactId}">
<description>${project.description}</description>
<artifact>mvn:${project.groupId}/onos-ospf-api/${project.version}</artifact>
<artifact>mvn:${project.groupId}/onos-ospf-ctl/${project.version}</artifact>
<artifact>mvn:${project.groupId}/onos-ospf-protocol/${project.version}</artifact>
<artifact>mvn:${project.groupId}/onos-ospf-provider-topology/${project.version}</artifact>
<artifact>mvn:${project.groupId}/onos-ospf-provider-cfg/${project.version}</artifact>
<artifact>mvn:${project.groupId}/onos-ospf-provider-cli/${project.version}</artifact>
</app>

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ Copyright 2016-present Open Networking Laboratory
~
~ 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.
-->
<features xmlns="http://karaf.apache.org/xmlns/features/v1.2.0" name="${project.artifactId}-${project.version}">
<feature name="${project.artifactId}" version="${project.version}"
description="${project.description}">
<feature>onos-api</feature>
<bundle>mvn:${project.groupId}/onos-ospf-api/${project.version}</bundle>
<bundle>mvn:${project.groupId}/onos-ospf-ctl/${project.version}</bundle>
<bundle>mvn:${project.groupId}/onos-ospf-protocol/${project.version}</bundle>
<bundle>mvn:${project.groupId}/onos-ospf-provider-topology/${project.version}</bundle>
<bundle>mvn:${project.groupId}/onos-ospf-provider-cfg/${project.version}</bundle>
<bundle>mvn:${project.groupId}/onos-ospf-provider-cli/${project.version}</bundle>
</feature>
</features>

View File

@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2016-present Open Networking Laboratory
~
~ 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.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-providers</artifactId>
<version>1.7.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>onos-ospf-app</artifactId>
<packaging>pom</packaging>
<description>OSPF protocol southbound providers</description>
<dependencies>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-ctl</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-protocol</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-provider-topology</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-provider-cfg</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-provider-cli</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

9
providers/ospf/cfg/BUCK Normal file
View File

@ -0,0 +1,9 @@
COMPILE_DEPS = [
'//lib:CORE_DEPS',
'//protocols/ospf/api:onos-protocols-ospf-api',
]
osgi_jar_with_tests (
deps = COMPILE_DEPS,
)

View File

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2016-present Open Networking Laboratory
~
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-providers</artifactId>
<version>1.7.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>onos-ospf-provider-cfg</artifactId>
<packaging>bundle</packaging>
<description>ONOS OSPF Providers</description>
<dependencies>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.compendium</artifactId>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-ctl</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-api</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,72 @@
/*
* Copyright 2016-present Open Networking Laboratory
*
* 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 org.onosproject.provider.ospf.cfg.impl;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.onlab.osgi.DefaultServiceDirectory;
import org.onosproject.core.ApplicationId;
import org.onosproject.net.config.Config;
import org.onosproject.ospf.controller.OspfController;
/**
* Configuration object for OSPF.
*/
public class OspfAppConfig extends Config<ApplicationId> {
public static final String METHOD = "method";
public static final String ATTRIBUTE = "attribute";
public static final String PROCESSES = "processes";
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
private OspfController ospfController;
/**
* Returns the configuration method, add, delete etc.
*
* @return the configuration method, add, delete etc
*/
public String method() {
return get(METHOD, null);
}
/**
* Returns the configuration attribute, area, process etc.
*
* @return the configuration attribute, area, process etc
*/
public String attribute() {
return get(ATTRIBUTE, null);
}
/**
* Returns the configured processes.
*
* @return the configured processes
*/
public JsonNode processes() {
JsonNode jsonNodes = object.get(PROCESSES);
return jsonNodes;
}
@Override
public boolean isValid() {
this.ospfController = DefaultServiceDirectory.getService(OspfController.class);
return true;
}
}

View File

@ -0,0 +1,129 @@
/*
* Copyright 2016-present Open Networking Laboratory
*
* 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 org.onosproject.provider.ospf.cfg.impl;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Service;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.net.config.ConfigFactory;
import org.onosproject.net.config.NetworkConfigEvent;
import org.onosproject.net.config.NetworkConfigListener;
import org.onosproject.net.config.NetworkConfigRegistry;
import org.onosproject.net.config.NetworkConfigService;
import org.onosproject.net.config.basics.SubjectFactories;
import org.onosproject.net.provider.AbstractProvider;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.ospf.controller.OspfController;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Provider which advertises device descriptions to the core.
*/
@Component(immediate = true)
@Service
public class OspfCfgProvider extends AbstractProvider {
static final String PROVIDER_ID = "org.onosproject.provider.ospf.cfg";
private static final Logger log = getLogger(OspfCfgProvider.class);
private final ConfigFactory configFactory =
new ConfigFactory(SubjectFactories.APP_SUBJECT_FACTORY, OspfAppConfig.class, "ospfapp") {
@Override
public OspfAppConfig createConfig() {
return new OspfAppConfig();
}
};
private final NetworkConfigListener configListener = new InternalConfigListener();
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected OspfController ospfController;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected CoreService coreService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected NetworkConfigRegistry configRegistry;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected NetworkConfigService configService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected OspfController controller;
private ApplicationId appId;
/**
* Creates an OSPF device provider.
*/
public OspfCfgProvider() {
super(new ProviderId("ospf", PROVIDER_ID));
}
public void setOspfController(OspfController ospfController) {
this.ospfController = ospfController;
}
@Activate
public void activate() {
appId = coreService.registerApplication(PROVIDER_ID);
configService.addListener(configListener);
configRegistry.registerConfigFactory(configFactory);
log.info("activated...!!!");
}
@Deactivate
public void deactivate() {
configRegistry.unregisterConfigFactory(configFactory);
configService.removeListener(configListener);
log.info("deactivated...!!!");
}
private void updateConfig() {
OspfAppConfig ospfAppConfig = configRegistry.getConfig(appId, OspfAppConfig.class);
if ("ADD".equalsIgnoreCase(ospfAppConfig.method())) {
JsonNode jsonNode = ospfAppConfig.processes();
ospfController.updateConfig(jsonNode);
} else {
log.debug("Please signify prop1 and prop2");
}
}
/**
* OSPF config listener to populate the configuration.
*/
private class InternalConfigListener implements NetworkConfigListener {
@Override
public void event(NetworkConfigEvent event) {
log.debug("InternalConfigListener:: event is getting called");
if (!event.configClass().equals(OspfAppConfig.class)) {
return;
}
switch (event.type()) {
case CONFIG_ADDED:
updateConfig();
break;
case CONFIG_UPDATED:
updateConfig();
break;
case CONFIG_REMOVED:
break;
default:
break;
}
}
}
}

View File

@ -0,0 +1,20 @@
/*
* Copyright 2016-present Open Networking Laboratory
*
* 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.
*/
/**
* Provider that uses OSPF capability request as a means of infrastructure device discovery.
*/
package org.onosproject.provider.ospf.cfg.impl;

View File

@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2016-present Open Networking Laboratory
~
~ 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.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-providers</artifactId>
<version>1.7.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>onos-ospf-provider-cli</artifactId>
<packaging>bundle</packaging>
<description>OSPF cli implementation</description>
<dependencies>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-cli</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-ctl</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-protocol</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.compendium</artifactId>
</dependency>
<dependency>
<groupId>org.apache.karaf.shell</groupId>
<artifactId>org.apache.karaf.shell.console</artifactId>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.scr.annotations</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,401 @@
/*
* Copyright 2016-present Open Networking Laboratory
*
* 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 org.onosproject.ospf.cli;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.ospf.controller.OspfArea;
import org.onosproject.ospf.controller.OspfController;
import org.onosproject.ospf.controller.OspfInterface;
import org.onosproject.ospf.controller.OspfLsaType;
import org.onosproject.ospf.controller.OspfNbr;
import org.onosproject.ospf.controller.OspfProcess;
import org.onosproject.ospf.protocol.lsa.LsaHeader;
import org.onosproject.ospf.protocol.lsa.types.RouterLsa;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Representation of OSPF cli commands.
*/
@Component(immediate = true)
@Command(scope = "onos", name = "ospf", description = "list database")
public class ApplicationOspfCommand extends AbstractShellCommand {
protected static final String FORMAT6 = "%-20s%-20s%-20s%-20s%-20s%-20s\n";
protected static final String FORMAT5 = "%-20s%-20s%-20s%-20s%-20s\n";
protected static final String NETWORK = "NETWORK";
protected static final String SUMMARY = "SUMMARY";
protected static final String ASBR = "ABSR";
protected static final String EXTERNAL = "EXTERNAL";
protected static final String LINKLOOPAQ = "LINKLOCALOPAQUE";
protected static final String AREALOCOPAQ = "AREALOCALOPAQUE";
protected static final String ASOPAQ = "ASOPAQUE";
protected static final String DR = "DR";
protected static final String BACKUP = "BACKUP";
protected static final String DROTHER = "DROther";
static final String DATABASE = "database";
static final String NEIGHBORLIST = "neighbors";
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected OspfController ospfController;
@Argument(index = 0, name = "name",
description = "database|neighborlist",
required = true, multiValued = false)
private String name = null;
@Argument(index = 1, name = "processid",
description = "processId",
required = true, multiValued = false)
private String process = null;
@Argument(index = 2, name = "areaid",
description = "areaId",
required = false, multiValued = false)
private String area = null;
private List<String> routerLsa = new ArrayList<>();
private List<String> networkLsa = new ArrayList<>();
private List<String> summaryLsa = new ArrayList<>();
private List<String> externalLsa = new ArrayList<>();
private List<String> asbrSumm = new ArrayList<>();
private List<String> areaLocalOpaqLsa = new ArrayList<>();
private List<String> linkLocalOpqLsa = new ArrayList<>();
private List<String> asOpqLsa = new ArrayList<>();
private List<String> undefinedLsa = new ArrayList<>();
private List<OspfArea> areaList = new ArrayList<>();
@Activate
public void activate() {
print("OSPF cli activated...!!!");
log.debug("OSPF cli activated...!!!");
}
@Deactivate
public void deactivate() {
log.debug("OSPF cli deactivated...!!!");
}
@Override
protected void execute() {
if (DATABASE.equals(name)) {
buildOspfDatabaseInformation();
} else if (NEIGHBORLIST.equals(name)) {
buildNeighborInformation();
} else {
print("Please check the command (database|neighbor)");
}
}
/**
* Clears all the lists.
*/
private void clearLists() {
routerLsa.clear();
networkLsa.clear();
summaryLsa.clear();
externalLsa.clear();
asbrSumm.clear();
areaLocalOpaqLsa.clear();
linkLocalOpqLsa.clear();
asOpqLsa.clear();
undefinedLsa.clear();
areaList.clear();
}
/**
* Builds OSPF database information.
*/
private void buildOspfDatabaseInformation() {
try {
//Builds LSA details
buildLsaLists();
for (OspfArea area : areaList) {
if (routerLsa.size() > 0) {
printRouterFormat(area.areaId().toString(), area.routerId().toString(), process);
for (String str : routerLsa) {
String[] lsaVal = str.split("\\,");
if (area.areaId().toString().equalsIgnoreCase(lsaVal[0])) {
print(FORMAT6, lsaVal[2], lsaVal[3], lsaVal[4], lsaVal[5], lsaVal[6], lsaVal[7]);
}
}
}
if (networkLsa.size() > 0) {
printNetworkFormat(area.areaId().toString(), NETWORK);
printDetails(networkLsa, area.areaId().toString());
}
if (summaryLsa.size() > 0) {
printNetworkFormat(area.areaId().toString(), SUMMARY);
printDetails(summaryLsa, area.areaId().toString());
}
if (externalLsa.size() > 0) {
printNetworkFormat(area.areaId().toString(), EXTERNAL);
printDetails(externalLsa, area.areaId().toString());
}
if (asbrSumm.size() > 0) {
printNetworkFormat(area.areaId().toString(), ASBR);
printDetails(asbrSumm, area.areaId().toString());
}
if (areaLocalOpaqLsa.size() > 0) {
printNetworkFormat(area.areaId().toString(), AREALOCOPAQ);
printDetails(areaLocalOpaqLsa, area.areaId().toString());
}
if (linkLocalOpqLsa.size() > 0) {
printNetworkFormat(area.areaId().toString(), LINKLOOPAQ);
printDetails(linkLocalOpqLsa, area.areaId().toString());
}
if (asOpqLsa.size() > 0) {
printNetworkFormat(area.areaId().toString(), ASOPAQ);
printDetails(asOpqLsa, area.areaId().toString());
}
if (undefinedLsa.size() > 0) {
printRouterFormat(area.areaId().toString(), area.routerId().toString(), process);
printDetails(undefinedLsa, area.areaId().toString());
}
}
clearLists();
} catch (Exception ex) {
clearLists();
print("Error occured while Ospf controller getting called" + ex.getMessage());
}
}
/**
* Prints LSA details.
*
* @param lsaDetails LSA details
* @param areaId area ID
*/
private void printDetails(List<String> lsaDetails, String areaId) {
for (String str : lsaDetails) {
String[] lsaVal = str.split("\\,");
if (areaId.equalsIgnoreCase(lsaVal[0])) {
print(FORMAT5, lsaVal[2], lsaVal[3], lsaVal[4], lsaVal[5], lsaVal[6]);
}
}
}
/**
* Builds all LSA lists with LSA details.
*/
private void buildLsaLists() {
this.ospfController = get(OspfController.class);
List<OspfProcess> listOfProcess = ospfController.getAllConfiguredProcesses();
Iterator<OspfProcess> itrProcess = listOfProcess.iterator();
while (itrProcess.hasNext()) {
OspfProcess ospfProcess = itrProcess.next();
if (process.equalsIgnoreCase(ospfProcess.processId())) {
List<OspfArea> listAreas = ospfProcess.areas();
Iterator<OspfArea> itrArea = listAreas.iterator();
while (itrArea.hasNext()) {
OspfArea area = itrArea.next();
List<LsaHeader> lsas = area.database()
.getAllLsaHeaders(false, area.isOpaqueEnabled());
List<LsaHeader> tmpLsaList = new ArrayList<>(lsas);
log.debug("OSPFController::size of database::" + (lsas != null ? lsas.size() : null));
Iterator<LsaHeader> itrLsaHeader = tmpLsaList.iterator();
areaList.add(area);
if (itrLsaHeader != null) {
while (itrLsaHeader.hasNext()) {
LsaHeader header = itrLsaHeader.next();
populateLsaLists(header, area);
}
}
}
}
}
}
/**
* Populates the LSA lists based on the input.
*
* @param header LSA header instance
* @param area OSPF area instance
*/
private void populateLsaLists(LsaHeader header, OspfArea area) {
String seqNo = Long.toHexString(header.lsSequenceNo());
String checkSum = Long.toHexString(header.lsCheckSum());
if (seqNo.length() == 16) {
seqNo = seqNo.substring(8, seqNo.length());
}
if (checkSum.length() == 16) {
checkSum = checkSum.substring(8, checkSum.length());
}
StringBuffer strBuf = getBuffList(area.areaId().toString(), area.routerId().toString(),
header.linkStateId(),
header.advertisingRouter().toString(),
header.age(), seqNo, checkSum);
if (header.lsType() == OspfLsaType.ROUTER.value()) {
strBuf.append(",");
strBuf.append(((RouterLsa) header).noLink());
routerLsa.add(strBuf.toString());
} else if (header.lsType() == OspfLsaType.NETWORK.value()) {
strBuf.append(",");
strBuf.append("0");
networkLsa.add(strBuf.toString());
} else if (header.lsType() == OspfLsaType.SUMMARY.value()) {
strBuf.append(",");
strBuf.append("0");
summaryLsa.add(strBuf.toString());
} else if (header.lsType() == OspfLsaType.EXTERNAL_LSA.value()) {
strBuf.append(",");
strBuf.append("0");
externalLsa.add(strBuf.toString());
} else if (header.lsType() == OspfLsaType.ASBR_SUMMARY.value()) {
strBuf.append(",");
strBuf.append("0");
asbrSumm.add(strBuf.toString());
} else if (header.lsType() == OspfLsaType.AREA_LOCAL_OPAQUE_LSA.value()) {
strBuf.append(",");
strBuf.append("0");
areaLocalOpaqLsa.add(strBuf.toString());
} else if (header.lsType() == OspfLsaType.LINK_LOCAL_OPAQUE_LSA.value()) {
strBuf.append(",");
strBuf.append("0");
linkLocalOpqLsa.add(strBuf.toString());
} else if (header.lsType() == OspfLsaType.AS_OPAQUE_LSA.value()) {
strBuf.append(",");
strBuf.append("0");
asOpqLsa.add(strBuf.toString());
} else {
strBuf.append(",");
strBuf.append("0");
undefinedLsa.add(strBuf.toString());
}
}
/**
* Builds OSPF neighbor information.
*/
private void buildNeighborInformation() {
try {
this.ospfController = get(OspfController.class);
List<OspfProcess> listOfProcess = ospfController.getAllConfiguredProcesses();
boolean flag = false;
printNeighborsFormat();
Iterator<OspfProcess> itrProcess = listOfProcess.iterator();
while (itrProcess.hasNext()) {
OspfProcess process = itrProcess.next();
List<OspfArea> listAreas = process.areas();
Iterator<OspfArea> itrArea = listAreas.iterator();
while (itrArea.hasNext()) {
OspfArea area = itrArea.next();
List<OspfInterface> itrefaceList = area.ospfInterfaceList();
for (OspfInterface interfc : itrefaceList) {
List<OspfNbr> nghbrList = new ArrayList<>(interfc.listOfNeighbors().values());
for (OspfNbr neigbor : nghbrList) {
print("%-20s%-20s%-20s%-20s%-20s\n", neigbor.neighborId(), neigbor.routerPriority(),
neigbor.getState() + "/" + checkDrBdrOther(neigbor.neighborIpAddr().toString(),
neigbor.neighborDr().toString(),
neigbor.neighborBdr().toString()),
neigbor.neighborIpAddr().toString(), interfc.ipAddress());
}
}
}
}
} catch (Exception ex) {
print("Error occured while Ospf controller getting called" + ex.getMessage());
}
}
/**
* Prints input after formatting.
*
* @param areaId area ID
* @param routerId router ID
* @param processId process ID
*/
private void printRouterFormat(String areaId, String routerId, String processId) {
print("%s (%s) %s %s\n", "OSPF Router with ID", routerId, "Process Id", processId);
print("%s ( Area %s)\n", "Router Link States", areaId);
print("%-20s%-20s%-20s%-20s%-20s%-20s\n", "Link Id", "ADV Router", "Age", "Seq#",
"CkSum", "Link Count");
}
/**
* Prints input after formatting.
*
* @param areaId area ID
* @param type network type
*/
private void printNetworkFormat(String areaId, String type) {
print("%s %s ( Area %s)\n", type, "Link States", areaId);
print("%-20s%-20s%-20s%-20s%-20s\n", "Link Id", "ADV Router", "Age", "Seq#", "CkSum");
}
/**
* Prints input after formatting.
*/
private void printNeighborsFormat() {
print("%-20s%-20s%-20s%-20s%-20s\n", "Neighbor Id", "Pri", "State",
"Address", "Interface");
}
/**
* Checks whether the neighbor is DR or BDR.
*
* @param ip IP address to check
* @param drIP DRs IP address
* @param bdrIp BDRs IP address
* @return 1- neighbor is DR, 2- neighbor is BDR, 3- DROTHER
*/
public String checkDrBdrOther(String ip, String drIP, String bdrIp) {
if (ip.equalsIgnoreCase(drIP)) {
return DR;
} else if (ip.equalsIgnoreCase(bdrIp)) {
return BACKUP;
} else {
return DROTHER;
}
}
/**
* Returns inputs as formatted string.
*
* @param areaId area id
* @param routerId router id
* @param linkStateId link state id
* @param advertisingRouter advertising router
* @param age age
* @param seqNo sequence number
* @param checkSum checksum
* @return formatted string
*/
private StringBuffer getBuffList(String areaId, String routerId, String linkStateId,
String advertisingRouter, int age, String seqNo, String checkSum) {
StringBuffer strBuf = new StringBuffer();
strBuf.append(areaId);
strBuf.append(",");
strBuf.append(routerId);
strBuf.append(",");
strBuf.append(linkStateId);
strBuf.append(",");
strBuf.append(advertisingRouter);
strBuf.append(",");
strBuf.append(age);
strBuf.append(",");
strBuf.append(seqNo);
strBuf.append(",");
strBuf.append(checkSum);
return strBuf;
}
}

View File

@ -0,0 +1,20 @@
/*
* Copyright 2016-present Open Networking Laboratory
*
* 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.
*/
/**
* OSPF cli implementation.
*/
package org.onosproject.ospf.cli;

View File

@ -0,0 +1,24 @@
<!--
~ Copyright 2016-present Open Networking Laboratory
~
~ 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.
-->
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
<command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">
<command>
<action class="org.onosproject.ospf.cli.ApplicationOspfCommand"/>
</command>
</command-bundle>
</blueprint>

60
providers/ospf/pom.xml Normal file
View File

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2016-present Open Networking Laboratory
~
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.onosproject</groupId>
<artifactId>onos-providers</artifactId>
<version>1.7.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>onos-ospf-providers</artifactId>
<packaging>pom</packaging>
<description>ONOS OSPF protocol adapters</description>
<modules>
<module>app</module>
<module>cfg</module>
<module>cli</module>
<module>topology</module>
</modules>
<dependencies>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-ctl</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-api</artifactId>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,15 @@
COMPILE_DEPS = [
'//lib:CORE_DEPS',
'//protocols/ospf/api:onos-protocols-ospf-api',
'//protocols/ospf/ctl:onos-protocols-ospf-ctl',
]
TEST_DEPS = [
'//lib:TEST_ADAPTERS',
]
osgi_jar_with_tests (
deps = COMPILE_DEPS,
test_deps = TEST_DEPS,
)

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2016-present Open Networking Laboratory
~
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.onosproject</groupId>
<artifactId>onos-ospf-providers</artifactId>
<version>1.7.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>onos-ospf-provider-topology</artifactId>
<packaging>bundle</packaging>
<description>ONOS OSPF Topology Providers</description>
<dependencies>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.compendium</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,246 @@
/*
* Copyright 2016-present Open Networking Laboratory
*
* 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 org.onosproject.provider.ospf.topology.impl;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.onlab.packet.ChassisId;
import org.onlab.packet.Ip4Address;
import org.onosproject.net.AnnotationKeys;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Link;
import org.onosproject.net.MastershipRole;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DefaultDeviceDescription;
import org.onosproject.net.device.DefaultPortDescription;
import org.onosproject.net.device.DeviceDescription;
import org.onosproject.net.device.DeviceProvider;
import org.onosproject.net.device.DeviceProviderRegistry;
import org.onosproject.net.device.DeviceProviderService;
import org.onosproject.net.device.PortDescription;
import org.onosproject.net.link.DefaultLinkDescription;
import org.onosproject.net.link.LinkDescription;
import org.onosproject.net.link.LinkProvider;
import org.onosproject.net.link.LinkProviderRegistry;
import org.onosproject.net.link.LinkProviderService;
import org.onosproject.net.link.LinkService;
import org.onosproject.net.provider.AbstractProvider;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.ospf.controller.OspfController;
import org.onosproject.ospf.controller.OspfLinkTed;
import org.onosproject.ospf.controller.OspfRouter;
import org.onosproject.ospf.controller.OspfRouterId;
import org.onosproject.ospf.controller.OspfRouterListener;
import org.onosproject.ospf.controller.OspfLinkListener;
import org.slf4j.Logger;
import java.util.LinkedList;
import java.util.List;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Provider which advertises device descriptions to the core.
*/
@Component(immediate = true)
public class OspfTopologyProvider extends AbstractProvider implements DeviceProvider, LinkProvider {
public static final long PSEUDO_PORT = 0xffffffff;
private static final Logger log = getLogger(OspfTopologyProvider.class);
// Default values for tunable parameters
private static final String UNKNOWN = "unknown";
final InternalTopologyProvider listener = new InternalTopologyProvider();
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected DeviceProviderRegistry deviceProviderRegistry;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected LinkProviderRegistry linkProviderRegistry;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected LinkService linkService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected OspfController controller;
//This Interface that defines how this provider can interact with the core.
private LinkProviderService linkProviderService;
// The interface that defines how this Provider can interact with the core
private DeviceProviderService deviceProviderService;
/**
* Creates an OSPF device provider.
*/
public OspfTopologyProvider() {
super(new ProviderId("l3", "org.onosproject.provider.ospf"));
}
@Activate
public void activate() {
deviceProviderService = deviceProviderRegistry.register(this);
linkProviderService = linkProviderRegistry.register(this);
controller.addRouterListener(listener);
controller.addLinkListener(listener);
log.debug("IsisDeviceProvider::activate...!!!!");
}
@Deactivate
public void deactivate() {
log.debug("IsisDeviceProvider::deactivate...!!!!");
deviceProviderRegistry.unregister(this);
deviceProviderService = null;
linkProviderRegistry.unregister(this);
linkProviderService = null;
controller.removeRouterListener(listener);
controller.removeLinkListener(listener);
log.info("deactivated...!!!");
}
@Override
public boolean isReachable(DeviceId deviceId) {
return true;
}
@Override
public void changePortState(DeviceId deviceId, PortNumber portNumber, boolean enable) {
log.info("changePortState on device {}", deviceId);
}
@Override
public void triggerProbe(DeviceId deviceId) {
log.info("Triggering probe on device {}", deviceId);
}
@Override
public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
log.info("Accepting mastership role change for device {}", deviceId);
}
/**
* Builds link description.
*
* @param ospfRouter OSPF router instance
* @param ospfLinkTed OSPF link TED instance
* @return link description instance
*/
private LinkDescription buildLinkDes(OspfRouter ospfRouter, OspfLinkTed ospfLinkTed) {
long srcAddress = 0;
long dstAddress = 0;
boolean localPseduo = false;
//Changing of port numbers
srcAddress = Ip4Address.valueOf(ospfRouter.routerIp().toString()).toInt();
dstAddress = Ip4Address.valueOf(ospfRouter.neighborRouterId().toString()).toInt();
DeviceId srcId = DeviceId.deviceId(OspfRouterId.uri(ospfRouter.routerIp()));
DeviceId dstId = DeviceId.deviceId(OspfRouterId.uri(ospfRouter.neighborRouterId()));
if (ospfRouter.isDr()) {
localPseduo = true;
}
if (localPseduo && srcAddress == 0) {
srcAddress = PSEUDO_PORT;
}
ConnectPoint src = new ConnectPoint(srcId, PortNumber.portNumber(srcAddress));
ConnectPoint dst = new ConnectPoint(dstId, PortNumber.portNumber(dstAddress));
return new DefaultLinkDescription(src, dst, Link.Type.DIRECT, false);
}
/**
* Internal topology Provider implementation.
*/
protected class InternalTopologyProvider implements OspfRouterListener, OspfLinkListener {
@Override
public void routerAdded(OspfRouter ospfRouter) {
String routerId = ospfRouter.routerIp().toString();
log.info("Added device {}", routerId);
DeviceId deviceId = DeviceId.deviceId(OspfRouterId.uri(ospfRouter.routerIp()));
Device.Type deviceType = Device.Type.ROUTER;
//If our routerType is Dr or Bdr type is PSEUDO
if (ospfRouter.isDr()) {
deviceType = Device.Type.ROUTER;
} else {
deviceType = Device.Type.VIRTUAL;
}
//deviceId = DeviceId.deviceId(routerDetails);
ChassisId cId = new ChassisId();
DefaultAnnotations.Builder newBuilder = DefaultAnnotations.builder();
newBuilder.set(AnnotationKeys.TYPE, "l3");
newBuilder.set("routerId", routerId);
DeviceDescription description =
new DefaultDeviceDescription(OspfRouterId.uri(ospfRouter.routerIp()),
deviceType, UNKNOWN, UNKNOWN, UNKNOWN,
UNKNOWN, cId, newBuilder.build());
deviceProviderService.deviceConnected(deviceId, description);
}
@Override
public void routerRemoved(OspfRouter ospfRouter) {
String routerId = ospfRouter.routerIp().toString();
log.info("Delete device {}", routerId);
DeviceId deviceId = DeviceId.deviceId(OspfRouterId.uri(ospfRouter.routerIp()));
if (deviceProviderService == null) {
return;
}
deviceProviderService.deviceDisconnected(deviceId);
log.info("delete device {}", routerId);
}
@Override
public void addLink(OspfRouter ospfRouter, OspfLinkTed ospfLinkTed) {
log.debug("Addlink {}", ospfRouter.routerIp());
LinkDescription linkDes = buildLinkDes(ospfRouter, ospfLinkTed);
//If already link exists, return
if (linkService.getLink(linkDes.src(), linkDes.dst()) != null || linkProviderService == null) {
return;
}
//Updating ports of the link
List<PortDescription> srcPortDescriptions = new LinkedList<>();
srcPortDescriptions.add(new DefaultPortDescription(linkDes.src().port(), true));
deviceProviderService.updatePorts(linkDes.src().deviceId(), srcPortDescriptions);
List<PortDescription> dstPortDescriptions = new LinkedList<>();
dstPortDescriptions.add(new DefaultPortDescription(linkDes.dst().port(), true));
deviceProviderService.updatePorts(linkDes.dst().deviceId(), dstPortDescriptions);
linkProviderService.linkDetected(linkDes);
}
@Override
public void deleteLink(OspfRouter ospfRouter, OspfLinkTed ospfLinkTed) {
log.debug("Delete link {}", ospfRouter.routerIp().toString());
if (linkProviderService == null) {
return;
}
LinkDescription linkDes = buildLinkDes(ospfRouter, ospfLinkTed);
//Updating ports of the link
List<PortDescription> srcPortDescriptions = new LinkedList<>();
srcPortDescriptions.add(new DefaultPortDescription(linkDes.src().port(), true));
deviceProviderService.updatePorts(linkDes.src().deviceId(), srcPortDescriptions);
List<PortDescription> dstPortDescriptions = new LinkedList<>();
dstPortDescriptions.add(new DefaultPortDescription(linkDes.dst().port(), true));
deviceProviderService.updatePorts(linkDes.dst().deviceId(), dstPortDescriptions);
linkProviderService.linkVanished(linkDes);
}
@Override
public void routerChanged(OspfRouter ospfRouter) {
log.info("Router changed is not supported currently");
}
}
}

View File

@ -0,0 +1,20 @@
/*
* Copyright 2016-present Open Networking Laboratory
*
* 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.
*/
/**
* Provider that uses OSPF as a means of topology discovery.
*/
package org.onosproject.provider.ospf.topology.impl;

View File

@ -0,0 +1,380 @@
/*
* Copyright 2016-present Open Networking Laboratory
*
* 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 org.onosproject.provider.ospf.topology.impl;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.Ip4Address;
import org.onlab.util.Bandwidth;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Link;
import org.onosproject.net.MastershipRole;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DeviceDescription;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceProvider;
import org.onosproject.net.device.DeviceProviderRegistry;
import org.onosproject.net.device.DeviceProviderService;
import org.onosproject.net.device.DeviceServiceAdapter;
import org.onosproject.net.device.PortDescription;
import org.onosproject.net.device.PortStatistics;
import org.onosproject.net.link.LinkDescription;
import org.onosproject.net.link.LinkListener;
import org.onosproject.net.link.LinkProvider;
import org.onosproject.net.link.LinkProviderRegistry;
import org.onosproject.net.link.LinkProviderService;
import org.onosproject.net.link.LinkServiceAdapter;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.ospf.controller.OspfController;
import org.onosproject.ospf.controller.OspfDeviceTed;
import org.onosproject.ospf.controller.OspfLinkListener;
import org.onosproject.ospf.controller.OspfLinkTed;
import org.onosproject.ospf.controller.OspfProcess;
import org.onosproject.ospf.controller.OspfRouter;
import org.onosproject.ospf.controller.OspfRouterListener;
import org.onosproject.ospf.controller.impl.OspfDeviceTedImpl;
import org.onosproject.ospf.controller.impl.OspfLinkTedImpl;
import org.onosproject.ospf.controller.impl.OspfRouterImpl;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import static org.junit.Assert.*;
/**
* Test cases for OSPF topology provider.
*/
public class OspfTopologyProviderTest {
private final OspfTopologyProvider provider = new OspfTopologyProvider();
private final TestDeviceRegistry nodeRegistry = new TestDeviceRegistry();
private final TestLinkRegistry linkRegistry = new TestLinkRegistry();
private final TestController controller = new TestController();
private final TestLinkService linkService = new TestLinkService();
@Before
public void setUp() throws Exception {
provider.deviceProviderRegistry = nodeRegistry;
provider.linkProviderRegistry = linkRegistry;
provider.controller = controller;
provider.linkService = linkService;
provider.activate();
assertNotNull("provider should be registered", nodeRegistry.provider);
assertNotNull("listener should be registered", controller.nodeListener);
}
@After
public void tearDown() throws Exception {
provider.deactivate();
assertNull("listener should be removed", controller.nodeListener);
provider.controller = null;
provider.deviceProviderRegistry = null;
}
@Test
public void triggerProbe() {
DeviceId deviceId = DeviceId.deviceId("2.2.2.2");
provider.triggerProbe(deviceId);
}
@Test
public void roleChanged() {
DeviceId deviceId = DeviceId.deviceId("2.2.2.2");
provider.roleChanged(deviceId, MastershipRole.MASTER);
}
@Test
public void changePortState() {
DeviceId deviceId = DeviceId.deviceId("2.2.2.2");
provider.changePortState(deviceId, PortNumber.portNumber(0), false);
}
@Test
public void isReachable() {
DeviceId deviceId = DeviceId.deviceId("1.1.1.1");
provider.isReachable(deviceId);
}
/* Validate node is added to the device validating URI, RIB should get updated properly */
@Test
public void ospfTopologyProviderTestAddDevice1() {
int deviceAddCount = 0;
OspfRouter ospfRouter = new OspfRouterImpl();
ospfRouter.setDr(false);
ospfRouter.setOpaque(false);
ospfRouter.setNeighborRouterId(Ip4Address.valueOf("2.2.2.2"));
ospfRouter.setInterfaceId(Ip4Address.valueOf("10.10.10.2"));
ospfRouter.setAreaIdOfInterface(Ip4Address.valueOf("5.5.5.5"));
ospfRouter.setRouterIp(Ip4Address.valueOf("1.1.1.1"));
OspfDeviceTed ospfDeviceTed = new OspfDeviceTedImpl();
ospfDeviceTed.setAbr(false);
ospfDeviceTed.setAsbr(false);
ospfRouter.setDeviceTed(ospfDeviceTed);
OspfLinkTed ospfLinkTed = new OspfLinkTedImpl();
ospfLinkTed.setMaximumLink(Bandwidth.bps(10));
ospfLinkTed.setMaxReserved(Bandwidth.bps(20));
ospfLinkTed.setTeMetric(10);
OspfRouter ospfRouter1 = new OspfRouterImpl();
ospfRouter1.setDr(true);
ospfRouter1.setOpaque(true);
ospfRouter1.setNeighborRouterId(Ip4Address.valueOf("2.2.2.2"));
ospfRouter1.setInterfaceId(Ip4Address.valueOf("10.10.10.2"));
ospfRouter1.setAreaIdOfInterface(Ip4Address.valueOf("5.5.5.5"));
ospfRouter1.setRouterIp(Ip4Address.valueOf("1.1.1.1"));
OspfDeviceTed ospfDeviceTed1 = new OspfDeviceTedImpl();
ospfDeviceTed1.setAbr(false);
ospfDeviceTed1.setAsbr(false);
ospfRouter.setDeviceTed(ospfDeviceTed);
OspfLinkTed ospfLinkTed1 = new OspfLinkTedImpl();
ospfLinkTed1.setMaximumLink(Bandwidth.bps(10));
ospfLinkTed1.setMaxReserved(Bandwidth.bps(20));
ospfLinkTed1.setTeMetric(10);
for (OspfRouterListener l : controller.nodeListener) {
l.routerAdded(ospfRouter);
deviceAddCount = nodeRegistry.connected.size();
assertTrue(deviceAddCount == 1);
l.routerRemoved(ospfRouter);
deviceAddCount = nodeRegistry.connected.size();
assertTrue(deviceAddCount == 0);
}
for (OspfLinkListener l : controller.linkListener) {
l.addLink(ospfRouter, ospfLinkTed);
l.deleteLink(ospfRouter, ospfLinkTed);
}
}
@Test
public void ospfTopologyProviderTestAddDevice2() {
int deviceAddCount = 0;
OspfRouter ospfRouter = new OspfRouterImpl();
ospfRouter.setDr(true);
ospfRouter.setOpaque(true);
ospfRouter.setNeighborRouterId(Ip4Address.valueOf("3.3.3.3"));
ospfRouter.setInterfaceId(Ip4Address.valueOf("10.10.10.3"));
ospfRouter.setAreaIdOfInterface(Ip4Address.valueOf("6.6.6.6"));
ospfRouter.setRouterIp(Ip4Address.valueOf("7.7.7.7"));
OspfDeviceTed ospfDeviceTed = new OspfDeviceTedImpl();
ospfDeviceTed.setAbr(true);
ospfDeviceTed.setAsbr(true);
ospfRouter.setDeviceTed(ospfDeviceTed);
OspfLinkTed ospfLinkTed = new OspfLinkTedImpl();
ospfLinkTed.setMaximumLink(Bandwidth.bps(30));
ospfLinkTed.setMaxReserved(Bandwidth.bps(40));
ospfLinkTed.setTeMetric(50);
for (OspfRouterListener l : controller.nodeListener) {
l.routerAdded(ospfRouter);
deviceAddCount = nodeRegistry.connected.size();
assertTrue(deviceAddCount == 1);
l.routerRemoved(ospfRouter);
deviceAddCount = nodeRegistry.connected.size();
assertTrue(deviceAddCount == 0);
}
}
/* Class implement device test registry */
private class TestDeviceRegistry implements DeviceProviderRegistry {
DeviceProvider provider;
Set<DeviceId> connected = new HashSet<>();
@Override
public DeviceProviderService register(DeviceProvider provider) {
this.provider = provider;
return new TestProviderService();
}
@Override
public void unregister(DeviceProvider provider) {
}
@Override
public Set<ProviderId> getProviders() {
return null;
}
private class TestProviderService implements DeviceProviderService {
@Override
public DeviceProvider provider() {
return null;
}
@Override
public void deviceConnected(DeviceId deviceId, DeviceDescription deviceDescription) {
connected.add(deviceId);
}
@Override
public void deviceDisconnected(DeviceId deviceId) {
connected.remove(deviceId);
}
@Override
public void updatePorts(DeviceId deviceId, List<PortDescription> portDescriptions) {
// TODO Auto-generated method stub
}
@Override
public void portStatusChanged(DeviceId deviceId, PortDescription portDescription) {
// TODO Auto-generated method stub
}
@Override
public void receivedRoleReply(DeviceId deviceId, MastershipRole requested, MastershipRole response) {
// TODO Auto-generated method stub
}
@Override
public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
// TODO Auto-generated method stub
}
}
}
private class TestDeviceService extends DeviceServiceAdapter {
private DeviceListener listener;
@Override
public void addListener(DeviceListener listener) {
this.listener = listener;
}
@Override
public Iterable<Device> getDevices() {
return Collections.emptyList();
}
}
private class TestLinkService extends LinkServiceAdapter {
private LinkListener listener;
@Override
public void addListener(LinkListener listener) {
this.listener = listener;
}
@Override
public Iterable<Link> getLinks() {
return Collections.emptyList();
}
}
/* Class implement device test registry */
private class TestLinkRegistry implements LinkProviderRegistry {
LinkProvider provider;
Set<DeviceId> connected = new HashSet<>();
@Override
public LinkProviderService register(LinkProvider provider) {
this.provider = provider;
return new TestLinkProviderService();
}
@Override
public void unregister(LinkProvider provider) {
}
@Override
public Set<ProviderId> getProviders() {
return null;
}
private class TestLinkProviderService implements LinkProviderService {
@Override
public void linkDetected(LinkDescription linkDescription) {
}
@Override
public void linkVanished(LinkDescription linkDescription) {
}
@Override
public void linksVanished(ConnectPoint connectPoint) {
}
@Override
public void linksVanished(DeviceId deviceId) {
}
@Override
public LinkProvider provider() {
return null;
}
}
}
/* class implement test controller */
private class TestController implements OspfController {
protected Set<OspfRouterListener> nodeListener = new CopyOnWriteArraySet<>();
protected Set<OspfLinkListener> linkListener = new CopyOnWriteArraySet<>();
@Override
public void addRouterListener(OspfRouterListener nodeListener) {
this.nodeListener.add(nodeListener);
}
@Override
public void removeRouterListener(OspfRouterListener nodeListener) {
this.nodeListener = null;
}
@Override
public void addLinkListener(OspfLinkListener listener) {
this.linkListener.add(listener);
}
@Override
public void removeLinkListener(OspfLinkListener listener) {
this.nodeListener = null;
}
@Override
public void updateConfig(JsonNode processesNode) {
}
@Override
public void deleteConfig(List<OspfProcess> processes, String attribute) {
}
@Override
public Set<OspfRouterListener> listener() {
return null;
}
@Override
public Set<OspfLinkListener> linkListener() {
return null;
}
@Override
public List<OspfProcess> getAllConfiguredProcesses() {
return null;
}
}
}

View File

@ -48,6 +48,7 @@
<module>bmv2</module>
<module>isis</module>
<module>lisp</module>
<module>ospf</module>
</modules>
<dependencies>