From: Ed Warnicke Date: Mon, 30 Jun 2014 16:38:29 +0000 (+0000) Subject: Merge "Introducing the Modification classses" X-Git-Tag: release/helium~580 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?p=controller.git;a=commitdiff_plain;h=bd165724c2279b280cb6ff20543f899f68e551c7;hp=3c0667dedcd089624c4de1fdf39f9c971bdce209 Merge "Introducing the Modification classses" --- diff --git a/features/base/pom.xml b/features/base/pom.xml index 922b2d6bdf..d925f51b94 100644 --- a/features/base/pom.xml +++ b/features/base/pom.xml @@ -22,6 +22,24 @@ + + org.apache.karaf.tooling + karaf-maven-plugin + ${karaf.version} + true + + + features-create-kar + + features-create-kar + + + ${project.build.directory}/classes/${features.file} + + + + + org.apache.maven.plugins maven-resources-plugin diff --git a/features/base/src/main/resources/features.xml b/features/base/src/main/resources/features.xml index dd6eec8222..60286175c1 100644 --- a/features/base/src/main/resources/features.xml +++ b/features/base/src/main/resources/features.xml @@ -121,6 +121,7 @@ mvn:orbit/org.apache.juli.extras/7.0.32.v201211081135 mvn:orbit/org.apache.tomcat.api/7.0.32.v201211081135 mvn:orbit/org.apache.tomcat.util/7.0.32.v201211201952 + wrap:mvn:virgomirror/org.eclipse.jdt.core.compiler.batch/3.8.0.I20120518-2145 mvn:org.ow2.asm/asm-all/${asm.version} diff --git a/opendaylight/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPReply.java b/opendaylight/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPReply.java index a6ee60f65d..1a446b83db 100644 --- a/opendaylight/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPReply.java +++ b/opendaylight/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPReply.java @@ -23,14 +23,17 @@ public class ARPReply extends ARPEvent { private final byte[] tMac; private final byte[] sMac; private final InetAddress sIP; + private final short vlan; @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); + result = prime * result + ((port == null) ? 0 : port.hashCode()); result = prime * result + ((sIP == null) ? 0 : sIP.hashCode()); result = prime * result + Arrays.hashCode(sMac); result = prime * result + Arrays.hashCode(tMac); + result = prime * result + vlan; return result; } @@ -39,13 +42,20 @@ public class ARPReply extends ARPEvent { if (this == obj) { return true; } - if (obj == null) { + if (!super.equals(obj)) { return false; } if (!(obj instanceof ARPReply)) { return false; } ARPReply other = (ARPReply) obj; + if (port == null) { + if (other.port != null) { + return false; + } + } else if (!port.equals(other.port)) { + return false; + } if (sIP == null) { if (other.sIP != null) { return false; @@ -59,23 +69,28 @@ public class ARPReply extends ARPEvent { if (!Arrays.equals(tMac, other.tMac)) { return false; } + if (vlan != other.vlan) { + return false; + } return true; } - public ARPReply(NodeConnector port, InetAddress sIP, byte[] sMAC, InetAddress tIP, byte[] tMAC) { + public ARPReply(NodeConnector port, InetAddress sIP, byte[] sMAC, InetAddress tIP, byte[] tMAC, short vlan) { super(tIP); this.tMac = tMAC; this.sIP = sIP; this.sMac = sMAC; this.port = port; + this.vlan = vlan; } - public ARPReply(InetAddress tIP, byte[] tMAC) { + public ARPReply(InetAddress tIP, byte[] tMAC, short vlan) { super(tIP); this.tMac = tMAC; this.sIP = null; this.sMac = null; this.port = null; + this.vlan = vlan; } public byte[] getTargetMac() { @@ -94,6 +109,10 @@ public class ARPReply extends ARPEvent { return port; } + public short getVlan() { + return vlan; + } + /* * (non-Javadoc) * @@ -122,6 +141,10 @@ public class ARPReply extends ARPEvent { builder.append("sIP=") .append(sIP); } + if (vlan != 0) { + builder.append(", vlan=") + .append(vlan); + } builder.append("]"); return builder.toString(); } diff --git a/opendaylight/arphandler/src/main/java/org/opendaylight/controller/arphandler/internal/ArpHandler.java b/opendaylight/arphandler/src/main/java/org/opendaylight/controller/arphandler/internal/ArpHandler.java index e549182439..fe456f3f8e 100644 --- a/opendaylight/arphandler/src/main/java/org/opendaylight/controller/arphandler/internal/ArpHandler.java +++ b/opendaylight/arphandler/src/main/java/org/opendaylight/controller/arphandler/internal/ArpHandler.java @@ -49,12 +49,12 @@ import org.opendaylight.controller.sal.core.NodeConnector; import org.opendaylight.controller.sal.packet.ARP; import org.opendaylight.controller.sal.packet.Ethernet; import org.opendaylight.controller.sal.packet.IDataPacketService; +import org.opendaylight.controller.sal.packet.IEEE8021Q; import org.opendaylight.controller.sal.packet.IListenDataPacket; import org.opendaylight.controller.sal.packet.IPv4; import org.opendaylight.controller.sal.packet.Packet; import org.opendaylight.controller.sal.packet.PacketResult; import org.opendaylight.controller.sal.packet.RawPacket; -import org.opendaylight.controller.sal.routing.IRouting; import org.opendaylight.controller.sal.utils.EtherTypes; import org.opendaylight.controller.sal.utils.HexEncode; import org.opendaylight.controller.sal.utils.NetUtils; @@ -96,7 +96,6 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA private ISwitchManager switchManager; private ITopologyManager topologyManager; private IDataPacketService dataPacketService; - private IRouting routing; private IClusterContainerServices clusterContainerService; private IConnectionManager connectionManager; private Set hostListeners = new CopyOnWriteArraySet(); @@ -182,7 +181,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA } } - protected void sendARPReply(NodeConnector p, byte[] sMAC, InetAddress sIP, byte[] tMAC, InetAddress tIP) { + protected void sendARPReply(NodeConnector p, byte[] sMAC, InetAddress sIP, byte[] tMAC, InetAddress tIP, short vlan) { byte[] senderIP = sIP.getAddress(); byte[] targetIP = tIP.getAddress(); ARP arp = createARP(ARP.REPLY, sMAC, senderIP, tMAC, targetIP); @@ -193,7 +192,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA sIP, HexEncode.bytesToHexString(tMAC), tIP, p); } - Ethernet ethernet = createEthernet(sMAC, tMAC, arp); + Ethernet ethernet = createEthernet(sMAC, tMAC, arp, vlan); RawPacket destPkt = this.dataPacketService.encodeDataPacket(ethernet); destPkt.setOutgoingNodeConnector(p); @@ -201,26 +200,24 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA this.dataPacketService.transmitDataPacket(destPkt); } - private void logArpPacket(ARP pkt, NodeConnector p) { + private void logArpPacket(ARP pkt, NodeConnector p, short vlan) { try { - if (pkt.getOpCode() == ARP.REQUEST) { - log.trace("Received Arp Request with srcMac {} - srcIp {} - dstMac {} - dstIp {} - inport {}", HexEncode.bytesToHexString(pkt.getSenderHardwareAddress()), - InetAddress.getByAddress(pkt.getSenderProtocolAddress()), HexEncode.bytesToHexString(pkt.getTargetHardwareAddress()), - InetAddress.getByAddress(pkt.getTargetProtocolAddress()), p); - } else if(pkt.getOpCode() == ARP.REPLY) { - log.trace("Received Arp Reply with srcMac {} - srcIp {} - dstMac {} - dstIp {} - inport {}", HexEncode.bytesToHexString(pkt.getSenderHardwareAddress()), - InetAddress.getByAddress(pkt.getSenderProtocolAddress()), HexEncode.bytesToHexString(pkt.getTargetHardwareAddress()), - InetAddress.getByAddress(pkt.getTargetProtocolAddress()), p); - } - } catch(UnknownHostException e) { + log.trace("Received Arp {} with srcMac {} - srcIp {} - dstMac {} - dstIp {} - inport {} {}", + ((pkt.getOpCode() == ARP.REQUEST) ? "Request" : "Reply"), + HexEncode.bytesToHexString(pkt.getSenderHardwareAddress()), + InetAddress.getByAddress(pkt.getSenderProtocolAddress()), + HexEncode.bytesToHexString(pkt.getTargetHardwareAddress()), + InetAddress.getByAddress(pkt.getTargetProtocolAddress()), p, (vlan != 0 ? "on vlan " + vlan : "")); + + } catch (UnknownHostException e) { log.warn("Illegal Ip Address in the ARP packet", e); } } - protected void handleARPPacket(Ethernet eHeader, ARP pkt, NodeConnector p) { + protected void handleARPPacket(Ethernet eHeader, ARP pkt, NodeConnector p, short vlan) { if(log.isTraceEnabled()) { - logArpPacket(pkt, p); + logArpPacket(pkt, p, vlan); } byte[] sourceMAC = eHeader.getSourceMACAddress(); @@ -264,7 +261,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA HostNodeConnector requestor = null; if (NetUtils.isUnicastMACAddr(sourceMAC) && p.getNode() != null) { try { - requestor = new HostNodeConnector(sourceMAC, sourceIP, p, subnet.getVlan()); + requestor = new HostNodeConnector(sourceMAC, sourceIP, p, vlan); } catch (ConstructionException e) { log.debug("Received ARP packet with invalid MAC: {}", HexEncode.bytesToHexString(sourceMAC)); return; @@ -294,7 +291,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA // the true value indicates we should generate replies to requestors // across the cluster log.trace("Received ARP reply packet from {}, reply to all requestors.", sourceIP); - arpRequestReplyEvent.put(new ARPReply(sourceIP, sourceMAC), true); + arpRequestReplyEvent.put(new ARPReply(sourceIP, sourceMAC, vlan), true); return; } @@ -315,11 +312,11 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA log.trace("Received local ARP req. for default gateway. Replying with controller MAC: {}", HexEncode.bytesToHexString(getControllerMAC())); } - sendARPReply(p, getControllerMAC(), targetIP, pkt.getSenderHardwareAddress(), sourceIP); + sendARPReply(p, getControllerMAC(), targetIP, pkt.getSenderHardwareAddress(), sourceIP, vlan); } else { log.trace("Received non-local ARP req. for default gateway. Raising reply event"); arpRequestReplyEvent.put( - new ARPReply(p, targetIP, getControllerMAC(), sourceIP, pkt.getSenderHardwareAddress()), false); + new ARPReply(p, targetIP, getControllerMAC(), sourceIP, pkt.getSenderHardwareAddress(), vlan), false); } return; } @@ -353,10 +350,10 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA log.trace("Received ARP req. for known host {}, sending reply...", targetIP); if (connectionManager.getLocalityStatus(p.getNode()) == ConnectionLocality.LOCAL) { sendARPReply(p, host.getDataLayerAddressBytes(), host.getNetworkAddress(), - pkt.getSenderHardwareAddress(), sourceIP); + pkt.getSenderHardwareAddress(), sourceIP, vlan); } else { arpRequestReplyEvent.put(new ARPReply(p, host.getNetworkAddress(), host.getDataLayerAddressBytes(), - sourceIP, pkt.getSenderHardwareAddress()), false); + sourceIP, pkt.getSenderHardwareAddress(), vlan), false); } } else { /* @@ -404,7 +401,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA } byte[] destMACAddress = NetUtils.getBroadcastMACAddr(); - Ethernet ethernet = createEthernet(getControllerMAC(), destMACAddress, arp); + Ethernet ethernet = createEthernet(getControllerMAC(), destMACAddress, arp, (short)0); // TODO For now send port-by-port, see how to optimize to // send to multiple ports at once @@ -416,9 +413,9 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA } /** - * Send a unicast ARP Request to the known host on a specific switch/port as - * defined in the host. The sender IP is the networkAddress of the subnet - * The sender MAC is the controller's MAC + * Send a unicast ARP Request to the known host on specific (switch/port, + * vlan) as defined in the host. The sender IP is the networkAddress of the + * subnet The sender MAC is the controller's MAC */ protected void sendUcastARPRequest(HostNodeConnector host, Subnet subnet) { log.trace("sendUcastARPRequest host:{} subnet:{}", host, subnet); @@ -440,7 +437,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA outPort); } - Ethernet ethernet = createEthernet(getControllerMAC(), targetMAC, arp); + Ethernet ethernet = createEthernet(getControllerMAC(), targetMAC, arp, host.getVlan()); RawPacket destPkt = this.dataPacketService.encodeDataPacket(ethernet); destPkt.setOutgoingNodeConnector(outPort); @@ -498,7 +495,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA * @param pkt * @param p */ - protected void handlePuntedIPPacket(IPv4 pkt, NodeConnector p) { + protected void handlePuntedIPPacket(IPv4 pkt, NodeConnector p, short vlan) { InetAddress dIP = NetUtils.getInetAddress(pkt.getDestinationAddress()); if (dIP == null) { @@ -653,13 +650,19 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA log.trace("Received a frame of size: {}", inPkt.getPacketData().length); Packet formattedPak = this.dataPacketService.decodeDataPacket(inPkt); if (formattedPak instanceof Ethernet) { - Object nextPak = formattedPak.getPayload(); + Packet nextPak = formattedPak.getPayload(); + short vlan = 0; + if (nextPak instanceof IEEE8021Q) { + vlan = ((IEEE8021Q) nextPak).getVid(); + log.trace("Moved after the dot1Q header"); + nextPak = ((IEEE8021Q) nextPak).getPayload(); + } if (nextPak instanceof IPv4) { log.trace("Handle IP packet: {}", formattedPak); - handlePuntedIPPacket((IPv4) nextPak, inPkt.getIncomingNodeConnector()); + handlePuntedIPPacket((IPv4) nextPak, inPkt.getIncomingNodeConnector(), vlan); } else if (nextPak instanceof ARP) { log.trace("Handle ARP packet: {}", formattedPak); - handleARPPacket((Ethernet) formattedPak, (ARP) nextPak, inPkt.getIncomingNodeConnector()); + handleARPPacket((Ethernet) formattedPak, (ARP) nextPak, inPkt.getIncomingNodeConnector(), vlan); } } return PacketResult.IGNORED; @@ -680,12 +683,21 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA return arp; } - private Ethernet createEthernet(byte[] sourceMAC, byte[] targetMAC, ARP arp) { + private Ethernet createEthernet(byte[] sourceMAC, byte[] targetMAC, ARP arp, short vlan) { Ethernet ethernet = new Ethernet(); ethernet.setSourceMACAddress(sourceMAC); ethernet.setDestinationMACAddress(targetMAC); - ethernet.setEtherType(EtherTypes.ARP.shortValue()); - ethernet.setPayload(arp); + if (vlan == 0) { + ethernet.setEtherType(EtherTypes.ARP.shortValue()); + ethernet.setPayload(arp); + } else { + IEEE8021Q dot1q = new IEEE8021Q(); + dot1q.setVid(vlan); + dot1q.setEtherType(EtherTypes.ARP.shortValue()); + dot1q.setPayload(arp); + ethernet.setEtherType(EtherTypes.VLANTAGGED.shortValue()); + ethernet.setPayload(dot1q); + } return ethernet; } @@ -731,7 +743,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA } } - private void generateAndSendReply(InetAddress sourceIP, byte[] sourceMAC) { + private void generateAndSendReply(InetAddress sourceIP, byte[] sourceMAC, short vlan) { if (log.isTraceEnabled()) { log.trace("generateAndSendReply called with params sourceIP:{} sourceMAC:{}", sourceIP, HexEncode.bytesToHexString(sourceMAC)); @@ -745,13 +757,14 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA for (HostNodeConnector host : hosts) { if (log.isTraceEnabled()) { log.trace( - "Sending ARP Reply with src {}/{}, target {}/{}", + "Sending ARP Reply with src {}/{}, target {}/{} {}", new Object[] { HexEncode.bytesToHexString(sourceMAC), sourceIP, - HexEncode.bytesToHexString(host.getDataLayerAddressBytes()), host.getNetworkAddress() }); + HexEncode.bytesToHexString(host.getDataLayerAddressBytes()), host.getNetworkAddress(), + (vlan != 0 ? "on vlan " + vlan : "") }); } if (connectionManager.getLocalityStatus(host.getnodeconnectorNode()) == ConnectionLocality.LOCAL) { sendARPReply(host.getnodeConnector(), sourceMAC, sourceIP, host.getDataLayerAddressBytes(), - host.getNetworkAddress()); + host.getNetworkAddress(), vlan); } else { /* * In the remote event a requestor moved to another controller @@ -760,7 +773,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA */ arpRequestReplyEvent.put( new ARPReply(host.getnodeConnector(), sourceIP, sourceMAC, host.getNetworkAddress(), host - .getDataLayerAddressBytes()), false); + .getDataLayerAddressBytes(), vlan), false); } } } @@ -822,12 +835,12 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA // requestors across the cluster if (ev.isNewReply()) { log.trace("Trigger a generateAndSendReply in response to {}", rep); - generateAndSendReply(rep.getTargetIP(), rep.getTargetMac()); + generateAndSendReply(rep.getTargetIP(), rep.getTargetMac(), rep.getVlan()); // Otherwise, a specific reply. If local, send out. } else if (connectionManager.getLocalityStatus(rep.getPort().getNode()) == ConnectionLocality.LOCAL) { log.trace("ARPCacheEventHandler - sendUcatARPReply locally in response to {}", rep); sendARPReply(rep.getPort(), rep.getSourceMac(), rep.getSourceIP(), rep.getTargetMac(), - rep.getTargetIP()); + rep.getTargetIP(), rep.getVlan()); } } } catch (InterruptedException e) { diff --git a/opendaylight/commons/opendaylight/pom.xml b/opendaylight/commons/opendaylight/pom.xml index c83bf751ee..de8caa0e67 100644 --- a/opendaylight/commons/opendaylight/pom.xml +++ b/opendaylight/commons/opendaylight/pom.xml @@ -996,12 +996,12 @@ netconf-client ${netconf.version} - - org.opendaylight.controller - netconf-client - ${netconf.version} - test-jar - + + org.opendaylight.controller + netconf-client + ${netconf.version} + test-jar + @@ -1126,11 +1126,6 @@ protocol_plugins.stub ${protocol_plugins.stub.version} - - org.opendaylight.controller - remoterpc-routingtable.implementation - ${mdsal.version} - org.opendaylight.controller routing.dijkstra_implementation @@ -1218,11 +1213,6 @@ sal-remote ${mdsal.version} - - org.opendaylight.controller - sal-remoterpc-connector - ${mdsal.version} - org.opendaylight.controller sal-rest-connector @@ -1479,16 +1469,6 @@ sample-toaster-provider ${mdsal.version} - - org.opendaylight.controller.tests - sal-remoterpc-connector-test-consumer - ${mdsal.version} - - - org.opendaylight.controller.tests - sal-remoterpc-connector-test-provider - ${mdsal.version} - org.opendaylight.controller.thirdparty com.sun.jersey.jersey-servlet diff --git a/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/ConfigSnapshotHolder.java b/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/ConfigSnapshotHolder.java index c00b26d9ce..ba13ebb8f0 100644 --- a/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/ConfigSnapshotHolder.java +++ b/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/ConfigSnapshotHolder.java @@ -12,13 +12,14 @@ import java.util.SortedSet; public interface ConfigSnapshotHolder { /** - * Get part of get-config document that contains just + * Get XML node that should be pushed to netconf's edit-config */ String getConfigSnapshot(); /** * Get only required capabilities referenced by the snapshot. + * If no value is specified, return empty set instead of null */ SortedSet getCapabilities(); diff --git a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/ConfigSnapshot.java b/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/ConfigSnapshot.java index d13052a7e2..7c069dab6b 100644 --- a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/ConfigSnapshot.java +++ b/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/ConfigSnapshot.java @@ -7,6 +7,7 @@ */ package org.opendaylight.controller.config.persist.storage.file.xml.model; +import java.util.TreeSet; import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder; import javax.xml.bind.annotation.XmlAnyElement; @@ -22,7 +23,7 @@ public class ConfigSnapshot { public static final String SNAPSHOT_ROOT_ELEMENT_NAME = "snapshot"; private String configSnapshot; - private SortedSet capabilities; + private SortedSet capabilities = new TreeSet<>(); ConfigSnapshot(String configXml, SortedSet capabilities) { this.configSnapshot = configXml; diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/AbsModuleGeneratedObjectFactory.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/AbsModuleGeneratedObjectFactory.java index aa06cb97d7..6eda364af0 100644 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/AbsModuleGeneratedObjectFactory.java +++ b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/AbsModuleGeneratedObjectFactory.java @@ -7,6 +7,7 @@ */ package org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory; +import static com.google.common.base.Preconditions.checkState; import static java.lang.String.format; import com.google.common.base.Joiner; @@ -212,7 +213,7 @@ public class AbsModuleGeneratedObjectFactory { "}\n", moduleField.getName(), osgi); } else { str = format( - "%1$sDependency = dependencyResolver.resolveInstance(%2$s.class, %1$s, %1$sJmxAttribute);", + "%1$sDependency = dependencyResolver.resolveInstance(%2$s.class, %1$s, %1$sJmxAttribute);\n", moduleField.getName(), osgi); } resolveDependenciesMap.put(moduleField, str); @@ -222,7 +223,8 @@ public class AbsModuleGeneratedObjectFactory { // wrap each field resolvation statement with if !=null when dependency is not mandatory for (Map.Entry entry : resolveDependenciesMap.entrySet()) { if (entry.getKey().getDependency().isMandatory() == false) { - result += format("if (%s!=null) {\n%s;\n}", entry.getKey().getName(), entry.getValue()); + checkState(entry.getValue().endsWith(";\n")); + result += format("if (%s!=null) {\n%s}\n", entry.getKey().getName(), entry.getValue()); } else { result += entry.getValue(); } @@ -401,7 +403,7 @@ public class AbsModuleGeneratedObjectFactory { parameters.put(ModuleIdentifier.class.getCanonicalName(), "identifier"); parameters.put(DependencyResolver.class.getCanonicalName(), "dependencyResolver"); - String setToNulls = "this.oldInstance=null;\n;" + + String setToNulls = "this.oldInstance=null;\n" + "this.oldModule=null;\n"; return getConstructorStart(abstractFQN, parameters, setToNulls); } diff --git a/opendaylight/distribution/opendaylight-karaf/pom.xml b/opendaylight/distribution/opendaylight-karaf/pom.xml index 7970b3aa00..8a23a6b5e6 100644 --- a/opendaylight/distribution/opendaylight-karaf/pom.xml +++ b/opendaylight/distribution/opendaylight-karaf/pom.xml @@ -38,13 +38,11 @@ xml runtime - org.opendaylight.controller base-features ${project.version} - pom + kar runtime diff --git a/opendaylight/distribution/opendaylight-karaf/src/main/resources/etc/custom.properties b/opendaylight/distribution/opendaylight-karaf/src/main/resources/etc/custom.properties index 502e1a261c..6c1ca421c2 100644 --- a/opendaylight/distribution/opendaylight-karaf/src/main/resources/etc/custom.properties +++ b/opendaylight/distribution/opendaylight-karaf/src/main/resources/etc/custom.properties @@ -1,11 +1,17 @@ # Extra packages to import from the boot class loader org.osgi.framework.system.packages.extra=org.apache.karaf.branding,sun.reflect,sun.reflect.misc,sun.misc,sun.nio.ch +# https://bugs.eclipse.org/bugs/show_bug.cgi?id=325578 +# Extend the framework to avoid the resources to be presented with +# a URL of type bundleresource: but to be presented as file: +osgi.hook.configurators.include=org.eclipse.virgo.kernel.equinox.extensions.hooks.ExtensionsHookConfigurator # Embedded Tomcat configuration File org.eclipse.gemini.web.tomcat.config.path=configuration/tomcat-server.xml org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true +# Use Equinox as default OSGi Framework Implementation +karaf.framework=equinox # Netconf startup configuration netconf.tcp.address=127.0.0.1 diff --git a/opendaylight/distribution/opendaylight-karaf/src/main/resources/etc/startup.properties b/opendaylight/distribution/opendaylight-karaf/src/main/resources/etc/startup.properties index 288fe629f8..ca8c83c380 100644 --- a/opendaylight/distribution/opendaylight-karaf/src/main/resources/etc/startup.properties +++ b/opendaylight/distribution/opendaylight-karaf/src/main/resources/etc/startup.properties @@ -7,7 +7,7 @@ mvn\:org.ops4j.pax.swissbox/pax-swissbox-bnd/1.7.0 = 5 mvn\:org.ops4j.pax.url/pax-url-maven-commons/1.6.0 = 5 mvn\:org.ops4j.pax.url/pax-url-aether/1.6.0 = 5 mvn\:org.ops4j.pax.url/pax-url-wrap/1.6.0 = 5 -#mvn\:javax.annotation/javax.annotation-api/1.2 = 5 +mvn\:javax.annotation/javax.annotation-api/1.2 = 5 mvn\:org.ops4j.pax.logging/pax-logging-api/1.7.2 = 8 mvn\:org.ops4j.pax.logging/pax-logging-service/1.7.2 = 8 mvn\:org.apache.karaf.service/org.apache.karaf.service.guard/3.0.1 = 10 diff --git a/opendaylight/distribution/opendaylight/pom.xml b/opendaylight/distribution/opendaylight/pom.xml index 149154334d..ef3b5f4fd9 100644 --- a/opendaylight/distribution/opendaylight/pom.xml +++ b/opendaylight/distribution/opendaylight/pom.xml @@ -935,12 +935,6 @@ protocol-framework - - - org.opendaylight.controller - remoterpc-routingtable.implementation - ${mdsal.version} - org.opendaylight.controller sal-binding-api @@ -1007,10 +1001,6 @@ org.opendaylight.controller sal-remote - - org.opendaylight.controller - sal-remoterpc-connector - org.opendaylight.controller sal-rest-connector diff --git a/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/01-netconf.xml b/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/01-netconf.xml new file mode 100644 index 0000000000..8fedbe4d4c --- /dev/null +++ b/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/01-netconf.xml @@ -0,0 +1,84 @@ + + + + + + + + + + + prefix:netconf-client-dispatcher + global-netconf-dispatcher + + prefix:netty-threadgroup + global-boss-group + + + prefix:netty-threadgroup + global-worker-group + + + prefix:netty-timer + global-timer + + + + + + prefix:threadfactory-naming + global-netconf-processing-executor-threadfactory + remote-connector-processing-executor + + + + prefix:threadpool-flexible + global-netconf-processing-executor + 1 + 4 + 600000 + + prefix:threadfactory + global-netconf-processing-executor-threadfactory + + + + + + + prefix:netconf-client-dispatcher + + global-netconf-dispatcher + /modules/module[type='netconf-client-dispatcher'][name='global-netconf-dispatcher'] + + + + prefix:threadfactory + + global-netconf-processing-executor-threadfactory + /modules/module[type='threadfactory-naming'][name='global-netconf-processing-executor-threadfactory'] + + + + prefix:threadpool + + global-netconf-processing-executor + /modules/module[type='threadpool-flexible'][name='global-netconf-processing-executor'] + + + + + + + + urn:opendaylight:params:xml:ns:yang:controller:config:netconf:client:dispatcher?module=odl-netconfig-client-cfg&revision=2014-04-08 + urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl?module=threadpool-impl&revision=2013-04-05 + urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl:flexible?module=threadpool-impl-flexible&revision=2013-12-01 + + diff --git a/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/02-clustering.xml b/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/02-clustering.xml deleted file mode 100644 index c5f99fd0c1..0000000000 --- a/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/02-clustering.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - prefix:remote-zeromq-rpc-server - remoter - 5666 - - prefix:dom-broker-osgi-registry - dom-broker - - - - - - - - - - urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom?module=opendaylight-md-sal-dom&revision=2013-10-28 - urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl?module=opendaylight-sal-dom-broker-impl&revision=2013-10-28 - urn:opendaylight:params:xml:ns:yang:controller:md:sal:common?module=opendaylight-md-sal-common&revision=2013-10-28 - urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote:rpc?module=odl-sal-dom-rpc-remote-cfg&revision=2013-10-28 - - - diff --git a/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/99-netconf-connector.xml b/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/99-netconf-connector.xml index b4b433dbca..7155eb8883 100644 --- a/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/99-netconf-connector.xml +++ b/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/99-netconf-connector.xml @@ -11,43 +11,6 @@ - - - - prefix:netconf-client-dispatcher - global-netconf-dispatcher - - prefix:netty-threadgroup - global-boss-group - - - prefix:netty-threadgroup - global-worker-group - - - prefix:netty-timer - global-timer - - - - - - prefix:threadfactory-naming - global-netconf-processing-executor-threadfactory - remote-connector-processing-executor - - - prefix:threadpool-flexible - global-netconf-processing-executor - 1 - 4 - 600000 - - prefix:threadfactory - global-netconf-processing-executor-threadfactory - - - prefix:sal-netconf-connector @@ -79,37 +42,9 @@ - - - - prefix:netconf-client-dispatcher - - global-netconf-dispatcher - /modules/module[type='netconf-client-dispatcher'][name='global-netconf-dispatcher'] - - - - prefix:threadfactory - - global-netconf-processing-executor-threadfactory - /modules/module[type='threadfactory-naming'][name='global-netconf-processing-executor-threadfactory'] - - - - prefix:threadpool - - global-netconf-processing-executor - /modules/module[type='threadpool-flexible'][name='global-netconf-processing-executor'] - - - - urn:opendaylight:params:xml:ns:yang:controller:md:sal:connector:netconf?module=odl-sal-netconf-connector-cfg&revision=2013-10-28 - urn:opendaylight:params:xml:ns:yang:controller:config:netconf:client:dispatcher?module=odl-netconfig-client-cfg&revision=2014-04-08 - urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl?module=threadpool-impl&revision=2013-04-05 - urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl:flexible?module=threadpool-impl-flexible&revision=2013-12-01 diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/ComponentActivator.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/ComponentActivator.java index ba68d523af..d71858e5c3 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/ComponentActivator.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/ComponentActivator.java @@ -83,6 +83,7 @@ public class ComponentActivator extends ComponentActivatorAbstractBase { @Override protected void init() { + // TODO: deprecated, should be removed soon NodeIDType.registerIDType(NodeMapping.MD_SAL_TYPE, String.class); NodeConnectorIDType.registerIDType(NodeMapping.MD_SAL_TYPE, String.class, NodeMapping.MD_SAL_TYPE); } @@ -232,8 +233,8 @@ public class ComponentActivator extends ComponentActivatorAbstractBase { private Dictionary properties() { final Hashtable props = new Hashtable(); - props.put(GlobalConstants.PROTOCOLPLUGINTYPE.toString(), NodeMapping.MD_SAL_TYPE); - props.put("protocolName", NodeMapping.MD_SAL_TYPE); + props.put(GlobalConstants.PROTOCOLPLUGINTYPE.toString(), NodeIDType.OPENFLOW); + props.put("protocolName", NodeIDType.OPENFLOW); return props; } } diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/FlowProgrammerAdapter.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/FlowProgrammerAdapter.java index ba7377e8ff..acb54ba51a 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/FlowProgrammerAdapter.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/FlowProgrammerAdapter.java @@ -247,7 +247,8 @@ public class FlowProgrammerAdapter implements IPluginInFlowProgrammerService, Sa flowId = UUID.randomUUID(); cache.put(flow, flowId); - return this.writeFlowAsync(MDFlowMapping.toMDFlow(flow, flowId.toString()), new NodeKey(new NodeId(node.getNodeIDString()))); + return this.writeFlowAsync(MDFlowMapping.toMDFlow(flow, flowId.toString()), new NodeKey( + new NodeId(NodeMapping.OPENFLOW_ID_PREFIX + node.getID()))); } private Future> internalModifyFlowAsync(final Node node, final Flow oldFlow, final Flow newFlow, final long rid) { @@ -261,7 +262,8 @@ public class FlowProgrammerAdapter implements IPluginInFlowProgrammerService, Sa } cache.put(newFlow, flowId); - return this.writeFlowAsync(MDFlowMapping.toMDFlow(newFlow, flowId.toString()), new NodeKey(new NodeId(node.getNodeIDString()))); + return this.writeFlowAsync(MDFlowMapping.toMDFlow(newFlow, flowId.toString()), new NodeKey( + new NodeId(NodeMapping.OPENFLOW_ID_PREFIX + node.getID()))); } private Future> internalRemoveFlowAsync(final Node node, final Flow adflow, final long rid) { @@ -275,7 +277,8 @@ public class FlowProgrammerAdapter implements IPluginInFlowProgrammerService, Sa final org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow flow = MDFlowMapping.toMDFlow(adflow, flowId.toString()); final DataModificationTransaction modification = this.dataBrokerService.beginTransaction(); - modification.removeConfigurationData(flowPath(flow, new NodeKey(new NodeId(node.getNodeIDString())))); + modification.removeConfigurationData(flowPath(flow, new NodeKey( + new NodeId(NodeMapping.OPENFLOW_ID_PREFIX + node.getID())))); return modification.commit(); } diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java index 2830165425..5959d23366 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java @@ -26,6 +26,7 @@ import org.opendaylight.controller.sal.core.Edge; import org.opendaylight.controller.sal.core.Node; import org.opendaylight.controller.sal.core.NodeConnector; import org.opendaylight.controller.sal.core.NodeTable; +import org.opendaylight.controller.sal.core.NodeTable.NodeTableIDType; import org.opendaylight.controller.sal.core.Property; import org.opendaylight.controller.sal.core.UpdateType; import org.opendaylight.controller.sal.inventory.IPluginInInventoryService; @@ -489,7 +490,7 @@ public class InventoryAndReadAdapter implements IPluginInReadService, IPluginInI } try { - final Node adNode = new Node(NodeMapping.MD_SAL_TYPE, NodeMapping.toADNodeId(node.getId())); + final Node adNode = NodeMapping.toADNode(node.getId()); props.put(adNode, perNodePropMap); } catch (ConstructionException e) { LOG.warn("Failed to construct node for {}, skipping it", node, e); @@ -572,7 +573,7 @@ public class InventoryAndReadAdapter implements IPluginInReadService, IPluginInI it.setLookupCount(tableStats.getPacketsLookedUp().getValue().longValue()); it.setMatchedCount(tableStats.getPacketsMatched().getValue().longValue()); it.setName(tableId.toString()); - it.setNodeTable(new NodeTable(NodeMapping.MD_SAL_TYPE, tableId, node)); + it.setNodeTable(new NodeTable(NodeTableIDType.OPENFLOW, tableId.byteValue(), node)); return it; } diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/MDFlowMapping.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/MDFlowMapping.java index 67af3e428f..9b5d0e8875 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/MDFlowMapping.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/MDFlowMapping.java @@ -357,7 +357,7 @@ public final class MDFlowMapping { } public static Uri toUri(final NodeConnector connector) { - return new NodeConnectorId(((String) connector.getID())); + return new NodeConnectorId(NodeMapping.OPENFLOW_ID_PREFIX + connector.getNode().getID() + ":" + (connector.getID())); } public static MacAddress toMacAddress(final byte[] bytes) { diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/NodeMapping.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/NodeMapping.java index f5701bfaf2..a700c86b9c 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/NodeMapping.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/NodeMapping.java @@ -11,7 +11,6 @@ import java.math.BigInteger; import java.util.Date; import java.util.HashSet; import java.util.List; - import org.opendaylight.controller.sal.common.util.Arguments; import org.opendaylight.controller.sal.core.AdvertisedBandwidth; import org.opendaylight.controller.sal.core.Bandwidth; @@ -19,8 +18,10 @@ import org.opendaylight.controller.sal.core.Buffers; import org.opendaylight.controller.sal.core.Capabilities; import org.opendaylight.controller.sal.core.Config; import org.opendaylight.controller.sal.core.ConstructionException; +import org.opendaylight.controller.sal.core.Description; import org.opendaylight.controller.sal.core.MacAddress; import org.opendaylight.controller.sal.core.Name; +import org.opendaylight.controller.sal.core.Node.NodeIDType; import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType; import org.opendaylight.controller.sal.core.PeerBandwidth; import org.opendaylight.controller.sal.core.Property; @@ -44,6 +45,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.fl import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortConfig; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortFeatures; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.flow.capable.port.State; +import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.OutputPortValues; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorUpdated; @@ -56,12 +58,21 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.No import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.google.common.base.Objects; import com.google.common.base.Preconditions; public final class NodeMapping { - public final static String MD_SAL_TYPE = "MD_SAL"; + + private static final Logger LOG = LoggerFactory + .getLogger(NodeMapping.class); + + /** openflow id prefix */ + public static final String OPENFLOW_ID_PREFIX = "openflow:"; + + public final static String MD_SAL_TYPE = "MD_SAL_DEPRECATED"; private final static Class NODE_CLASS = Node.class; @@ -77,8 +88,19 @@ public final class NodeMapping { } public static org.opendaylight.controller.sal.core.Node toADNode(final NodeId id) throws ConstructionException { - String aDNodeId = NodeMapping.toADNodeId(id); - return new org.opendaylight.controller.sal.core.Node(NodeMapping.MD_SAL_TYPE, aDNodeId); + Long aDNodeId = openflowFullNodeIdToLong(NodeMapping.toADNodeId(id)); + return new org.opendaylight.controller.sal.core.Node(NodeIDType.OPENFLOW, aDNodeId); + } + + /** + * @param adNodeId + * @return + */ + private static Long openflowFullNodeIdToLong(String adNodeId) { + if (adNodeId == null) { + return null; + } + return Long.valueOf(adNodeId.replaceFirst("^.*:", "")); } public static NodeId toNodeId(final InstanceIdentifier id) { @@ -87,7 +109,14 @@ public final class NodeMapping { return key.getId(); } + /** + * @param nodeId containing "<NodeTypeString>:<plainIntegerId>" + * @return adNodeId form + */ public static String toADNodeId(final NodeId nodeId) { + if (nodeId == null) { + return null; + } return nodeId.getValue(); } @@ -104,6 +133,28 @@ public final class NodeMapping { return new org.opendaylight.controller.sal.core.NodeConnector(nodeConnectorType, aDNodeConnectorId, aDNode); } + /** + * @param ncid nodeConnector identifier, e.g.: OF:21 or CTRL + * @param node + * @return nodeConnector attached to given node + * @throws ConstructionException + */ + public static org.opendaylight.controller.sal.core.NodeConnector toADNodeConnector( + final NodeConnectorId ncid, final org.opendaylight.controller.sal.core.Node aDNode) throws ConstructionException { + NodeId nid = NodeMapping.toNodeId(aDNode); + String nodeConnectorType = NodeMapping.toNodeConnectorType(ncid, nid); + Object aDNodeConnectorId = NodeMapping.toADNodeConnectorId(ncid, nid); + return new org.opendaylight.controller.sal.core.NodeConnector(nodeConnectorType, aDNodeConnectorId, aDNode); + } + + /** + * @param aDNode + * @return + */ + private static NodeId toNodeId(org.opendaylight.controller.sal.core.Node aDNode) { + return new NodeId(aDNode.getType() + ":" +String.valueOf(aDNode.getID())); + } + public static String toNodeConnectorType(final NodeConnectorId ncId, final NodeId nodeId) { if (ncId.equals(toLocalNodeConnectorId(nodeId))) { return NodeConnectorIDType.SWSTACK; @@ -112,7 +163,7 @@ public final class NodeMapping { } else if (ncId.equals(toControllerNodeConnectorId(nodeId))) { return NodeConnectorIDType.CONTROLLER; } - return MD_SAL_TYPE; + return NodeConnectorIDType.OPENFLOW; } public static Object toADNodeConnectorId(final NodeConnectorId nodeConnectorId, final NodeId nodeId) { @@ -121,7 +172,18 @@ public final class NodeMapping { nodeConnectorId.equals(toControllerNodeConnectorId(nodeId))) { return org.opendaylight.controller.sal.core.NodeConnector.SPECIALNODECONNECTORID; } - return nodeConnectorId.getValue(); + + String nodeConnectorIdStripped = nodeConnectorId.getValue().replaceFirst("^.*:", ""); + if (nodeConnectorIdStripped.matches("[0-9]+")) { + Short nodeConnectorIdVal = null; + try { + nodeConnectorIdVal = Short.valueOf(nodeConnectorIdStripped); + } catch (NumberFormatException e) { + LOG.warn("nodeConnectorId not supported (short): {}", nodeConnectorIdStripped, e); + } + return nodeConnectorIdVal; + } + return nodeConnectorIdStripped; } public static NodeId toAdNodeId(final NodeConnectorId nodeConnectorId) { @@ -133,21 +195,21 @@ public final class NodeMapping { } public static NodeConnectorId toControllerNodeConnectorId(final NodeId node) { - return new NodeConnectorId(node.getValue() + ":" + 4294967293L); + return new NodeConnectorId(node.getValue() + ":" + OutputPortValues.CONTROLLER.toString()); } public static NodeConnectorId toLocalNodeConnectorId(final NodeId node) { - return new NodeConnectorId(node.getValue() + ":" + 4294967294L); + return new NodeConnectorId(node.getValue() + ":" + OutputPortValues.LOCAL.toString()); } public static NodeConnectorId toNormalNodeConnectorId(final NodeId node) { - return new NodeConnectorId(node.getValue() + ":" + 4294967290L); + return new NodeConnectorId(node.getValue() + ":" + OutputPortValues.NORMAL.toString()); } public static NodeRef toNodeRef(final org.opendaylight.controller.sal.core.Node node) { - Preconditions.checkArgument(MD_SAL_TYPE.equals(node.getType())); - final String nodeId = Arguments.checkInstanceOf(node.getID(), String.class); - final NodeKey nodeKey = new NodeKey(new NodeId(nodeId)); + Preconditions.checkArgument(NodeIDType.OPENFLOW.equals(node.getType())); + final Long nodeId = Arguments.checkInstanceOf(node.getID(), Long.class); + final NodeKey nodeKey = new NodeKey(new NodeId(OPENFLOW_ID_PREFIX+nodeId)); final InstanceIdentifier nodePath = InstanceIdentifier.builder(Nodes.class).child(NODE_CLASS, nodeKey).toInstance(); return new NodeRef(nodePath); } @@ -170,7 +232,8 @@ public final class NodeMapping { nodeConnectorId = toControllerNodeConnectorId(nodeId); } } else { - nodeConnectorId = new NodeConnectorId(Arguments.checkInstanceOf(nodeConnector.getID(), String.class)); + nodeConnectorId = new NodeConnectorId(OPENFLOW_ID_PREFIX + + Arguments.checkInstanceOf(nodeConnector.getID(), Short.class)); } final NodeConnectorKey connectorKey = new NodeConnectorKey(nodeConnectorId); final InstanceIdentifier path = nodePath.child(NODECONNECTOR_CLASS, connectorKey); @@ -184,11 +247,27 @@ public final class NodeMapping { public static HashSet toADNodeConnectorProperties(final NodeConnectorUpdated nc) { final FlowCapableNodeConnectorUpdated fcncu = nc.getAugmentation(FlowCapableNodeConnectorUpdated.class); if (!Objects.equal(fcncu, null)) { - return NodeMapping.toADNodeConnectorProperties(fcncu); + HashSet adNodeConnectorProperties = NodeMapping.toADNodeConnectorProperties(fcncu); + return adNodeConnectorProperties; } return new HashSet(); } + /** + * @param id + * @return node description in AD form, e.g.: OF|00:00:00:...:01 + */ + private static Description toADDescription(NodeRef nodeRef) { + Description desc; + try { + desc = new Description(toADNode(nodeRef).toString()); + } catch (ConstructionException e) { + desc = new Description("none"); + LOG.warn("node description extraction failed: {}", nodeRef); + } + return desc; + } + public static HashSet toADNodeConnectorProperties(final NodeConnector nc) { final FlowCapableNodeConnector fcnc = nc.getAugmentation(FlowCapableNodeConnector.class); if (!Objects.equal(fcnc, null)) { @@ -303,7 +382,9 @@ public final class NodeMapping { public static HashSet toADNodeProperties(final NodeUpdated nu) { final FlowCapableNodeUpdated fcnu = nu.getAugmentation(FlowCapableNodeUpdated.class); if (fcnu != null) { - return toADNodeProperties(fcnu, nu.getId()); + HashSet adNodeProperties = toADNodeProperties(fcnu, nu.getId()); + adNodeProperties.add(toADDescription(nu.getNodeRef())); + return adNodeProperties; } return new HashSet(); } @@ -342,7 +423,7 @@ public final class NodeMapping { } public static MacAddress toADMacAddress(final NodeId id) { - final String nodeId = id.getValue().replaceAll("openflow:", ""); + final String nodeId = id.getValue().replaceAll(OPENFLOW_ID_PREFIX, ""); BigInteger nodeIdRaw = new BigInteger(nodeId); long lNodeId = nodeIdRaw.longValue(); byte[] bytesFromDpid = ToSalConversionsUtils.bytesFromDpid(lNodeId); diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/ToSalConversionsUtils.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/ToSalConversionsUtils.java index 97a25bf71c..7bbf7f10e0 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/ToSalConversionsUtils.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/ToSalConversionsUtils.java @@ -208,7 +208,8 @@ public class ToSalConversionsUtils { Uri nodeConnector = ((OutputActionCase) sourceAction).getOutputAction().getOutputNodeConnector(); if (nodeConnector != null) { //for (Uri uri : nodeConnectors) { - targetAction.add(new Output(fromNodeConnectorRef(nodeConnector, node))); + Uri fullNodeConnector = new Uri(node.getType()+":"+node.getID()+":"+nodeConnector.getValue()); + targetAction.add(new Output(fromNodeConnectorRef(fullNodeConnector, node))); //} } } else if (sourceAction instanceof PopMplsActionCase) { @@ -376,12 +377,19 @@ public class ToSalConversionsUtils { return null; } - private static NodeConnector fromNodeConnectorRef(Uri uri, Node node) { + /** + * @param openflow nodeConnector uri + * @param node + * @return assembled nodeConnector + */ + public static NodeConnector fromNodeConnectorRef(Uri uri, Node node) { NodeConnector nodeConnector = null; try { - nodeConnector = new NodeConnector(NodeMapping.MD_SAL_TYPE,node.getNodeIDString()+":"+uri.getValue(),node); + NodeConnectorId nodeConnectorId = new NodeConnectorId(uri.getValue()); + nodeConnector = NodeMapping.toADNodeConnector(nodeConnectorId, node); } catch (ConstructionException e) { - e.printStackTrace(); + LOG.warn("nodeConnector creation failed at node: {} with nodeConnectorUri: {}", + node, uri.getValue()); } return nodeConnector; } diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/topology/TopologyMapping.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/topology/TopologyMapping.java index 476a71a4ac..6bc669f60b 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/topology/TopologyMapping.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/topology/TopologyMapping.java @@ -18,7 +18,9 @@ import org.opendaylight.controller.sal.compatibility.NodeMapping; import org.opendaylight.controller.sal.core.ConstructionException; import org.opendaylight.controller.sal.core.Edge; import org.opendaylight.controller.sal.core.Node; +import org.opendaylight.controller.sal.core.Node.NodeIDType; import org.opendaylight.controller.sal.core.NodeConnector; +import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType; import org.opendaylight.controller.sal.core.Property; import org.opendaylight.controller.sal.core.UpdateType; import org.opendaylight.controller.sal.topology.TopoEdgeUpdate; @@ -93,20 +95,20 @@ public final class TopologyMapping { } public static String toADNodeId(final NodeId nodeId) { - return nodeId.getValue(); + return nodeId.getValue().replaceFirst("^.*:", ""); } public static NodeConnector toADNodeConnector(final TpId source, final NodeId nodeId) throws ConstructionException { checkNotNull(source); - return new NodeConnector(NodeMapping.MD_SAL_TYPE, toADNodeConnectorId(source), toADNode(nodeId)); + return new NodeConnector(NodeConnectorIDType.OPENFLOW, Short.valueOf(toADNodeConnectorId(source)), toADNode(nodeId)); } public static String toADNodeConnectorId(final TpId nodeConnectorId) { - return nodeConnectorId.getValue(); + return nodeConnectorId.getValue().replaceFirst("^.*:", ""); } public static Node toADNode(final NodeId nodeId) throws ConstructionException { checkNotNull(nodeId); - return new Node(NodeMapping.MD_SAL_TYPE, toADNodeId(nodeId)); + return new Node(NodeIDType.OPENFLOW, Long.valueOf(toADNodeId(nodeId))); } } diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/MDFlowMappingTest.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/MDFlowMappingTest.java new file mode 100644 index 0000000000..4e5f318d4c --- /dev/null +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/MDFlowMappingTest.java @@ -0,0 +1,39 @@ +/** + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.sal.compatibility.test; + +import junit.framework.Assert; + +import org.junit.Test; +import org.opendaylight.controller.sal.compatibility.MDFlowMapping; +import org.opendaylight.controller.sal.core.ConstructionException; +import org.opendaylight.controller.sal.core.Node; +import org.opendaylight.controller.sal.core.Node.NodeIDType; +import org.opendaylight.controller.sal.core.NodeConnector; +import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri; + +/** + * test for {@link MDFlowMapping} + */ +public class MDFlowMappingTest { + + /** + * Test method for {@link org.opendaylight.controller.sal.compatibility.MDFlowMapping#toUri(org.opendaylight.controller.sal.core.NodeConnector)}. + * @throws ConstructionException + */ + @Test + public void testToUri() throws ConstructionException { + Node node = new Node(NodeIDType.OPENFLOW, 41L); + NodeConnector connector = new NodeConnector(NodeConnectorIDType.OPENFLOW, (short) 42, node); + Uri observed = MDFlowMapping.toUri(connector ); + + Assert.assertEquals("openflow:41:42", observed.getValue()); + } + +} diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/NodeMappingTest.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/NodeMappingTest.java index b418e6dc25..8a23ebc933 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/NodeMappingTest.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/NodeMappingTest.java @@ -10,9 +10,18 @@ package org.opendaylight.controller.sal.compatibility.test; import org.junit.Assert; import org.junit.Test; import org.opendaylight.controller.sal.compatibility.NodeMapping; +import org.opendaylight.controller.sal.core.ConstructionException; import org.opendaylight.controller.sal.core.MacAddress; +import org.opendaylight.controller.sal.core.Node.NodeIDType; +import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType; +import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.OutputPortValues; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector; +import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; +import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; /** * test of {@link NodeMapping} utility class @@ -67,8 +76,118 @@ public class NodeMappingTest { observed = NodeMapping.toAdNodeId(null); Assert.assertNull(observed); - observed = NodeMapping.toAdNodeId(new NodeConnectorId("MD_SAL|openflow:5:2")); - Assert.assertEquals("MD_SAL|openflow:5", observed.getValue()); + observed = NodeMapping.toAdNodeId(new NodeConnectorId("openflow:5:2")); + Assert.assertEquals("openflow:5", observed.getValue()); } + /** + * Test method for + * {@link org.opendaylight.controller.sal.compatibility.NodeMapping#toADNode(NodeId)} + * . + */ + @Test + public void testToAdNode1() { + org.opendaylight.controller.sal.core.Node observed; + try { + observed = NodeMapping.toADNode((NodeId) null); + } catch (NullPointerException | ConstructionException e) { + //expected + } + + NodeId nodeId = new NodeId("openflow:1"); + try { + observed = NodeMapping.toADNode(nodeId); + Assert.assertEquals("OF|00:00:00:00:00:00:00:01", observed.toString()); + } catch (ConstructionException e) { + Assert.fail("should succeed to construct Node: "+e.getMessage()); + } + } + + /** + * Test method for + * {@link org.opendaylight.controller.sal.compatibility.NodeMapping#toNodeConnectorType(NodeConnectorId, NodeId)} + * . + */ + @Test + public void testToNodeConnectorType() { + NodeConnectorId ncId; + NodeId nodeId = buildNodeId("1"); + + ncId = buildNodeConnectorId("1", "42"); + Assert.assertEquals(NodeConnectorIDType.OPENFLOW, NodeMapping.toNodeConnectorType(ncId, nodeId )); + + ncId = buildNodeConnectorId("1", OutputPortValues.CONTROLLER.toString()); + Assert.assertEquals(NodeConnectorIDType.CONTROLLER, NodeMapping.toNodeConnectorType(ncId, nodeId )); + + ncId = buildNodeConnectorId("1", OutputPortValues.NORMAL.toString()); + Assert.assertEquals(NodeConnectorIDType.HWPATH, NodeMapping.toNodeConnectorType(ncId, nodeId )); + + ncId = buildNodeConnectorId("1", OutputPortValues.LOCAL.toString()); + Assert.assertEquals(NodeConnectorIDType.SWSTACK, NodeMapping.toNodeConnectorType(ncId, nodeId )); + } + + /** + * Test method for + * {@link org.opendaylight.controller.sal.compatibility.NodeMapping#toADNodeConnectorId(NodeConnectorId, NodeId)} + * . + */ + @Test + public void testToAdNodeConnectorId() { + NodeConnectorId nodeConnectorId = buildNodeConnectorId("1", "2"); + NodeId nodeId = buildNodeId("1"); + Assert.assertEquals(Short.valueOf((short) 2), NodeMapping.toADNodeConnectorId(nodeConnectorId , nodeId)); + } + + /** + * Test method for + * {@link org.opendaylight.controller.sal.compatibility.NodeMapping#toNodeRef(Node)} + * . + * @throws ConstructionException + */ + @Test + public void testToNodeRef() throws ConstructionException { + org.opendaylight.controller.sal.core.Node node = new org.opendaylight.controller.sal.core.Node(NodeIDType.OPENFLOW, 42L); + InstanceIdentifier nodePath = NodeMapping.toNodeRef(node).getValue(); + + String observedId = nodePath.firstKeyOf(Node.class, NodeKey.class).getId().getValue(); + Assert.assertEquals("openflow:42", observedId); + } + + /** + * Test method for + * {@link org.opendaylight.controller.sal.compatibility.NodeMapping#toNodeConnectorRef(org.opendaylight.controller.sal.core.NodeConnector)} + * . + * @throws ConstructionException + */ + @Test + public void testToNodeConnectorRef() throws ConstructionException { + org.opendaylight.controller.sal.core.Node node = new org.opendaylight.controller.sal.core.Node(NodeIDType.OPENFLOW, 42L); + org.opendaylight.controller.sal.core.NodeConnector nodeConnector = + new org.opendaylight.controller.sal.core.NodeConnector( + NodeConnectorIDType.OPENFLOW, (short) 1, node); + + InstanceIdentifier nodeConnectorPath = NodeMapping.toNodeConnectorRef(nodeConnector ).getValue(); + String observedNodeId = nodeConnectorPath.firstKeyOf(Node.class, NodeKey.class).getId().getValue(); + Assert.assertEquals("openflow:42", observedNodeId); + + String observedNodeConnectorId = nodeConnectorPath.firstKeyOf(NodeConnector.class, NodeConnectorKey.class).getId().getValue(); + Assert.assertEquals("openflow:1", observedNodeConnectorId); + } + + /** + * @param nodeId + * @param portId + * @return nodeConnectorId + */ + public static NodeConnectorId buildNodeConnectorId(String nodeId, String portId) { + return new NodeConnectorId(NodeConnectorIDType.OPENFLOW+"|" + nodeId + ":" + portId); + } + + /** + * @param id + * @return nodeId + */ + public static NodeId buildNodeId(String id) { + return new NodeId(NodeConnectorIDType.OPENFLOW+"|" + id); + } } diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/TestToSalConversionsUtils.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/TestToSalConversionsUtils.java index 4d3509769c..0157bc0c64 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/TestToSalConversionsUtils.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/TestToSalConversionsUtils.java @@ -22,6 +22,8 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import junit.framework.Assert; + import org.junit.Test; import org.opendaylight.controller.sal.action.Flood; import org.opendaylight.controller.sal.action.FloodAll; @@ -47,6 +49,7 @@ import org.opendaylight.controller.sal.compatibility.ToSalConversionsUtils; import org.opendaylight.controller.sal.core.ConstructionException; import org.opendaylight.controller.sal.core.Node; import org.opendaylight.controller.sal.core.Node.NodeIDType; +import org.opendaylight.controller.sal.core.NodeConnector; import org.opendaylight.controller.sal.flowprogrammer.Flow; import org.opendaylight.controller.sal.match.MatchType; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Dscp; @@ -182,6 +185,17 @@ public class TestToSalConversionsUtils { checkSalFlow(salFlow); } + /** + * test of {@link ToSalConversionsUtils#fromNodeConnectorRef(Uri, Node)} + * @throws ConstructionException + */ + @Test + public void testFromNodeConnectorRef() throws ConstructionException { + Node node = new Node(NodeIDType.OPENFLOW, 42L); + NodeConnector nodeConnector = ToSalConversionsUtils.fromNodeConnectorRef(new Uri("1"), node); + Assert.assertEquals("OF|1@OF|00:00:00:00:00:00:00:2a", nodeConnector.toString()); + } + private void checkSalMatch(org.opendaylight.controller.sal.match.Match match, MtchType mt) { switch (mt) { case other: diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/topology/test/TopologyMappingTest.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/topology/test/TopologyMappingTest.java new file mode 100644 index 0000000000..b76370a538 --- /dev/null +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/topology/test/TopologyMappingTest.java @@ -0,0 +1,72 @@ +/** + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.sal.compatibility.topology.test; + +import junit.framework.Assert; + +import org.junit.Test; +import org.opendaylight.controller.sal.compatibility.topology.TopologyMapping; +import org.opendaylight.controller.sal.core.ConstructionException; +import org.opendaylight.controller.sal.core.Node; +import org.opendaylight.controller.sal.core.NodeConnector; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId; + +/** + * test for {@link TopologyMapping} + */ +public class TopologyMappingTest { + + /** + * Test method for {@link org.opendaylight.controller.sal.compatibility.topology.TopologyMapping#toADNodeId(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId)}. + */ + @Test + public void testToADNodeId() { + NodeId nodeId = new NodeId("openflow:1"); + String observedNodeId = TopologyMapping.toADNodeId(nodeId); + + Assert.assertEquals("1", observedNodeId); + } + + /** + * Test method for {@link org.opendaylight.controller.sal.compatibility.topology.TopologyMapping#toADNodeConnector(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId, org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId)}. + * @throws ConstructionException + */ + @Test + public void testToADNodeConnector() throws ConstructionException { + NodeId nodeId = new NodeId("openflow:1"); + TpId source = new TpId("foo:2"); + NodeConnector observedNodeConnector = TopologyMapping.toADNodeConnector(source, nodeId); + + Assert.assertEquals("OF|2@OF|00:00:00:00:00:00:00:01", observedNodeConnector.toString()); + } + + /** + * Test method for {@link org.opendaylight.controller.sal.compatibility.topology.TopologyMapping#toADNodeConnectorId(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId)}. + */ + @Test + public void testToADNodeConnectorId() { + TpId source = new TpId("foo:2"); + String observedNodeConnectorId = TopologyMapping.toADNodeConnectorId(source); + + Assert.assertEquals("2", observedNodeConnectorId); + } + + /** + * Test method for {@link org.opendaylight.controller.sal.compatibility.topology.TopologyMapping#toADNode(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId)}. + * @throws ConstructionException + */ + @Test + public void testToADNode() throws ConstructionException { + NodeId nodeId = new NodeId("openflow:1"); + Node observedNode = TopologyMapping.toADNode(nodeId); + + Assert.assertEquals("OF|00:00:00:00:00:00:00:01", observedNode.toString()); + } + +} diff --git a/opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-match-types.yang b/opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-match-types.yang index efe1ce3e3a..deff6f1798 100644 --- a/opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-match-types.yang +++ b/opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-match-types.yang @@ -275,6 +275,17 @@ module opendaylight-match-types { } } + grouping "tunnel-ipv4-match-fields" { + leaf tunnel-ipv4-source { + description "IPv4 source tunnel endpoint address."; + type inet:ipv4-prefix; + } + leaf tunnel-ipv4-destination { + description "IPv4 destination tunnel endpoint address."; + type inet:ipv4-prefix; + } + } + grouping match { leaf in-port { type inv:node-connector-id; @@ -321,6 +332,9 @@ module opendaylight-match-types { case "arp-match" { uses "arp-match-fields"; } + case "tunnel-ipv4-match" { + uses "tunnel-ipv4-match-fields"; + } } choice layer-4-match { diff --git a/opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-port-types.yang b/opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-port-types.yang index f1cbd8dc29..9e88098752 100644 --- a/opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-port-types.yang +++ b/opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-port-types.yang @@ -62,7 +62,10 @@ module opendaylight-port-types { grouping common-port { leaf port-number { - type uint32; + type union { + type uint32; + type string; + } } leaf hardware-address { diff --git a/opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-table-types.yang b/opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-table-types.yang index c271f8f4d0..393f6db9fe 100644 --- a/opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-table-types.yang +++ b/opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-table-types.yang @@ -192,6 +192,14 @@ module opendaylight-table-types { base match-field; description "TCP Flag Match"; } + identity tunnel_ipv4_dst { + base match-field; + description "IPv4 destination tunnel endpoint address."; + } + identity tunnel_ipv4_src { + base match-field; + description "IPv4 source tunnel endpoint address."; + } grouping set-field-match { list set-field-match { diff --git a/opendaylight/md-sal/pom.xml b/opendaylight/md-sal/pom.xml index 8f11b955a0..24dcfad02b 100644 --- a/opendaylight/md-sal/pom.xml +++ b/opendaylight/md-sal/pom.xml @@ -54,9 +54,6 @@ compatibility - - remoterpc-routingtable/implementation - sal-remoterpc-connector/implementation sal-rest-docgen diff --git a/opendaylight/md-sal/remoterpc-routingtable/implementation/pom.xml b/opendaylight/md-sal/remoterpc-routingtable/implementation/pom.xml deleted file mode 100644 index 8cab0b546c..0000000000 --- a/opendaylight/md-sal/remoterpc-routingtable/implementation/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - sal-parent - 1.1-SNAPSHOT - ../.. - - - remoterpc-routingtable.implementation - bundle - - - - com.google.guava - guava - - - - org.opendaylight.controller - clustering.services - ${clustering.services.version} - - - - org.opendaylight.controller - sal - - - org.osgi - org.osgi.compendium - - - - - org.opendaylight.controller - sal-connector-api - ${project.version} - - - - junit - junit - test - - - org.mockito - mockito-all - test - - - - - - - - org.apache.felix - maven-bundle-plugin - ${bundle.plugin.version} - true - - - org.opendaylight.controller.sal.connector.remoterpc.api, - org.opendaylight.controller.sal.connector.remoterpc.impl - javax.xml.bind.annotation, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.topology, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.md.sal.common.api.data, - org.opendaylight.yangtools.yang.binding, - org.osgi.service.component, - org.slf4j, - org.apache.felix.dm, - org.apache.commons.lang3.builder, - org.apache.commons.lang3.tuple, - org.eclipse.osgi.framework.console, - org.osgi.framework, - javax.transaction, - com.google.common.base, - com.google.common.collect - org.opendaylight.controller.sal.connector.remoterpc.impl.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RouteChangeListener.java b/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RouteChangeListener.java deleted file mode 100644 index c9b47ed54b..0000000000 --- a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RouteChangeListener.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.connector.remoterpc.api; - -import java.util.EventListener; - -public interface RouteChangeListener extends EventListener { - - - void onRouteUpdated(I key, R new_value); - - void onRouteDeleted(I key); -} diff --git a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RoutingTable.java b/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RoutingTable.java deleted file mode 100644 index e5e314cd87..0000000000 --- a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RoutingTable.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.connector.remoterpc.api; - -import java.util.Set; - -public interface RoutingTable { - - /** - * Adds a network address for the route. If the route already exists, - * it throws DuplicateRouteException. - * This method would be used when registering a global service. - * - * - * @param routeId route identifier - * @param route network address - * @throws DuplicateRouteException - * @throws RoutingTableException - */ - public void addGlobalRoute(I routeId, R route) throws RoutingTableException, SystemException; - - /** - * Remove the route. - * This method would be used when registering a global service. - * @param routeId - * @throws RoutingTableException - * @throws SystemException - */ - public void removeGlobalRoute(I routeId) throws RoutingTableException, SystemException; - - /** - * Adds a network address for the route. If the route already exists, - * it throws DuplicateRouteException. - * This method would be used when registering a global service. - * - * - * @param routeId route identifier - * @param route network address - * @throws DuplicateRouteException - * @throws RoutingTableException - */ - public R getGlobalRoute(I routeId) throws RoutingTableException, SystemException; - - /** - * Adds a network address for the route. If address for route - * exists, appends the address to the list - * - * @param routeId route identifier - * @param route network address - * @throws RoutingTableException for any logical exception - * @throws SystemException - */ - public void addRoute(I routeId, R route) throws RoutingTableException,SystemException; - - - /** - * Removes the network address for the route from routing table. If only - * one network address existed, remove the route as well. - * @param routeId - * @param route - */ - public void removeRoute(I routeId, R route) throws RoutingTableException,SystemException; - - /** - * Adds address for a set of route identifiers. If address for route - * exists, appends the address to the set. - * - * @param routeIds a set of routeIds - * @param route network address - * @throws RoutingTableException for any logical exception - * @throws SystemException - */ - public void addRoutes(Set routeIds, R route) throws RoutingTableException,SystemException; - - /** - * Removes address for a set of route identifiers. - * - * @param routeIds a set of routeIds - * @param route network address - * @throws RoutingTableException for any logical exception - * @throws SystemException - */ - public void removeRoutes(Set routeIds, R route) throws RoutingTableException,SystemException; - - /** - * Returns a set of network addresses associated with this route - * @param routeId - * @return - */ - public Set getRoutes(I routeId); - - - /** - * Returns the last inserted address from the list of network addresses - * associated with the route. - * @param routeId - * @return - */ - public R getLastAddedRoute(I routeId); - - public class DuplicateRouteException extends RoutingTableException { - public DuplicateRouteException(String message) { - super(message); - } - - } - -} diff --git a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RoutingTableException.java b/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RoutingTableException.java deleted file mode 100644 index fc7f6f1b7b..0000000000 --- a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RoutingTableException.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.connector.remoterpc.api; - -/** - * @author: syedbahm - */ -public class RoutingTableException extends Exception { - - /** - * Constructs a new exception with {@code null} as its detail message. - * The cause is not initialized, and may subsequently be initialized by a - * call to {@link #initCause}. - */ - public RoutingTableException() { - super(); - } - - /** - * Constructs a new exception with the specified detail message. The - * cause is not initialized, and may subsequently be initialized by - * a call to {@link #initCause}. - * - * @param message the detail message. The detail message is saved for - * later retrieval by the {@link #getMessage()} method. - */ - public RoutingTableException(String message) { - super(message); - } - - /** - * Constructs a new exception with the specified detail message and - * cause.

Note that the detail message associated with - * {@code cause} is not automatically incorporated in - * this exception's detail message. - * - * @param message the detail message (which is saved for later retrieval - * by the {@link #getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - */ - public RoutingTableException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/SystemException.java b/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/SystemException.java deleted file mode 100644 index 491858e2aa..0000000000 --- a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/SystemException.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - - - -package org.opendaylight.controller.sal.connector.remoterpc.api; - -/** - * @author: syedbahm - * - */ -public class SystemException extends Exception { - /** - * Constructs a new exception with {@code null} as its detail message. - * The cause is not initialized, and may subsequently be initialized by a - * call to {@link #initCause}. - */ - public SystemException() { - super(); - } - - /** - * Constructs a new exception with the specified detail message. The - * cause is not initialized, and may subsequently be initialized by - * a call to {@link #initCause}. - * - * @param message the detail message. The detail message is saved for - * later retrieval by the {@link #getMessage()} method. - */ - public SystemException(String message) { - super(message); - } - - /** - * Constructs a new exception with the specified detail message and - * cause.

Note that the detail message associated with - * {@code cause} is not automatically incorporated in - * this exception's detail message. - * - * @param message the detail message (which is saved for later retrieval - * by the {@link #getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.4 - */ - public SystemException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/impl/Activator.java b/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/impl/Activator.java deleted file mode 100644 index a826a3c1d7..0000000000 --- a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/impl/Activator.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc.impl; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.sal.connector.remoterpc.api.RouteChangeListener; -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Dictionary; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Set; - -/** - * @author: syedbahm - */ -public class Activator extends ComponentActivatorAbstractBase { - - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - private static final String CACHE_UPDATE_AWARE_REGISTRY_KEY = "cachenames" ; - - - /** - * Method which tells how many Global implementations are - * supported by the bundle. This way we can tune the number of - * components created. This components will be created ONLY at the - * time of bundle startup and will be destroyed only at time of - * bundle destruction, this is the major difference with the - * implementation retrieved via getImplementations where all of - * them are assumed to be in a container! - * - * - * @return The list of implementations the bundle will support, - * in Global version - */ - - @Override - protected Object[] getGlobalImplementations(){ - logger.debug("Calling getGlobalImplementations to return:", RoutingTableImpl.class); - return new Object[] { - RoutingTableImpl.class - }; - } - - /** - * Configure the dependency for a given instance Global - * - * @param c Component assigned for this instance, this will be - * what will be used for configuration - * @param imp implementation to be configured - * - */ - @Override - protected void configureGlobalInstance(Component c, Object imp){ - if (imp.equals(RoutingTableImpl.class)) { - Dictionary> props = new Hashtable>(); - Set propSet = new HashSet(); - propSet.add(RoutingTableImpl.GLOBALRPC_CACHE); - propSet.add(RoutingTableImpl.RPC_CACHE); - props.put(CACHE_UPDATE_AWARE_REGISTRY_KEY, propSet); - - c.setInterface(new String[] { RoutingTable.class.getName(),ICacheUpdateAware.class.getName() }, props); - logger.debug("configureGlobalInstance adding dependency:", IClusterGlobalServices.class); - - - // RouteChangeListener services will be none or many so the - // dependency is optional - c.add(createServiceDependency() - .setService(RouteChangeListener.class) - .setCallbacks("setRouteChangeListener", "unsetRouteChangeListener") - .setRequired(false)); - - //dependency is required as it provides us the caching support - c.add(createServiceDependency().setService( - IClusterGlobalServices.class).setCallbacks( - "setClusterGlobalServices", - "unsetClusterGlobalServices").setRequired(true)); - - } - } - - -} diff --git a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/impl/RoutingTableImpl.java b/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/impl/RoutingTableImpl.java deleted file mode 100644 index e242b0a393..0000000000 --- a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/impl/RoutingTableImpl.java +++ /dev/null @@ -1,464 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc.impl; - -import java.util.Collections; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; - -import javax.transaction.HeuristicMixedException; -import javax.transaction.HeuristicRollbackException; -import javax.transaction.NotSupportedException; -import javax.transaction.RollbackException; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.CacheListenerAddException; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable; -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTableException; -import org.opendaylight.controller.sal.connector.remoterpc.api.SystemException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableSet; - -public class RoutingTableImpl implements RoutingTable, ICacheUpdateAware { - - private final Logger log = LoggerFactory.getLogger(RoutingTableImpl.class); - - private IClusterGlobalServices clusterGlobalServices = null; - - private ConcurrentMap globalRpcCache = null; - private ConcurrentMap> rpcCache = null; //need routes to ordered by insert-order - - public static final String GLOBALRPC_CACHE = "remoterpc_routingtable.globalrpc_cache"; - public static final String RPC_CACHE = "remoterpc_routingtable.rpc_cache"; - - public RoutingTableImpl() { - } - - @Override - public R getGlobalRoute(final I routeId) throws RoutingTableException, SystemException { - Preconditions.checkNotNull(routeId, "getGlobalRoute: routeId cannot be null!"); - return globalRpcCache.get(routeId); - } - - @Override - public void addGlobalRoute(final I routeId, final R route) throws RoutingTableException, SystemException { - Preconditions.checkNotNull(routeId, "addGlobalRoute: routeId cannot be null!"); - Preconditions.checkNotNull(route, "addGlobalRoute: route cannot be null!"); - try { - - log.debug("addGlobalRoute: adding a new route with id[{}] and value [{}]", routeId, route); - clusterGlobalServices.tbegin(); - if (globalRpcCache.putIfAbsent(routeId, route) != null) { - throw new DuplicateRouteException(" There is already existing route " + routeId); - } - clusterGlobalServices.tcommit(); - - } catch (NotSupportedException | HeuristicRollbackException | RollbackException | HeuristicMixedException e) { - throw new RoutingTableException("Transaction error - while trying to create route id=" - + routeId + "with route" + route, e); - } catch (javax.transaction.SystemException e) { - throw new SystemException("System error occurred - while trying to create with value", e); - } - - } - - @Override - public void removeGlobalRoute(final I routeId) throws RoutingTableException, SystemException { - Preconditions.checkNotNull(routeId, "removeGlobalRoute: routeId cannot be null!"); - try { - log.debug("removeGlobalRoute: removing a new route with id [{}]", routeId); - - clusterGlobalServices.tbegin(); - globalRpcCache.remove(routeId); - clusterGlobalServices.tcommit(); - - } catch (NotSupportedException | HeuristicRollbackException | RollbackException | HeuristicMixedException e) { - throw new RoutingTableException("Transaction error - while trying to remove route id=" - + routeId, e); - } catch (javax.transaction.SystemException e) { - throw new SystemException("System error occurred - while trying to remove with value", e); - } - } - - - @Override - public Set getRoutes(final I routeId) { - Preconditions.checkNotNull(routeId, "getRoutes: routeId cannot be null!"); - Set routes = rpcCache.get(routeId); - - if (routes == null) { - return Collections.emptySet(); - } - - return ImmutableSet.copyOf(routes); - } - - - - @Override - public R getLastAddedRoute(final I routeId) { - - Set routes = getRoutes(routeId); - - if (routes.isEmpty()) { - return null; - } - - R route = null; - Iterator iter = routes.iterator(); - while (iter.hasNext()) { - route = iter.next(); - } - - return route; - } - - @Override - public void addRoute(final I routeId, final R route) throws RoutingTableException, SystemException { - Preconditions.checkNotNull(routeId, "addRoute: routeId cannot be null"); - Preconditions.checkNotNull(route, "addRoute: route cannot be null"); - - try{ - clusterGlobalServices.tbegin(); - log.debug("addRoute: adding a route with k/v [{}/{}]", routeId, route); - threadSafeAdd(routeId, route); - clusterGlobalServices.tcommit(); - - } catch (NotSupportedException | HeuristicRollbackException | RollbackException | HeuristicMixedException e) { - throw new RoutingTableException("Transaction error - while trying to remove route id=" - + routeId, e); - } catch (javax.transaction.SystemException e) { - throw new SystemException("System error occurred - while trying to remove with value", e); - } - } - - @Override - public void addRoutes(final Set routeIds, final R route) throws RoutingTableException, SystemException { - Preconditions.checkNotNull(routeIds, "addRoutes: routeIds must not be null"); - for (I routeId : routeIds){ - addRoute(routeId, route); - } - } - - @Override - public void removeRoute(final I routeId, final R route) throws RoutingTableException, SystemException { - Preconditions.checkNotNull(routeId, "removeRoute: routeId cannot be null!"); - Preconditions.checkNotNull(route, "removeRoute: route cannot be null!"); - - LinkedHashSet routes = rpcCache.get(routeId); - if (routes == null) { - return; - } - - try { - log.debug("removeRoute: removing a new route with k/v [{}/{}]", routeId, route); - - clusterGlobalServices.tbegin(); - threadSafeRemove(routeId, route); - clusterGlobalServices.tcommit(); - - } catch (NotSupportedException | HeuristicRollbackException | RollbackException | HeuristicMixedException e) { - throw new RoutingTableException("Transaction error - while trying to remove route id=" - + routeId, e); - } catch (javax.transaction.SystemException e) { - throw new SystemException("System error occurred - while trying to remove with value", e); - } - } - - @Override - public void removeRoutes(final Set routeIds, final R route) throws RoutingTableException, SystemException { - Preconditions.checkNotNull(routeIds, "removeRoutes: routeIds must not be null"); - for (I routeId : routeIds){ - removeRoute(routeId, route); - } - } - - /** - * This method guarantees that no 2 thread over write each other's changes. - * Just so that we dont end up in infinite loop, it tries for 100 times then throw - */ - private void threadSafeAdd(final I routeId, final R route) { - - for (int i=0;i<100;i++){ - - LinkedHashSet updatedRoutes = new LinkedHashSet<>(); - updatedRoutes.add(route); - LinkedHashSet oldRoutes = rpcCache.putIfAbsent(routeId, updatedRoutes); - if (oldRoutes == null) { - return; - } - - updatedRoutes = new LinkedHashSet<>(oldRoutes); - updatedRoutes.add(route); - - if (rpcCache.replace(routeId, oldRoutes, updatedRoutes)) { - return; - } - } - //the method did not already return means it failed to add route in 10 attempts - throw new IllegalStateException("Failed to add route [" + routeId + "]"); - } - - /** - * This method guarantees that no 2 thread over write each other's changes. - * Just so that we dont end up in infinite loop, it tries for 10 times then throw - */ - private void threadSafeRemove(final I routeId, final R route) { - LinkedHashSet updatedRoutes = null; - for (int i=0;i<10;i++){ - LinkedHashSet oldRoutes = rpcCache.get(routeId); - - // if route to be deleted is the only entry in the set then remove routeId from the cache - if ((oldRoutes.size() == 1) && oldRoutes.contains(route)){ - rpcCache.remove(routeId); - return; - } - - // if there are multiple routes for this routeId, remove the route to be deleted only from the set. - updatedRoutes = new LinkedHashSet<>(oldRoutes); - updatedRoutes.remove(route); - if (rpcCache.replace(routeId, oldRoutes, updatedRoutes)) { - return; - } - - } - //the method did not already return means it failed to remove route in 10 attempts - throw new IllegalStateException("Failed to remove route [" + routeId + "]"); - } - - - // /** - // * @deprecated doesn't do anything will be removed once listeners used - // * whiteboard pattern Registers listener for sending any change - // * notification - // * @param listener - // */ - // @Override - // public void registerRouteChangeListener(RouteChangeListener listener) { - // - // } - - // public void setRouteChangeListener(RouteChangeListener rcl) { - // if(rcl != null){ - // routeChangeListeners.add(rcl); - // }else{ - // log.warn("setRouteChangeListener called with null listener"); - // } - // } - // - // public void unSetRouteChangeListener(RouteChangeListener rcl) { - // if(rcl != null){ - // routeChangeListeners.remove(rcl); - // }else{ - // log.warn("unSetRouteChangeListener called with null listener"); - // } - // } - - /** - * Returning the set of route change listeners for Unit testing Note: the - * package scope is default - * - * @return List of registered RouteChangeListener listeners - */ - // Set getRegisteredRouteChangeListeners() { - // return routeChangeListeners; - // } - public void setClusterGlobalServices(final IClusterGlobalServices clusterGlobalServices) { - this.clusterGlobalServices = clusterGlobalServices; - } - - public void unsetClusterGlobalServices(final IClusterGlobalServices clusterGlobalServices) { - if ((clusterGlobalServices != null) && (this.clusterGlobalServices.equals(clusterGlobalServices))) { - this.clusterGlobalServices = null; - } - } - - /** - * Finds OR Creates clustered cache for Global RPCs - * - * @throws CacheExistException -- cluster global services exception when cache exist - * @throws CacheConfigException -- cluster global services exception during cache config - * @throws CacheListenerAddException -- cluster global services exception during adding of listener - */ - - @SuppressWarnings("unchecked") - void findOrCreateGlobalRpcCache() throws CacheExistException, CacheConfigException, - CacheListenerAddException { - // TBD: HOW DO WE DECIDE ON PROPERTIES OF THE CACHE i.e. what duration it - // should be caching? - - // let us check here if the cache already exists -- if so don't create - if (!clusterGlobalServices.existCache(GLOBALRPC_CACHE)) { - - globalRpcCache = (ConcurrentMap) clusterGlobalServices.createCache(GLOBALRPC_CACHE, - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - log.debug("Cache created [{}] ", GLOBALRPC_CACHE); - - } else { - globalRpcCache = (ConcurrentMap) clusterGlobalServices.getCache(GLOBALRPC_CACHE); - log.debug("Cache exists [{}] ", GLOBALRPC_CACHE); - } - } - - /** - * Finds OR Creates clustered cache for Routed RPCs - * - * @throws CacheExistException -- cluster global services exception when cache exist - * @throws CacheConfigException -- cluster global services exception during cache config - * @throws CacheListenerAddException -- cluster global services exception during adding of listener - */ - - @SuppressWarnings("unchecked") - void findOrCreateRpcCache() throws CacheExistException, CacheConfigException, - CacheListenerAddException { - // TBD: HOW DO WE DECIDE ON PROPERTIES OF THE CACHE i.e. what duration it - // should be caching? - - if (clusterGlobalServices.existCache(RPC_CACHE)){ - rpcCache = (ConcurrentMap>) clusterGlobalServices.getCache(RPC_CACHE); - log.debug("Cache exists [{}] ", RPC_CACHE); - return; - } - - //cache doesnt exist, create one - rpcCache = (ConcurrentMap>) clusterGlobalServices.createCache(RPC_CACHE, - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - log.debug("Cache created [{}] ", RPC_CACHE); - } - - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - */ - void init(final Component c) { - try { - - findOrCreateGlobalRpcCache(); - findOrCreateRpcCache(); - - } catch (CacheExistException|CacheConfigException|CacheListenerAddException e) { - throw new IllegalStateException("could not construct routing table cache"); - } - } - - /** - * Useful for unit testing It has package - * scope - */ - ConcurrentMap getGlobalRpcCache() { - return this.globalRpcCache; - } - - /** - * Useful for unit testing It has package - * scope - */ - ConcurrentMap> getRpcCache() { - return this.rpcCache; - } - - /** - * This is used from integration test NP rest API to check out the result of the - * cache population - * For testing purpose only-- use it wisely - * - * @return - */ - public String dumpGlobalRpcCache() { - Set> cacheEntrySet = this.globalRpcCache.entrySet(); - StringBuilder sb = new StringBuilder(); - for (Map.Entry entry : cacheEntrySet) { - sb.append("Key:").append(entry.getKey()).append("---->Value:") - .append((entry.getValue() != null) ? entry.getValue() : "null") - .append("\n"); - } - return sb.toString(); - } - - public String dumpRpcCache() { - Set>> cacheEntrySet = this.rpcCache.entrySet(); - StringBuilder sb = new StringBuilder(); - for (Map.Entry> entry : cacheEntrySet) { - sb.append("Key:").append(entry.getKey()).append("---->Value:") - .append((entry.getValue() != null) ? entry.getValue() : "null") - .append("\n"); - } - return sb.toString(); - } - /** - * Invoked when a new entry is available in the cache, the key is only - * provided, the value will come as an entryUpdate invocation - * - * @param key Key for the entry just created - * @param cacheName name of the cache for which update has been received - * @param originLocal true if the event is generated from this node - */ - @Override - public void entryCreated(final I key, final String cacheName, final boolean originLocal) { - // TBD: do we require this. - if (log.isDebugEnabled()) { - log.debug("RoutingTableUpdates: entryCreated routeId = " + key + " cacheName=" + cacheName); - } - } - - /** - * Called anytime a given entry is updated - * - * @param key Key for the entry modified - * @param new_value the new value the key will have - * @param cacheName name of the cache for which update has been received - * @param originLocal true if the event is generated from this node - */ - @Override - public void entryUpdated(final I key, final R new_value, final String cacheName, final boolean originLocal) { - if (log.isDebugEnabled()) { - log.debug("RoutingTableUpdates: entryUpdated routeId = " + key + ",value = " + new_value - + " ,cacheName=" + cacheName + " originLocal=" + originLocal); - } - // if (!originLocal) { - // for (RouteChangeListener rcl : routeChangeListeners) { - // rcl.onRouteUpdated(key, new_value); - // } - // } - } - - /** - * Called anytime a given key is removed from the ConcurrentHashMap we are - * listening to. - * - * @param key Key of the entry removed - * @param cacheName name of the cache for which update has been received - * @param originLocal true if the event is generated from this node - */ - @Override - public void entryDeleted(final I key, final String cacheName, final boolean originLocal) { - if (log.isDebugEnabled()) { - log.debug("RoutingTableUpdates: entryUpdated routeId = " + key + " local = " + originLocal - + " cacheName=" + cacheName + " originLocal=" + originLocal); - } - // if (!originLocal) { - // for (RouteChangeListener rcl : routeChangeListeners) { - // rcl.onRouteDeleted(key); - // } - // } - } -} diff --git a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/impl/RoutingTableImplTest.java b/opendaylight/md-sal/remoterpc-routingtable/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/impl/RoutingTableImplTest.java deleted file mode 100644 index 1ff49c1543..0000000000 --- a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/impl/RoutingTableImplTest.java +++ /dev/null @@ -1,334 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc.impl; - -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.when; - -import java.net.URI; -import java.util.EnumSet; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import junit.framework.Assert; - -import org.apache.felix.dm.Component; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.sal.connector.api.RpcRouter; -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; - -public class RoutingTableImplTest { - - private final URI namespace = URI.create("http://cisco.com/example"); - private final QName QNAME = new QName(namespace, "global"); - - private IClusterGlobalServices clusterService; - private RoutingTableImpl, String> routingTable; - ConcurrentMap mockGlobalRpcCache; - ConcurrentMap mockRpcCache; - - @Before - public void setUp() throws Exception{ - clusterService = mock(IClusterGlobalServices.class); - routingTable = new RoutingTableImpl, String>(); - mockGlobalRpcCache = new ConcurrentHashMap<>(); - mockRpcCache = new ConcurrentHashMap<>(); - createRoutingTableCache(); - } - - @After - public void tearDown(){ - reset(clusterService); - mockGlobalRpcCache = null; - mockRpcCache = null; - } - - @Test - public void addGlobalRoute_ValidArguments_ShouldAdd() throws Exception { - - Assert.assertNotNull(mockGlobalRpcCache); - RpcRouter.RouteIdentifier routeIdentifier = getRouteIdentifier(); - - final String expectedRoute = "172.27.12.1:5000"; - routingTable.addGlobalRoute(routeIdentifier, expectedRoute); - - ConcurrentMap latestCache = routingTable.getGlobalRpcCache(); - Assert.assertEquals(mockGlobalRpcCache, latestCache); - Assert.assertEquals(expectedRoute, latestCache.get(routeIdentifier)); - } - - @Test (expected = RoutingTable.DuplicateRouteException.class) - public void addGlobalRoute_DuplicateRoute_ShouldThrow() throws Exception{ - - Assert.assertNotNull(mockGlobalRpcCache); - - RpcRouter.RouteIdentifier routeIdentifier = getRouteIdentifier(); - routingTable.addGlobalRoute(routeIdentifier, new String()); - routingTable.addGlobalRoute(routeIdentifier, new String()); - } - - @Test - public void getGlobalRoute_ExistingRouteId_ShouldReturnRoute() throws Exception { - - Assert.assertNotNull(mockGlobalRpcCache); - RpcRouter.RouteIdentifier routeIdentifier = getRouteIdentifier(); - String expectedRoute = "172.27.12.1:5000"; - - routingTable.addGlobalRoute(routeIdentifier, expectedRoute); - - String actualRoute = routingTable.getGlobalRoute(routeIdentifier); - Assert.assertEquals(expectedRoute, actualRoute); - } - - @Test - public void getGlobalRoute_NonExistentRouteId_ShouldReturnNull() throws Exception { - - Assert.assertNotNull(mockGlobalRpcCache); - RpcRouter.RouteIdentifier routeIdentifier = getRouteIdentifier(); - - String actualRoute = routingTable.getGlobalRoute(routeIdentifier); - Assert.assertNull(actualRoute); - } - - @Test - public void removeGlobalRoute_ExistingRouteId_ShouldRemove() throws Exception { - - Assert.assertNotNull(mockGlobalRpcCache); - RpcRouter.RouteIdentifier routeIdentifier = getRouteIdentifier(); - - ConcurrentMap cache = routingTable.getGlobalRpcCache(); - Assert.assertTrue(cache.size() == 0); - routingTable.addGlobalRoute(routeIdentifier, "172.27.12.1:5000"); - Assert.assertTrue(cache.size() == 1); - - routingTable.removeGlobalRoute(routeIdentifier); - Assert.assertTrue(cache.size() == 0); - - } - - @Test - public void removeGlobalRoute_NonExistentRouteId_ShouldDoNothing() throws Exception { - - Assert.assertNotNull(mockGlobalRpcCache); - RpcRouter.RouteIdentifier routeIdentifier = getRouteIdentifier(); - - ConcurrentMap cache = routingTable.getGlobalRpcCache(); - Assert.assertTrue(cache.size() == 0); - - routingTable.removeGlobalRoute(routeIdentifier); - Assert.assertTrue(cache.size() == 0); - - } - - @Test - public void addRoute_ForNewRouteId_ShouldAddRoute() throws Exception { - Assert.assertTrue(mockRpcCache.size() == 0); - - RpcRouter.RouteIdentifier routeId = getRouteIdentifier(); - - routingTable.addRoute(routeId, new String()); - Assert.assertTrue(mockRpcCache.size() == 1); - - Set routes = routingTable.getRoutes(routeId); - Assert.assertEquals(1, routes.size()); - } - - @Test - public void addRoute_ForExistingRouteId_ShouldAppendRoute() throws Exception { - - Assert.assertTrue(mockRpcCache.size() == 0); - - RpcRouter.RouteIdentifier routeId = getRouteIdentifier(); - - String route_1 = "10.0.0.1:5955"; - String route_2 = "10.0.0.2:5955"; - - routingTable.addRoute(routeId, route_1); - routingTable.addRoute(routeId, route_2); - - Assert.assertTrue(mockRpcCache.size() == 1); - - Set routes = routingTable.getRoutes(routeId); - Assert.assertEquals(2, routes.size()); - Assert.assertTrue(routes.contains(route_1)); - Assert.assertTrue(routes.contains(route_2)); - } - - @Test - public void addRoute_UsingMultipleThreads_ShouldNotOverwrite(){ - ExecutorService threadPool = Executors.newCachedThreadPool(); - - int numOfRoutesToAdd = 100; - String routePrefix_1 = "10.0.0.1:555"; - RpcRouter.RouteIdentifier routeId = getRouteIdentifier(); - threadPool.submit(addRoutes(numOfRoutesToAdd, routePrefix_1, routeId)); - String routePrefix_2 = "10.0.0.1:556"; - threadPool.submit(addRoutes(numOfRoutesToAdd, routePrefix_2, routeId)); - - // wait for all tasks to complete; timeout in 10 sec - threadPool.shutdown(); - try { - threadPool.awaitTermination(10, TimeUnit.SECONDS); // - } catch (InterruptedException e) { - e.printStackTrace(); - } - - Assert.assertEquals(2*numOfRoutesToAdd, routingTable.getRoutes(routeId).size()); - } - - @Test(expected = NullPointerException.class) - public void addRoute_NullRouteId_shouldThrowNpe() throws Exception { - - routingTable.addRoute(null, new String()); - } - - @Test(expected = NullPointerException.class) - public void addRoute_NullRoute_shouldThrowNpe() throws Exception{ - - routingTable.addRoute(getRouteIdentifier(), null); - } - - @Test (expected = UnsupportedOperationException.class) - public void getRoutes_Call_ShouldReturnImmutableCopy() throws Exception{ - Assert.assertNotNull(routingTable); - RpcRouter.RouteIdentifier routeId = getRouteIdentifier(); - routingTable.addRoute(routeId, new String()); - - Set routes = routingTable.getRoutes(routeId); //returns Immutable Set - - routes.add(new String()); //can not be modified; should throw - } - - @Test - public void getRoutes_With2RoutesFor1RouteId_ShouldReturnASetWithSize2() throws Exception{ - Assert.assertNotNull(routingTable); - RpcRouter.RouteIdentifier routeId = getRouteIdentifier(); - routingTable.addRoute(routeId, "10.0.0.1:5555"); - routingTable.addRoute(routeId, "10.0.0.2:5555"); - - Set routes = routingTable.getRoutes(routeId); //returns Immutable Set - - Assert.assertEquals(2, routes.size()); - } - - @Test - public void getLastAddedRoute_WhenMultipleRoutesExists_ShouldReturnLatestRoute() - throws Exception { - - Assert.assertNotNull(routingTable); - RpcRouter.RouteIdentifier routeId = getRouteIdentifier(); - String route_1 = "10.0.0.1:5555"; - String route_2 = "10.0.0.2:5555"; - routingTable.addRoute(routeId, route_1); - routingTable.addRoute(routeId, route_2); - - Assert.assertEquals(route_2, routingTable.getLastAddedRoute(routeId)); - } - - @Test - public void removeRoute_WhenMultipleRoutesExist_RemovesGivenRoute() throws Exception{ - Assert.assertNotNull(routingTable); - RpcRouter.RouteIdentifier routeId = getRouteIdentifier(); - String route_1 = "10.0.0.1:5555"; - String route_2 = "10.0.0.2:5555"; - - routingTable.addRoute(routeId, route_1); - routingTable.addRoute(routeId, route_2); - - Assert.assertEquals(2, routingTable.getRoutes(routeId).size()); - - routingTable.removeRoute(routeId, route_1); - Assert.assertEquals(1, routingTable.getRoutes(routeId).size()); - - } - - @Test - public void removeRoute_WhenOnlyOneRouteExists_RemovesRouteId() throws Exception{ - Assert.assertNotNull(routingTable); - RpcRouter.RouteIdentifier routeId = getRouteIdentifier(); - String route_1 = "10.0.0.1:5555"; - - routingTable.addRoute(routeId, route_1); - Assert.assertEquals(1, routingTable.getRoutes(routeId).size()); - - routingTable.removeRoute(routeId, route_1); - ConcurrentMap cache = routingTable.getRpcCache(); - Assert.assertFalse(cache.containsKey(routeId)); - - } - - /* - * Private helper methods - */ - private void createRoutingTableCache() throws Exception { - - //here init - Component c = mock(Component.class); - - when(clusterService.existCache( - RoutingTableImpl.GLOBALRPC_CACHE)).thenReturn(false); - - when(clusterService.createCache(RoutingTableImpl.GLOBALRPC_CACHE, - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL))). - thenReturn(mockGlobalRpcCache); - - when(clusterService.existCache( - RoutingTableImpl.RPC_CACHE)).thenReturn(false); - - when(clusterService.createCache(RoutingTableImpl.RPC_CACHE, - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL))). - thenReturn(mockRpcCache); - - doNothing().when(clusterService).tbegin(); - doNothing().when(clusterService).tcommit(); - - routingTable.setClusterGlobalServices(this.clusterService); - routingTable.init(c); - - Assert.assertEquals(mockGlobalRpcCache, routingTable.getGlobalRpcCache()); - Assert.assertEquals(mockRpcCache, routingTable.getRpcCache()); - } - - private RpcRouter.RouteIdentifier getRouteIdentifier(){ - RpcRouter.RouteIdentifier routeIdentifier = mock(RpcRouter.RouteIdentifier.class); - InstanceIdentifier identifier = mock(InstanceIdentifier.class); - when(routeIdentifier.getType()).thenReturn(QNAME); - when(routeIdentifier.getRoute()).thenReturn(identifier); - - return routeIdentifier; - } - - private Runnable addRoutes(final int numRoutes, final String routePrefix, final RpcRouter.RouteIdentifier routeId){ - return new Runnable() { - @Override - public void run() { - for (int i=0;i - - 4.0.0 - - org.opendaylight.controller - commons.integrationtest - 0.5.1-SNAPSHOT - ../../../commons/integrationtest - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - HEAD - - - remoterpc-routingtable.integrationtest - 0.4.1-SNAPSHOT - - - - org.opendaylight.controller - remoterpc-routingtable.implementation - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.implementation - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - containermanager.it.implementation - - - org.opendaylight.controller - clustering.stub - - - junit - junit - - - org.ops4j.pax.exam - pax-exam-container-native - test - - - org.ops4j.pax.exam - pax-exam-link-mvn - test - - - org.ops4j.pax.url - pax-url-aether - test - - - org.slf4j - log4j-over-slf4j - - - ch.qos.logback - logback-core - - - ch.qos.logback - logback-classic - - - org.apache.felix - org.apache.felix.dependencymanager.shell - - - eclipselink - javax.resource - - - com.google.guava - guava - - - org.opendaylight.controller - sal - - - org.opendaylight.yangtools - yang-binding - - - org.opendaylight.yangtools - yang-common - - - org.opendaylight.controller - sal-connector-api - - - org.opendaylight.controller - sal-common-util - - - - junit - junit - - - org.opendaylight.controller - sal-common-api - - - org.opendaylight.controller - sal-binding-broker-impl - - - org.ops4j.pax.exam - pax-exam-container-native - ${exam.version} - test - - - org.ops4j.pax.exam - pax-exam-junit4 - ${exam.version} - test - - - org.ops4j.pax.exam - pax-exam-link-mvn - ${exam.version} - test - - - - org.opendaylight.controller - config-manager - - - equinoxSDK381 - org.eclipse.osgi - test - - - org.slf4j - log4j-over-slf4j - - - ch.qos.logback - logback-core - - - ch.qos.logback - logback-classic - - - org.opendaylight.yangtools.thirdparty - antlr4-runtime-osgi-nohead - - - org.opendaylight.yangtools.thirdparty - xtend-lib-osgi - - - - org.opendaylight.controller - clustering.services - - - junit - junit - test - - - - equinoxSDK381 - org.eclipse.osgi - - - org.ops4j.pax.exam - pax-exam-junit4 - ${exam.version} - - - org.ops4j.pax.exam - pax-exam - ${exam.version} - - - - - ../implementation/target/jacoco.exec - ../implementation/target/jacoco-it.exec - - - - - org.jacoco - jacoco-maven-plugin - - ../implementation/target/jacoco-it.exec - org.opendaylight.controller.* - - - - pre-test - - prepare-agent - - - - post-test - - true - - - - - - - diff --git a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/impl/ZeroMQRoutingTableTestIT.java b/opendaylight/md-sal/remoterpc-routingtable/integrationtest/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/impl/ZeroMQRoutingTableTestIT.java deleted file mode 100644 index 924921264f..0000000000 --- a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/impl/ZeroMQRoutingTableTestIT.java +++ /dev/null @@ -1,330 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.connector.remoterpc.impl; - -import junit.framework.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.opendaylight.controller.sal.connector.api.RpcRouter; -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; -import org.ops4j.pax.exam.Configuration; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.junit.PaxExam; -import org.ops4j.pax.exam.util.PathUtils; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import java.io.Serializable; -import java.net.URI; -import java.util.Set; - -import static org.ops4j.pax.exam.CoreOptions.junitBundles; -import static org.ops4j.pax.exam.CoreOptions.mavenBundle; -import static org.ops4j.pax.exam.CoreOptions.options; -import static org.ops4j.pax.exam.CoreOptions.systemPackages; -import static org.ops4j.pax.exam.CoreOptions.systemProperty; - - - - -@RunWith(PaxExam.class) -public class - ZeroMQRoutingTableTestIT { - private Logger log = LoggerFactory - .getLogger(ZeroMQRoutingTableTestIT.class); - - public static final String ODL = "org.opendaylight.controller"; - public static final String YANG = "org.opendaylight.yangtools"; - public static final String CONTROLLER = "org.opendaylight.controller"; - public static final String YANGTOOLS = "org.opendaylight.yangtools"; - RoutingIdentifierImpl rii = new RoutingIdentifierImpl(); - // get the OSGI bundle context - @Inject - private BundleContext bc; - @Inject - private RoutingTable routingTable = null; - - // Configure the OSGi container - @Configuration - public Option[] config() { - return options( - // - systemProperty("logback.configurationFile").value( - "file:" + PathUtils.getBaseDir() - + "/src/test/resources/logback.xml"), - // To start OSGi console for inspection remotely - systemProperty("osgi.console").value("2401"), - // Set the systemPackages (used by clustering) - systemPackages("sun.reflect", "sun.reflect.misc", "sun.misc"), - // List framework bundles - - mavenBundle("equinoxSDK381", - "org.eclipse.equinox.console").versionAsInProject(), - mavenBundle("equinoxSDK381", - "org.eclipse.equinox.util").versionAsInProject(), - mavenBundle("equinoxSDK381", - "org.eclipse.osgi.services").versionAsInProject(), - mavenBundle("equinoxSDK381", - "org.eclipse.equinox.ds").versionAsInProject(), - mavenBundle("equinoxSDK381", - "org.apache.felix.gogo.command").versionAsInProject(), - mavenBundle("equinoxSDK381", - "org.apache.felix.gogo.runtime").versionAsInProject(), - mavenBundle("equinoxSDK381", - "org.apache.felix.gogo.shell").versionAsInProject(), - // List logger bundles - mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(), - mavenBundle("org.slf4j", "log4j-over-slf4j").versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-core").versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject(), - // List all the bundles on which the test case depends - mavenBundle(ODL, - "clustering.services").versionAsInProject(), - - mavenBundle(ODL, "sal").versionAsInProject(), - mavenBundle(ODL, - "sal.implementation").versionAsInProject(), - mavenBundle(ODL, "containermanager").versionAsInProject(), - mavenBundle(ODL, - "containermanager.it.implementation").versionAsInProject(), - mavenBundle("org.jboss.spec.javax.transaction", - "jboss-transaction-api_1.1_spec").versionAsInProject(), - mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject(), - mavenBundle("org.apache.felix", - "org.apache.felix.dependencymanager").versionAsInProject(), - mavenBundle("org.apache.felix", - "org.apache.felix.dependencymanager.shell").versionAsInProject(), - mavenBundle("eclipselink", "javax.resource").versionAsInProject(), - - mavenBundle("com.google.guava","guava").versionAsInProject(), - // List logger bundles - mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(), - mavenBundle("org.slf4j", "log4j-over-slf4j") - .versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-core") - .versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-classic") - .versionAsInProject(), - - mavenBundle(ODL, "clustering.services") - .versionAsInProject(), - mavenBundle(ODL, "clustering.stub") - .versionAsInProject(), - - - // List all the bundles on which the test case depends - mavenBundle(ODL, "sal") - .versionAsInProject(), - mavenBundle(ODL, "sal-connector-api") - .versionAsInProject(), - mavenBundle(ODL, "remoterpc-routingtable.implementation") - .versionAsInProject(), - - mavenBundle("org.jboss.spec.javax.transaction", - "jboss-transaction-api_1.1_spec").versionAsInProject(), - mavenBundle("org.apache.commons", "commons-lang3") - .versionAsInProject(), - mavenBundle("org.apache.felix", - "org.apache.felix.dependencymanager") - .versionAsInProject(), - - mavenBundle(ODL, - "sal-core-api") - .versionAsInProject(), - mavenBundle("org.opendaylight.yangtools","yang-data-api") - .versionAsInProject(), - mavenBundle("org.opendaylight.yangtools","yang-model-api") - .versionAsInProject(), - mavenBundle("org.opendaylight.yangtools","yang-binding") - .versionAsInProject(), - - mavenBundle(CONTROLLER, "sal-binding-api").versionAsInProject(), // - mavenBundle(CONTROLLER, "sal-binding-config").versionAsInProject(), - mavenBundle(CONTROLLER, "sal-binding-broker-impl").versionAsInProject(), // - mavenBundle("org.javassist", "javassist").versionAsInProject(), // - mavenBundle(CONTROLLER, "sal-common-util").versionAsInProject(), // - - mavenBundle(YANGTOOLS, "yang-data-api").versionAsInProject(), // - mavenBundle(YANGTOOLS, "yang-data-impl").versionAsInProject(), // - mavenBundle(YANGTOOLS, "yang-model-api").versionAsInProject(), // - mavenBundle(YANGTOOLS, "yang-model-util").versionAsInProject(), // - mavenBundle(YANGTOOLS, "yang-parser-api").versionAsInProject(), - mavenBundle(YANGTOOLS, "yang-parser-impl").versionAsInProject(), - - - mavenBundle(YANGTOOLS, "binding-generator-spi").versionAsInProject(), // - mavenBundle(YANGTOOLS, "binding-model-api").versionAsInProject(), // - mavenBundle(YANGTOOLS, "binding-generator-util").versionAsInProject(), - mavenBundle(YANGTOOLS, "yang-parser-impl").versionAsInProject(), - mavenBundle(YANGTOOLS, "binding-type-provider").versionAsInProject(), - mavenBundle(YANGTOOLS, "binding-generator-api").versionAsInProject(), - mavenBundle(YANGTOOLS, "binding-generator-spi").versionAsInProject(), - mavenBundle(YANGTOOLS, "binding-generator-impl").versionAsInProject(), - - - mavenBundle(CONTROLLER, "sal-core-api").versionAsInProject().update(), // - mavenBundle(CONTROLLER, "sal-broker-impl").versionAsInProject(), // - mavenBundle(CONTROLLER, "sal-core-spi").versionAsInProject().update(), // - - mavenBundle(YANGTOOLS + ".thirdparty", "antlr4-runtime-osgi-nohead").versionAsInProject(), // - - mavenBundle(YANG+".thirdparty", "xtend-lib-osgi").versionAsInProject(), - mavenBundle("com.google.guava", "guava").versionAsInProject(), // - mavenBundle("org.javassist", "javassist").versionAsInProject(), - mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(), // - mavenBundle("org.slf4j", "log4j-over-slf4j").versionAsInProject(), // - mavenBundle("ch.qos.logback", "logback-core").versionAsInProject(), // - mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject(), // - - mavenBundle(ODL, "sal-common").versionAsInProject(), // - mavenBundle(ODL, "sal-common-api").versionAsInProject(),// - mavenBundle(ODL, "sal-common-impl").versionAsInProject(), // - mavenBundle(ODL, "sal-common-util").versionAsInProject(), // - - mavenBundle(ODL, "config-api").versionAsInProject(), // - mavenBundle(ODL, "config-manager").versionAsInProject(), // - mavenBundle("commons-io", "commons-io").versionAsInProject(), - mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject(), - - mavenBundle(ODL, "sal-binding-api").versionAsInProject(), // - mavenBundle(ODL, "sal-binding-config").versionAsInProject(), - mavenBundle("org.javassist", "javassist").versionAsInProject(), // - mavenBundle(ODL, "sal-common-util").versionAsInProject(), // - - mavenBundle(YANG, "yang-data-api").versionAsInProject(), // - mavenBundle(YANG, "yang-data-impl").versionAsInProject(), // - mavenBundle(YANG, "yang-model-api").versionAsInProject(), // - mavenBundle(YANG, "yang-model-util").versionAsInProject(), // - mavenBundle(YANG, "yang-parser-api").versionAsInProject(), - mavenBundle(YANG, "yang-parser-impl").versionAsInProject(), - - - mavenBundle(YANG, "binding-generator-spi").versionAsInProject(), // - mavenBundle(YANG, "binding-model-api").versionAsInProject(), // - mavenBundle(YANG, "binding-generator-util").versionAsInProject(), - mavenBundle(YANG, "yang-parser-impl").versionAsInProject(), - mavenBundle(YANG, "binding-type-provider").versionAsInProject(), - mavenBundle(YANG, "binding-generator-api").versionAsInProject(), - mavenBundle(YANG, "binding-generator-spi").versionAsInProject(), - mavenBundle(YANG, "binding-generator-impl").versionAsInProject(), - - - mavenBundle(ODL, "sal-core-api").versionAsInProject().update(), // - mavenBundle(ODL, "sal-broker-impl").versionAsInProject(), // - mavenBundle(ODL, "sal-core-spi").versionAsInProject().update(), // - - mavenBundle(YANG + ".thirdparty", "antlr4-runtime-osgi-nohead").versionAsInProject(), // - - mavenBundle(YANG, "concepts").versionAsInProject(), - mavenBundle(YANG, "yang-binding").versionAsInProject(), // - mavenBundle(YANG, "yang-common").versionAsInProject(), // - mavenBundle(YANG+".thirdparty", "xtend-lib-osgi").versionAsInProject(), - mavenBundle("com.google.guava", "guava").versionAsInProject(), // - mavenBundle("org.javassist", "javassist").versionAsInProject(), - - junitBundles()); - } - - private String stateToString(int state) { - switch (state) { - case Bundle.ACTIVE: - return "ACTIVE"; - case Bundle.INSTALLED: - return "INSTALLED"; - case Bundle.RESOLVED: - return "RESOLVED"; - case Bundle.UNINSTALLED: - return "UNINSTALLED"; - default: - return "Not CONVERTED"; - } - } - - @Test - public void testAddGlobalRoute () throws Exception{ - - routingTable.addGlobalRoute(rii,"172.27.12.1:5000"); - - Set routes = routingTable.getRoutes(rii); - - for(String route:routes){ - Assert.assertEquals(route,"172.27.12.1:5000"); - } - - - } - - - @Test - public void testDeleteGlobalRoute () throws Exception{ - - routingTable.removeGlobalRoute(rii); - - Set routes = routingTable.getRoutes(rii); - - Assert.assertNull(routes); - - - } - - - - class RoutingIdentifierImpl implements RpcRouter.RouteIdentifier,Serializable { - - private final URI namespace = URI.create("http://cisco.com/example"); - private final QName QNAME = new QName(namespace,"global"); - private final QName instance = new QName(URI.create("127.0.0.1"),"local"); - - @Override - public QName getContext() { - return QNAME; - } - - @Override - public QName getType() { - return QNAME; - } - - @Override - public org.opendaylight.yangtools.yang.data.api.InstanceIdentifier getRoute() { - return InstanceIdentifier.of(instance); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - RoutingIdentifierImpl that = (RoutingIdentifierImpl) o; - - if (QNAME != null ? !QNAME.equals(that.QNAME) : that.QNAME != null) return false; - if (instance != null ? !instance.equals(that.instance) : that.instance != null) return false; - if (namespace != null ? !namespace.equals(that.namespace) : that.namespace != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = namespace != null ? namespace.hashCode() : 0; - result = 31 * result + (QNAME != null ? QNAME.hashCode() : 0); - result = 31 * result + (instance != null ? instance.hashCode() : 0); - return result; - } - } - - - - - -} diff --git a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/src/test/resources/logback.xml b/opendaylight/md-sal/remoterpc-routingtable/integrationtest/src/test/resources/logback.xml deleted file mode 100644 index 6d9dfda9a3..0000000000 --- a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/src/test/resources/logback.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - diff --git a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/pom.xml b/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/pom.xml deleted file mode 100644 index d74e7130a4..0000000000 --- a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/pom.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - 4.0.0 - - sal-remoterpc-connector-test-parent - org.opendaylight.controller.tests - 1.1-SNAPSHOT - - - remoterpc-routingtable-nb-it - bundle - - - - - org.apache.felix - maven-bundle-plugin - ${bundle.plugin.version} - true - - - - org.opendaylight.controller.tests.zmqroutingtable.rest - - - com.sun.jersey.spi.container.servlet, - com.fasterxml.jackson.annotation, - javax.ws.rs, - javax.ws.rs.core, - javax.xml.bind, - javax.xml.bind.annotation, - org.slf4j, - org.apache.catalina.filters, - org.codehaus.jackson.jaxrs, - org.opendaylight.controller.sal.utils, - org.opendaylight.yangtools.yang.common, - org.opendaylight.controller.sal.connector.api, - org.opendaylight.controller.sal.connector.remoterpc.api, - org.opendaylight.controller.sal.connector.remoterpc.impl, - org.osgi.framework, - com.google.common.base, - org.opendaylight.yangtools.yang.data.api, - !org.codehaus.enunciate.jaxrs - - - /controller/nb/v2/zmqnbrt - ,${classes;ANNOTATION;javax.ws.rs.Path} - - ${project.basedir}/src/main/resources/META-INF - - - - - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - sal - - - - org.osgi - org.osgi.core - - - junit - junit - - - org.opendaylight.controller - remoterpc-routingtable.implementation - - - com.google.guava - guava - - - - diff --git a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqroutingtable/rest/RouteIdentifierImpl.java b/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqroutingtable/rest/RouteIdentifierImpl.java deleted file mode 100644 index eb5ecd798c..0000000000 --- a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqroutingtable/rest/RouteIdentifierImpl.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.tests.zmqroutingtable.rest; - -import org.opendaylight.controller.sal.connector.api.RpcRouter; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; - -import java.io.Serializable; -import java.net.URI; - -/** - * @author: syedbahm - * Date: 12/10/13 - */ -public class RouteIdentifierImpl implements RpcRouter.RouteIdentifier, Serializable { - - private final URI namespace; - private final QName QNAME; - private final QName instance; - - public RouteIdentifierImpl() { - namespace = URI.create("http://cisco.com/example"); - QNAME = new QName(namespace, "global"); - instance = new QName(URI.create("127.0.0.1"), "local"); - } - - public RouteIdentifierImpl(String url,String instanceIP){ - namespace = URI.create(url); - QNAME = new QName(namespace,"global"); - instance = new QName(URI.create(instanceIP), "local"); - } - - - @Override - public QName getContext() { - return QNAME; - } - - @Override - public QName getType() { - return QNAME; - } - - @Override - public org.opendaylight.yangtools.yang.data.api.InstanceIdentifier getRoute() { - return InstanceIdentifier.of(instance); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - RouteIdentifierImpl that = (RouteIdentifierImpl) o; - - if (!QNAME.equals(that.QNAME)) return false; - if (!instance.equals(that.instance)) return false; - if (!namespace.equals(that.namespace)) return false; - - return true; - } - - @Override - public int hashCode() { - int result = namespace.hashCode(); - result = 31 * result + QNAME.hashCode(); - result = 31 * result + instance.hashCode(); - return result; - } -} diff --git a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqroutingtable/rest/Router.java b/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqroutingtable/rest/Router.java deleted file mode 100644 index 9bf6e53424..0000000000 --- a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqroutingtable/rest/Router.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.tests.zmqroutingtable.rest; - -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable; -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTableException; -import org.opendaylight.controller.sal.connector.remoterpc.api.SystemException; -import org.opendaylight.controller.sal.connector.remoterpc.impl.RoutingTableImpl; -import org.opendaylight.yangtools.yang.common.QName; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleReference; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import java.io.Serializable; -import java.net.URI; - -@Path("router") -public class Router implements Serializable { - private Logger _logger = LoggerFactory.getLogger(Router.class); - private final URI namespace = URI.create("http://cisco.com/example"); - private final QName QNAME = new QName(namespace, "heartbeat"); - - - @GET - @Path("/hello") - @Produces(MediaType.TEXT_PLAIN) - public String hello() { - return "Hello"; - } - - - - - @GET - @Path("/rtadd") - @Produces(MediaType.TEXT_PLAIN) - public String addToRoutingTable(@QueryParam("nsp") String namespace,@QueryParam("inst") String instance,@QueryParam("port") String port) { - _logger.info("Invoking adding an entry in routing table"); - - BundleContext ctx = getBundleContext(); - ServiceReference routingTableServiceReference = ctx.getServiceReference(RoutingTable.class); - if (routingTableServiceReference == null) { - _logger.debug("Could not get routing table impl reference"); - return "Could not get routingtable referen "; - } - RoutingTableImpl routingTable = (RoutingTableImpl) ctx.getService(routingTableServiceReference); - if (routingTable == null) { - _logger.info("Could not get routing table service"); - return "Could not get routing table service"; - } - - - RouteIdentifierImpl rii = new RouteIdentifierImpl(namespace,instance); - try { - routingTable.addGlobalRoute(rii, instance+":"+ port); - } catch (RoutingTableException e) { - _logger.error("error in adding routing identifier" + e.getMessage()); - - } catch (SystemException e) { - _logger.error("error in adding routing identifier" + e.getMessage()); - } - - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("Result of adding route:").append("\n") - .append(routingTable.dumpRoutingTableCache()); - return stringBuilder.toString(); - } - - @GET - @Path("/rtdelete") - @Produces(MediaType.TEXT_PLAIN) - public String invokeDeleteRoutingTable(@QueryParam("nsp") String namespace,@QueryParam("inst") String instance) { - _logger.info("Invoking delete an entry in routing table"); - - BundleContext ctx = getBundleContext(); - ServiceReference routingTableServiceReference = ctx.getServiceReference(RoutingTable.class); - if (routingTableServiceReference == null) { - _logger.debug("Could not get routing table impl reference"); - return "Could not get routingtable referen "; - } - RoutingTableImpl routingTable = (RoutingTableImpl) ctx.getService(routingTableServiceReference); - if (routingTable == null) { - _logger.info("Could not get routing table service"); - return "Could not get routing table service"; - } - - - RouteIdentifierImpl rii = new RouteIdentifierImpl(namespace,instance); - try { - routingTable.removeGlobalRoute(rii); - } catch (RoutingTableException e) { - _logger.error("error in adding routing identifier" + e.getMessage()); - - } catch (SystemException e) { - _logger.error("error in adding routing identifier" + e.getMessage()); - } - - - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("Result of deleting route:").append("\n") - .append(routingTable.dumpRoutingTableCache()); - - return stringBuilder.toString(); - } - - @GET - @Path("/routingtable") - @Produces(MediaType.TEXT_PLAIN) - public String invokeGetRoutingTable() { - _logger.info("Invoking getting of routing table"); - - BundleContext ctx = getBundleContext(); - ServiceReference routingTableServiceReference = ctx.getServiceReference(RoutingTable.class); - if (routingTableServiceReference == null) { - _logger.debug("Could not get routing table impl reference"); - return "Could not get routingtable referen "; - } - RoutingTableImpl routingTable = (RoutingTableImpl) ctx.getService(routingTableServiceReference); - if (routingTable == null) { - _logger.info("Could not get routing table service"); - return "Could not get routing table service"; - } - - - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("Result of getting routetable:").append("\n") - .append(routingTable.dumpRoutingTableCache()); - - return stringBuilder.toString(); - } - - - - private BundleContext getBundleContext() { - ClassLoader tlcl = Thread.currentThread().getContextClassLoader(); - Bundle bundle = null; - - if (tlcl instanceof BundleReference) { - bundle = ((BundleReference) tlcl).getBundle(); - } else { - _logger.info("Unable to determine the bundle context based on " + - "thread context classloader."); - bundle = FrameworkUtil.getBundle(this.getClass()); - } - return (bundle == null ? null : bundle.getBundleContext()); - } - - - -} diff --git a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/resources/WEB-INF/web.xml b/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 2a0f3f3651..0000000000 --- a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - - JAXRSZmqRT - com.sun.jersey.spi.container.servlet.ServletContainer - - javax.ws.rs.Application - org.opendaylight.controller.northbound.commons.NorthboundApplication - - 1 - - - - JAXRSZmqRT - /* - - - - - - - NB api - /* - POST - GET - PUT - PATCH - DELETE - HEAD - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - BASIC - opendaylight - - diff --git a/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataBroker.java b/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/DataBroker.java similarity index 51% rename from opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataBroker.java rename to opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/DataBroker.java index 7eee5c8b62..0b3658a6a6 100644 --- a/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataBroker.java +++ b/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/DataBroker.java @@ -13,17 +13,23 @@ import org.opendaylight.yangtools.concepts.ListenerRegistration; import org.opendaylight.yangtools.yang.binding.DataObject; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -public interface BindingDataBroker extends AsyncDataBroker, DataObject, BindingDataChangeListener>, BindingService { +/** + * Provides access to a conceptual data tree store and also provides the ability to + * subscribe for changes to data under a given branch of the tree. + *

+ * For more information on usage, please see the documentation in {@link AsyncDataBroker}. + */ +public interface DataBroker extends AsyncDataBroker, DataObject, DataChangeListener>, BindingService { @Override - BindingDataReadTransaction newReadOnlyTransaction(); + ReadOnlyTransaction newReadOnlyTransaction(); @Override - BindingDataReadWriteTransaction newReadWriteTransaction(); + ReadWriteTransaction newReadWriteTransaction(); @Override - BindingDataWriteTransaction newWriteOnlyTransaction(); + WriteTransaction newWriteOnlyTransaction(); @Override - ListenerRegistration registerDataChangeListener(LogicalDatastoreType store, - InstanceIdentifier path, BindingDataChangeListener listener, DataChangeScope triggeringScope); + ListenerRegistration registerDataChangeListener(LogicalDatastoreType store, + InstanceIdentifier path, DataChangeListener listener, DataChangeScope triggeringScope); } diff --git a/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataChangeListener.java b/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/DataChangeListener.java similarity index 87% rename from opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataChangeListener.java rename to opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/DataChangeListener.java index 94ac2d21a3..65257a328a 100644 --- a/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataChangeListener.java +++ b/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/DataChangeListener.java @@ -12,7 +12,7 @@ import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListene import org.opendaylight.yangtools.yang.binding.DataObject; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -public interface BindingDataChangeListener extends AsyncDataChangeListener, DataObject> { +public interface DataChangeListener extends AsyncDataChangeListener, DataObject> { @Override void onDataChanged(AsyncDataChangeEvent, DataObject> change); } diff --git a/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/ReadOnlyTransaction.java b/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/ReadOnlyTransaction.java new file mode 100644 index 0000000000..f3b42b96f0 --- /dev/null +++ b/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/ReadOnlyTransaction.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.md.sal.binding.api; + +import org.opendaylight.controller.md.sal.common.api.data.AsyncReadOnlyTransaction; +import org.opendaylight.yangtools.yang.binding.DataObject; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; + +/** + * A transaction that provides a stateful read-only view of the data tree. + *

+ * For more information on usage and examples, please see the documentation in + * {@link org.opendaylight.controller.md.sal.common.api.data.AsyncReadTransaction}. + */ +public interface ReadOnlyTransaction extends ReadTransaction, AsyncReadOnlyTransaction, DataObject> { + +} diff --git a/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataReadTransaction.java b/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/ReadTransaction.java similarity index 88% rename from opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataReadTransaction.java rename to opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/ReadTransaction.java index 93df3eb1e2..a7b5f32957 100644 --- a/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataReadTransaction.java +++ b/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/ReadTransaction.java @@ -15,7 +15,7 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import com.google.common.base.Optional; import com.google.common.util.concurrent.ListenableFuture; -public interface BindingDataReadTransaction extends AsyncReadTransaction, DataObject> { +public interface ReadTransaction extends AsyncReadTransaction, DataObject> { @Override ListenableFuture> read(LogicalDatastoreType store, InstanceIdentifier path); } diff --git a/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataReadWriteTransaction.java b/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/ReadWriteTransaction.java similarity index 64% rename from opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataReadWriteTransaction.java rename to opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/ReadWriteTransaction.java index 0dcf020c37..9fbbbe5a73 100644 --- a/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataReadWriteTransaction.java +++ b/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/ReadWriteTransaction.java @@ -12,9 +12,10 @@ import org.opendaylight.yangtools.yang.binding.DataObject; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; /** - * Logical capture of a combination of both {@link BindingDataReadTransaction} and - * {@link BindingDataWriteTransaction}. + * A transaction that enables combined read/write capabilities. + *

+ * For more information on usage and examples, please see the documentation in {@link AsyncReadWriteTransaction}. */ -public interface BindingDataReadWriteTransaction extends BindingDataReadTransaction, BindingDataWriteTransaction, AsyncReadWriteTransaction, DataObject> { +public interface ReadWriteTransaction extends ReadTransaction, WriteTransaction, AsyncReadWriteTransaction, DataObject> { } diff --git a/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataWriteTransaction.java b/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/WriteTransaction.java similarity index 74% rename from opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataWriteTransaction.java rename to opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/WriteTransaction.java index e989f73f39..0cef81d359 100644 --- a/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataWriteTransaction.java +++ b/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/WriteTransaction.java @@ -12,7 +12,12 @@ import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.yangtools.yang.binding.DataObject; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -public interface BindingDataWriteTransaction extends AsyncWriteTransaction, DataObject> { +/** + * A transaction that provides mutation capabilities on a data tree. + *

+ * For more information on usage and examples, please see the documentation in {@link AsyncWriteTransaction}. + */ +public interface WriteTransaction extends AsyncWriteTransaction, DataObject> { @Override void put(LogicalDatastoreType store, InstanceIdentifier path, DataObject data); diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedDataBroker.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedDataBroker.java index b09cd1c80a..f24809de45 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedDataBroker.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedDataBroker.java @@ -14,7 +14,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import org.opendaylight.controller.md.sal.binding.api.BindingDataChangeListener; +import org.opendaylight.controller.md.sal.binding.api.DataChangeListener; import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope; import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; @@ -83,8 +83,8 @@ public abstract class AbstractForwardedDataBroker implements Delegator registerDataChangeListener(final LogicalDatastoreType store, - final InstanceIdentifier path, final BindingDataChangeListener listener, + public ListenerRegistration registerDataChangeListener(final LogicalDatastoreType store, + final InstanceIdentifier path, final DataChangeListener listener, final DataChangeScope triggeringScope) { DOMDataChangeListener domDataChangeListener = new TranslatingDataChangeInvoker(store, path, listener, triggeringScope); @@ -143,13 +143,13 @@ public abstract class AbstractForwardedDataBroker implements Delegator path; private final DataChangeScope triggeringScope; public TranslatingDataChangeInvoker(final LogicalDatastoreType store, final InstanceIdentifier path, - final BindingDataChangeListener bindingDataChangeListener, final DataChangeScope triggeringScope) { + final DataChangeListener bindingDataChangeListener, final DataChangeScope triggeringScope) { this.store = store; this.path = path; this.bindingDataChangeListener = bindingDataChangeListener; @@ -250,10 +250,10 @@ public abstract class AbstractForwardedDataBroker implements Delegator { + private static class ListenerRegistrationImpl extends AbstractListenerRegistration { private final ListenerRegistration registration; - public ListenerRegistrationImpl(final BindingDataChangeListener listener, + public ListenerRegistrationImpl(final DataChangeListener listener, final ListenerRegistration registration) { super(listener); this.registration = registration; diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedTransaction.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedTransaction.java index a935a33a5e..3fac0dc93a 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedTransaction.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedTransaction.java @@ -180,8 +180,8 @@ public class AbstractForwardedTransaction> doRead(final DOMDataReadTransaction readTransaction, diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/ForwardedBackwardsCompatibleDataBroker.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/ForwardedBackwardsCompatibleDataBroker.java index bf18454f4d..49d04d04b3 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/ForwardedBackwardsCompatibleDataBroker.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/ForwardedBackwardsCompatibleDataBroker.java @@ -18,7 +18,6 @@ import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; -import org.opendaylight.controller.md.sal.binding.api.BindingDataChangeListener; import org.opendaylight.controller.md.sal.common.api.RegistrationListener; import org.opendaylight.controller.md.sal.common.api.TransactionStatus; import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope; @@ -113,11 +112,11 @@ public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDat final InstanceIdentifier path, final DataChangeListener listener) { - BindingDataChangeListener asyncOperListener = new BackwardsCompatibleOperationalDataChangeInvoker(listener); - BindingDataChangeListener asyncCfgListener = new BackwardsCompatibleConfigurationDataChangeInvoker(listener); + org.opendaylight.controller.md.sal.binding.api.DataChangeListener asyncOperListener = new BackwardsCompatibleOperationalDataChangeInvoker(listener); + org.opendaylight.controller.md.sal.binding.api.DataChangeListener asyncCfgListener = new BackwardsCompatibleConfigurationDataChangeInvoker(listener); - ListenerRegistration cfgReg = registerDataChangeListener(LogicalDatastoreType.CONFIGURATION, path, asyncCfgListener, DataChangeScope.SUBTREE); - ListenerRegistration operReg = registerDataChangeListener(LogicalDatastoreType.OPERATIONAL, path, asyncOperListener, DataChangeScope.SUBTREE); + ListenerRegistration cfgReg = registerDataChangeListener(LogicalDatastoreType.CONFIGURATION, path, asyncCfgListener, DataChangeScope.SUBTREE); + ListenerRegistration operReg = registerDataChangeListener(LogicalDatastoreType.OPERATIONAL, path, asyncOperListener, DataChangeScope.SUBTREE); return new LegacyListenerRegistration(listener,cfgReg,operReg); } @@ -387,12 +386,12 @@ public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDat private static final class LegacyListenerRegistration implements ListenerRegistration { private final DataChangeListener instance; - private final ListenerRegistration cfgReg; - private final ListenerRegistration operReg; + private final ListenerRegistration cfgReg; + private final ListenerRegistration operReg; public LegacyListenerRegistration(final DataChangeListener listener, - final ListenerRegistration cfgReg, - final ListenerRegistration operReg) { + final ListenerRegistration cfgReg, + final ListenerRegistration operReg) { this.instance = listener; this.cfgReg = cfgReg; this.operReg = operReg; @@ -411,7 +410,7 @@ public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDat } - private static class BackwardsCompatibleOperationalDataChangeInvoker implements BindingDataChangeListener, Delegator { + private static class BackwardsCompatibleOperationalDataChangeInvoker implements org.opendaylight.controller.md.sal.binding.api.DataChangeListener, Delegator { private final org.opendaylight.controller.md.sal.common.api.data.DataChangeListener delegate; @@ -436,7 +435,7 @@ public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDat } - private static class BackwardsCompatibleConfigurationDataChangeInvoker implements BindingDataChangeListener, Delegator { + private static class BackwardsCompatibleConfigurationDataChangeInvoker implements org.opendaylight.controller.md.sal.binding.api.DataChangeListener, Delegator { private final org.opendaylight.controller.md.sal.common.api.data.DataChangeListener delegate; public BackwardsCompatibleConfigurationDataChangeInvoker(final DataChangeListener listener) { diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/ForwardedBindingDataBroker.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/ForwardedBindingDataBroker.java index 5ab088e20e..5b008ad4bc 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/ForwardedBindingDataBroker.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/ForwardedBindingDataBroker.java @@ -7,15 +7,16 @@ */ package org.opendaylight.controller.md.sal.binding.impl; -import org.opendaylight.controller.md.sal.binding.api.BindingDataBroker; -import org.opendaylight.controller.md.sal.binding.api.BindingDataReadTransaction; -import org.opendaylight.controller.md.sal.binding.api.BindingDataReadWriteTransaction; -import org.opendaylight.controller.md.sal.binding.api.BindingDataWriteTransaction; + +import org.opendaylight.controller.md.sal.binding.api.DataBroker; +import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction; +import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; +import org.opendaylight.controller.md.sal.binding.api.WriteTransaction; import org.opendaylight.controller.md.sal.common.api.TransactionStatus; import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; -import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction; +import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction; import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction; import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction; import org.opendaylight.controller.sal.core.api.model.SchemaService; @@ -40,24 +41,25 @@ import com.google.common.util.concurrent.ListenableFuture; * NormalizedNode once the MappingService is updated * */ -public class ForwardedBindingDataBroker extends AbstractForwardedDataBroker implements BindingDataBroker { +public class ForwardedBindingDataBroker extends AbstractForwardedDataBroker implements DataBroker { public ForwardedBindingDataBroker(final DOMDataBroker domDataBroker, final BindingIndependentMappingService mappingService, final SchemaService schemaService) { super(domDataBroker, mappingService,schemaService); } @Override - public BindingDataReadTransaction newReadOnlyTransaction() { + + public ReadOnlyTransaction newReadOnlyTransaction() { return new BindingDataReadTransactionImpl(getDelegate().newReadOnlyTransaction(),getCodec()); } @Override - public BindingDataReadWriteTransaction newReadWriteTransaction() { + public ReadWriteTransaction newReadWriteTransaction() { return new BindingDataReadWriteTransactionImpl(getDelegate().newReadWriteTransaction(),getCodec()); } @Override - public BindingDataWriteTransaction newWriteOnlyTransaction() { + public WriteTransaction newWriteOnlyTransaction() { return new BindingDataWriteTransactionImpl(getDelegate().newWriteOnlyTransaction(),getCodec()); } @@ -73,17 +75,13 @@ public class ForwardedBindingDataBroker extends AbstractForwardedDataBroker impl return getDelegate().getIdentifier(); } - @Override - public void close() { - getDelegate().close(); - } - } - private class BindingDataReadTransactionImpl extends AbstractBindingTransaction implements - BindingDataReadTransaction { - protected BindingDataReadTransactionImpl(final DOMDataReadTransaction delegate, + private class BindingDataReadTransactionImpl extends AbstractBindingTransaction implements + ReadOnlyTransaction { + + protected BindingDataReadTransactionImpl(final DOMDataReadOnlyTransaction delegate, final BindingToNormalizedNodeCodec codec) { super(delegate, codec); } @@ -93,10 +91,15 @@ public class ForwardedBindingDataBroker extends AbstractForwardedDataBroker impl final InstanceIdentifier path) { return doRead(getDelegate(), store, path); } + + @Override + public void close() { + getDelegate().close(); + } } private class BindingDataWriteTransactionImpl extends - AbstractBindingTransaction implements BindingDataWriteTransaction { + AbstractBindingTransaction implements WriteTransaction { protected BindingDataWriteTransactionImpl(final T delegate, final BindingToNormalizedNodeCodec codec) { super(delegate, codec); @@ -104,8 +107,8 @@ public class ForwardedBindingDataBroker extends AbstractForwardedDataBroker impl } @Override - public void cancel() { - doCancel(getDelegate()); + public boolean cancel() { + return doCancel(getDelegate()); } @Override @@ -130,7 +133,7 @@ public class ForwardedBindingDataBroker extends AbstractForwardedDataBroker impl } private class BindingDataReadWriteTransactionImpl extends - BindingDataWriteTransactionImpl implements BindingDataReadWriteTransaction { + BindingDataWriteTransactionImpl implements ReadWriteTransaction { protected BindingDataReadWriteTransactionImpl(final DOMDataReadWriteTransaction delegate, final BindingToNormalizedNodeCodec codec) { diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/RootBindingAwareBroker.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/RootBindingAwareBroker.java index 8acad1b2d7..d810149c70 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/RootBindingAwareBroker.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/RootBindingAwareBroker.java @@ -9,7 +9,7 @@ package org.opendaylight.controller.sal.binding.impl; import static com.google.common.base.Preconditions.checkState; -import org.opendaylight.controller.md.sal.binding.api.BindingDataBroker; +import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.md.sal.binding.util.AbstractBindingSalProviderInstance; import org.opendaylight.controller.md.sal.binding.util.BindingContextUtils; import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener; @@ -54,7 +54,7 @@ public class RootBindingAwareBroker implements // private DataProviderService legacyDataBroker; - private BindingDataBroker dataBroker; + private DataBroker dataBroker; private MountPointManagerImpl mountManager; @@ -124,7 +124,7 @@ public class RootBindingAwareBroker implements // consBuilder.put(DataBrokerService.class, getRoot()); consBuilder.put(RpcConsumerRegistry.class, getRoot()); if(dataBroker != null) { - consBuilder.put(BindingDataBroker.class, dataBroker); + consBuilder.put(DataBroker.class, dataBroker); } consBuilder.put(MountService.class, mountManager).build(); supportedConsumerServices = consBuilder.build(); @@ -183,7 +183,7 @@ public class RootBindingAwareBroker implements // } } - public void setDataBroker(final BindingDataBroker asyncDataBroker) { + public void setDataBroker(final DataBroker asyncDataBroker) { dataBroker = asyncDataBroker; } } diff --git a/opendaylight/md-sal/sal-binding-config/src/main/yang/opendaylight-md-sal-binding.yang b/opendaylight/md-sal/sal-binding-config/src/main/yang/opendaylight-md-sal-binding.yang index 4a2ec8a063..8636ff613b 100644 --- a/opendaylight/md-sal/sal-binding-config/src/main/yang/opendaylight-md-sal-binding.yang +++ b/opendaylight/md-sal/sal-binding-config/src/main/yang/opendaylight-md-sal-binding.yang @@ -25,7 +25,7 @@ module opendaylight-md-sal-binding { identity binding-async-data-broker { base "config:service-type"; - config:java-class "org.opendaylight.controller.md.sal.binding.api.BindingDataBroker"; + config:java-class "org.opendaylight.controller.md.sal.binding.api.DataBroker"; } identity binding-data-consumer-broker { diff --git a/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/md/sal/binding/data/ListProcessingAndOrderingTest.java b/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/md/sal/binding/data/ListProcessingAndOrderingTest.java index 800c1b4cc4..667887ac80 100644 --- a/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/md/sal/binding/data/ListProcessingAndOrderingTest.java +++ b/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/md/sal/binding/data/ListProcessingAndOrderingTest.java @@ -20,7 +20,7 @@ import java.util.concurrent.ExecutionException; import org.junit.Test; import org.opendaylight.controller.md.sal.common.api.TransactionStatus; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction; +import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction; import org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction; import org.opendaylight.controller.sal.binding.test.AbstractDataServiceTest; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.store.rev140422.Lists; @@ -139,7 +139,7 @@ public class ListProcessingAndOrderingTest extends AbstractDataServiceTest { private NormalizedNode resolveDataAsserted( final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier domPath) { - try (DOMDataReadTransaction readTx = testContext.getDomAsyncDataBroker().newReadOnlyTransaction()){ + try (DOMDataReadOnlyTransaction readTx = testContext.getDomAsyncDataBroker().newReadOnlyTransaction()){ ListenableFuture>> data = readTx.read(LogicalDatastoreType.OPERATIONAL, domPath); Optional> potential = data.get(); assertTrue(potential.isPresent()); diff --git a/opendaylight/md-sal/sal-binding-it/src/test/resources/controller.xml b/opendaylight/md-sal/sal-binding-it/src/test/resources/controller.xml index 37ef257224..63a921d6f3 100644 --- a/opendaylight/md-sal/sal-binding-it/src/test/resources/controller.xml +++ b/opendaylight/md-sal/sal-binding-it/src/test/resources/controller.xml @@ -20,7 +20,6 @@ urn:ietf:params:xml:ns:yang:ietf-inet-types?module=ietf-inet-types&revision=2010-09-24 - urn:ietf:params:netconf:capability:rollback-on-error:1.0 urn:ietf:params:xml:ns:yang:ietf-yang-types?module=ietf-yang-types&revision=2010-09-24 diff --git a/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncDataBroker.java b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncDataBroker.java index fb429e5fd1..3a68092f07 100644 --- a/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncDataBroker.java +++ b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncDataBroker.java @@ -12,14 +12,11 @@ import org.opendaylight.yangtools.concepts.Path; /** * - * Provides access to a conceptual data tree store. + * Base interface that provides access to a conceptual data tree store and also provides the ability to + * subscribe for changes to data under a given branch of the tree. * *

- * Also provides the ability to subscribe for changes to data under a given - * branch of the tree. - * - *

- * All operations on data tree are performed via one of the transactions: + * All operations on the data tree are performed via one of the transactions: *

    *
  • Read-Only - allocated using {@link #newReadOnlyTransaction()} *
  • Write-Only - allocated using {@link #newWriteOnlyTransaction()} @@ -133,7 +130,7 @@ public interface AsyncDataBroker

    , D, L extends AsyncDataChange * {@inheritDoc} */ @Override - public AsyncReadTransaction newReadOnlyTransaction(); + public AsyncReadOnlyTransaction newReadOnlyTransaction(); /** * {@inheritDoc} diff --git a/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncDataTransactionFactory.java b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncDataTransactionFactory.java index cedd883b22..a558b96b2d 100644 --- a/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncDataTransactionFactory.java +++ b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncDataTransactionFactory.java @@ -72,7 +72,7 @@ public interface AsyncDataTransactionFactory

    , D> { * * @return new read-only transaction */ - AsyncReadTransaction newReadOnlyTransaction(); + AsyncReadOnlyTransaction newReadOnlyTransaction(); /** * Allocates new read-write transaction which provides a mutable view of the data diff --git a/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncReadOnlyTransaction.java b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncReadOnlyTransaction.java new file mode 100644 index 0000000000..4beb5c62e3 --- /dev/null +++ b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncReadOnlyTransaction.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.md.sal.common.api.data; + +import org.opendaylight.yangtools.concepts.Path; + +/** + * Read-only transaction, which provides stable view of data + * and is {@link AutoCloseable} resource. + * + * @see AsyncReadTransaction + * +* @param

    + * Type of path (subtree identifier), which represents location in + * tree + * @param + * Type of data (payload), which represents data payload + */ +public interface AsyncReadOnlyTransaction

    , D> extends AsyncReadTransaction, AutoCloseable { + + /** + * Closes this transaction and releases all resources associated with it. + * + */ + @Override + public void close(); +} diff --git a/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncReadTransaction.java b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncReadTransaction.java index 6cf5a5b532..e1cd4a712a 100644 --- a/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncReadTransaction.java +++ b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncReadTransaction.java @@ -14,7 +14,7 @@ import com.google.common.util.concurrent.ListenableFuture; /** * - * Provides a stateful read-only view of the data tree. + * Provides a stateful read view of the data tree. * *

    * View of the data tree is a stable point-in-time snapshot of the current data tree state when @@ -25,8 +25,8 @@ import com.google.common.util.concurrent.ListenableFuture; * Implementation Note: This interface is not intended to be implemented * by users of MD-SAL, but only to be consumed by them. * - *

    Transaction isolation example

    Lest assume initial state of data tree - * for PATH is A. + *

    Transaction isolation example

    + * Lets assume initial state of data tree for PATH is A. * *
      * txRead = broker.newReadOnlyTransaction();   // read Transaction is snapshot of data
    diff --git a/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncReadWriteTransaction.java b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncReadWriteTransaction.java
    index 34101366c8..16b4ed4fe2 100644
    --- a/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncReadWriteTransaction.java
    +++ b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncReadWriteTransaction.java
    @@ -124,6 +124,8 @@ import org.opendaylight.yangtools.concepts.Path;
      * or other functions from {@link com.google.common.util.concurrent.Futures} to
      * register more specific listeners.
      *
    + * @see AsyncReadTransaction
    + * @see AsyncWriteTransaction
      *
      * @param 

    * Type of path (subtree identifier), which represents location in diff --git a/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncTransaction.java b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncTransaction.java index c7cc91528b..08ddfe6898 100644 --- a/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncTransaction.java +++ b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncTransaction.java @@ -29,15 +29,10 @@ import org.opendaylight.yangtools.concepts.Path; * @param Type of data (payload), which represents data payload */ public interface AsyncTransaction

    ,D> extends // - Identifiable, - AutoCloseable { + Identifiable { @Override public Object getIdentifier(); - /** - * Closes transaction and releases all resources associated with it. - */ - @Override - public void close(); + } diff --git a/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncWriteTransaction.java b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncWriteTransaction.java index e2734eaddc..f7eae27320 100644 --- a/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncWriteTransaction.java +++ b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncWriteTransaction.java @@ -53,13 +53,19 @@ public interface AsyncWriteTransaction

    , D> extends AsyncTransa * {@link TransactionStatus#NEW} or {@link TransactionStatus#SUBMITED} * * Invoking cancel() on {@link TransactionStatus#FAILED} or - * {@link TransactionStatus#CANCELED} will have no effect. + * {@link TransactionStatus#CANCELED} will have no effect, and transaction + * is considered cancelled. * - * @throws IllegalStateException - * If transaction status is {@link TransactionStatus#COMMITED} + * Invoking cancel() on finished transaction (future returned by {@link #commit()} + * already completed with {@link TransactionStatus#COMMITED}) will always + * fail (return false). + * + * @return false if the task could not be cancelled, + * typically because it has already completed normally; + * true otherwise * */ - public void cancel(); + public boolean cancel(); /** * Store a piece of data at specified path. This acts as an add / replace @@ -141,20 +147,6 @@ public interface AsyncWriteTransaction

    , D> extends AsyncTransa */ public void delete(LogicalDatastoreType store, P path); - /** - * - * Closes transaction and resources allocated to the transaction. - * - * This call does not change Transaction status. Client SHOULD explicitly - * {@link #commit()} or {@link #cancel()} transaction. - * - * @throws IllegalStateException - * if the transaction has not been updated by invoking - * {@link #commit()} or {@link #cancel()}. - */ - @Override - public void close(); - /** * Submits transaction to be applied to update logical data tree. *

    diff --git a/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/TransactionChain.java b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/TransactionChain.java index e7e0eb0ff8..940559ef89 100644 --- a/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/TransactionChain.java +++ b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/TransactionChain.java @@ -27,7 +27,7 @@ public interface TransactionChain

    , D> extends AutoCloseable, A * @throws TransactionChainClosedException if the chain has been closed. */ @Override - public AsyncReadTransaction newReadOnlyTransaction(); + public AsyncReadOnlyTransaction newReadOnlyTransaction(); /** diff --git a/opendaylight/md-sal/sal-common-impl/src/test/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizerTest.java b/opendaylight/md-sal/sal-common-impl/src/test/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizerTest.java index ddf089c68f..ce861f7e7a 100644 --- a/opendaylight/md-sal/sal-common-impl/src/test/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizerTest.java +++ b/opendaylight/md-sal/sal-common-impl/src/test/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizerTest.java @@ -18,6 +18,7 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.util.AbstractMap; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; @@ -390,15 +391,44 @@ public class DataNormalizerTest { Collections.sort(unorderdChildData, new Comparator() { @Override public int compare(LegacyNodeData arg1, LegacyNodeData arg2) { - String str1 = arg1.nodeKey.getLocalName(); - if (!(arg1.nodeData instanceof List)) - str1 += arg1.nodeData; // add simple node value - - String str2 = arg2.nodeKey.getLocalName(); - if (!(arg2.nodeData instanceof List)) - str2 += arg2.nodeData; // add simple node value - - return str1.compareTo(str2); + if (!(arg1.nodeData instanceof List) && !(arg2.nodeData instanceof List)) { + // if neither is a list, just compare them + String str1 = arg1.nodeKey.getLocalName() + arg1.nodeData; + String str2 = arg2.nodeKey.getLocalName() + arg2.nodeData; + return str1.compareTo(str2); + } else if (arg1.nodeData instanceof List && arg2.nodeData instanceof List) { + // if both are lists, first check their local name + String str1 = arg1.nodeKey.getLocalName(); + String str2 = arg2.nodeKey.getLocalName(); + if (!str1.equals(str2)) { + return str1.compareTo(str2); + } else { + // if local names are the same, then look at the list contents + List l1 = (List) arg1.nodeData; + List l2 = (List) arg2.nodeData; + + if (l1.size() != l2.size()) { + // if the sizes are different, use that + return l2.size() - l1.size(); + } else { + // lastly sort and recursively check the list contents + Collections.sort(l1, this); + Collections.sort(l2, this); + + for (int i = 0 ; i < l1.size() ; i++) { + int diff = this.compare(l1.get(i), l2.get(i)); + if (diff != 0) { + return diff; + } + } + return 0; + } + } + } else if( arg1.nodeData instanceof List ) { + return -1; + } else{ + return 1; + } } }); @@ -417,15 +447,49 @@ public class DataNormalizerTest { Collections.sort(unorderedChildNodes, new Comparator>() { @Override public int compare(Node n1, Node n2) { - String str1 = n1.getKey().getLocalName(); - if (n1 instanceof SimpleNode) - str1 += ((SimpleNode) n1).getValue(); - - String str2 = n2.getKey().getLocalName(); - if (n2 instanceof SimpleNode) - str2 += ((SimpleNode) n2).getValue(); - - return str1.compareTo(str2); + if (n1 instanceof SimpleNode && n2 instanceof SimpleNode) { + // if they're SimpleNodes just compare their strings + String str1 = n1.getKey().getLocalName() + ((SimpleNode)n1).getValue(); + String str2 = n2.getKey().getLocalName() + ((SimpleNode)n2).getValue(); + return str1.compareTo(str2); + } else if (n1 instanceof CompositeNode && n2 instanceof CompositeNode) { + // if they're CompositeNodes, things are more interesting + String str1 = n1.getKey().getLocalName(); + String str2 = n2.getKey().getLocalName(); + if (!str1.equals(str2)) { + // if their local names differ, return that difference + return str1.compareTo(str2); + } else { + // otherwise, we need to look at their contents + ArrayList> l1 = new ArrayList>( ((CompositeNode)n1).getValue() ); + ArrayList> l2 = new ArrayList>( ((CompositeNode)n2).getValue() ); + + if (l1.size() != l2.size()) { + // if they have different numbers of things in them return that + return l2.size() - l1.size(); + } else { + // otherwise, compare the individual elements, first sort them + Collections.sort(l1, this); + Collections.sort(l2, this); + + // then compare them individually + for(int i = 0 ; i < l2.size() ; i++) { + int diff = this.compare(l1.get(i), l2.get(i)); + if(diff != 0){ + return diff; + } + } + return 0; + } + } + } else if (n1 instanceof CompositeNode && n2 instanceof SimpleNode) { + return -1; + } else if (n2 instanceof CompositeNode && n1 instanceof SimpleNode) { + return 1; + } else { + assertTrue("Expected either SimpleNodes CompositeNodes", false); + return 0; + } } }); diff --git a/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataBroker.java b/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataBroker.java index c120508f87..613cf1bfe2 100644 --- a/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataBroker.java +++ b/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataBroker.java @@ -29,7 +29,7 @@ public interface DOMDataBroker extends * {@inheritDoc} */ @Override - DOMDataReadTransaction newReadOnlyTransaction(); + DOMDataReadOnlyTransaction newReadOnlyTransaction(); /** * {@inheritDoc} diff --git a/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataReadOnlyTransaction.java b/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataReadOnlyTransaction.java new file mode 100644 index 0000000000..18fb988661 --- /dev/null +++ b/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataReadOnlyTransaction.java @@ -0,0 +1,9 @@ +package org.opendaylight.controller.md.sal.dom.api; + +import org.opendaylight.controller.md.sal.common.api.data.AsyncReadOnlyTransaction; +import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; + +public interface DOMDataReadOnlyTransaction extends DOMDataReadTransaction, AsyncReadOnlyTransaction> { + +} diff --git a/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMTransactionChain.java b/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMTransactionChain.java index b894911ffa..73a0c28465 100644 --- a/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMTransactionChain.java +++ b/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMTransactionChain.java @@ -24,7 +24,7 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; public interface DOMTransactionChain extends TransactionChain> { @Override - DOMDataReadTransaction newReadOnlyTransaction(); + DOMDataReadOnlyTransaction newReadOnlyTransaction(); @Override DOMDataReadWriteTransaction newReadWriteTransaction(); diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/AbstractDOMForwardedCompositeTransaction.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/AbstractDOMForwardedCompositeTransaction.java index 0c07b0684c..0be4327f7a 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/AbstractDOMForwardedCompositeTransaction.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/AbstractDOMForwardedCompositeTransaction.java @@ -75,8 +75,7 @@ abstract class AbstractDOMForwardedCompositeTransaction builder = ImmutableMap.builder(); for (Entry store : storeTxFactories.entrySet()) { diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMForwardedReadOnlyTransaction.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMForwardedReadOnlyTransaction.java index d2543f02bc..f207783c29 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMForwardedReadOnlyTransaction.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMForwardedReadOnlyTransaction.java @@ -8,7 +8,7 @@ package org.opendaylight.controller.md.sal.dom.broker.impl; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction; +import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction; import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction; import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; @@ -26,7 +26,7 @@ import com.google.common.util.concurrent.ListenableFuture; */ class DOMForwardedReadOnlyTransaction extends AbstractDOMForwardedCompositeTransaction implements - DOMDataReadTransaction { + DOMDataReadOnlyTransaction { protected DOMForwardedReadOnlyTransaction(final Object identifier, final ImmutableMap backingTxs) { @@ -39,4 +39,9 @@ class DOMForwardedReadOnlyTransaction extends return getSubtransaction(store).read(path); } + @Override + public void close() { + closeSubtransactions(); + } + } diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMForwardedWriteTransaction.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMForwardedWriteTransaction.java index eeb345e9ce..f791522a2a 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMForwardedWriteTransaction.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMForwardedWriteTransaction.java @@ -50,13 +50,31 @@ import com.google.common.util.concurrent.ListenableFuture; class DOMForwardedWriteTransaction extends AbstractDOMForwardedCompositeTransaction implements DOMDataWriteTransaction { + /** + * Implementation of real commit. + * + * Transaction can not be commited if commitImpl is null, + * so this seting this property to null is also used to + * prevent write to + * already commited / canceled transaction {@link #checkNotCanceled() + * + * + */ @GuardedBy("this") - private DOMDataCommitImplementation commitImpl; - - @GuardedBy("this") - private boolean canceled; + private volatile DOMDataCommitImplementation commitImpl; + + /** + * + * Future task of transaction commit. + * + * This value is initially null, and is once updated if transaction + * is commited {@link #commit()}. + * If this future exists, transaction MUST not be commited again + * and all modifications should fail. See {@link #checkNotCommited()}. + * + */ @GuardedBy("this") - private ListenableFuture> commitFuture; + private volatile ListenableFuture> commitFuture; protected DOMForwardedWriteTransaction(final Object identifier, final ImmutableMap backingTxs, final DOMDataCommitImplementation commitImpl) { @@ -83,15 +101,19 @@ class DOMForwardedWriteTransaction extends } @Override - public synchronized void cancel() { - checkState(!canceled, "Transaction was canceled."); - if (commitFuture != null) { - // FIXME: Implement cancelation of commit future - // when Broker impl will support cancelation. - throw new UnsupportedOperationException("Not implemented yet."); + public synchronized boolean cancel() { + // Transaction is already canceled, we are safe to return true + final boolean cancelationResult; + if (commitImpl == null && commitFuture != null) { + // Transaction is submitted, we try to cancel future. + cancelationResult = commitFuture.cancel(false); + } else if(commitImpl == null) { + return true; + } else { + cancelationResult = true; + commitImpl = null; } - canceled = true; - commitImpl = null; + return cancelationResult; } @@ -105,20 +127,26 @@ class DOMForwardedWriteTransaction extends } ImmutableList cohorts = cohortsBuilder.build(); commitFuture = commitImpl.commit(this, cohorts); + + /* + *We remove reference to Commit Implementation in order + *to prevent memory leak + */ + commitImpl = null; return commitFuture; } private void checkNotReady() { - checkNotCanceled(); checkNotCommited(); + checkNotCanceled(); } private void checkNotCanceled() { - Preconditions.checkState(!canceled, "Transaction was canceled."); + Preconditions.checkState(commitImpl != null, "Transaction was canceled."); } private void checkNotCommited() { - checkState(commitFuture == null, "Transaction was already commited."); + checkState(commitFuture == null, "Transaction was already submited."); } } \ No newline at end of file diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/compat/BackwardsCompatibleTransaction.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/compat/BackwardsCompatibleTransaction.java index 29f2af511e..b3fb7b6da8 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/compat/BackwardsCompatibleTransaction.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/compat/BackwardsCompatibleTransaction.java @@ -24,6 +24,7 @@ import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException; import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation; import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer; +import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction; import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction; import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction; import org.opendaylight.controller.sal.core.api.data.DataModificationTransaction; @@ -55,10 +56,10 @@ public abstract class BackwardsCompatibleTransaction readOnlyTransaction(final DOMDataReadTransaction readTx, + public static BackwardsCompatibleTransaction readOnlyTransaction(final DOMDataReadOnlyTransaction readTx, final DataNormalizer normalizer) { - return new BackwardsCompatibleTransaction(readTx, normalizer) { + return new BackwardsCompatibleTransaction(readTx, normalizer) { @Override public TransactionStatus getStatus() { diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/DOMDataBrokerProxy.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/DOMDataBrokerProxy.java index b0ccfb995d..4f44f361d5 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/DOMDataBrokerProxy.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/DOMDataBrokerProxy.java @@ -4,7 +4,7 @@ import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener; import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener; -import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction; +import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction; import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction; import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction; import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain; @@ -19,7 +19,7 @@ public class DOMDataBrokerProxy extends AbstractBrokerServiceProxy 0, "must be > 0", betweenAttemptsTimeoutMillisJmxAttribute); - // FIXME BUG-944 remove backwards compatibility - if(getClientDispatcher() == null) { - checkCondition(getBossThreadGroup() != null, "Client dispatcher was not set, thread groups have to be set instead", bossThreadGroupJmxAttribute); - checkCondition(getWorkerThreadGroup() != null, "Client dispatcher was not set, thread groups have to be set instead", workerThreadGroupJmxAttribute); - } + checkNotNull(getClientDispatcher(), clientDispatcherJmxAttribute); + checkNotNull(getBindingRegistry(), bindingRegistryJmxAttribute); + checkNotNull(getProcessingExecutor(), processingExecutorJmxAttribute); // Check username + password in case of ssh if(getTcpOnly() == false) { @@ -89,33 +82,21 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co checkNotNull(getPassword(), passwordJmxAttribute); } - // FIXME BUG 944 remove this warning - if(getBindingRegistry() == null) { - logger.warn("Configuration property: \"binding-registry\" not set for sal-netconf-connector (" + getIdentifier() + "). " + - "Netconf-connector now requires a dependency on \"binding-broker-osgi-registry\". " + - "The dependency is optional for now to preserve backwards compatibility, but will be mandatory in the future. " + - "Please set the property as in \"01-netconf-connector\" initial config file. " + - "The service will be retrieved from OSGi service registry now."); - } + } - // FIXME BUG 944 remove this warning - if(getProcessingExecutor() == null) { - logger.warn("Configuration property: \"processing-executor\" not set for sal-netconf-connector (" + getIdentifier() + "). " + - "Netconf-connector now requires a dependency on \"threadpool\". " + - "The dependency is optional for now to preserve backwards compatibility, but will be mandatory in the future. " + - "Please set the property as in \"01-netconf-connector\" initial config file. " + - "New instance will be created for the executor."); - } + private boolean isHostAddressPresent(Host address) { + return address.getDomainName() != null || + address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null); } @Override public java.lang.AutoCloseable createInstance() { final RemoteDeviceId id = new RemoteDeviceId(getIdentifier()); - final ExecutorService globalProcessingExecutor = getGlobalProcessingExecutor(); + final ExecutorService globalProcessingExecutor = getProcessingExecutorDependency().getExecutor(); final Broker domBroker = getDomRegistryDependency(); - final BindingAwareBroker bindingBroker = getBindingRegistryBackwards(); + final BindingAwareBroker bindingBroker = getBindingRegistryDependency(); final RemoteDeviceHandler salFacade = new NetconfDeviceSalFacade(id, domBroker, bindingBroker, bundleContext, globalProcessingExecutor); final NetconfDevice device = @@ -123,8 +104,7 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co final NetconfDeviceCommunicator listener = new NetconfDeviceCommunicator(id, device); final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(listener); - // FIXME BUG-944 remove backwards compatibility - final NetconfClientDispatcher dispatcher = getClientDispatcher() == null ? createDispatcher() : getClientDispatcherDependency(); + final NetconfClientDispatcher dispatcher = getClientDispatcherDependency(); listener.initializeRemoteConnection(dispatcher, clientConfig); return new AutoCloseable() { @@ -136,30 +116,6 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co }; } - private BindingAwareBroker getBindingRegistryBackwards() { - if(getBindingRegistry() != null) { - return getBindingRegistryDependency(); - } else { - // FIXME BUG 944 remove backwards compatibility - final ServiceReference serviceReference = bundleContext.getServiceReference(BindingAwareBroker.class); - Preconditions - .checkNotNull( - serviceReference, - "Unable to retrieve %s from OSGi service registry, use binding-registry config property to inject %s with config subsystem", - BindingAwareBroker.class, BindingAwareBroker.class); - return bundleContext.getService(serviceReference); - } - } - - private ExecutorService getGlobalProcessingExecutor() { - if(getProcessingExecutor() != null) { - return getProcessingExecutorDependency().getExecutor(); - } else { - // FIXME BUG 944 remove backwards compatibility - return Executors.newCachedThreadPool(); - } - } - private synchronized AbstractCachingSchemaSourceProvider getGlobalNetconfSchemaProvider() { if(GLOBAL_NETCONF_SOURCE_PROVIDER == null) { final String storageFile = "cache/schema"; @@ -171,16 +127,6 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co return GLOBAL_NETCONF_SOURCE_PROVIDER; } - // FIXME BUG-944 remove backwards compatibility - /** - * @deprecated Use getClientDispatcherDependency method instead to retrieve injected dispatcher. - * This one creates new instance of NetconfClientDispatcher and will be removed in near future. - */ - @Deprecated - private NetconfClientDispatcher createDispatcher() { - return new NetconfClientDispatcherImpl(getBossThreadGroupDependency(), getWorkerThreadGroupDependency(), new HashedWheelTimer()); - } - public void setBundleContext(final BundleContext bundleContext) { this.bundleContext = bundleContext; } @@ -226,15 +172,12 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co } private InetSocketAddress getSocketAddress() { - /* - * Uncomment after Switch to IP Address - if(getAddress().getIpv4Address() != null) { - addressValue = getAddress().getIpv4Address().getValue(); + if(getAddress().getDomainName() != null) { + return new InetSocketAddress(getAddress().getDomainName().getValue(), getPort().getValue()); } else { - addressValue = getAddress().getIpv6Address().getValue(); + IpAddress ipAddress = getAddress().getIpAddress(); + String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue(); + return new InetSocketAddress(ip, getPort().getValue()); } - */ - final InetAddress inetAddress = InetAddresses.forString(getAddress()); - return new InetSocketAddress(inetAddress, getPort().intValue()); } } diff --git a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceCommitHandler.java b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceCommitHandler.java index 457b8c36b9..8b6ac7d567 100644 --- a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceCommitHandler.java +++ b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceCommitHandler.java @@ -48,7 +48,7 @@ public final class NetconfDeviceCommitHandler implements DataCommitHandlerabsent(), Optional.of(value))); + sendEditRpc(createEditConfigStructure(key, Optional.absent(), Optional.of(value)), Optional.absent()); } private void sendDelete(final InstanceIdentifier toDelete) throws InterruptedException, ExecutionException { - sendEditRpc(createEditConfigStructure(toDelete, Optional.of("delete"), Optional.absent())); + // FIXME use org.opendaylight.yangtools.yang.data.api.ModifyAction instead of strings + // TODO add string lowercase value to ModifyAction enum entries + sendEditRpc(createEditConfigStructure(toDelete, Optional.of("delete"), Optional.absent()), Optional.of("none")); } - private void sendEditRpc(final CompositeNode editStructure) throws InterruptedException, ExecutionException { - final ImmutableCompositeNode editConfigRequest = createEditConfigRequest(editStructure); + private void sendEditRpc(final CompositeNode editStructure, final Optional defaultOperation) throws InterruptedException, ExecutionException { + final ImmutableCompositeNode editConfigRequest = createEditConfigRequest(editStructure, defaultOperation); final RpcResult rpcResult = rpc.invokeRpc(NETCONF_EDIT_CONFIG_QNAME, editConfigRequest).get(); - // TODO 874 add default operation when sending delete // Check result if(rpcResult.isSuccessful() == false) { @@ -106,16 +108,26 @@ final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransact } } - private ImmutableCompositeNode createEditConfigRequest(final CompositeNode editStructure) { + private ImmutableCompositeNode createEditConfigRequest(final CompositeNode editStructure, Optional defaultOperation) { final CompositeNodeBuilder ret = ImmutableCompositeNode.builder(); + // Target final Node targetWrapperNode = ImmutableCompositeNode.create(NETCONF_TARGET_QNAME, ImmutableList.>of(targetNode)); ret.add(targetWrapperNode); + // Default operation + if(defaultOperation.isPresent()) { + SimpleNode defOp = NodeFactory.createImmutableSimpleNode(NETCONF_DEFAULT_OPERATION_QNAME, null, defaultOperation.get()); + ret.add(defOp); + } + + // Error option if(rollbackSupported) { ret.addLeaf(NETCONF_ERROR_OPTION_QNAME, ROLLBACK_ON_ERROR_OPTION); } + ret.setQName(NETCONF_EDIT_CONFIG_QNAME); + // Edit content ret.add(editStructure); return ret.toInstance(); } diff --git a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java index 2adc1be79e..21f94474f8 100644 --- a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java +++ b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java @@ -70,6 +70,8 @@ public class NetconfMessageTransformer implements MessageTransformer> RUNNING = Collections.> singletonList(new SimpleNodeTOImpl<>(NETCONF_RUNNING_QNAME, - null, null)); + static List> RUNNING = Collections.> singletonList(new SimpleNodeTOImpl<>(NETCONF_RUNNING_QNAME, null, null)); public static QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source"); public static CompositeNode CONFIG_SOURCE_RUNNING = new CompositeNodeTOImpl(NETCONF_SOURCE_QNAME, null, RUNNING); public static QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate"); @@ -65,6 +63,7 @@ public class NetconfMessageTransformUtil { public static QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config"); public static QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit"); public static QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation"); + public static QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation"); public static QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config"); public static QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config"); public static QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type"); diff --git a/opendaylight/md-sal/sal-netconf-connector/src/main/yang/odl-sal-netconf-connector-cfg.yang b/opendaylight/md-sal/sal-netconf-connector/src/main/yang/odl-sal-netconf-connector-cfg.yang index c59c41c437..6bad4798c2 100644 --- a/opendaylight/md-sal/sal-netconf-connector/src/main/yang/odl-sal-netconf-connector-cfg.yang +++ b/opendaylight/md-sal/sal-netconf-connector/src/main/yang/odl-sal-netconf-connector-cfg.yang @@ -9,6 +9,7 @@ module odl-sal-netconf-connector-cfg { import opendaylight-md-sal-dom {prefix dom;} import opendaylight-md-sal-binding {prefix md-sal-binding; revision-date 2013-10-28;} import odl-netconf-cfg { prefix cfg-net; revision-date 2014-04-08; } + import ietf-inet-types {prefix inet; revision-date "2010-09-24";} description "Service definition for Binding Aware MD-SAL."; @@ -38,11 +39,11 @@ module odl-sal-netconf-connector-cfg { when "/config:modules/config:module/config:type = 'sal-netconf-connector'"; leaf address { - type string; + type inet:host; } leaf port { - type uint32; + type inet:port-number; } leaf tcp-only { @@ -69,40 +70,16 @@ module odl-sal-netconf-connector-cfg { container binding-registry { uses config:service-ref { refine type { - // FIXME BUG-944 make mandatory (remove backwards compatibility) - mandatory false; + mandatory true; config:required-identity md-sal-binding:binding-broker-osgi-registry; } } } - // FIXME BUG-944 remove backwards compatibility - // Deprecated, replaced by client dispatcher. - // This dependency will be removed in near future and all configurations of netconf-connector need to be changed to use dispatcher dependency. - container boss-thread-group { - uses config:service-ref { - refine type { - mandatory false; - config:required-identity netty:netty-threadgroup; - } - } - } - - // FIXME BUG-944 remove backwards compatibility - // Deprecated, replaced by client dispatcher. - // This dependency will be removed in near future and all configurations of netconf-connector need to be changed to use dispatcher dependency. - container worker-thread-group { - uses config:service-ref { - refine type { - mandatory false; - config:required-identity netty:netty-threadgroup; - } - } - } - container event-executor { uses config:service-ref { refine type { + mandatory true; config:required-identity netty:netty-event-executor; } } @@ -111,8 +88,7 @@ module odl-sal-netconf-connector-cfg { container processing-executor { uses config:service-ref { refine type { - // FIXME BUG-944 make mandatory (remove backwards compatibility) - mandatory false; + mandatory true; config:required-identity th:threadpool; } } @@ -120,7 +96,6 @@ module odl-sal-netconf-connector-cfg { description "Makes up for flaws in netty threading design"; } - // Replaces thread group dependencies container client-dispatcher { uses config:service-ref { refine type { diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/pom.xml b/opendaylight/md-sal/sal-remoterpc-connector/implementation/pom.xml deleted file mode 100644 index 63b80e9181..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/pom.xml +++ /dev/null @@ -1,176 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - sal-parent - 1.1-SNAPSHOT - ../.. - - - sal-remoterpc-connector - bundle - - - 1.0.1 - 0.3.1 - - - - - ${project.groupId} - sal-common-util - ${project.version} - - - ${project.groupId} - sal-connector-api - ${project.version} - - - - ${project.groupId} - sal-core-api - ${project.version} - - - com.fasterxml.jackson.core - jackson-annotations - - - - com.fasterxml.jackson.core - jackson-core - - - - com.fasterxml.jackson.core - jackson-databind - - - com.google.guava - guava - - - - - junit - junit - - - org.mockito - mockito-all - - - org.opendaylight.controller - remoterpc-routingtable.implementation - ${project.version} - - - - - org.opendaylight.controller - sal - - - - - org.opendaylight.yangtools - yang-common - - - org.opendaylight.yangtools - yang-data-api - - - org.opendaylight.yangtools - yang-data-impl - - - - - org.osgi - org.osgi.core - - - org.slf4j - slf4j-api - - - org.zeromq - jeromq - ${zeromq.version} - - - - stax - stax-api - ${stax.version} - - - ch.qos.logback - logback-classic - test - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - *, - !org.codehaus.enunciate.jaxrs - org.opendaylight.controller.config.yang.md.sal.remote.rpc, - org.opendaylight.controller.sal.connector.remoterpc.util, - org.opendaylight.controller.sal.connector.remoterpc.dto, - org.opendaylight.controller.sal.connector.remoterpc.RemoteRpcClient, - org.opendaylight.controller.sal.connector.remoterpc.RemoteRpcServer, - org.opendaylight.controller.sal.connector.remoterpc.RemoteRpcProvider - ${project.groupId}.${project.artifactId} - - - - - - org.opendaylight.yangtools - yang-maven-plugin - - - - generate-sources - - - - - org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator - ${jmxGeneratorPath} - - urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang - - - - org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl - ${salGeneratorPath} - - - org.opendaylight.yangtools.yang.unified.doc.generator.maven.DocumentationGeneratorImpl - target/site/models - - - - org.opendaylight.yangtools.yang.unified.doc.generator.maven.DocumentationGeneratorImpl - target/site/models - - - true - - - - - - - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/config/yang/md/sal/remote/rpc/ZeroMQServerModule.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/config/yang/md/sal/remote/rpc/ZeroMQServerModule.java deleted file mode 100644 index e3ac9bab30..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/config/yang/md/sal/remote/rpc/ZeroMQServerModule.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.config.yang.md.sal.remote.rpc; - -import org.opendaylight.controller.sal.connector.remoterpc.ClientImpl; -import org.opendaylight.controller.sal.connector.remoterpc.RemoteRpcProvider; -import org.opendaylight.controller.sal.connector.remoterpc.RoutingTableProvider; -import org.opendaylight.controller.sal.connector.remoterpc.ServerImpl; -import org.opendaylight.controller.sal.core.api.Broker; -import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry; -import org.osgi.framework.BundleContext; - -/** - * - */ -public final class ZeroMQServerModule -extends org.opendaylight.controller.config.yang.md.sal.remote.rpc.AbstractZeroMQServerModule { - - private static final Integer ZEROMQ_ROUTER_PORT = 5554; - private BundleContext bundleContext; - - public ZeroMQServerModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, - final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { - super(identifier, dependencyResolver); - } - - public ZeroMQServerModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, - final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, - final ZeroMQServerModule oldModule, final java.lang.AutoCloseable oldInstance) { - - super(identifier, dependencyResolver, oldModule, oldInstance); - } - - @Override - protected void customValidation() { - // Add custom validation for module attributes here. - } - - @Override - public java.lang.AutoCloseable createInstance() { - - Broker broker = getDomBrokerDependency(); - - final int port = getPort() != null ? getPort() : ZEROMQ_ROUTER_PORT; - - ServerImpl serverImpl = new ServerImpl(port); - - ClientImpl clientImpl = new ClientImpl(); - - RoutingTableProvider provider = new RoutingTableProvider(bundleContext);//,serverImpl); - - RemoteRpcProvider facade = new RemoteRpcProvider(serverImpl, clientImpl); - facade.setRoutingTableProvider(provider); - facade.setContext(bundleContext); - facade.setRpcProvisionRegistry((RpcProvisionRegistry) broker); - - broker.registerProvider(facade, bundleContext); - return facade; - } - - public void setBundleContext(final BundleContext bundleContext) { - this.bundleContext = bundleContext; - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/config/yang/md/sal/remote/rpc/ZeroMQServerModuleFactory.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/config/yang/md/sal/remote/rpc/ZeroMQServerModuleFactory.java deleted file mode 100644 index 0c2a370e06..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/config/yang/md/sal/remote/rpc/ZeroMQServerModuleFactory.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.config.yang.md.sal.remote.rpc; - -import org.opendaylight.controller.config.api.DependencyResolver; -import org.opendaylight.controller.config.api.DynamicMBeanWithInstance; -import org.opendaylight.controller.config.spi.Module; -import org.osgi.framework.BundleContext; - -/** -* -*/ -public class ZeroMQServerModuleFactory extends org.opendaylight.controller.config.yang.md.sal.remote.rpc.AbstractZeroMQServerModuleFactory -{ - - @Override - public Module createModule(String instanceName, DependencyResolver dependencyResolver, BundleContext bundleContext) { - ZeroMQServerModule module = (ZeroMQServerModule) super.createModule(instanceName, dependencyResolver, bundleContext); - module.setBundleContext(bundleContext); - return module; - } - - @Override - public Module createModule(String instanceName, DependencyResolver dependencyResolver, - DynamicMBeanWithInstance old, BundleContext bundleContext) throws Exception { - ZeroMQServerModule module = (ZeroMQServerModule) super.createModule(instanceName, dependencyResolver, old,bundleContext); - module.setBundleContext(bundleContext); - return module; - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/CapturedMessageHandler.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/CapturedMessageHandler.java deleted file mode 100644 index 2dc5eee59a..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/CapturedMessageHandler.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.zeromq.ZMQ; - -public class CapturedMessageHandler implements Runnable { - - private Logger _logger = LoggerFactory.getLogger(CapturedMessageHandler.class); - - private ZMQ.Socket socket; - - public CapturedMessageHandler(ZMQ.Socket socket){ - this.socket = socket; - } - - @Override - public void run(){ - - try { - while (!Thread.currentThread().isInterrupted()){ - String message = socket.recvStr(); - _logger.debug("Captured [{}]", message); - } - } catch (Exception e) { - _logger.error("Exception raised [{}]", e.getMessage()); - } - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ClientImpl.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ClientImpl.java deleted file mode 100644 index 200ebaee6a..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ClientImpl.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.FutureTask; -import java.util.concurrent.TimeUnit; - -import org.opendaylight.controller.sal.common.util.RpcErrors; -import org.opendaylight.controller.sal.common.util.Rpcs; -import org.opendaylight.controller.sal.connector.api.RpcRouter; -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable; -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTableException; -import org.opendaylight.controller.sal.connector.remoterpc.api.SystemException; -import org.opendaylight.controller.sal.connector.remoterpc.dto.Message; -import org.opendaylight.controller.sal.connector.remoterpc.dto.RouteIdentifierImpl; -import org.opendaylight.controller.sal.connector.remoterpc.util.XmlUtils; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.RpcError; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; -import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.zeromq.ZMQ; - -import com.google.common.base.Optional; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; - -/** - * An implementation of {@link org.opendaylight.controller.sal.core.api.RpcImplementation} that makes - * remote RPC calls - */ -public class ClientImpl implements RemoteRpcClient { - - private final Logger _logger = LoggerFactory.getLogger(ClientImpl.class); - - private final ZMQ.Context context = ZMQ.context(1); - private final ClientRequestHandler handler; - private RoutingTableProvider routingTableProvider; - - public ClientImpl(){ - handler = new ClientRequestHandler(context); - start(); - } - - public ClientImpl(ClientRequestHandler handler){ - this.handler = handler; - start(); - } - - public RoutingTableProvider getRoutingTableProvider() { - return routingTableProvider; - } - - @Override - public void setRoutingTableProvider(RoutingTableProvider routingTableProvider) { - this.routingTableProvider = routingTableProvider; - } - - @Override - public void start() {/*NOOPS*/} - - @Override - public void stop() { - closeZmqContext(); - handler.close(); - _logger.info("Stopped"); - } - - @Override - public void close(){ - stop(); - } - - /** - * Finds remote server that can execute this rpc and sends a message to it - * requesting execution. - * The call blocks until a response from remote server is received. Its upto - * the client of this API to implement a timeout functionality. - * - * @param rpc remote service to be executed - * @param input payload for the remote service - * @return - */ - public ListenableFuture> invokeRpc(QName rpc, CompositeNode input) { - RouteIdentifierImpl routeId = new RouteIdentifierImpl(); - routeId.setType(rpc); - - String address = lookupRemoteAddressForGlobalRpc(routeId); - return sendMessage(input, routeId, address); - } - - /** - * Finds remote server that can execute this routed rpc and sends a message to it - * requesting execution. - * The call blocks until a response from remote server is received. Its upto - * the client of this API to implement a timeout functionality. - * - * @param rpc - * rpc to be called - * @param identifier - * instance identifier on which rpc is to be executed - * @param input - * payload - * @return - */ - public ListenableFuture> invokeRpc(QName rpc, InstanceIdentifier identifier, CompositeNode input) { - - RouteIdentifierImpl routeId = new RouteIdentifierImpl(); - routeId.setType(rpc); - routeId.setRoute(identifier); - - String address = lookupRemoteAddressForRpc(routeId); - - return sendMessage(input, routeId, address); - } - - private ListenableFuture> sendMessage(CompositeNode input, RouteIdentifierImpl routeId, String address) { - Message request = new Message.MessageBuilder() - .type(Message.MessageType.REQUEST) - .sender(Context.getInstance().getLocalUri()) - .recipient(address) - .route(routeId) - .payload(XmlUtils.compositeNodeToXml(input)) - .build(); - - List errors = new ArrayList(); - - try{ - Message response = handler.handle(request); - CompositeNode payload = null; - - if ( response != null ) { - - _logger.info("Received response [{}]", response); - - Object rawPayload = response.getPayload(); - switch (response.getType()) { - case ERROR: - if ( rawPayload instanceof List ) - errors = (List) rawPayload; - break; - - case RESPONSE: - payload = XmlUtils.xmlToCompositeNode((String) rawPayload); - break; - - default: - errors.add( - RpcErrors.getRpcError(null, null,null,null,"Unable to get response from remote controller", null, null) - ); - break; - - } - } - return Futures.immediateFuture(Rpcs.getRpcResult(true, payload, errors)); - - } catch (Exception e){ - collectErrors(e, errors); - return Futures.immediateFuture(Rpcs.getRpcResult(false, null, errors)); - } - } - - /** - * Find address for the given route identifier in routing table - * @param routeId route identifier - * @return remote network address - */ - private String lookupRemoteAddressForGlobalRpc(RpcRouter.RouteIdentifier routeId){ - checkNotNull(routeId, "route must not be null"); - - Optional, String>> routingTable = routingTableProvider.getRoutingTable(); - checkNotNull(routingTable.isPresent(), "Routing table is null"); - - String address = null; - try { - address = routingTable.get().getGlobalRoute(routeId); - } catch (RoutingTableException|SystemException e) { - _logger.error("Exception caught while looking up remote address " + e); - } - checkState(address != null, "Address not found for route [%s]", routeId); - - return address; - } - - /** - * Find address for the given route identifier in routing table - * @param routeId route identifier - * @return remote network address - */ - private String lookupRemoteAddressForRpc(RpcRouter.RouteIdentifier routeId){ - checkNotNull(routeId, "route must not be null"); - - Optional, String>> routingTable = routingTableProvider.getRoutingTable(); - checkNotNull(routingTable.isPresent(), "Routing table is null"); - - String address = routingTable.get().getLastAddedRoute(routeId); - checkState(address != null, "Address not found for route [%s]", routeId); - - return address; - } - - private void collectErrors(Exception e, List errors){ - if (e == null) return; - if (errors == null) errors = new ArrayList(); - - errors.add(RpcErrors.getRpcError(null, null, null, null, e.getMessage(), null, e.getCause())); - for (Throwable t : e.getSuppressed()) { - errors.add(RpcErrors.getRpcError(null, null, null, null, t.getMessage(), null, t)); - } - } - - /** - * Closes ZMQ Context. It tries to gracefully terminate the context. If - * termination takes more than a second, its forcefully shutdown. - */ - private void closeZmqContext() { - ExecutorService exec = Executors.newSingleThreadExecutor(); - FutureTask zmqTermination = new FutureTask(new Runnable() { - - @Override - public void run() { - try { - if (context != null) - context.term(); - _logger.debug("ZMQ Context terminated"); - } catch (Exception e) { - _logger.debug("ZMQ Context termination threw exception [{}]. Continuing shutdown...", e); - } - } - }, null); - - exec.execute(zmqTermination); - - try { - zmqTermination.get(1L, TimeUnit.SECONDS); - } catch (Exception e) {/*ignore and continue with shutdown*/} - - exec.shutdownNow(); - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ClientRequestHandler.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ClientRequestHandler.java deleted file mode 100644 index fe70fb77be..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ClientRequestHandler.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc; - -import com.google.common.base.Preconditions; -import org.opendaylight.controller.sal.connector.remoterpc.dto.Message; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.zeromq.ZMQ; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * - */ -class ClientRequestHandler implements AutoCloseable{ - - private Logger _logger = LoggerFactory.getLogger(ClientRequestHandler.class); - private final String DEFAULT_NAME = "remoterpc-client-worker"; - private final String INPROC_PROTOCOL_PREFIX = "inproc://"; - private final String TCP_PROTOCOL_PREFIX = "tcp://"; - - private ZMQ.Context context; - - /* - * Worker thread pool. Each thread runs a ROUTER-DEALER pair - */ - private ExecutorService workerPool; - - /* - * Set of remote servers this client is currently connected to - */ - private Map connectedServers; - - protected ClientRequestHandler(ZMQ.Context context) { - this.context = context; - connectedServers = new ConcurrentHashMap(); - start(); - } - - /** - * Starts a pool of worker as needed. A worker thread that has not been used for 5 min - * is terminated and removed from the pool. If thread dies due to an exception, its - * restarted. - */ - private void start(){ - - workerPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE, - 5L, TimeUnit.MINUTES, - new SynchronousQueue()){ - - @Override - protected void afterExecute(Runnable r, Throwable t) { - if (isTerminating() || isTerminated() || isShutdown()) - return; - - Worker worker = (Worker) r; - Preconditions.checkState( worker != null ); - String remoteServerAddress = worker.getRemoteServerAddress(); - connectedServers.remove(remoteServerAddress); - - if ( t != null ){ - _logger.debug("Exception caught while terminating worker [{},{}]. " + - "Restarting worker...", t.getClass(), t.getMessage()); - - connectedServers.put(remoteServerAddress, remoteServerAddress); - this.execute(r); - } - super.afterExecute(r, null); - } - }; - } - - public Message handle(Message request) throws IOException, ClassNotFoundException, InterruptedException { - - String remoteServerAddress = request.getRecipient(); - //if we already have router-dealer bridge setup for this address the send request - //otherwise first create the bridge and then send request - if ( connectedServers.containsKey(remoteServerAddress) ) - return sendMessage(request, remoteServerAddress); - - else{ - workerPool.execute(new Worker(remoteServerAddress)); - connectedServers.put(remoteServerAddress, remoteServerAddress); - //give little time for sockets to get initialized - //TODO: Add socket ping-pong message to ensure socket init rather than thread.sleep. - Thread.sleep(1000); - return sendMessage(request, remoteServerAddress); - } - } - - private Message sendMessage(Message request, String address) throws IOException, ClassNotFoundException { - Message response = null; - ZMQ.Socket socket = context.socket(ZMQ.REQ); - - try { - String inProcessSocketAddress = INPROC_PROTOCOL_PREFIX + address; - socket.connect( inProcessSocketAddress ); - _logger.debug("Sending request [{}]", request); - socket.send(Message.serialize(request)); - _logger.info("Request sent. Waiting for reply..."); - byte[] reply = socket.recv(0); - _logger.info("Response received"); - response = (Message) Message.deserialize(reply); - _logger.debug("Response [{}]", response); - } finally { - socket.close(); - } - return response; - } - - /** - * This gets called automatically if used with try-with-resources - */ - @Override - public void close(){ - workerPool.shutdown(); - _logger.info("Request Handler closed"); - } - - /** - * Total number of workers in the pool. Number of workers represent - * number of remote servers {@link org.opendaylight.controller.sal.connector.remoterpc.ClientImpl} is connected to. - * - * @return worker count - */ - public int getWorkerCount(){ - - if (workerPool == null) return 0; - - return ((ThreadPoolExecutor)workerPool).getActiveCount(); - } - /** - * Handles RPC request - */ - private class Worker implements Runnable { - private String name; - private String remoteServer; // - - public Worker(String address){ - this.name = DEFAULT_NAME + "[" + address + "]"; - this.remoteServer = address; - } - - public String getRemoteServerAddress(){ - return this.remoteServer; - } - - @Override - public void run() { - Thread.currentThread().setName(name); - _logger.debug("Starting ... "); - - ZMQ.Socket router = context.socket(ZMQ.ROUTER); - ZMQ.Socket dealer = context.socket(ZMQ.DEALER); - - try { - int success = router.bind(INPROC_PROTOCOL_PREFIX + remoteServer); - Preconditions.checkState(-1 != success, "Could not bind to " + remoteServer); - - dealer.connect(TCP_PROTOCOL_PREFIX + remoteServer); - - _logger.info("Worker started for [{}]", remoteServer); - - //TODO: Add capture handler - //This code will block until the zmq context is terminated. - ZMQ.proxy(router, dealer, null); - - } catch (Exception e) { - _logger.debug("Ignoring exception [{}, {}]", e.getClass(), e.getMessage()); - } finally { - try { - router.close(); - dealer.close(); - } catch (Exception x) { - _logger.debug("Exception while closing socket [{}]", x); - } - _logger.debug("Closing..."); - } - } - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/Context.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/Context.java deleted file mode 100644 index 37bff7b7bb..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/Context.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc; - -import java.net.Inet4Address; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.util.Enumeration; - -import org.zeromq.ZMQ; - -/** - * Provides a ZeroMQ Context object - */ -public class Context { - private final ZMQ.Context zmqContext = ZMQ.context(1); - private String uri; - private final String DEFAULT_RPC_PORT = "5554"; - - private static Context _instance = new Context(); - - private Context() {} - - public static Context getInstance(){ - return _instance; - } - - public ZMQ.Context getZmqContext(){ - return this.zmqContext; - } - - public String getLocalUri(){ - uri = (uri != null) ? uri - : new StringBuilder().append(getIpAddress()).append(":") - .append(getRpcPort()).toString(); - - return uri; - } - - public String getRpcPort(){ - String rpcPort = (System.getProperty("rpc.port") != null) - ? System.getProperty("rpc.port") - : DEFAULT_RPC_PORT; - - return rpcPort; - } - - private String getIpAddress(){ - String ipAddress = (System.getProperty("local.ip") != null) - ? System.getProperty("local.ip") - : findIpAddress(); - - return ipAddress; - } - - /** - * Finds IPv4 address of the local VM - * TODO: This method is non-deterministic. There may be more than one IPv4 address. Cant say which - * address will be returned. Read IP from a property file or enhance the code to make it deterministic. - * Should we use IP or hostname? - * - * @return - */ - private String findIpAddress() { - String hostAddress = null; - Enumeration e = null; - try { - e = NetworkInterface.getNetworkInterfaces(); - } catch (SocketException e1) { - e1.printStackTrace(); - } - while (e.hasMoreElements()) { - - NetworkInterface n = (NetworkInterface) e.nextElement(); - - Enumeration ee = n.getInetAddresses(); - while (ee.hasMoreElements()) { - InetAddress i = (InetAddress) ee.nextElement(); - if ((i instanceof Inet4Address) && (i.isSiteLocalAddress())) - hostAddress = i.getHostAddress(); - } - } - return hostAddress; - - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcClient.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcClient.java deleted file mode 100644 index 94e3232f17..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcClient.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc; - -public interface RemoteRpcClient extends AutoCloseable{ - - void setRoutingTableProvider(RoutingTableProvider provider); - - void stop(); - - void start(); -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcProvider.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcProvider.java deleted file mode 100644 index 76df25682e..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcProvider.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc; - -import static com.google.common.base.Preconditions.checkState; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.opendaylight.controller.md.sal.common.api.routing.RouteChange; -import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener; -import org.opendaylight.controller.sal.connector.api.RpcRouter; -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable; -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTableException; -import org.opendaylight.controller.sal.connector.remoterpc.api.SystemException; -import org.opendaylight.controller.sal.connector.remoterpc.dto.RouteIdentifierImpl; -import org.opendaylight.controller.sal.core.api.Broker.ProviderSession; -import org.opendaylight.controller.sal.core.api.Provider; -import org.opendaylight.controller.sal.core.api.RoutedRpcDefaultImplementation; -import org.opendaylight.controller.sal.core.api.RpcImplementation; -import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry; -import org.opendaylight.controller.sal.core.api.RpcRegistrationListener; -import org.opendaylight.controller.sal.core.api.RpcRoutingContext; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; -import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; -import org.osgi.framework.BundleContext; -import org.osgi.util.tracker.ServiceTracker; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Optional; -import com.google.common.util.concurrent.ListenableFuture; - -public class RemoteRpcProvider implements - RpcImplementation, - RoutedRpcDefaultImplementation, - AutoCloseable, - Provider { - - private final Logger _logger = LoggerFactory.getLogger(RemoteRpcProvider.class); - - private final ServerImpl server; - private final ClientImpl client; - private RoutingTableProvider routingTableProvider; - private final RpcListener listener = new RpcListener(); - private final RoutedRpcListener routeChangeListener = new RoutedRpcListener(); - private ProviderSession brokerSession; - private RpcProvisionRegistry rpcProvisionRegistry; - private BundleContext context; - private ServiceTracker clusterTracker; - - public RemoteRpcProvider(ServerImpl server, ClientImpl client) { - this.server = server; - this.client = client; - } - - public void setRoutingTableProvider(RoutingTableProvider provider) { - this.routingTableProvider = provider; - client.setRoutingTableProvider(provider); - } - - public void setContext(BundleContext context){ - this.context = context; - } - - public void setRpcProvisionRegistry(RpcProvisionRegistry rpcProvisionRegistry){ - this.rpcProvisionRegistry = rpcProvisionRegistry; - } - - @Override - public void onSessionInitiated(ProviderSession session) { - brokerSession = session; - server.setBrokerSession(session); - start(); - } - - @Override - public Set getSupportedRpcs() { - //TODO: Ask Tony if we need to get this from routing table - return Collections.emptySet(); - } - - @Override - public Collection getProviderFunctionality() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture> invokeRpc(QName rpc, CompositeNode input) { - return client.invokeRpc(rpc, input); - } - - @Override - public ListenableFuture> invokeRpc(QName rpc, InstanceIdentifier identifier, CompositeNode input) { - return client.invokeRpc(rpc, identifier, input); - } - - public void start() { - server.start(); - client.start(); - brokerSession.addRpcRegistrationListener(listener); - rpcProvisionRegistry.setRoutedRpcDefaultDelegate(this); - rpcProvisionRegistry.registerRouteChangeListener(routeChangeListener); - - announceSupportedRpcs(); - announceSupportedRoutedRpcs(); - } - - @Override - public void close() throws Exception { - unregisterSupportedRpcs(); - unregisterSupportedRoutedRpcs(); - server.close(); - client.close(); - } - - public void stop() { - server.stop(); - client.stop(); - } - - /** - * Add all the locally registered RPCs in the clustered routing table - */ - private void announceSupportedRpcs(){ - Set currentlySupported = brokerSession.getSupportedRpcs(); - for (QName rpc : currentlySupported) { - listener.onRpcImplementationAdded(rpc); - } - } - - /** - * Add all the locally registered Routed RPCs in the clustered routing table - */ - private void announceSupportedRoutedRpcs(){ - - //TODO: announce all routed RPCs as well - - } - - /** - * Un-Register all the supported RPCs from clustered routing table - */ - private void unregisterSupportedRpcs(){ - Set currentlySupported = brokerSession.getSupportedRpcs(); - //TODO: remove all routed RPCs as well - for (QName rpc : currentlySupported) { - listener.onRpcImplementationRemoved(rpc); - } - } - - /** - * Un-Register all the locally supported Routed RPCs from clustered routing table - */ - private void unregisterSupportedRoutedRpcs(){ - - //TODO: remove all routed RPCs as well - - } - - private RoutingTable, String> getRoutingTable(){ - Optional, String>> routingTable = - routingTableProvider.getRoutingTable(); - - checkState(routingTable.isPresent(), "Routing table is null"); - - return routingTable.get(); - } - - /** - * Listener for rpc registrations in broker - */ - private class RpcListener implements RpcRegistrationListener { - - @Override - public void onRpcImplementationAdded(QName rpc) { - - _logger.debug("Adding registration for [{}]", rpc); - RouteIdentifierImpl routeId = new RouteIdentifierImpl(); - routeId.setType(rpc); - - RoutingTable, String> routingTable = getRoutingTable(); - - try { - routingTable.addGlobalRoute(routeId, server.getServerAddress()); - _logger.debug("Route added [{}-{}]", routeId, server.getServerAddress()); - - } catch (RoutingTableException | SystemException e) { - //TODO: This can be thrown when route already exists in the table. Broker - //needs to handle this. - _logger.error("Unhandled exception while adding global route to routing table [{}]", e); - - } - } - - @Override - public void onRpcImplementationRemoved(QName rpc) { - - _logger.debug("Removing registration for [{}]", rpc); - RouteIdentifierImpl routeId = new RouteIdentifierImpl(); - routeId.setType(rpc); - - RoutingTable, String> routingTable = getRoutingTable(); - - try { - routingTable.removeGlobalRoute(routeId); - } catch (RoutingTableException | SystemException e) { - _logger.error("Route delete failed {}", e); - } - } - } - - /** - * Listener for Routed Rpc registrations in broker - */ - private class RoutedRpcListener - implements RouteChangeListener { - - /** - * - * @param routeChange - */ - @Override - public void onRouteChange(RouteChange routeChange) { - Map> announcements = routeChange.getAnnouncements(); - announce(getRouteIdentifiers(announcements)); - - Map> removals = routeChange.getRemovals(); - remove(getRouteIdentifiers(removals)); - } - - /** - * - * @param announcements - */ - private void announce(Set> announcements) { - _logger.debug("Announcing [{}]", announcements); - RoutingTable, String> routingTable = getRoutingTable(); - try { - routingTable.addRoutes(announcements, server.getServerAddress()); - } catch (RoutingTableException | SystemException e) { - _logger.error("Route announcement failed {}", e); - } - } - - /** - * - * @param removals - */ - private void remove(Set> removals){ - _logger.debug("Removing [{}]", removals); - RoutingTable, String> routingTable = getRoutingTable(); - try { - routingTable.removeRoutes(removals, server.getServerAddress()); - } catch (RoutingTableException | SystemException e) { - _logger.error("Route removal failed {}", e); - } - } - - /** - * - * @param changes - * @return - */ - private Set> getRouteIdentifiers(Map> changes) { - RouteIdentifierImpl routeId = null; - Set> routeIdSet = new HashSet<>(); - - for (RpcRoutingContext context : changes.keySet()){ - routeId = new RouteIdentifierImpl(); - routeId.setType(context.getRpc()); - //routeId.setContext(context.getContext()); - - for (InstanceIdentifier instanceId : changes.get(context)){ - routeId.setRoute(instanceId); - routeIdSet.add(routeId); - } - } - return routeIdSet; - } - - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcServer.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcServer.java deleted file mode 100644 index e845e43c2a..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcServer.java +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc; - -public interface RemoteRpcServer extends AutoCloseable { - -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RoutingTableProvider.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RoutingTableProvider.java deleted file mode 100644 index d960303fcf..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RoutingTableProvider.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc; - -import org.opendaylight.controller.sal.connector.api.RpcRouter; -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable; -import org.opendaylight.controller.sal.connector.remoterpc.impl.RoutingTableImpl; -import org.osgi.framework.BundleContext; -import org.osgi.util.tracker.ServiceTracker; - -import com.google.common.base.Optional; - -public class RoutingTableProvider implements AutoCloseable { - - @SuppressWarnings("rawtypes") - final ServiceTracker tracker; - - private RoutingTableImpl routingTableImpl = null; - - //final private RouteChangeListener routeChangeListener; - - - public RoutingTableProvider(BundleContext ctx){//,RouteChangeListener rcl) { - @SuppressWarnings("rawtypes") - ServiceTracker rawTracker = new ServiceTracker<>(ctx, RoutingTable.class, null); - tracker = rawTracker; - tracker.open(); - - //routeChangeListener = rcl; - } - - public Optional, String>> getRoutingTable() { - @SuppressWarnings("unchecked") - RoutingTable, String> tracked = tracker.getService(); - - if(tracked instanceof RoutingTableImpl){ - if(routingTableImpl != tracked){ - routingTableImpl= (RoutingTableImpl)tracked; - //routingTableImpl.setRouteChangeListener(routeChangeListener); - } - } - - return Optional.fromNullable(tracked); - } - - @Override - public void close() throws Exception { - tracker.close(); - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ServerImpl.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ServerImpl.java deleted file mode 100644 index 3acea356ce..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ServerImpl.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.connector.remoterpc; - -import java.net.Inet4Address; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.FutureTask; -import java.util.concurrent.TimeUnit; - -import org.opendaylight.controller.sal.core.api.Broker.ProviderSession; -import org.opendaylight.yangtools.yang.common.QName; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.zeromq.ZMQ; - -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; - -/** - * ZeroMq based implementation of RpcRouter. - */ -public class ServerImpl implements RemoteRpcServer { - - private final Logger _logger = LoggerFactory.getLogger(ServerImpl.class); - - private ExecutorService serverPool; - protected ServerRequestHandler handler; - - private Set remoteServices; - private ProviderSession brokerSession; - private ZMQ.Context context; - - private final String HANDLER_INPROC_ADDRESS = "inproc://rpc-request-handler"; - private final int HANDLER_WORKER_COUNT = 2; - private final int HWM = 200;//high water mark on sockets - private volatile State status = State.STOPPED; - - private String serverAddress; - private final int port; - - public static enum State { - STARTING, STARTED, STOPPED; - } - - public ServerImpl(int port) { - this.port = port; - } - - public State getStatus() { - return this.status; - } - - public Optional getHandler() { - return Optional.fromNullable(this.handler); - } - - public void setBrokerSession(ProviderSession session) { - this.brokerSession = session; - } - - public Optional getBrokerSession() { - return Optional.fromNullable(this.brokerSession); - } - - public Optional getZmqContext() { - return Optional.fromNullable(this.context); - } - - public String getServerAddress() { - return serverAddress; - } - - public String getHandlerAddress() { - return HANDLER_INPROC_ADDRESS; - } - - /** - * - */ - public void start() { - Preconditions.checkState(State.STOPPED == this.getStatus(), - "Remote RPC Server is already running"); - - status = State.STARTING; - _logger.debug("Remote RPC Server is starting..."); - - String hostIpAddress = findIpAddress(); - - //Log and silently die as per discussion in the bug (bug-362) - //https://bugs.opendaylight.org/show_bug.cgi?id=362 - // - // A tracking enhancement defect (bug-366) is created to properly fix this issue - //https://bugs.opendaylight.org/show_bug.cgi?id=366 - //checkState(hostIpAddress != null, "Remote RPC Server could not acquire host ip address"); - - if (hostIpAddress == null) { - _logger.error("Remote RPC Server could not acquire host ip address. Stopping..."); - stop(); - return; - } - - this.serverAddress = new StringBuilder(hostIpAddress). - append(":"). - append(port). - toString(); - - context = ZMQ.context(1); - remoteServices = new HashSet();// - serverPool = Executors.newSingleThreadExecutor();//main server thread - serverPool.execute(receive()); // Start listening rpc requests - - status = State.STARTED; - _logger.info("Remote RPC Server started [{}]", getServerAddress()); - } - - public void stop(){ - close(); - } - - /** - * - */ - @Override - public void close() { - - if (State.STOPPED == this.getStatus()) return; //do nothing - - if (serverPool != null) - serverPool.shutdown(); - - closeZmqContext(); - - status = State.STOPPED; - _logger.info("Remote RPC Server stopped"); - } - - /** - * Closes ZMQ Context. It tries to gracefully terminate the context. If - * termination takes more than 5 seconds, its forcefully shutdown. - */ - private void closeZmqContext() { - ExecutorService exec = Executors.newSingleThreadExecutor(); - FutureTask zmqTermination = new FutureTask(new Runnable() { - - @Override - public void run() { - try { - if (context != null) - context.term(); - _logger.debug("ZMQ Context terminated gracefully!"); - } catch (Exception e) { - _logger.debug("ZMQ Context termination threw exception [{}]. Continuing shutdown...", e); - } - } - }, null); - - exec.execute(zmqTermination); - - try { - zmqTermination.get(5L, TimeUnit.SECONDS); - } catch (Exception e) {/*ignore and continue with shutdown*/} - - exec.shutdownNow(); - } - - /** - * Main listener thread that spawns {@link ServerRequestHandler} as workers. - * - * @return - */ - private Runnable receive() { - return new Runnable() { - - @Override - public void run() { - Thread.currentThread().setName("remote-rpc-server"); - _logger.debug("Remote RPC Server main thread starting..."); - - //socket clients connect to (frontend) - ZMQ.Socket clients = context.socket(ZMQ.ROUTER); - - //socket RequestHandlers connect to (backend) - ZMQ.Socket workers = context.socket(ZMQ.DEALER); - - try (SocketPair capturePair = new SocketPair(); - ServerRequestHandler requestHandler = new ServerRequestHandler(context, - brokerSession, - HANDLER_WORKER_COUNT, - HANDLER_INPROC_ADDRESS, - getServerAddress());) { - - handler = requestHandler; - clients.setHWM(HWM); - clients.bind("tcp://*:" + port); - workers.setHWM(HWM); - workers.bind(HANDLER_INPROC_ADDRESS); - //start worker threads - _logger.debug("Remote RPC Server worker threads starting..."); - requestHandler.start(); - //start capture thread - // handlerPool.execute(new CaptureHandler(capturePair.getReceiver())); - // Connect work threads to client threads via a queue - ZMQ.proxy(clients, workers, null);//capturePair.getSender()); - - } catch (Exception e) { - _logger.debug("Unhandled exception [{}, {}]", e.getClass(), e.getMessage()); - } finally { - if (clients != null) clients.close(); - if (workers != null) workers.close(); - _logger.info("Remote RPC Server stopped"); - } - } - }; - } - - /** - * Finds IPv4 address of the local VM - * TODO: This method is non-deterministic. There may be more than one IPv4 address. Cant say which - * address will be returned. Read IP from a property file or enhance the code to make it deterministic. - * Should we use IP or hostname? - * - * @return - */ - private String findIpAddress() { - Enumeration e = null; - try { - e = NetworkInterface.getNetworkInterfaces(); - } catch (SocketException e1) { - _logger.error("Failed to get list of interfaces", e1); - return null; - } - while (e.hasMoreElements()) { - - NetworkInterface n = (NetworkInterface) e.nextElement(); - - Enumeration ee = n.getInetAddresses(); - while (ee.hasMoreElements()) { - InetAddress i = (InetAddress) ee.nextElement(); - _logger.debug("Trying address {}", i); - if ((i instanceof Inet4Address) && (!i.isLoopbackAddress())) { - String hostAddress = i.getHostAddress(); - _logger.debug("Settled on host address {}", hostAddress); - return hostAddress; - } - } - } - - _logger.error("Failed to find a suitable host address"); - return null; - } - -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ServerRequestHandler.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ServerRequestHandler.java deleted file mode 100644 index a25387d297..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ServerRequestHandler.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.opendaylight.controller.sal.connector.api.RpcRouter; -import org.opendaylight.controller.sal.connector.remoterpc.dto.Message; -import org.opendaylight.controller.sal.connector.remoterpc.util.XmlUtils; -import org.opendaylight.controller.sal.core.api.Broker; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.zeromq.ZMQ; - -/** - * - */ -public class ServerRequestHandler implements AutoCloseable{ - - private final Logger _logger = LoggerFactory.getLogger(ServerRequestHandler.class); - private final String DEFAULT_NAME = "remote-rpc-worker"; - private final String dealerAddress; - private final String serverAddress; - private final int workerCount; - private final ZMQ.Context context; - private final Broker.ProviderSession broker; - - private RequestHandlerThreadPool workerPool; - private final AtomicInteger threadId = new AtomicInteger(); - - public ServerRequestHandler(ZMQ.Context context, - Broker.ProviderSession session, - int workerCount, - String dealerAddress, - String serverAddress) { - this.context = context; - this.dealerAddress = dealerAddress; - this.serverAddress = serverAddress; - this.broker = session; - this.workerCount = workerCount; - } - - public ThreadPoolExecutor getWorkerPool(){ - return workerPool; - } - - public void start(){ - workerPool = new RequestHandlerThreadPool( - workerCount, workerCount, - 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue()); - //unbound is ok. Task will never be submitted - - for (int i=0;i> rpc = null; - RpcResult result = null; - - //TODO Call this in a new thread with timeout - try { - rpc = broker.rpc( - (QName) request.getRoute().getType(), - XmlUtils.xmlToCompositeNode((String) request.getPayload())); - - result = (rpc != null) ? rpc.get() : null; - - handler.sendResponse(result); - - } catch (Exception e) { - _logger.debug("Broker threw [{}]", e); - handler.sendError(e.getMessage()); - } - } - - } - } catch (Exception e) { - printException(e); - } finally { - closeSocket(socket); - } - } - - private void printException(Exception e) { - try (StringWriter s = new StringWriter(); - PrintWriter p = new PrintWriter(s)) { - e.printStackTrace(p); - _logger.debug(s.toString()); - } catch (IOException e1) {/*Ignore and continue*/ } - } - - private void closeSocket(ZMQ.Socket socket) { - try { - if (socket != null) socket.close(); - } catch (Exception x) { - _logger.debug("Exception while closing socket [{}]", x); - } finally { - if (socket != null) socket.close(); - } - _logger.debug("Closing..."); - } - } - - - /** - * - */ - public class RequestHandlerThreadPool extends ThreadPoolExecutor{ - - public RequestHandlerThreadPool(int corePoolSize, - int maximumPoolSize, - long keepAliveTime, - TimeUnit unit, - BlockingQueue workQueue) { - super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); - } - - @Override - protected void afterExecute(Runnable r, Throwable t) { - if (isTerminating() || isTerminated() || isShutdown()) - return; - - if ( t != null ){ - _logger.debug("Exception caught while terminating worker [{},{}]", t.getClass(), t.getMessage()); - } - - this.execute(new Worker(threadId.incrementAndGet())); - super.afterExecute(r, null); - } - } - - class MessageHandler{ - private final ZMQ.Socket socket; - private Message message; //parsed message received on zmq server port - private boolean messageForBroker = false; //if the message is valid and not a "ping" message - - public MessageHandler(ZMQ.Socket socket){ - this.socket = socket; - } - - void receiveMessage(){ - byte[] bytes = socket.recv(); //this blocks - _logger.debug("Received bytes:[{}]", bytes.length); - - Object objectRecvd = null; - try{ - objectRecvd = Message.deserialize(bytes); - }catch (Exception e){ - sendError(e.getMessage()); - return; - } - - if (!(objectRecvd instanceof Message)) { - sendError("Invalid message received"); - return; - } - - message = (Message) objectRecvd; - - _logger.info("Received request [{}]", message); - - if (Message.MessageType.PING == message.getType()){ - sendPong(); - return; - } - - messageForBroker = true; - } - - boolean hasMessageForBroker(){ - return messageForBroker; - } - - Message getMessage(){ - return message; - } - - void sendResponse(RpcResult result){ - CompositeNode payload = (result != null) ? result.getResult() : null; - - String recipient = null; - RpcRouter.RouteIdentifier routeId = null; - - if (message != null) { - recipient = message.getSender(); - routeId = message.getRoute(); - } - - Message response = new Message.MessageBuilder() - .type(Message.MessageType.RESPONSE) - .sender(serverAddress) - .recipient(recipient) - .route(routeId) - .payload(XmlUtils.compositeNodeToXml(payload)) - .build(); - - send(response); - } - - private void sendError(String msg){ - Message errorResponse = new Message.MessageBuilder() - .type(Message.MessageType.ERROR) - .sender(serverAddress) - .payload(msg) - .build(); - - send(errorResponse); - } - - private void sendPong(){ - Message pong = new Message.MessageBuilder() - .type(Message.MessageType.PONG) - .sender(serverAddress) - .build(); - - send(pong); - } - - private void send(Message msg){ - byte[] serializedMessage = null; - try { - serializedMessage = Message.serialize(msg); - } catch (Exception e) { - _logger.debug("Unexpected error during serialization of response [{}]", msg); - return; - } - - if (serializedMessage != null) - if (socket.send(serializedMessage)) - _logger.info("Response sent [{}]", msg); - else _logger.debug("Failed to send serialized message"); - } - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/SocketPair.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/SocketPair.java deleted file mode 100644 index f569944a7f..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/SocketPair.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.connector.remoterpc; - -import org.zeromq.ZMQ; - -import java.util.UUID; - -/** - * - */ -public class SocketPair implements AutoCloseable{ - private ZMQ.Socket sender; - private ZMQ.Socket receiver; - - private static final String INPROC_PREFIX = "inproc://"; - - public SocketPair(){ - String address = new StringBuilder(INPROC_PREFIX) - .append(UUID.randomUUID()) - .toString(); - - receiver = Context.getInstance().getZmqContext().socket(ZMQ.PAIR); - receiver.bind(address); - - sender = Context.getInstance().getZmqContext().socket(ZMQ.PAIR); - sender.connect(address); - } - - public ZMQ.Socket getSender(){ - return this.sender; - } - - public ZMQ.Socket getReceiver(){ - return this.receiver; - } - - @Override - public void close() throws Exception { - sender.close(); - receiver.close(); - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/Message.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/Message.java deleted file mode 100644 index cbcfe3e2a9..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/Message.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc.dto; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; - -import org.opendaylight.controller.sal.connector.api.RpcRouter; - -public class Message implements Serializable { - private static final long serialVersionUID = 1L; - - public static enum MessageType { - PING((byte) 0), - PONG((byte) 1), - REQUEST((byte) 2), - RESPONSE((byte) 3), - ERROR((byte)4); - - private final byte type; - - MessageType(byte type) { - this.type = type; - } - - public byte getType(){ - return this.type; - } - } - - private MessageType type; - private String sender; - private String recipient; - private RpcRouter.RouteIdentifier route; - private Object payload; - - public MessageType getType() { - return type; - } - - public void setType(MessageType type) { - this.type = type; - } - - public String getSender() { - return sender; - } - - public void setSender(String sender) { - this.sender = sender; - } - - public RpcRouter.RouteIdentifier getRoute() { - return route; - } - - public void setRoute(RpcRouter.RouteIdentifier route) { - this.route = route; - } - - public Object getPayload() { - return payload; - } - - public void setPayload(Object payload) { - this.payload = payload; - } - - public String getRecipient() { - return recipient; - } - - public void setRecipient(String recipient) { - this.recipient = recipient; - } - - @Override - public String toString() { - return "Message{" + - "type=" + type + - ", sender='" + sender + '\'' + - ", recipient='" + recipient + '\'' + - ", route=" + route + - ", payload=" + payload + - '}'; - } - - /** - * Converts any {@link Serializable} object to byte[] - * - * @param obj - * @return - * @throws IOException - */ - public static byte[] serialize(Object obj) throws IOException { - ByteArrayOutputStream b = new ByteArrayOutputStream(); - ObjectOutputStream o = new ObjectOutputStream(b); - o.writeObject(obj); - return b.toByteArray(); - } - - /** - * Converts byte[] to a java object - * - * @param bytes - * @return - * @throws IOException - * @throws ClassNotFoundException - */ - public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException { - ByteArrayInputStream b = new ByteArrayInputStream(bytes); - ObjectInputStream o = new ObjectInputStream(b); - return o.readObject(); - } - - public static class Response extends Message implements RpcRouter.RpcReply { - private static final long serialVersionUID = 1L; - private ResponseCode code; // response code - - public static enum ResponseCode { - SUCCESS(200), BADREQUEST(400), TIMEOUT(408), GONE(410), SERVERERROR(500), SERVICEUNAVAILABLE(503); - - private final int code; - - ResponseCode(int code) { - this.code = code; - } - } - - public ResponseCode getCode() { - return code; - } - - public void setCode(ResponseCode code) { - this.code = code; - } - } - - /** - * Builds a {@link Message} object - */ - public static class MessageBuilder{ - - private final Message message; - - public MessageBuilder(){ - message = new Message(); - } - - - public MessageBuilder type(MessageType type){ - message.setType(type); - return this; - } - - public MessageBuilder sender(String sender){ - message.setSender(sender); - return this; - } - - public MessageBuilder recipient(String recipient){ - message.setRecipient(recipient); - return this; - } - - public MessageBuilder route(RpcRouter.RouteIdentifier route){ - message.setRoute(route); - return this; - } - - public MessageBuilder payload(Object obj){ - message.setPayload(obj); - return this; - } - - public Message build(){ - return message; - } - } -} - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/MessageWrapper.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/MessageWrapper.java deleted file mode 100644 index 85f4113663..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/MessageWrapper.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc.dto; - -import org.zeromq.ZMQ; - -/** - * A class encapsulating {@link Message} and the {@link ZMQ.Socket} over which it is transmitted - */ -public class MessageWrapper { - - private Message _message; - private ZMQ.Socket _receiveSocket; - - public MessageWrapper(Message message, ZMQ.Socket receiveSocket) { - this._message = message; - this._receiveSocket = receiveSocket; - } - - public Message getMessage() { - return _message; - } - - public ZMQ.Socket getReceiveSocket() { - return _receiveSocket; - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/RouteIdentifierImpl.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/RouteIdentifierImpl.java deleted file mode 100644 index 53c7cc0b8d..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/RouteIdentifierImpl.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.connector.remoterpc.dto; - -import java.io.Serializable; - -import org.opendaylight.controller.sal.connector.api.RpcRouter; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; - -public class RouteIdentifierImpl implements RpcRouter.RouteIdentifier,Serializable { - private static final long serialVersionUID = 1L; - - private QName context; - private QName type; - private InstanceIdentifier route; - - @Override - public QName getContext() { - return this.context; - } - - @Override - public QName getType() { - return this.type; - } - - @Override - public InstanceIdentifier getRoute() { - return this.route; - } - - public void setContext(QName context) { - this.context = context; - } - - public void setType(QName type) { - this.type = type; - } - - public void setRoute(InstanceIdentifier route) { - this.route = route; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - RouteIdentifierImpl that = (RouteIdentifierImpl) o; - - if (context == null){ - if (that.getContext() != null) return false; - }else - if (!context.equals(that.context)) return false; - - if (route == null){ - if (that.getRoute() != null) return false; - }else - if (!route.equals(that.route)) return false; - - if (type == null){ - if (that.getType() != null) return false; - }else - if (!type.equals(that.type)) return false; - - return true; - } - - @Override - public int hashCode() { - int prime = 31; - int result = 0; - result = prime * result + (context == null ? 0:context.hashCode()); - result = prime * result + (type == null ? 0:type.hashCode()); - result = prime * result + (route == null ? 0:route.hashCode()); - return result; - } - - @Override - public String toString() { - return "RouteIdentifierImpl{" + - "context=" + context + - ", type=" + type + - ", route=" + route + - '}'; - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/util/XmlUtils.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/util/XmlUtils.java deleted file mode 100644 index 3bc39630e1..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/util/XmlUtils.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc.util; - -import org.opendaylight.yangtools.yang.data.api.CompositeNode; -import org.opendaylight.yangtools.yang.data.api.Node; -import org.opendaylight.yangtools.yang.data.api.SimpleNode; -import org.opendaylight.yangtools.yang.data.impl.NodeUtils; -import org.opendaylight.yangtools.yang.data.impl.XmlTreeBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; - -import javax.xml.stream.XMLStreamException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.io.ByteArrayInputStream; -import java.io.StringWriter; - -public class XmlUtils { - - private static final Logger _logger = LoggerFactory.getLogger(XmlUtils.class); - - public static String compositeNodeToXml(CompositeNode cNode){ - if (cNode == null) return new String(); - - Document domTree = NodeUtils.buildShadowDomTree(cNode); - StringWriter writer = new StringWriter(); - try { - TransformerFactory tf = TransformerFactory.newInstance(); - Transformer transformer = tf.newTransformer(); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - transformer.transform(new DOMSource(domTree), new StreamResult(writer)); - } catch (TransformerException e) { - _logger.error("Error during translation of Document to OutputStream", e); - } - - return writer.toString(); - } - - public static CompositeNode xmlToCompositeNode(String xml){ - if (xml==null || xml.length()==0) return null; - - Node dataTree; - try { - dataTree = XmlTreeBuilder.buildDataTree(new ByteArrayInputStream(xml.getBytes())); - } catch (XMLStreamException e) { - _logger.error("Error during building data tree from XML", e); - return null; - } - if (dataTree == null) { - _logger.error("data tree is null"); - return null; - } - if (dataTree instanceof SimpleNode) { - _logger.error("RPC XML was resolved as SimpleNode"); - return null; - } - return (CompositeNode) dataTree; - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/yang/odl-sal-dom-rpc-remote-cfg.yang b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/yang/odl-sal-dom-rpc-remote-cfg.yang deleted file mode 100644 index beeb936c97..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/yang/odl-sal-dom-rpc-remote-cfg.yang +++ /dev/null @@ -1,50 +0,0 @@ -module odl-sal-dom-rpc-remote-cfg { - yang-version 1; - namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote:rpc"; - prefix "rpc-cluster"; - - import config { prefix config; revision-date 2013-04-05; } - import opendaylight-md-sal-dom {prefix dom;} - - description - "Service definition for Binding Aware MD-SAL."; - - revision "2013-10-28" { - description - "Initial revision"; - } - - identity remote-rpc-server { - base config:service-type; - config:java-class "org.opendaylight.controller.sal.connector.remoterpc.RemoteRpcServer"; - } - - identity remote-rpc-client { - base config:service-type; - config:java-class "org.opendaylight.controller.sal.connector.remoterpc.RemoteRpcClient"; - } - - identity remote-zeromq-rpc-server { - base config:module-type; - config:java-name-prefix ZeroMQServer; - } - - augment "/config:modules/config:module/config:configuration" { - case remote-zeromq-rpc-server { - when "/config:modules/config:module/config:type = 'remote-zeromq-rpc-server'"; - - container dom-broker { - uses config:service-ref { - refine type { - mandatory true; - config:required-identity dom:dom-broker-osgi-registry; - } - } - } - - leaf port { - type uint16; - } - } - } -} \ No newline at end of file diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ClientImplTest.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ClientImplTest.java deleted file mode 100644 index f8d14ce62e..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ClientImplTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.connector.remoterpc; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.IOException; - -import junit.framework.Assert; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.controller.sal.connector.api.RpcRouter; -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable; -import org.opendaylight.controller.sal.connector.remoterpc.dto.Message; -import org.opendaylight.controller.sal.connector.remoterpc.utils.MessagingUtil; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; - -import com.google.common.base.Optional; - -/** - * - */ -public class ClientImplTest { - RoutingTableProvider routingTableProvider; - ClientImpl client; - ClientRequestHandler mockHandler; - - @Before - public void setUp() throws Exception { - - //mock routing table - routingTableProvider = mock(RoutingTableProvider.class); - RoutingTable, String> mockRoutingTable = new MockRoutingTable(); - Optional, String>> optionalRoutingTable = Optional.fromNullable(mockRoutingTable); - when(routingTableProvider.getRoutingTable()).thenReturn(optionalRoutingTable); - - //mock ClientRequestHandler - mockHandler = mock(ClientRequestHandler.class); - - client = new ClientImpl(mockHandler); - client.setRoutingTableProvider(routingTableProvider); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void getRoutingTableProvider_Call_ShouldReturnMockProvider() throws Exception { - Assert.assertEquals(routingTableProvider, client.getRoutingTableProvider()); - - } - - @Test - public void testStart() throws Exception { - - } - - @Test - public void testStop() throws Exception { - - } - - @Test - public void testClose() throws Exception { - - } - - //@Test - public void invokeRpc_NormalCall_ShouldReturnSuccess() throws Exception { - - when(mockHandler.handle(any(Message.class))). - thenReturn(MessagingUtil.createEmptyMessage()); - - RpcResult result = client.invokeRpc(null, null).get(); - - Assert.assertTrue(result.isSuccessful()); - Assert.assertTrue(result.getErrors().isEmpty()); - Assert.assertNull(result.getResult()); - } - - //@Test - public void invokeRpc_HandlerThrowsException_ShouldReturnError() throws Exception { - - when(mockHandler.handle(any(Message.class))). - thenThrow(new IOException()); - - RpcResult result = client.invokeRpc(null, null).get(); - - Assert.assertFalse(result.isSuccessful()); - Assert.assertFalse(result.getErrors().isEmpty()); - Assert.assertNull(result.getResult()); - } - -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ClientRequestHandlerTest.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ClientRequestHandlerTest.java deleted file mode 100644 index 09188683cd..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ClientRequestHandlerTest.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.connector.remoterpc; - -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.FutureTask; -import java.util.concurrent.TimeUnit; - -import junit.framework.Assert; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.controller.sal.connector.remoterpc.dto.Message; -import org.opendaylight.controller.sal.connector.remoterpc.utils.MessagingUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.zeromq.ZMQ; - -/** - * - */ -public class ClientRequestHandlerTest { - - private final Logger _logger = LoggerFactory.getLogger(ClientRequestHandlerTest.class); - - ZMQ.Context context; - ExecutorService serverThread; - final String SERVER_ADDRESS = "localhost:5553"; - - ClientRequestHandler handler; - - @Before - public void setUp() throws Exception { - context = ZMQ.context(1); - serverThread = Executors.newCachedThreadPool(); - handler = new ClientRequestHandler(context); - } - - @After - public void tearDown() throws Exception { - serverThread.shutdown(); - MessagingUtil.closeZmqContext(context); - handler.close(); - } - - @Test - public void handle_SingleRemote_ShouldReturnResponse() throws Exception { - serverThread.execute(MessagingUtil.startReplyServer(context, SERVER_ADDRESS, 1)); - Message request = new Message(); - request.setRecipient(SERVER_ADDRESS); - Message response = handleMessageWithTimeout(request); - Assert.assertNotNull(response); - //should be connected to only 1 remote server - Assert.assertEquals(1, handler.getWorkerCount()); - Assert.assertEquals(response.getRecipient(), SERVER_ADDRESS); - } - - // @Test - public void handle_MultiRemote_ShouldReturnResponses() throws Exception { - ExecutorService threadPool = Executors.newCachedThreadPool(); - final int port = 5555; - String serverAddress = null; - for (int i = 0; i < 5; i++) { - serverAddress = "localhost:" + (port + i); - serverThread.execute(MessagingUtil.startReplyServer(context, serverAddress, 1)); - threadPool.execute(createEmptyMessageTaskAndHandle(handler, serverAddress)); - } - Thread.sleep(5000);//wait for all messages to get processed - //should be connected to 5 remote server - Assert.assertEquals(5, handler.getWorkerCount()); - } - - private Runnable createEmptyMessageTaskAndHandle(final ClientRequestHandler handler, final String serverAddress) { - - return new Runnable() { - @Override - public void run() { - Message request = new Message(); - request.setRecipient(serverAddress); - try { - Message response = handleMessageWithTimeout(request); - Assert.assertNotNull(response); - Assert.assertEquals(response.getRecipient(), serverAddress); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - }; - } - - private Message handleMessageWithTimeout(final Message request) { - Message response = null; - - FutureTask task = new FutureTask(new Callable() { - - @Override - public Message call() { - try { - return handler.handle(request); - } catch (Exception e) { - _logger.debug("Client handler failed to handle request. Exception is [{}]", e); - } - return null; - } - }); - - serverThread.execute(task); - - try { - response = (Message) task.get(5L, TimeUnit.SECONDS); //wait for max 5 sec for server to respond - } catch (Exception e) {/*ignore and continue*/} - - return response; - } - -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/MockRoutingTable.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/MockRoutingTable.java deleted file mode 100644 index 179051e4d4..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/MockRoutingTable.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.connector.remoterpc; - -import java.util.HashSet; -import java.util.Set; - -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable; -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTableException; -import org.opendaylight.controller.sal.connector.remoterpc.api.SystemException; - -/** - * Mock implementation of routing table - */ -public class MockRoutingTable implements RoutingTable { - - - @Override - public void addRoute(Object o, Object o2) throws RoutingTableException, SystemException { - - } - - @Override - public void addGlobalRoute(Object o, Object o2) throws RoutingTableException, SystemException { - - } - - @Override - public void removeRoute(Object o, Object o2) { - - } - - @Override - public void addRoutes(Set set, Object o) throws RoutingTableException, SystemException { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void removeRoutes(Set set, Object o) throws RoutingTableException, SystemException { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void removeGlobalRoute(Object o) throws RoutingTableException, SystemException { - - } - - @Override - public Object getGlobalRoute(Object o) throws RoutingTableException, SystemException { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public Set getRoutes(Object o) { - Set routes = new HashSet(); - routes.add("localhost:5554"); - return routes; - } - - @Override - public Object getLastAddedRoute(Object o) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - -// @Override -// public Set getAllRoutes() { -// return Collections.emptySet(); -// } - -// @Override -// public Object getARoute(Object o) { -// return null; -// } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcProviderTest.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcProviderTest.java deleted file mode 100644 index 06360aa7b3..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcProviderTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.opendaylight.controller.sal.connector.remoterpc; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class RemoteRpcProviderTest { - @Before - public void setUp() throws Exception { - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testSetRoutingTableProvider() throws Exception { - - } - - @Test - public void testOnSessionInitiated() throws Exception { - - } - - @Test - public void testGetSupportedRpcs() throws Exception { - - } - - @Test - public void testGetProviderFunctionality() throws Exception { - - } - - @Test - public void testInvokeRpc() throws Exception { - - } - - @Test - public void testInvokeRoutedRpc() throws Exception { - - } - - @Test - public void testStart() throws Exception { - - } - - @Test - public void testClose() throws Exception { - - } - - @Test - public void testStop() throws Exception { - - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/SerilizationTest.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/SerilizationTest.java deleted file mode 100644 index 41422fd680..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/SerilizationTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.connector.remoterpc; - -import org.junit.Test; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; -import org.opendaylight.yangtools.yang.data.api.Node; -import org.opendaylight.yangtools.yang.data.api.SimpleNode; -import org.opendaylight.yangtools.yang.data.impl.NodeUtils; -import org.opendaylight.yangtools.yang.data.impl.XmlTreeBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; - -import javax.xml.stream.XMLStreamException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.StringWriter; - -public class SerilizationTest { - - private static final Logger _logger = LoggerFactory.getLogger(SerilizationTest.class); - - public void fromXml() { - } - - @Test - public void toXml() throws FileNotFoundException { - - //InputStream xmlStream = SerilizationTest.class.getResourceAsStream("/FourSimpleChildren.xml"); - InputStream xmlStream = SerilizationTest.class.getResourceAsStream("/AddFlow.xml"); - StringWriter writer = new StringWriter(); - - CompositeNode data = loadCompositeNode(xmlStream); - Document domTree = NodeUtils.buildShadowDomTree(data); - try { - TransformerFactory tf = TransformerFactory.newInstance(); - Transformer transformer = tf.newTransformer(); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - //transformer.setOutputProperty(OutputKeys.METHOD, "xml"); - //transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - //transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - //transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); - transformer.transform(new DOMSource(domTree), new StreamResult(writer)); - } catch (TransformerException e) { - _logger.error("Error during translation of Document to OutputStream", e); - } - - _logger.info("Parsed xml [{}]", writer.toString()); - } - - // Figure out how to include TestUtils through pom ...was getting errors - private CompositeNode loadCompositeNode(InputStream xmlInputStream) throws FileNotFoundException { - if (xmlInputStream == null) { - throw new IllegalArgumentException(); - } - Node dataTree; - try { - dataTree = XmlTreeBuilder.buildDataTree(xmlInputStream); - } catch (XMLStreamException e) { - _logger.error("Error during building data tree from XML", e); - return null; - } - if (dataTree == null) { - _logger.error("data tree is null"); - return null; - } - if (dataTree instanceof SimpleNode) { - _logger.error("RPC XML was resolved as SimpleNode"); - return null; - } - return (CompositeNode) dataTree; - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ServerImplTest.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ServerImplTest.java deleted file mode 100644 index 7ffdf17ce7..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ServerImplTest.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc; - - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ThreadPoolExecutor; - -import junit.framework.Assert; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.controller.sal.connector.api.RpcRouter; -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable; -import org.opendaylight.controller.sal.connector.remoterpc.utils.MessagingUtil; -import org.opendaylight.controller.sal.core.api.Broker; -import org.opendaylight.controller.sal.core.api.RpcRegistrationListener; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; -import org.zeromq.ZMQ; - -import zmq.Ctx; -import zmq.SocketBase; - -import com.google.common.base.Optional; - -public class ServerImplTest { - - private static ZMQ.Context context; - private ServerImpl server; - private Broker.ProviderSession brokerSession; - private RoutingTableProvider routingTableProvider; - private RpcRegistrationListener listener; - - ExecutorService pool; - - //Server configuration - private final int HANDLER_COUNT = 2; - private final int HWM = 200; - private final int port = 5554; - //server address - private final String SERVER_ADDRESS = "tcp://localhost:5554"; - - //@BeforeClass - public static void init() { - context = ZMQ.context(1); - } - - //@AfterClass - public static void destroy() { - MessagingUtil.closeZmqContext(context); - } - - @Before - public void setup() throws InterruptedException { - context = ZMQ.context(1); - brokerSession = mock(Broker.ProviderSession.class); - routingTableProvider = mock(RoutingTableProvider.class); - listener = mock(RpcRegistrationListener.class); - - server = new ServerImpl(port); - server.setBrokerSession(brokerSession); - - RoutingTable, String> mockRoutingTable = new MockRoutingTable(); - Optional, String>> optionalRoutingTable = Optional.fromNullable(mockRoutingTable); - when(routingTableProvider.getRoutingTable()).thenReturn(optionalRoutingTable); - - when(brokerSession.addRpcRegistrationListener(listener)).thenReturn(null); - when(brokerSession.getSupportedRpcs()).thenReturn(Collections.emptySet()); - when(brokerSession.rpc(null, mock(CompositeNode.class))).thenReturn(null); - server.start(); - Thread.sleep(5000);//wait for server to start - } - - @After - public void tearDown() throws InterruptedException { - - if (pool != null) - pool.shutdown(); - - if (server != null) - server.stop(); - - MessagingUtil.closeZmqContext(context); - - Thread.sleep(5000);//wait for server to stop - Assert.assertEquals(ServerImpl.State.STOPPED, server.getStatus()); - } - - @Test - public void getBrokerSession_Call_ShouldReturnBrokerSession() throws Exception { - Optional mayBeBroker = server.getBrokerSession(); - - if (mayBeBroker.isPresent()) - Assert.assertEquals(brokerSession, mayBeBroker.get()); - else - Assert.fail("Broker does not exist in Remote RPC Server"); - - } - - @Test - public void start_Call_ShouldSetServerStatusToStarted() throws Exception { - Assert.assertEquals(ServerImpl.State.STARTED, server.getStatus()); - - } - - @Test - public void start_Call_ShouldCreateNZmqSockets() throws Exception { - final int EXPECTED_COUNT = 2 + HANDLER_COUNT; //1 ROUTER + 1 DEALER + HANDLER_COUNT - - Optional mayBeContext = server.getZmqContext(); - if (mayBeContext.isPresent()) - Assert.assertEquals(EXPECTED_COUNT, findSocketCount(mayBeContext.get())); - else - Assert.fail("ZMQ Context does not exist in Remote RPC Server"); - } - - @Test - public void start_Call_ShouldCreate1ServerThread() { - final String SERVER_THREAD_NAME = "remote-rpc-server"; - final int EXPECTED_COUNT = 1; - List serverThreads = findThreadsWithName(SERVER_THREAD_NAME); - Assert.assertEquals(EXPECTED_COUNT, serverThreads.size()); - } - - @Test - public void start_Call_ShouldCreateNHandlerThreads() { - //final String WORKER_THREAD_NAME = "remote-rpc-worker"; - final int EXPECTED_COUNT = HANDLER_COUNT; - - Optional serverRequestHandlerOptional = server.getHandler(); - if (serverRequestHandlerOptional.isPresent()){ - ServerRequestHandler handler = serverRequestHandlerOptional.get(); - ThreadPoolExecutor workerPool = handler.getWorkerPool(); - Assert.assertEquals(EXPECTED_COUNT, workerPool.getPoolSize()); - } else { - Assert.fail("Server is in illegal state. ServerHandler does not exist"); - } - - } - - @Test - public void testStop() throws Exception { - - } - - @Test - public void testOnRouteUpdated() throws Exception { - - } - - @Test - public void testOnRouteDeleted() throws Exception { - - } - - private int findSocketCount(ZMQ.Context context) - throws NoSuchFieldException, IllegalAccessException { - Field ctxField = context.getClass().getDeclaredField("ctx"); - ctxField.setAccessible(true); - Ctx ctx = Ctx.class.cast(ctxField.get(context)); - - Field socketListField = ctx.getClass().getDeclaredField("sockets"); - socketListField.setAccessible(true); - List sockets = List.class.cast(socketListField.get(ctx)); - - return sockets.size(); - } - - private List findThreadsWithName(String name) { - Thread[] threads = new Thread[Thread.activeCount()]; - Thread.enumerate(threads); - - List foundThreads = new ArrayList(); - for (Thread t : threads) { - if (t.getName().startsWith(name)) - foundThreads.add(t); - } - - return foundThreads; - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ServerRequestHandlerTest.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ServerRequestHandlerTest.java deleted file mode 100644 index e5fbc761b4..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ServerRequestHandlerTest.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc; - -import static org.mockito.Mockito.mock; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import junit.framework.Assert; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.controller.sal.connector.remoterpc.utils.MessagingUtil; -import org.opendaylight.controller.sal.core.api.Broker; -import org.zeromq.ZMQ; - -public class ServerRequestHandlerTest { - - ServerRequestHandler handler; - ZMQ.Context context; - ExecutorService executorService = Executors.newCachedThreadPool(); - private final int workerCount = 2; - private final String mockDealerAddress = "inproc://rpc-request-handler"; - private final String mockServerIp = "localhost"; - private final int mockServerPort = 5554; - - @Before - public void setUp() throws Exception { - context = ZMQ.context(1); - String mockServerAddress = mockServerIp + ":" + mockServerPort; - Broker.ProviderSession mockSession = mock(Broker.ProviderSession.class); - handler = new ServerRequestHandler(context, mockSession, workerCount, mockDealerAddress, mockServerAddress); - handler.start(); - } - - @After - public void tearDown() throws Exception { - executorService.shutdown(); - MessagingUtil.closeZmqContext(context); - handler.close(); - } - - @Test - public void testStart() throws Exception { - //should start workers == workerCount - Assert.assertEquals(workerCount, handler.getWorkerPool().getPoolSize()); - - //killing a thread should recreate another one - - //start router-dealer bridge - executorService.execute(MessagingUtil.createRouterDealerBridge(context, mockDealerAddress, mockServerPort)); - Thread.sleep(1000); //give sometime for socket initialization - - //this will kill the thread - final String WORKER_THREAD_NAME = "remote-rpc-worker"; - interruptAThreadWithName(WORKER_THREAD_NAME); - - //send 4 message to router - for (int i = 0; i < 4; i++) - executorService.execute(MessagingUtil.sendAnEmptyMessage(context, "tcp://" + mockServerIp + ":" + mockServerPort)); - - //worker pool size should not change. - Assert.assertEquals(workerCount, handler.getWorkerPool().getPoolSize()); - - Thread.sleep(10000); //wait for processing to complete - } - - @Test - public void testClose() throws Exception { - - } - - /** - * Interrupts the first thread found whose name starts with the provided name - * - * @param name - */ - private void interruptAThreadWithName(String name) { - List workerThreads = findThreadsWithName(name); - if (workerThreads.size() > 0) workerThreads.get(0).interrupt(); - } - - /** - * Find all threads that start with the given name - * - * @param name - * @return - */ - private List findThreadsWithName(String name) { - Thread[] threads = new Thread[Thread.activeCount()]; - Thread.enumerate(threads); - - List foundThreads = new ArrayList(); - for (Thread t : threads) { - if (t.getName().startsWith(name)) - foundThreads.add(t); - } - - return foundThreads; - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/utils/MessagingUtil.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/utils/MessagingUtil.java deleted file mode 100644 index 883aa52f3f..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/utils/MessagingUtil.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connector.remoterpc.utils; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.FutureTask; -import java.util.concurrent.TimeUnit; - -import junit.framework.Assert; - -import org.opendaylight.controller.sal.connector.remoterpc.dto.Message; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.zeromq.ZMQ; - -public class MessagingUtil { - - private static final Logger _logger = LoggerFactory.getLogger(MessagingUtil.class); - - public static Runnable startReplyServer(final ZMQ.Context context, - final String serverAddress, - final int numRequests /*number of requests after which server shuts down*/) { - return new Runnable() { - - @Override - public void run() { - final ZMQ.Socket socket = context.socket(ZMQ.REP); - try { - int returnCode = socket.bind("tcp://" + serverAddress); - Assert.assertNotSame(-1, returnCode); - _logger.info(" Starting reply server[{}] for test...", serverAddress); - - //for (int i=0;i zmqTermination = new FutureTask(new Runnable() { - - @Override - public void run() { - try { - if (context != null) - context.term(); - _logger.debug("ZMQ Context terminated gracefully!"); - } catch (Exception e) {/*Ignore and continue shutdown*/} - } - }, null); - - exec.execute(zmqTermination); - - try { - zmqTermination.get(1L, TimeUnit.SECONDS); - } catch (Exception e) { - _logger.debug("ZMQ Context terminated forcefully!"); - } - - exec.shutdownNow(); - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/utils/RemoteServerTestClient.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/utils/RemoteServerTestClient.java deleted file mode 100644 index 7a4f4a5974..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/utils/RemoteServerTestClient.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.opendaylight.controller.sal.connector.remoterpc.utils; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import org.opendaylight.controller.sal.connector.api.RpcRouter; -import org.opendaylight.controller.sal.connector.remoterpc.dto.Message; -import org.opendaylight.controller.sal.connector.remoterpc.util.XmlUtils; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; -import org.zeromq.ZMQ; - -public class RemoteServerTestClient { - - - - public static void main(String args[]) throws Exception{ - String serverAddress = "tcp://10.195.128.108:5666"; - ZMQ.Context ctx = ZMQ.context(1); - ExecutorService executor = Executors.newSingleThreadExecutor(); - RemoteServerTestClient client = new RemoteServerTestClient(); - executor.execute( - MessagingUtil.sendAMessage(ctx, serverAddress, client.createPingMessage(serverAddress)) - ); - MessagingUtil.sendAMessage(ctx, serverAddress, client.createPingMessage(serverAddress)); - - Thread.sleep(5000); - MessagingUtil.closeZmqContext(ctx); - executor.shutdown(); - } - - public Message createPingMessage(String serverAddress){ - Message ping = new Message.MessageBuilder() - .type(Message.MessageType.PING) - .sender("localhost:5444") - .recipient(serverAddress) - .build(); - - return ping; - } - public Message createAddFlowMessage(String serverAddress ){ - - RpcRouter.RouteIdentifier routeIdentifier = getAddFlowRpcIdentifier(); - - Message addFlow = new Message.MessageBuilder() - .type(Message.MessageType.REQUEST) - .sender("localhost:5444") - .recipient(serverAddress) - .route(routeIdentifier) - .payload(getAddFlowPayload(1,1)) - .build(); - - return addFlow; - } - - private RpcRouter.RouteIdentifier getAddFlowRpcIdentifier(){ - throw new UnsupportedOperationException(); - } - - private CompositeNode getAddFlowPayload(int flowId, int tableId){ - final String xml = - "" - + "5" - + "Foo" - + "" - + "" - + "" - + "2048" - + "" - + "" - + "10.0.10.2/24" - + "" - + "" + flowId + "" - + "" + tableId + "" - + "" - + "" - + "0" - + "" - + "" - + "0" - + "" - + "" - + "" - + "" - + "" - + ""; - - return XmlUtils.xmlToCompositeNode(xml); - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/AddFlow.xml b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/AddFlow.xml deleted file mode 100644 index b042b8f65b..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/AddFlow.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - BA-7 - 4 - 5 - - /(urn:opendaylight:inventory?revision=2013-08-19)nodes/(urn:opendaylight:inventory?revision=2013-08-19)node[{(urn:opendaylight:inventory?revision=2013-08-19)id=openflow:1}] - - - 10.0.10.2/24 - - - 2048 - - - - - - 0 - - - 0 - - - - - - - /(urn:opendaylight:inventory?revision=2013-08-19)nodes/(urn:opendaylight:inventory?revision=2013-08-19)node[{(urn:opendaylight:inventory?revision=2013-08-19)id=openflow:1}]/(urn:opendaylight:flow:inventory?revision=2013-08-19)table[{(urn:opendaylight:flow:inventory?revision=2013-08-19)id=4}] - - - /(urn:opendaylight:inventory?revision=2013-08-19)nodes/(urn:opendaylight:inventory?revision=2013-08-19)node[{(urn:opendaylight:inventory?revision=2013-08-19)id=openflow:1}]/(urn:opendaylight:flow:inventory?revision=2013-08-19)table[{(urn:opendaylight:flow:inventory?revision=2013-08-19)id=4}]/(urn:opendaylight:flow:inventory?revision=2013-08-19)flow[{(urn:opendaylight:flow:inventory?revision=2013-08-19)id=4}] - - Foo - - \ No newline at end of file diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/FourSimpleChildren.xml b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/FourSimpleChildren.xml deleted file mode 100644 index 5ac991b120..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/FourSimpleChildren.xml +++ /dev/null @@ -1,6 +0,0 @@ - - eth0 - ethernetCsmacd - false - some interface - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/logback-test.xml b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/logback-test.xml deleted file mode 100644 index 7eb75b90c7..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/logback-test.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/pom.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/pom.xml deleted file mode 100644 index 8435884e7b..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/pom.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller.tests - sal-remoterpc-connector-test-parent - 1.1-SNAPSHOT - - sal-remoterpc-connector-test-consumer - bundle - - - - - org.opendaylight.controller - containermanager - - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal-binding-api - - - org.opendaylight.controller - sal-common-util - - - - org.opendaylight.controller - sal-common-util - - - org.opendaylight.controller - sal-core-api - - - org.opendaylight.yangtools - yang-binding - - - org.opendaylight.yangtools - yang-common - - - org.opendaylight.yangtools - yang-data-api - - - org.opendaylight.yangtools - yang-data-impl - ${yangtools.version} - - - - - - - org.apache.felix - maven-bundle-plugin - - - org.opendaylight.controller.sample.zeromq.consumer.ExampleConsumer - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL - - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/java/org/opendaylight/controller/sample/zeromq/consumer/ExampleConsumer.java b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/java/org/opendaylight/controller/sample/zeromq/consumer/ExampleConsumer.java deleted file mode 100644 index aac6da47ba..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/java/org/opendaylight/controller/sample/zeromq/consumer/ExampleConsumer.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sample.zeromq.consumer; - -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.net.URI; -import java.util.Hashtable; -import java.util.concurrent.Future; - -import org.opendaylight.controller.sal.core.api.AbstractConsumer; -import org.opendaylight.controller.sal.core.api.Broker.ConsumerSession; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; -import org.opendaylight.yangtools.yang.data.api.Node; -import org.opendaylight.yangtools.yang.data.api.SimpleNode; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.opendaylight.yangtools.yang.data.impl.XmlTreeBuilder; - -import javax.xml.stream.XMLStreamException; - -public class ExampleConsumer extends AbstractConsumer { - - private final URI namespace = URI.create("http://cisco.com/example"); - private final QName QNAME = new QName(namespace, "heartbeat"); - - private ConsumerSession session; - - private ServiceRegistration thisReg; - private Logger _logger = LoggerFactory.getLogger(ExampleConsumer.class); - - @Override - public void onSessionInitiated(ConsumerSession session) { - this.session = session; - } - - public RpcResult invokeRpc(QName qname, CompositeNode input) { - _logger.info("Invoking RPC:[{}] with Input:[{}]", qname.getLocalName(), input); - RpcResult result = null; - Future> future = ExampleConsumer.this.session.rpc(qname, input); - try { - result = future.get(); - } catch (Exception e) { - e.printStackTrace(); - } - _logger.info("Returning Result:[{}]", result); - return result; - } - - @Override - protected void startImpl(BundleContext context){ - thisReg = context.registerService(ExampleConsumer.class, this, new Hashtable()); - } - @Override - protected void stopImpl(BundleContext context) { - super.stopImpl(context); - thisReg.unregister(); - } - - public CompositeNode getValidCompositeNodeWithOneSimpleChild() throws FileNotFoundException { - InputStream xmlStream = ExampleConsumer.class.getResourceAsStream("/OneSimpleChild.xml"); - return loadCompositeNode(xmlStream); - } - - public CompositeNode getValidCompositeNodeWithTwoSimpleChildren() throws FileNotFoundException { - InputStream xmlStream = ExampleConsumer.class.getResourceAsStream("/TwoSimpleChildren.xml"); - return loadCompositeNode(xmlStream); - } - - public CompositeNode getValidCompositeNodeWithFourSimpleChildren() throws FileNotFoundException { - InputStream xmlStream = ExampleConsumer.class.getResourceAsStream("/FourSimpleChildren.xml"); - return loadCompositeNode(xmlStream); - } - - public CompositeNode getValidCompositeNodeWithOneSimpleOneCompositeChild() throws FileNotFoundException { - InputStream xmlStream = ExampleConsumer.class.getResourceAsStream("/OneSimpleOneCompositeChild.xml"); - return loadCompositeNode(xmlStream); - } - - public CompositeNode getValidCompositeNodeWithTwoCompositeChildren() throws FileNotFoundException { - InputStream xmlStream = ExampleConsumer.class.getResourceAsStream("/TwoCompositeChildren.xml"); - return loadCompositeNode(xmlStream); - } - - public CompositeNode getInvalidCompositeNodeSimpleChild() throws FileNotFoundException { - InputStream xmlStream = ExampleConsumer.class.getResourceAsStream("/InvalidSimpleChild.xml"); - return loadCompositeNode(xmlStream); - } - - public CompositeNode getInvalidCompositeNodeCompositeChild() throws FileNotFoundException { - InputStream xmlStream = ExampleConsumer.class.getResourceAsStream("/InvalidCompositeChild.xml"); - return loadCompositeNode(xmlStream); - } - - //Note to self: Stolen from TestUtils - ///Users/alefan/odl/controller4/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java - // Figure out how to include TestUtils through pom ...was getting errors - private CompositeNode loadCompositeNode(InputStream xmlInputStream) throws FileNotFoundException { - if (xmlInputStream == null) { - throw new IllegalArgumentException(); - } - Node dataTree; - try { - dataTree = XmlTreeBuilder.buildDataTree(xmlInputStream); - } catch (XMLStreamException e) { - _logger.error("Error during building data tree from XML", e); - return null; - } - if (dataTree == null) { - _logger.error("data tree is null"); - return null; - } - if (dataTree instanceof SimpleNode) { - _logger.error("RPC XML was resolved as SimpleNode"); - return null; - } - return (CompositeNode) dataTree; - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/FourSimpleChildren.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/FourSimpleChildren.xml deleted file mode 100644 index 5ac991b120..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/FourSimpleChildren.xml +++ /dev/null @@ -1,6 +0,0 @@ - - eth0 - ethernetCsmacd - false - some interface - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/InvalidCompositeChild.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/InvalidCompositeChild.xml deleted file mode 100644 index 3979d02ccf..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/InvalidCompositeChild.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - eth1 - ethernet - false - some interface - - - error - ethernet - true - some interface - - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/InvalidSimpleChild.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/InvalidSimpleChild.xml deleted file mode 100644 index 6082d72a71..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/InvalidSimpleChild.xml +++ /dev/null @@ -1,3 +0,0 @@ - - error - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/OneSimpleChild.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/OneSimpleChild.xml deleted file mode 100644 index f431b0453d..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/OneSimpleChild.xml +++ /dev/null @@ -1,3 +0,0 @@ - - eth0 - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/OneSimpleOneCompositeChild.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/OneSimpleOneCompositeChild.xml deleted file mode 100644 index bca7682ee7..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/OneSimpleOneCompositeChild.xml +++ /dev/null @@ -1,9 +0,0 @@ - - eth0 - - eth1 - ethernetCsmacd - false - some interface - - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/TwoCompositeChildren.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/TwoCompositeChildren.xml deleted file mode 100644 index c49407e4c0..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/TwoCompositeChildren.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - eth1 - ethernet - false - some interface - - - eth2 - ethernet - true - some interface - - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/TwoSimpleChildren.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/TwoSimpleChildren.xml deleted file mode 100644 index 5f4729c99d..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/TwoSimpleChildren.xml +++ /dev/null @@ -1,4 +0,0 @@ - - eth0 - ethernetCsmacd - \ No newline at end of file diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/pom.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/pom.xml deleted file mode 100644 index 3f47700f8d..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/pom.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - sal-parent - 1.1-SNAPSHOT - ../.. - - org.opendaylight.controller.tests - sal-remoterpc-connector-test-parent - pom - - - consumer-service - provider-service - test-it - test-nb - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL - - - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/provider-service/pom.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/provider-service/pom.xml deleted file mode 100644 index 2b9dc0cf25..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/provider-service/pom.xml +++ /dev/null @@ -1,82 +0,0 @@ - - 4.0.0 - - sal-remoterpc-connector-test-parent - org.opendaylight.controller.tests - 1.1-SNAPSHOT - - sal-remoterpc-connector-test-provider - bundle - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL - - - - - - - org.apache.felix - maven-bundle-plugin - - - org.opendaylight.controller.sample.zeromq.provider.ExampleProvider - - - - - - - - - org.opendaylight.controller - sal-binding-api - - - org.opendaylight.controller - sal-common-util - - - org.opendaylight.controller - sal-core-api - - - - - org.opendaylight.controller - containermanager - - - - org.opendaylight.controller - sal - - - org.opendaylight.yangtools - yang-binding - - - org.opendaylight.yangtools - yang-common - - - org.opendaylight.yangtools - yang-data-api - - - org.opendaylight.yangtools - yang-data-impl - - - org.opendaylight.controller - sal-common-util - - - org.opendaylight.controller - sal-remoterpc-connector - - - - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/provider-service/src/main/java/org/opendaylight/controller/sample/zeromq/provider/ExampleProvider.java b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/provider-service/src/main/java/org/opendaylight/controller/sample/zeromq/provider/ExampleProvider.java deleted file mode 100644 index ff930db6fd..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/provider-service/src/main/java/org/opendaylight/controller/sample/zeromq/provider/ExampleProvider.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sample.zeromq.provider; - -import org.opendaylight.controller.sal.common.util.RpcErrors; -import org.opendaylight.controller.sal.common.util.Rpcs; -import org.opendaylight.controller.sal.core.api.AbstractProvider; -import org.opendaylight.controller.sal.core.api.Broker.ProviderSession; -import org.opendaylight.controller.sal.core.api.Broker.RpcRegistration; -import org.opendaylight.controller.sal.core.api.RpcImplementation; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.RpcError; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; -import org.opendaylight.yangtools.yang.data.api.Node; -import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl; -import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class ExampleProvider extends AbstractProvider implements RpcImplementation { - - private final URI namespace = URI.create("http://cisco.com/example"); - private final QName QNAME = new QName(namespace, "heartbeat"); - private RpcRegistration reg; - - private ServiceRegistration thisReg; - - private ProviderSession session; - private Logger _logger = LoggerFactory.getLogger(ExampleProvider.class); - - @Override - public void onSessionInitiated(ProviderSession session) { - this.session = session; - } - - @Override - public Set getSupportedRpcs() { - Set supportedRpcs = new HashSet(); - supportedRpcs.add(QNAME); - return supportedRpcs; - } - - @Override - public RpcResult invokeRpc(final QName rpc, CompositeNode input) { - boolean success = false; - CompositeNode output = null; - Collection errors = new ArrayList<>(); - - // Only handle supported RPC calls - if (getSupportedRpcs().contains(rpc)) { - if (input == null) { - errors.add(RpcErrors.getRpcError("app", "tag", "info", RpcError.ErrorSeverity.WARNING, "message:null input", RpcError.ErrorType.RPC, null)); - } - else { - if (isErroneousInput(input)) { - errors.add(RpcErrors.getRpcError("app", "tag", "info", RpcError.ErrorSeverity.ERROR, "message:error", RpcError.ErrorType.RPC, null)); - } - else { - success = true; - output = addSuccessNode(input); - } - } - } - return Rpcs.getRpcResult(success, output, errors); - } - - // Examines input -- dives into CompositeNodes and finds any value equal to "error" - private boolean isErroneousInput(CompositeNode input) { - for (Node n : input.getChildren()) { - if (n instanceof CompositeNode) { - if (isErroneousInput((CompositeNode)n)) { - return true; - } - } - else { //SimpleNode - if ((input.getChildren().get(0).getValue()).equals("error")) { - return true; - } - } - } - return false; - } - - // Adds a child SimpleNode containing the value "success" to the input CompositeNode - private CompositeNode addSuccessNode(CompositeNode input) { - List> list = new ArrayList>(input.getChildren()); - SimpleNodeTOImpl simpleNode = new SimpleNodeTOImpl(QNAME, input, "success"); - list.add(simpleNode); - return new CompositeNodeTOImpl(QNAME, null, list); - } - - @Override - protected void startImpl(BundleContext context) { - thisReg = context.registerService(ExampleProvider.class, this, new Hashtable()); - } - - @Override - protected void stopImpl(BundleContext context) { - if (reg != null) { - try { - reg.close(); - thisReg.unregister(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - public void announce(QName name) { - _logger.debug("Announcing [{}]\n\n\n", name); - reg = this.session.addRpcImplementation(name, this); - } - -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/pom.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/pom.xml deleted file mode 100644 index 0ffc330f90..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/pom.xml +++ /dev/null @@ -1,467 +0,0 @@ - - 4.0.0 - - sal-remoterpc-connector-test-parent - org.opendaylight.controller.tests - 1.1-SNAPSHOT - - sal-remoterpc-connector-test-it - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL - - - - - - - org.ops4j.pax.exam - maven-paxexam-plugin - - - generate-config - - generate-depends-file - - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - ${lifecycle.mapping.version} - - - - - - - org.ops4j.pax.exam - - - maven-paxexam-plugin - - - [1.2.4,) - - - - generate-depends-file - - - - - - - - - - - - - - - - - - org.opendaylight.yangtools.thirdparty - xtend-lib-osgi - - - org.opendaylight.controller.tests - sal-remoterpc-connector-test-provider - - - org.opendaylight.controller.tests - sal-remoterpc-connector-test-consumer - - - org.opendaylight.controller - sal-broker-impl - - - org.ops4j.pax.exam - pax-exam-container-native - ${exam.version} - test - - - org.ops4j.pax.exam - pax-exam-junit4 - ${exam.version} - test - - - org.ops4j.pax.exam - pax-exam-link-mvn - ${exam.version} - test - - - org.ops4j.pax.url - pax-url-aether - test - - - equinoxSDK381 - org.eclipse.osgi - test - - - org.slf4j - log4j-over-slf4j - - - ch.qos.logback - logback-core - - - ch.qos.logback - logback-classic - - - org.opendaylight.controller - sal-binding-api - - - org.opendaylight.controller - sal-common-util - - - org.opendaylight.controller - sal-core-api - - - org.opendaylight.controller - sal-remoterpc-connector - - - - org.opendaylight.controller - containermanager - - - org.osgi - org.osgi.compendium - - - commons-io - commons-io - - - - - - org.opendaylight.yangtools - yang-binding - - - org.opendaylight.yangtools - yang-common - - - org.opendaylight.yangtools - yang-data-api - - - - org.opendaylight.yangtools - yang-parser-impl - ${yangtools.version} - - - org.opendaylight.controller - sal-common-util - - - org.opendaylight.yangtools.thirdparty - antlr4-runtime-osgi-nohead - - - - - org.opendaylight.controller - zeromq-routingtable.implementation - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - sal - - - org.osgi - org.osgi.compendium - - - - - org.opendaylight.controller - sal.implementation - - - commons-io - commons-io - - - - - org.opendaylight.controller - containermanager - - - org.osgi - org.osgi.compendium - - - commons-io - commons-io - - - - - org.opendaylight.controller - containermanager.it.implementation - - - commons-io - commons-io - - - - - org.opendaylight.controller - clustering.stub - - - commons-io - commons-io - - - - - - org.apache.felix - org.apache.felix.dependencymanager.shell - - - org.osgi - org.osgi.compendium - - - - - eclipselink - javax.resource - - - com.google.guava - guava - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - ietf-netconf-monitoring - - - org.opendaylight.yangtools - yang-binding - - - org.opendaylight.yangtools.model - yang-ext - - - org.opendaylight.yangtools.model - opendaylight-l2-types - - - org.opendaylight.controller - sal-binding-it - - - org.opendaylight.controller - sal-binding-config - - - org.opendaylight.controller - sal-binding-broker-impl - - - org.opendaylight.controller - sal-broker-impl - - - - org.opendaylight.controller.model - model-inventory - - - org.opendaylight.yangtools - yang-common - - - org.opendaylight.controller - sal-connector-api - - - org.opendaylight.controller - sal-common-util - - - - org.opendaylight.controller - clustering.services - - - - equinoxSDK381 - org.eclipse.osgi - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson.version} - - - - com.fasterxml.jackson.core - jackson-core - ${jackson.version} - - - - org.zeromq - jeromq - - - - org.opendaylight.yangtools.thirdparty - xtend-lib-osgi - test - - - org.opendaylight.controller - sal-binding-broker-impl - provided - - - org.ops4j.pax.exam - pax-exam-container-native - ${exam.version} - test - - - org.ops4j.pax.exam - pax-exam-junit4 - ${exam.version} - test - - - org.opendaylight.controller - config-netconf-connector - test - - - org.opendaylight.controller - logback-config - - - org.opendaylight.controller - config-persister-impl - - - org.opendaylight.controller - config-persister-file-xml-adapter - - - org.opendaylight.controller - netconf-impl - - - org.opendaylight.controller - netconf-client - - - org.ops4j.pax.exam - pax-exam - ${exam.version} - - compile - - - org.ops4j.pax.exam - pax-exam-link-mvn - ${exam.version} - test - - - equinoxSDK381 - org.eclipse.osgi - test - - - org.slf4j - log4j-over-slf4j - - - ch.qos.logback - logback-core - - - ch.qos.logback - logback-classic - - - org.mockito - mockito-all - test - - - org.opendaylight.controller.model - model-flow-service - provided - - - org.opendaylight.controller - config-manager - - - commons-io - commons-io - - - - - org.opendaylight.controller.model - model-flow-management - provided - - - org.opendaylight.yangtools.thirdparty - antlr4-runtime-osgi-nohead - - - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/src/test/java/org/opendaylight/controller/sample/zeromq/test/it/RouterTest.java b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/src/test/java/org/opendaylight/controller/sample/zeromq/test/it/RouterTest.java deleted file mode 100644 index e02e290a29..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/src/test/java/org/opendaylight/controller/sample/zeromq/test/it/RouterTest.java +++ /dev/null @@ -1,452 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sample.zeromq.test.it; - -import junit.framework.Assert; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.opendaylight.controller.sal.connector.remoterpc.RemoteRpcClient; - -import org.opendaylight.controller.sal.connector.remoterpc.dto.Message; -import org.opendaylight.controller.sal.core.api.Broker; -import org.opendaylight.controller.sample.zeromq.consumer.ExampleConsumer; -import org.opendaylight.controller.sample.zeromq.provider.ExampleProvider; - -import org.opendaylight.controller.test.sal.binding.it.TestHelper; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.RpcError; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; -import org.ops4j.pax.exam.Configuration; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.junit.PaxExam; -import org.ops4j.pax.exam.util.Filter; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleException; -import org.osgi.framework.ServiceReference; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.zeromq.ZMQ; - -import javax.inject.Inject; - -import java.io.IOException; -import java.net.URI; - -import static org.opendaylight.controller.test.sal.binding.it.TestHelper.baseModelBundles; -import static org.opendaylight.controller.test.sal.binding.it.TestHelper.bindingAwareSalBundles; - -//import static org.ops4j.pax.exam.CoreOptions.*; - -@RunWith(PaxExam.class) -public class RouterTest { - - private Logger _logger = LoggerFactory.getLogger(RouterTest.class); - - public static final String ODL = "org.opendaylight.controller"; - public static final String YANG = "org.opendaylight.yangtools"; - public static final String SAMPLE = "org.opendaylight.controller.tests"; - private final URI namespace = URI.create("http://cisco.com/example"); - private final QName QNAME = new QName(namespace, "heartbeat"); - - - @Inject - org.osgi.framework.BundleContext ctx; - - @Inject - @Filter(timeout=60*1000) - Broker broker; - - private ZMQ.Context zmqCtx = ZMQ.context(1); - //private Server router; - //private ExampleProvider provider; - - //@Test - public void testInvokeRpc() throws Exception{ - //Thread.sleep(1000); - //Send announcement - ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class); - Assert.assertNotNull(providerRef); - - ExampleProvider provider = (ExampleProvider)ctx.getService(providerRef); - Assert.assertNotNull(provider); - - ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class); - Assert.assertNotNull(consumerRef); - ExampleConsumer consumer = (ExampleConsumer)ctx.getService(consumerRef); - Assert.assertNotNull(consumer); - - - _logger.debug("Provider sends announcement [{}]", "heartbeat"); - provider.announce(QNAME); - ServiceReference routerRef = ctx.getServiceReference(RemoteRpcClient.class); - RemoteRpcClient router = (RemoteRpcClient) ctx.getService(routerRef); - _logger.debug("Found router[{}]", router); - _logger.debug("Invoking RPC [{}]", QNAME); - for (int i = 0; i < 3; i++) { - RpcResult result = router.invokeRpc(QNAME, consumer.getValidCompositeNodeWithOneSimpleChild()); - _logger.debug("{}-> Result is: Successful:[{}], Payload:[{}], Errors: [{}]", i, result.isSuccessful(), result.getResult(), result.getErrors()); - Assert.assertNotNull(result); - } - } - - @Test - public void testInvokeRpcWithValidSimpleNode() throws Exception{ - //Thread.sleep(1500); - - ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class); - Assert.assertNotNull(providerRef); - ExampleProvider provider = (ExampleProvider)ctx.getService(providerRef); - Assert.assertNotNull(provider); - ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class); - Assert.assertNotNull(consumerRef); - ExampleConsumer consumer = (ExampleConsumer)ctx.getService(consumerRef); - Assert.assertNotNull(consumer); - - // Provider sends announcement - _logger.debug("Provider sends announcement [{}]", "heartbeat"); - provider.announce(QNAME); - // Consumer invokes RPC - _logger.debug("Invoking RPC [{}]", QNAME); - CompositeNode input = consumer.getValidCompositeNodeWithOneSimpleChild(); - for (int i = 0; i < 3; i++) { - RpcResult result = consumer.invokeRpc(QNAME, input); - Assert.assertNotNull(result); - _logger.debug("{}-> Result is: Successful:[{}], Payload:[{}], Errors: [{}]", i, result.isSuccessful(), result.getResult(), result.getErrors()); - Assert.assertTrue(result.isSuccessful()); - Assert.assertNotNull(result.getResult()); - Assert.assertEquals(0, result.getErrors().size()); - Assert.assertEquals(input.getChildren().size()+1, result.getResult().getChildren().size()); - } - } - - @Test - public void testInvokeRpcWithValidSimpleNodes() throws Exception{ - //Thread.sleep(1500); - - ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class); - Assert.assertNotNull(providerRef); - ExampleProvider provider = (ExampleProvider)ctx.getService(providerRef); - Assert.assertNotNull(provider); - ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class); - Assert.assertNotNull(consumerRef); - ExampleConsumer consumer = (ExampleConsumer)ctx.getService(consumerRef); - Assert.assertNotNull(consumer); - - // Provider sends announcement - _logger.debug("Provider sends announcement [{}]", "heartbeat"); - provider.announce(QNAME); - // Consumer invokes RPC - _logger.debug("Invoking RPC [{}]", QNAME); - CompositeNode input = consumer.getValidCompositeNodeWithFourSimpleChildren(); - for (int i = 0; i < 3; i++) { - RpcResult result = consumer.invokeRpc(QNAME, input); - Assert.assertNotNull(result); - _logger.debug("{}-> Result is: Successful:[{}], Payload:[{}], Errors: [{}]", i, result.isSuccessful(), result.getResult(), result.getErrors()); - Assert.assertTrue(result.isSuccessful()); - Assert.assertNotNull(result.getResult()); - Assert.assertEquals(0, result.getErrors().size()); - Assert.assertEquals(input.getChildren().size()+1, result.getResult().getChildren().size()); - } - } - - @Test - public void testInvokeRpcWithValidCompositeNode() throws Exception{ - //Thread.sleep(1500); - - ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class); - Assert.assertNotNull(providerRef); - ExampleProvider provider = (ExampleProvider)ctx.getService(providerRef); - Assert.assertNotNull(provider); - ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class); - Assert.assertNotNull(consumerRef); - ExampleConsumer consumer = (ExampleConsumer)ctx.getService(consumerRef); - Assert.assertNotNull(consumer); - - // Provider sends announcement - _logger.debug("Provider sends announcement [{}]", "heartbeat"); - provider.announce(QNAME); - // Consumer invokes RPC - _logger.debug("Invoking RPC [{}]", QNAME); - CompositeNode input = consumer.getValidCompositeNodeWithTwoCompositeChildren(); - for (int i = 0; i < 3; i++) { - RpcResult result = consumer.invokeRpc(QNAME, input); - Assert.assertNotNull(result); - _logger.debug("{}-> Result is: Successful:[{}], Payload:[{}], Errors: [{}]", i, result.isSuccessful(), result.getResult(), result.getErrors()); - Assert.assertTrue(result.isSuccessful()); - Assert.assertNotNull(result.getResult()); - Assert.assertEquals(0, result.getErrors().size()); - Assert.assertEquals(input.getChildren().size()+1, result.getResult().getChildren().size()); - } - } - - @Test - public void testInvokeRpcWithNullInput() throws Exception{ - //Thread.sleep(1500); - - ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class); - Assert.assertNotNull(providerRef); - ExampleProvider provider = (ExampleProvider)ctx.getService(providerRef); - Assert.assertNotNull(provider); - ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class); - Assert.assertNotNull(consumerRef); - ExampleConsumer consumer = (ExampleConsumer)ctx.getService(consumerRef); - Assert.assertNotNull(consumer); - - // Provider sends announcement - _logger.debug("Provider sends announcement [{}]", QNAME.getLocalName()); - provider.announce(QNAME); - // Consumer invokes RPC - _logger.debug("Invoking RPC [{}]", QNAME); - for (int i = 0; i < 3; i++) { - RpcResult result = consumer.invokeRpc(QNAME, null); - Assert.assertNotNull(result); - _logger.debug("{}-> Result is: Successful:[{}], Payload:[{}], Errors: [{}]", i, result.isSuccessful(), result.getResult(), result.getErrors()); - Assert.assertFalse(result.isSuccessful()); - Assert.assertNull(result.getResult()); - Assert.assertEquals(1, result.getErrors().size()); - Assert.assertEquals(RpcError.ErrorSeverity.WARNING, ((RpcError)result.getErrors().toArray()[0]).getSeverity()); - } - } - - @Test - public void testInvokeRpcWithInvalidSimpleNode() throws Exception{ - //Thread.sleep(1500); - - ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class); - Assert.assertNotNull(providerRef); - ExampleProvider provider = (ExampleProvider)ctx.getService(providerRef); - Assert.assertNotNull(provider); - ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class); - Assert.assertNotNull(consumerRef); - ExampleConsumer consumer = (ExampleConsumer)ctx.getService(consumerRef); - Assert.assertNotNull(consumer); - - // Provider sends announcement - _logger.debug("Provider sends announcement [{}]", QNAME.getLocalName()); - provider.announce(QNAME); - // Consumer invokes RPC - _logger.debug("Invoking RPC [{}]", QNAME); - CompositeNode input = consumer.getInvalidCompositeNodeSimpleChild(); - for (int i = 0; i < 3; i++) { - RpcResult result = consumer.invokeRpc(QNAME, input); - Assert.assertNotNull(result); - _logger.debug("{}-> Result is: Successful:[{}], Payload:[{}], Errors: [{}]", i, result.isSuccessful(), result.getResult(), result.getErrors()); - Assert.assertFalse(result.isSuccessful()); - Assert.assertNull(result.getResult()); - Assert.assertEquals(1, result.getErrors().size()); - Assert.assertEquals(RpcError.ErrorSeverity.ERROR, ((RpcError)result.getErrors().toArray()[0]).getSeverity()); - } - } - - @Test - public void testInvokeRpcWithInvalidCompositeNode() throws Exception{ - //Thread.sleep(1500); - - ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class); - Assert.assertNotNull(providerRef); - ExampleProvider provider = (ExampleProvider)ctx.getService(providerRef); - Assert.assertNotNull(provider); - ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class); - Assert.assertNotNull(consumerRef); - ExampleConsumer consumer = (ExampleConsumer)ctx.getService(consumerRef); - Assert.assertNotNull(consumer); - - // Provider sends announcement - _logger.debug("Provider sends announcement [{}]", QNAME.getLocalName()); - provider.announce(QNAME); - // Consumer invokes RPC - _logger.debug("Invoking RPC [{}]", QNAME); - CompositeNode input = consumer.getInvalidCompositeNodeCompositeChild(); - for (int i = 0; i < 3; i++) { - RpcResult result = consumer.invokeRpc(QNAME, input); - Assert.assertNotNull(result); - _logger.debug("{}-> Result is: Successful:[{}], Payload:[{}], Errors: [{}]", i, result.isSuccessful(), result.getResult(), result.getErrors()); - Assert.assertFalse(result.isSuccessful()); - Assert.assertNull(result.getResult()); - Assert.assertEquals(1, result.getErrors().size()); - Assert.assertEquals(RpcError.ErrorSeverity.ERROR, ((RpcError)result.getErrors().toArray()[0]).getSeverity()); - } - } - - //@Test - // This method is UNTESTED -- need to get around the bundling issues before I know if this even work -// public void testInvokeRpcWithValidCompositeNode() throws Exception{ -// Thread.sleep(10000); -// //Send announcement -// ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class); -// Assert.assertNotNull(providerRef); -// -// ExampleProvider provider = (ExampleProvider)ctx.getService(providerRef); -// Assert.assertNotNull(provider); -// -// ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class); -// Assert.assertNotNull(consumerRef); -// -// ExampleConsumer consumer = (ExampleConsumer)ctx.getService(consumerRef); -// Assert.assertNotNull(consumer); -// -// _logger.debug("Provider sends announcement [{}]", "heartbeat"); -// provider.announce(QNAME); -// ServiceReference routerRef = ctx.getServiceReference(Client.class); -// Client router = (Client) ctx.getService(routerRef); -// _logger.debug("Found router[{}]", router); -// _logger.debug("Invoking RPC [{}]", QNAME); -// for (int i = 0; i < 3; i++) { -// RpcResult result = router.getInstance().invokeRpc(QNAME, consumer.getValidCompositeNodeWithOneSimpleChild()); -// _logger.debug("{}-> Result is: Successful:[{}], Payload:[{}], Errors: [{}]", i, result.isSuccessful(), result.getResult(), result.getErrors()); -// Assert.assertNotNull(result); -// } -// } - - private Message send(Message msg) throws IOException { - ZMQ.Socket reqSocket = zmqCtx.socket(ZMQ.REQ); - reqSocket.connect("tcp://localhost:5555"); - reqSocket.send(Message.serialize(msg)); - Message response = parseMessage(reqSocket); - - return response; - } - - /** - * @param socket - * @return - */ - private Message parseMessage(ZMQ.Socket socket) { - - Message msg = null; - try { - byte[] bytes = socket.recv(); - _logger.debug("Received bytes:[{}]", bytes.length); - msg = (Message) Message.deserialize(bytes); - } catch (Throwable t) { - t.printStackTrace(); - } - return msg; - } - - - private void printState(){ - Bundle[] b = ctx.getBundles(); - _logger.debug("\n\nNumber of bundles [{}]\n\n]", b.length); - for (int i=0;i - - - - - urn:opendaylight:params:xml:ns:yang:controller:config?module=config&revision=2013-04-05 - - - urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl?module=opendaylight-sal-binding-broker-impl&revision=2013-10-28 - - - urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding?module=opendaylight-md-sal-binding&revision=2013-10-28 - - - urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl?module=opendaylight-sal-dom-broker-impl&revision=2013-10-28 - - urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom?module=opendaylight-md-sal-dom&revision=2013-10-28 - - urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote:rpc?module=odl-sal-dom-rpc-remote-cfg&revision=2013-10-28 - - - - - - - - - prefix:schema-service-singleton - - yang-schema-service - - - - prefix:hash-map-data-store - - hash-map-data-store - - - - prefix:dom-broker-impl - - dom-broker - - - dom:dom-data-store - - ref_hash-map-data-store - - - - - prefix:binding-broker-impl - - binding-broker-impl - - - binding:binding-notification-service - - ref_binding-notification-broker - - - - binding:binding-data-broker - - ref_binding-data-broker - - - - - prefix:runtime-generated-mapping - - runtime-mapping-singleton - - - - prefix:binding-notification-broker - - binding-notification-broker - - - - prefix:binding-data-broker - - binding-data-broker - - - dom:dom-broker-osgi-registry - - ref_dom-broker - - - - binding:binding-dom-mapping-service - - ref_runtime-mapping-singleton - - - - - prefix:remote-zeromq-rpc-server - - remoter - 5666 - - - prefix:dom-broker-osgi-registry - - ref_dom-broker - - - - - - - - dom:schema-service - - - ref_yang-schema-service - - /config/modules/module[name='schema-service-singleton']/instance[name='yang-schema-service'] - - - - - - binding:binding-notification-service - - - ref_binding-notification-broker - - /config/modules/module[name='binding-notification-broker']/instance[name='binding-notification-broker'] - - - - - - dom:dom-data-store - - - ref_hash-map-data-store - - /config/modules/module[name='hash-map-data-store']/instance[name='hash-map-data-store'] - - - - - - binding:binding-broker-osgi-registry - - - ref_binding-broker-impl - - /config/modules/module[name='binding-broker-impl']/instance[name='binding-broker-impl'] - - - - - - binding-impl:binding-dom-mapping-service - - - ref_runtime-mapping-singleton - - /config/modules/module[name='runtime-generated-mapping']/instance[name='runtime-mapping-singleton'] - - - - - - dom:dom-broker-osgi-registry - - - ref_dom-broker - /config/modules/module[name='dom-broker-impl']/instance[name='dom-broker'] - - - - - - binding:binding-data-broker - - - ref_binding-data-broker - - /config/modules/module[name='binding-data-broker']/instance[name='binding-data-broker'] - - - - - - - - - - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/src/test/resources/logback.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/src/test/resources/logback.xml deleted file mode 100644 index 1d17796373..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/src/test/resources/logback.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/pom.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/pom.xml deleted file mode 100644 index b681db27fb..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/pom.xml +++ /dev/null @@ -1,101 +0,0 @@ - - - 4.0.0 - - sal-remoterpc-connector-test-parent - org.opendaylight.controller.tests - 1.1-SNAPSHOT - - - sal-remoterpc-connector-test-nb - bundle - - - - - org.apache.felix - maven-bundle-plugin - ${bundle.plugin.version} - true - - - - - - com.sun.jersey.spi.container.servlet, - !org.codehaus.jackson.annotate, - javax.ws.rs, - javax.ws.rs.core, - javax.xml.bind, - javax.xml.bind.annotation, - org.slf4j, - org.apache.catalina.filters, - !org.codehaus.jackson.jaxrs, - org.opendaylight.controller.sample.zeromq.provider, - org.opendaylight.controller.sample.zeromq.consumer, - org.opendaylight.controller.sal.utils, - org.opendaylight.yangtools.yang.common, - org.opendaylight.controller.sal.connector.api, - org.opendaylight.controller.sal.connector.remoterpc.api;version="[0.4,1)", - org.opendaylight.controller.sal.connector.remoterpc.impl;version="[0.4,1)", - org.opendaylight.controller.sal.connector.remoterpc.dto, - org.opendaylight.controller.sal.connector.remoterpc.util, - org.osgi.framework, - com.google.common.base, - org.opendaylight.yangtools.yang.data.api, - !org.codehaus.enunciate.jaxrs - - - /controller/nb/v2/zmqnb - ,${classes;ANNOTATION;javax.ws.rs.Path} - - ${project.basedir}/src/main/resources/META-INF - - - - - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - sal - - - org.opendaylight.controller.tests - sal-remoterpc-connector-test-provider - - - org.opendaylight.controller.tests - sal-remoterpc-connector-test-consumer - - - org.opendaylight.controller - sal-remoterpc-connector - - - org.osgi - org.osgi.core - - - junit - junit - - - org.opendaylight.controller - remoterpc-routingtable.implementation - - - com.google.guava - guava - - - - diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqrouter/rest/Router.java b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqrouter/rest/Router.java deleted file mode 100644 index e97be52f3d..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqrouter/rest/Router.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.tests.zmqrouter.rest; - -import org.opendaylight.controller.sal.connector.api.RpcRouter; -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable; -import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTableException; -import org.opendaylight.controller.sal.connector.remoterpc.api.SystemException; -import org.opendaylight.controller.sal.connector.remoterpc.impl.RoutingTableImpl; -import org.opendaylight.controller.sal.connector.remoterpc.util.XmlUtils; -import org.opendaylight.controller.sample.zeromq.consumer.ExampleConsumer; -import org.opendaylight.controller.sample.zeromq.provider.ExampleProvider; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; -import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import java.io.Serializable; -import java.net.URI; -import java.util.Set; - -@Path("router") -public class Router { - private Logger _logger = LoggerFactory.getLogger(Router.class); - private final URI namespace = URI.create("http://cisco.com/example"); - private final QName QNAME = new QName(namespace, "heartbeat"); - - - @GET - @Path("/hello") - @Produces(MediaType.TEXT_PLAIN) - public String hello() { - return "Hello"; - } - - @GET - @Path("/announce") - @Produces(MediaType.TEXT_PLAIN) - public String announce() { - _logger.info("Announce request received"); - - BundleContext ctx = getBundleContext(); - ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class); - if (providerRef == null) { - _logger.debug("Could not get provider reference"); - return "Could not get provider reference"; - } - - ExampleProvider provider = (ExampleProvider) ctx.getService(providerRef); - if (provider == null) { - _logger.info("Could not get provider service"); - return "Could not get provider service"; - } - - provider.announce(QNAME); - return "Announcement sent "; - - } - - @GET - @Path("/rpc") - @Produces(MediaType.TEXT_PLAIN) - public String invokeRpc() throws Exception { - _logger.info("Invoking RPC"); - - ExampleConsumer consumer = getConsumer(); - RpcResult result = consumer.invokeRpc(QNAME, consumer.getValidCompositeNodeWithOneSimpleChild()); - _logger.info("Result [{}]", result.isSuccessful()); - - return stringify(result); - } - - @GET - @Path("/rpc-success") - @Produces(MediaType.TEXT_PLAIN) - public String invokeRpcSuccess() throws Exception { - ExampleConsumer consumer = getConsumer(); - RpcResult result = consumer.invokeRpc(QNAME, consumer.getValidCompositeNodeWithFourSimpleChildren()); //TODO: Change this - _logger.info("Result [{}]", result.isSuccessful()); - - return stringify(result); - } - - @GET - @Path("/rpc-failure") - @Produces(MediaType.TEXT_PLAIN) - public String invokeRpcFailure() throws Exception { - ExampleConsumer consumer = getConsumer(); - //RpcResult result = consumer.invokeRpc(QNAME, consumer.getInvalidCompositeNodeCompositeChild()); //TODO: Change this - RpcResult result = consumer.invokeRpc(QNAME, null); //TODO: Change this - _logger.info("Result [{}]", result.isSuccessful()); - - return stringify(result); - } - - @GET - @Path("/routingtable") - @Produces(MediaType.TEXT_PLAIN) - public String invokeRoutingTable() { - _logger.info("Invoking adding an entry in routing table"); - - BundleContext ctx = getBundleContext(); - ServiceReference routingTableServiceReference = ctx.getServiceReference(RoutingTable.class); - if (routingTableServiceReference == null) { - _logger.debug("Could not get routing table impl reference"); - return "Could not get routingtable referen "; - } - RoutingTableImpl routingTable = (RoutingTableImpl) ctx.getService(routingTableServiceReference); - if (routingTable == null) { - _logger.info("Could not get routing table service"); - return "Could not get routing table service"; - } - - - RoutingIdentifierImpl rii = new RoutingIdentifierImpl(); - try { - routingTable.addGlobalRoute(rii.toString(), "172.27.12.1:5000"); - } catch (RoutingTableException e) { - _logger.error("error in adding routing identifier" + e.getMessage()); - - } catch (SystemException e) { - _logger.error("error in adding routing identifier" + e.getMessage()); - } - - String result = routingTable.dumpRoutingTableCache(); - - - - - _logger.info("Result [{}] routes added for route" + rii + result); - - return result; - } - - @GET - @Path("/routingtabledelete") - @Produces(MediaType.TEXT_PLAIN) - public String invokeDeleteRoutingTable() { - _logger.info("Invoking adding an entry in routing table"); - - BundleContext ctx = getBundleContext(); - ServiceReference routingTableServiceReference = ctx.getServiceReference(RoutingTable.class); - if (routingTableServiceReference == null) { - _logger.debug("Could not get routing table impl reference"); - return "Could not get routingtable referen "; - } - RoutingTable routingTable = (RoutingTableImpl) ctx.getService(routingTableServiceReference); - if (routingTable == null) { - _logger.info("Could not get routing table service"); - return "Could not get routing table service"; - } - - - RoutingIdentifierImpl rii = new RoutingIdentifierImpl(); - try { - routingTable.removeGlobalRoute(rii.toString()); - } catch (RoutingTableException e) { - _logger.error("error in adding routing identifier" + e.getMessage()); - - } catch (SystemException e) { - _logger.error("error in adding routing identifier" + e.getMessage()); - } - - Set routes = routingTable.getRoutes(rii.toString()); - - StringBuilder stringBuilder = new StringBuilder(); - if (routes != null) { - for (String route : routes) { - stringBuilder.append(route); - } - } else { - stringBuilder.append(" successfully"); - } - - _logger.info("Result [{}] routes removed for route" + rii + stringBuilder.toString()); - - return stringBuilder.toString(); - } - - private String stringify(RpcResult result) { - CompositeNode node = result.getResult(); - StringBuilder builder = new StringBuilder("result:").append(XmlUtils.compositeNodeToXml(node)).append("\n") - .append("error:").append(result.getErrors()).append("\n"); - - return builder.toString(); - } - - private BundleContext getBundleContext() { - ClassLoader tlcl = Thread.currentThread().getContextClassLoader(); - Bundle bundle = null; - - if (tlcl instanceof BundleReference) { - bundle = ((BundleReference) tlcl).getBundle(); - } else { - _logger.info("Unable to determine the bundle context based on " + - "thread context classloader."); - bundle = FrameworkUtil.getBundle(this.getClass()); - } - return (bundle == null ? null : bundle.getBundleContext()); - } - - private ExampleConsumer getConsumer() { - BundleContext ctx = getBundleContext(); - ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class); - if (consumerRef == null) { - _logger.debug("Could not get consumer reference"); - throw new NullPointerException("Could not get consumer reference"); - } - ExampleConsumer consumer = (ExampleConsumer) ctx.getService(consumerRef); - if (consumer == null) { - _logger.info("Could not get consumer service"); - throw new NullPointerException("Could not get consumer service"); - } - return consumer; - } - - class RoutingIdentifierImpl implements RpcRouter.RouteIdentifier, Serializable { - - private final URI namespace = URI.create("http://cisco.com/example"); - private final QName QNAME = new QName(namespace, "global"); - private final QName instance = new QName(URI.create("127.0.0.1"), "local"); - - @Override - public QName getContext() { - return QNAME; - } - - @Override - public QName getType() { - return QNAME; - } - - @Override - public org.opendaylight.yangtools.yang.data.api.InstanceIdentifier getRoute() { - return InstanceIdentifier.of(instance); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - RoutingIdentifierImpl that = (RoutingIdentifierImpl) o; - - if (!QNAME.equals(that.QNAME)) return false; - if (!instance.equals(that.instance)) return false; - if (!namespace.equals(that.namespace)) return false; - - return true; - } - - @Override - public int hashCode() { - int result = namespace.hashCode(); - result = 31 * result + QNAME.hashCode(); - result = 31 * result + instance.hashCode(); - return result; - } - } -} diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/src/main/resources/WEB-INF/web.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 5bd21398fb..0000000000 --- a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - - JAXRSZmq - com.sun.jersey.spi.container.servlet.ServletContainer - - javax.ws.rs.Application - org.opendaylight.controller.northbound.commons.NorthboundApplication - - 1 - - - - JAXRSZmq - /* - - - - - - - NB api - /* - POST - GET - PUT - PATCH - DELETE - HEAD - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - BASIC - opendaylight - - diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java index 1e5bfbd6b9..696bf71535 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java @@ -9,15 +9,15 @@ package org.opendaylight.controller.sal.rest.impl; import static com.google.common.base.Preconditions.checkNotNull; +import com.google.common.base.Preconditions; +import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.net.URI; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; - import javax.activation.UnsupportedDataTypeException; - import org.opendaylight.controller.sal.core.api.mount.MountInstance; import org.opendaylight.controller.sal.restconf.impl.ControllerContext; import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO; @@ -29,6 +29,7 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.Node; import org.opendaylight.yangtools.yang.data.api.SimpleNode; +import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode; import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode; import org.opendaylight.yangtools.yang.model.api.ChoiceNode; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; @@ -48,13 +49,8 @@ import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinit import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.base.Preconditions; -import com.google.gson.stream.JsonWriter; - class JsonMapper { - private final Set foundLeafLists = new HashSet<>(); - private final Set foundLists = new HashSet<>(); private MountInstance mountPoint; private final Logger logger = LoggerFactory.getLogger(JsonMapper.class); @@ -77,15 +73,14 @@ class JsonMapper { } writer.endObject(); - - foundLeafLists.clear(); - foundLists.clear(); } private void writeChildrenOfParent(final JsonWriter writer, final CompositeNode parent, final DataNodeContainer parentSchema) throws IOException { checkNotNull(parent); + final Set foundLists = new HashSet<>(); + Set parentSchemaChildNodes = parentSchema == null ? Collections.emptySet() : parentSchema.getChildNodes(); @@ -98,59 +93,88 @@ class JsonMapper { logger.debug( "No schema found for data node \"" + child.getNodeType() ); - handleNoSchemaFound( writer, child, parent ); + if( !foundLists.contains( child.getNodeType() ) ) { + handleNoSchemaFound( writer, child, parent ); + + // Since we don't have a schema, we don't know which nodes are supposed to be + // lists so treat every one as a potential list to avoid outputting duplicates. + + foundLists.add( child.getNodeType() ); + } } else if (childSchema instanceof ContainerSchemaNode) { Preconditions.checkState(child instanceof CompositeNode, "Data representation of Container should be CompositeNode - " + child.getNodeType()); writeContainer(writer, (CompositeNode) child, (ContainerSchemaNode) childSchema); } else if (childSchema instanceof ListSchemaNode) { - if (!foundLists.contains(childSchema)) { + if (!foundLists.contains( child.getNodeType() ) ) { Preconditions.checkState(child instanceof CompositeNode, "Data representation of List should be CompositeNode - " + child.getNodeType()); - foundLists.add((ListSchemaNode) childSchema); + foundLists.add( child.getNodeType() ); writeList(writer, parent, (CompositeNode) child, (ListSchemaNode) childSchema); } } else if (childSchema instanceof LeafListSchemaNode) { - if (!foundLeafLists.contains(childSchema)) { + if (!foundLists.contains( child.getNodeType() ) ) { Preconditions.checkState(child instanceof SimpleNode, "Data representation of LeafList should be SimpleNode - " + child.getNodeType()); - foundLeafLists.add((LeafListSchemaNode) childSchema); + foundLists.add( child.getNodeType() ); writeLeafList(writer, parent, (SimpleNode) child, (LeafListSchemaNode) childSchema); } } else if (childSchema instanceof LeafSchemaNode) { Preconditions.checkState(child instanceof SimpleNode, "Data representation of LeafList should be SimpleNode - " + child.getNodeType()); writeLeaf(writer, (SimpleNode) child, (LeafSchemaNode) childSchema); + } else if (childSchema instanceof AnyXmlSchemaNode) { + if( child instanceof CompositeNode ) { + writeContainer(writer, (CompositeNode) child, null); + } + else { + handleNoSchemaFound( writer, child, parent ); + } } else { throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode, ListSchemaNode, " + "LeafListSchemaNode, or LeafSchemaNode. Other types are not supported yet."); } } + } - for (Node child : parent.getValue()) { - DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchemaChildNodes); - if (childSchema instanceof LeafListSchemaNode) { - foundLeafLists.remove(childSchema); - } else if (childSchema instanceof ListSchemaNode) { - foundLists.remove(childSchema); - } + private void writeValue( final JsonWriter writer, Object value ) throws IOException { + if( value != null ) { + writer.value( String.valueOf( value ) ); + } + else { + writer.value( "" ); } } private void handleNoSchemaFound( final JsonWriter writer, final Node node, final CompositeNode parent ) throws IOException { if( node instanceof SimpleNode ) { - writeName( node, null, writer ); - Object value = node.getValue(); - if( value != null ) { - writer.value( String.valueOf( value ) ); + List> nodeLeafList = parent.getSimpleNodesByName( node.getNodeType() ); + if( nodeLeafList.size() == 1 ) { + writeName( node, null, writer ); + writeValue( writer, node.getValue() ); + } + else { // more than 1, write as a json array + writeName( node, null, writer ); + writer.beginArray(); + for( SimpleNode leafNode: nodeLeafList ) { + writeValue( writer, leafNode.getValue() ); + } + + writer.endArray(); } } else { // CompositeNode Preconditions.checkState( node instanceof CompositeNode, "Data representation of Container should be CompositeNode - " + node.getNodeType() ); - writeContainer( writer, (CompositeNode) node, null ); + List nodeList = parent.getCompositesByName( node.getNodeType() ); + if( nodeList.size() == 1 ) { + writeContainer( writer, (CompositeNode) node, null ); + } + else { // more than 1, write as a json array + writeList( writer, parent, (CompositeNode) node, null ); + } } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java index b0916f4500..6330c0a479 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java @@ -36,6 +36,7 @@ import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdent import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier; import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates; import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument; +import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode; import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode; import org.opendaylight.yangtools.yang.model.api.ChoiceNode; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; @@ -804,7 +805,8 @@ public class ControllerContext implements SchemaContextListener { public boolean isInstantiatedDataSchema( final DataSchemaNode node ) { return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode || - node instanceof ContainerSchemaNode || node instanceof ListSchemaNode; + node instanceof ContainerSchemaNode || node instanceof ListSchemaNode || + node instanceof AnyXmlSchemaNode; } private void addKeyValue( final HashMap map, final DataSchemaNode node, diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java index 9700d48bc2..4716a02be2 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java @@ -56,6 +56,7 @@ import org.opendaylight.yangtools.yang.data.api.Node; import org.opendaylight.yangtools.yang.data.api.SimpleNode; import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode; import org.opendaylight.yangtools.yang.data.impl.NodeFactory; +import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; @@ -1044,97 +1045,127 @@ public class RestconfImpl implements RestconfService { } } - if ((nodeBuilder instanceof CompositeNodeWrapper)) { - final List> children = ((CompositeNodeWrapper) nodeBuilder).getValues(); - for (final NodeWrapper child : children) { - final List potentialSchemaNodes = - this.controllerContext.findInstanceDataChildrenByName( - ((DataNodeContainer) schema), child.getLocalName()); + if ( nodeBuilder instanceof CompositeNodeWrapper ) { + if( schema instanceof DataNodeContainer ) { + normalizeCompositeNode( (CompositeNodeWrapper)nodeBuilder, (DataNodeContainer)schema, + mountPoint, currentAugment ); + } + else if( schema instanceof AnyXmlSchemaNode ) { + normalizeAnyXmlNode( (CompositeNodeWrapper)nodeBuilder, (AnyXmlSchemaNode)schema ); + } + } + else if ( nodeBuilder instanceof SimpleNodeWrapper ) { + normalizeSimpleNode( (SimpleNodeWrapper) nodeBuilder, schema, mountPoint ); + } + else if ((nodeBuilder instanceof EmptyNodeWrapper)) { + normalizeEmptyNode( (EmptyNodeWrapper) nodeBuilder, schema ); + } + } - if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) { - StringBuilder builder = new StringBuilder(); - for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) { - builder.append(" ").append(potentialSchemaNode.getQName().getNamespace().toString()) - .append("\n"); - } + private void normalizeAnyXmlNode( CompositeNodeWrapper compositeNode, AnyXmlSchemaNode schema ) { + List> children = compositeNode.getValues(); + for( NodeWrapper child : children ) { + child.setNamespace( schema.getQName().getNamespace() ); + if( child instanceof CompositeNodeWrapper ) { + normalizeAnyXmlNode( (CompositeNodeWrapper)child, schema ); + } + } + } - throw new RestconfDocumentedException( - "Node \"" + child.getLocalName() + - "\" is added as augment from more than one module. " + - "Therefore node must have namespace (XML format) or module name (JSON format)." + - "\nThe node is added as augment from modules with namespaces:\n" + builder, - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); - } + private void normalizeEmptyNode( EmptyNodeWrapper emptyNodeBuilder, DataSchemaNode schema ) { + if ((schema instanceof LeafSchemaNode)) { + emptyNodeBuilder.setComposite(false); + } + else { + if ((schema instanceof ContainerSchemaNode)) { + // FIXME: Add presence check + emptyNodeBuilder.setComposite(true); + } + } + } + + private void normalizeSimpleNode( SimpleNodeWrapper simpleNode, DataSchemaNode schema, + MountInstance mountPoint ) { + final Object value = simpleNode.getValue(); + Object inputValue = value; + TypeDefinition typeDefinition = this.typeDefinition(schema); + if ((typeDefinition instanceof IdentityrefTypeDefinition)) { + if ((value instanceof String)) { + inputValue = new IdentityValuesDTO( simpleNode.getNamespace().toString(), + (String) value, null, (String) value ); + } // else value is already instance of IdentityValuesDTO + } + + Object outputValue = inputValue; + + if( typeDefinition != null ) { + Codec codec = RestCodec.from(typeDefinition, mountPoint); + outputValue = codec == null ? null : codec.deserialize(inputValue); + } + + simpleNode.setValue(outputValue); + } - boolean rightNodeSchemaFound = false; + private void normalizeCompositeNode( CompositeNodeWrapper compositeNodeBuilder, + DataNodeContainer schema, MountInstance mountPoint, + QName currentAugment ) { + final List> children = compositeNodeBuilder.getValues(); + for (final NodeWrapper child : children) { + final List potentialSchemaNodes = + this.controllerContext.findInstanceDataChildrenByName( + schema, child.getLocalName()); + + if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) { + StringBuilder builder = new StringBuilder(); for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) { - if (!rightNodeSchemaFound) { - final QName potentialCurrentAugment = - this.normalizeNodeName(child, potentialSchemaNode, currentAugment, mountPoint); - if (child.getQname() != null ) { - this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint); - rightNodeSchemaFound = true; - } - } + builder.append(" ").append(potentialSchemaNode.getQName().getNamespace().toString()) + .append("\n"); } - if (!rightNodeSchemaFound) { - throw new RestconfDocumentedException( - "Schema node \"" + child.getLocalName() + "\" was not found in module.", - ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT ); - } + throw new RestconfDocumentedException( + "Node \"" + child.getLocalName() + + "\" is added as augment from more than one module. " + + "Therefore node must have namespace (XML format) or module name (JSON format)." + + "\nThe node is added as augment from modules with namespaces:\n" + builder, + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); } - if ((schema instanceof ListSchemaNode)) { - final List listKeys = ((ListSchemaNode) schema).getKeyDefinition(); - for (final QName listKey : listKeys) { - boolean foundKey = false; - for (final NodeWrapper child : children) { - if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) { - foundKey = true; - } - } - - if (!foundKey) { - throw new RestconfDocumentedException( - "Missing key in URI \"" + listKey.getLocalName() + - "\" of list \"" + schema.getQName().getLocalName() + "\"", - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + boolean rightNodeSchemaFound = false; + for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) { + if (!rightNodeSchemaFound) { + final QName potentialCurrentAugment = + this.normalizeNodeName(child, potentialSchemaNode, currentAugment, mountPoint); + if (child.getQname() != null ) { + this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint); + rightNodeSchemaFound = true; } } } - } - else { - if ((nodeBuilder instanceof SimpleNodeWrapper)) { - final SimpleNodeWrapper simpleNode = ((SimpleNodeWrapper) nodeBuilder); - final Object value = simpleNode.getValue(); - Object inputValue = value; - TypeDefinition typeDefinition = this.typeDefinition(schema); - if ((typeDefinition instanceof IdentityrefTypeDefinition)) { - if ((value instanceof String)) { - inputValue = new IdentityValuesDTO( nodeBuilder.getNamespace().toString(), - (String) value, null, (String) value ); - } // else value is already instance of IdentityValuesDTO - } - Codec codec = RestCodec.from(typeDefinition, mountPoint); - Object outputValue = codec == null ? null : codec.deserialize(inputValue); - - simpleNode.setValue(outputValue); + if (!rightNodeSchemaFound) { + throw new RestconfDocumentedException( + "Schema node \"" + child.getLocalName() + "\" was not found in module.", + ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT ); } - else { - if ((nodeBuilder instanceof EmptyNodeWrapper)) { - final EmptyNodeWrapper emptyNodeBuilder = ((EmptyNodeWrapper) nodeBuilder); - if ((schema instanceof LeafSchemaNode)) { - emptyNodeBuilder.setComposite(false); - } - else { - if ((schema instanceof ContainerSchemaNode)) { - // FIXME: Add presence check - emptyNodeBuilder.setComposite(true); - } + } + + if ((schema instanceof ListSchemaNode)) { + ListSchemaNode listSchemaNode = (ListSchemaNode)schema; + final List listKeys = listSchemaNode.getKeyDefinition(); + for (final QName listKey : listKeys) { + boolean foundKey = false; + for (final NodeWrapper child : children) { + if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) { + foundKey = true; } } + + if (!foundKey) { + throw new RestconfDocumentedException( + "Missing key in URI \"" + listKey.getLocalName() + + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + } } } } @@ -1237,6 +1268,9 @@ public class RestconfImpl implements RestconfService { else if (node instanceof LeafSchemaNode) { return _typeDefinition((LeafSchemaNode)node); } + else if (node instanceof AnyXmlSchemaNode) { + return null; + } else { throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(node).toString()); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java index 1ec7253b8d..93d32a1499 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java @@ -116,6 +116,75 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader } + static class ComplexAnyXmlVerifier extends LeafVerifier { + + ComplexAnyXmlVerifier() { + super( null, JsonToken.BEGIN_OBJECT ); + } + + @Override + void verify( JsonReader reader, String keyName ) throws IOException { + + reader.beginObject(); + String innerKey = reader.nextName(); + assertEquals( "Json reader child key for " + keyName, "data", innerKey ); + assertEquals( "Json token type for key " + innerKey, JsonToken.BEGIN_OBJECT, reader.peek() ); + + reader.beginObject(); + verifyLeaf( reader, innerKey, "leaf1", "leaf1-value" ); + verifyLeaf( reader, innerKey, "leaf2", "leaf2-value" ); + + String nextName = reader.nextName(); + assertEquals( "Json reader child key for " + innerKey, "leaf-list", nextName ); + reader.beginArray(); + assertEquals( "Json value for key " + nextName, "leaf-list-value1", reader.nextString() ); + assertEquals( "Json value for key " + nextName, "leaf-list-value2", reader.nextString() ); + reader.endArray(); + + nextName = reader.nextName(); + assertEquals( "Json reader child key for " + innerKey, "list", nextName ); + reader.beginArray(); + verifyNestedLists( reader, 1 ); + verifyNestedLists( reader, 3 ); + reader.endArray(); + + reader.endObject(); + reader.endObject(); + } + + void verifyNestedLists( JsonReader reader, int leafNum ) throws IOException { + reader.beginObject(); + + String nextName = reader.nextName(); + assertEquals( "Json reader next name", "nested-list", nextName ); + + reader.beginArray(); + + reader.beginObject(); + verifyLeaf( reader, "nested-list", "nested-leaf", "nested-value" + leafNum++ ); + reader.endObject(); + + reader.beginObject(); + verifyLeaf( reader, "nested-list", "nested-leaf", "nested-value" + leafNum ); + reader.endObject(); + + reader.endArray(); + reader.endObject(); + } + + void verifyLeaf( JsonReader reader, String parent, String name, String value ) throws IOException { + String nextName = reader.nextName(); + assertEquals( "Json reader child key for " + parent, name, nextName ); + assertEquals( "Json token type for key " + parent, JsonToken.STRING, reader.peek() ); + assertEquals( "Json value for key " + nextName, value, reader.nextString() ); + } + + @Override + Object getActualValue( JsonReader reader ) throws IOException { + return null; + } + } + @BeforeClass public static void initialize() { dataLoad("/cnsn-to-json/simple-data-types"); @@ -208,6 +277,9 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader expectedMap.put( "lfunion14", new StringVerifier( "zero" ) ); expectedMap.put( "lfempty", new EmptyVerifier() ); expectedMap.put( "identityref1", new StringVerifier( "simple-data-types:iden" ) ); + expectedMap.put( "complex-any", new ComplexAnyXmlVerifier() ); + expectedMap.put( "simple-any", new StringVerifier( "simple" ) ); + expectedMap.put( "empty-any", new StringVerifier( "" ) ); while (jReader.hasNext()) { String keyName = jReader.nextName(); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfDocumentedExceptionMapperTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfDocumentedExceptionMapperTest.java index e146cf8f4f..c5c4596189 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfDocumentedExceptionMapperTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfDocumentedExceptionMapperTest.java @@ -9,6 +9,7 @@ package org.opendaylight.controller.sal.restconf.impl.test; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -18,6 +19,12 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.google.common.io.ByteStreams; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -29,7 +36,8 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; - +import java.util.regex.Matcher; +import java.util.regex.Pattern; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -41,7 +49,6 @@ import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; - import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Before; @@ -63,13 +70,6 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.google.common.io.ByteStreams; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; - /** * Unit tests for RestconfDocumentedExceptionMapper. * @@ -842,6 +842,14 @@ public class RestconfDocumentedExceptionMapperTest extends JerseyTest { errorListEntrySet.iterator().next().getKey() ); assertTrue( "\"error\" Json element is not an Array", errorListElement.isJsonArray() ); + // As a final check, make sure there aren't multiple "error" array elements. Unfortunately, + // the call above to getAsJsonObject().entrySet() will out duplicate "error" elements. So + // we'll use regex on the json string to verify this. + + Matcher matcher = Pattern.compile( "\"error\"[ ]*:[ ]*\\[", Pattern.DOTALL ).matcher( bos.toString() ); + assertTrue( "Expected 1 \"error\" element", matcher.find() ); + assertFalse( "Found multiple \"error\" elements", matcher.find() ); + return errorListElement.getAsJsonArray(); } @@ -850,7 +858,6 @@ public class RestconfDocumentedExceptionMapperTest extends JerseyTest { final ErrorInfoVerifier errorInfoVerifier ) { JsonElement errorInfoElement = null; - Map actualErrorInfo = null; Map leafMap = Maps.newHashMap(); for( Entry entry: errorEntryElement.getAsJsonObject().entrySet() ) { String leafName = entry.getKey(); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/structures/LstItem.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/structures/LstItem.java index 9b382d210e..3617ed9fb0 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/structures/LstItem.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/structures/LstItem.java @@ -7,6 +7,7 @@ */ package org.opendaylight.controller.sal.restconf.impl.test.structures; +import static org.junit.Assert.assertFalse; import java.util.HashMap; import java.util.Map; @@ -56,10 +57,14 @@ public class LstItem { } public void addLfLst(LfLst lfLst) { + assertFalse( "Found multiple leaf list elements for " + lfLst.getName(), + lfLsts.containsKey( lfLst.getName() ) ); lfLsts.put(lfLst.getName(), lfLst); } public void addLst(Lst lst) { + assertFalse( "Found multiple list elements for " + lst.getName(), + lsts.containsKey( lst.getName() ) ); lsts.put(lst.getName(), lst); } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/simple-data-types/simple-data-types.yang b/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/simple-data-types/simple-data-types.yang index 9bdea81579..cf6e513b30 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/simple-data-types/simple-data-types.yang +++ b/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/simple-data-types/simple-data-types.yang @@ -269,6 +269,10 @@ module simple-data-types { } } - + anyxml complex-any; + + anyxml simple-any; + + anyxml empty-any; } } \ No newline at end of file diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/simple-data-types/xml/data.xml b/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/simple-data-types/xml/data.xml index 28d355dbab..ed02ca35f6 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/simple-data-types/xml/data.xml +++ b/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/simple-data-types/xml/data.xml @@ -23,7 +23,6 @@ enum3 bit3 bit2 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz - 324 33.3 55 @@ -38,5 +37,35 @@ false b1 zero + x:iden - \ No newline at end of file + + + leaf1-value + leaf2-value + + leaf-list-value1 + leaf-list-value2 + + + + nested-value1 + + + nested-value2 + + + + + + nested-value3 + + + nested-value4 + + + + + simple + + diff --git a/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationServiceImpl.java b/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationServiceImpl.java index 1069858b47..f5fe089d4d 100644 --- a/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationServiceImpl.java +++ b/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationServiceImpl.java @@ -95,8 +95,10 @@ public class NetconfOperationServiceImpl implements NetconfOperationService { Set capabilities = new HashSet<>(); // [RFC6241] 8.3. Candidate Configuration Capability capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0")); + + // TODO rollback on error not supported EditConfigXmlParser:100 // [RFC6241] 8.5. Rollback-on-Error Capability - capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:rollback-on-error:1.0")); + // capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:rollback-on-error:1.0")); Set modules = yangStoreSnapshot.getModules(); for (Module module : modules) { diff --git a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPusher.java b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPusher.java index 8d85a35bc7..eddad8b4c7 100644 --- a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPusher.java +++ b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPusher.java @@ -8,6 +8,11 @@ package org.opendaylight.controller.netconf.persist.impl; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.base.Function; +import com.google.common.base.Stopwatch; +import com.google.common.collect.Collections2; import java.io.IOException; import java.io.InputStream; import java.util.Collection; @@ -16,11 +21,10 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import java.util.Set; +import java.util.SortedSet; import java.util.TreeMap; import java.util.concurrent.TimeUnit; - import javax.annotation.concurrent.Immutable; - import org.opendaylight.controller.config.api.ConflictingVersionException; import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder; import org.opendaylight.controller.netconf.api.NetconfDocumentedException; @@ -41,11 +45,6 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; -import com.google.common.base.Function; -import com.google.common.base.Preconditions; -import com.google.common.base.Stopwatch; -import com.google.common.collect.Collections2; - @Immutable public class ConfigPusher { private static final Logger logger = LoggerFactory.getLogger(ConfigPusher.class); @@ -84,7 +83,11 @@ public class ConfigPusher { ConflictingVersionException lastException; Stopwatch stopwatch = new Stopwatch().start(); do { - try (NetconfOperationService operationService = getOperationServiceWithRetries(configSnapshotHolder.getCapabilities(), configSnapshotHolder.toString())) { + String idForReporting = configSnapshotHolder.toString(); + SortedSet expectedCapabilities = checkNotNull(configSnapshotHolder.getCapabilities(), + "Expected capabilities must not be null - %s, check %s", idForReporting, + configSnapshotHolder.getClass().getName()); + try (NetconfOperationService operationService = getOperationServiceWithRetries(expectedCapabilities, idForReporting)) { return pushConfig(configSnapshotHolder, operationService); } catch (ConflictingVersionException e) { lastException = e; @@ -252,7 +255,7 @@ public class ConfigPusher { private static NetconfMessage createEditConfigMessage(Element dataElement) throws NetconfDocumentedException { String editConfigResourcePath = "/netconfOp/editConfig.xml"; try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcePath)) { - Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcePath); + checkNotNull(stream, "Unable to load resource " + editConfigResourcePath); Document doc = XmlUtil.readXmlToDocument(stream); @@ -274,7 +277,7 @@ public class ConfigPusher { private static NetconfMessage getCommitMessage() { String resource = "/netconfOp/commit.xml"; try (InputStream stream = ConfigPusher.class.getResourceAsStream(resource)) { - Preconditions.checkNotNull(stream, "Unable to load resource " + resource); + checkNotNull(stream, "Unable to load resource " + resource); return new NetconfMessage(XmlUtil.readXmlToDocument(stream)); } catch (SAXException | IOException e) { // error reading the xml file bundled into the jar diff --git a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java index 148b0446e3..f7091beba5 100644 --- a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java +++ b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java @@ -143,8 +143,8 @@ public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest { } notificationVerifier.assertNotificationCount(2); - notificationVerifier.assertNotificationContent(0, 0, 0, 9); - notificationVerifier.assertNotificationContent(1, 4, 3, 9); + notificationVerifier.assertNotificationContent(0, 0, 0, 8); + notificationVerifier.assertNotificationContent(1, 4, 3, 8); mockedAggregator.assertSnapshotCount(2); // Capabilities are stripped for persister diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketMuxDemux.java b/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketMuxDemux.java index 5c2af6d8b4..932ac4e20b 100644 --- a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketMuxDemux.java +++ b/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketMuxDemux.java @@ -32,11 +32,15 @@ import org.opendaylight.controller.sal.core.Node; import org.opendaylight.controller.sal.core.NodeConnector; import org.opendaylight.controller.sal.core.Property; import org.opendaylight.controller.sal.core.UpdateType; +import org.opendaylight.controller.sal.match.Match; +import org.opendaylight.controller.sal.packet.Ethernet; import org.opendaylight.controller.sal.packet.IPluginOutDataPacketService; +import org.opendaylight.controller.sal.packet.PacketException; import org.opendaylight.controller.sal.packet.PacketResult; import org.opendaylight.controller.sal.packet.RawPacket; import org.opendaylight.controller.sal.utils.GlobalConstants; import org.opendaylight.controller.sal.utils.HexEncode; +import org.opendaylight.controller.sal.utils.NetUtils; import org.openflow.protocol.OFMessage; import org.openflow.protocol.OFPacketIn; import org.openflow.protocol.OFPacketOut; @@ -169,12 +173,10 @@ public class DataPacketMuxDemux implements IContainerListener, @Override public void receive(ISwitch sw, OFMessage msg) { - if (sw == null || msg == null - || this.pluginOutDataPacketServices == null) { + if (sw == null || msg == null || this.pluginOutDataPacketServices == null) { // Something fishy, we cannot do anything - logger.debug( - "sw: {} and/or msg: {} and/or pluginOutDataPacketServices: {} is null!", - new Object[] { sw, msg, this.pluginOutDataPacketServices }); + logger.debug("sw: {} and/or msg: {} and/or pluginOutDataPacketServices: {} is null!", new Object[] { sw, + msg, this.pluginOutDataPacketServices }); return; } @@ -185,8 +187,7 @@ public class DataPacketMuxDemux implements IContainerListener, logger.debug("Connection service refused DataPacketMuxDemux receive {} {}", sw, msg); return; } - } - catch (Exception e) { + } catch (Exception e) { return; } @@ -204,63 +205,72 @@ public class DataPacketMuxDemux implements IContainerListener, // pass the parsed packet simply because once the // packet infra is settled all the packets will passed // around as parsed and read-only - for (int i = 0; i < this.iDataPacketListen.size(); i++) { - IDataPacketListen s = this.iDataPacketListen.get(i); - if (s.receiveDataPacket(dataPacket).equals( - PacketResult.CONSUME)) { + for (IDataPacketListen s : this.iDataPacketListen) { + if (s.receiveDataPacket(dataPacket).equals(PacketResult.CONSUME)) { logger.trace("Consumed locally data packet"); return; } } - // Now dispatch the packet toward SAL at least for - // default container, we need to revisit this in a general - // slicing architecture refresh - IPluginOutDataPacketService defaultOutService = this.pluginOutDataPacketServices - .get(GlobalConstants.DEFAULT.toString()); - if (defaultOutService != null) { - defaultOutService.receiveDataPacket(dataPacket); - if (logger.isTraceEnabled()) { - logger.trace( - "Dispatched to apps a frame of size: {} on " + - "container: {}: {}", new Object[] { - ofPacket.getPacketData().length, - GlobalConstants.DEFAULT.toString(), - HexEncode.bytesToHexString(dataPacket - .getPacketData()) }); - } - } + boolean dispatched_to_container = false; + // Now check the mapping between nodeConnector and // Container and later on optimally filter based on // flowSpec List containersRX = this.nc2Container.get(p); if (containersRX != null) { - for (int i = 0; i < containersRX.size(); i++) { - String container = containersRX.get(i); - IPluginOutDataPacketService s = this.pluginOutDataPacketServices - .get(container); - if (s != null) { - // TODO add filtering on a per-flowSpec base - s.receiveDataPacket(dataPacket); - if (logger.isTraceEnabled()) { - logger.trace( - "Dispatched to apps a frame of size: {}" + - " on container: {}: {}", new Object[] { - ofPacket.getPacketData().length, - container, - HexEncode.bytesToHexString(dataPacket - .getPacketData()) }); + Ethernet frame = new Ethernet(); + byte data[] = dataPacket.getPacketData(); + frame.deserialize(data, 0, data.length * NetUtils.NumBitsInAByte); + Match packetMatch = frame.getMatch(); + for (String container : containersRX) { + boolean notify = true; + List containerFlows = this.container2FlowSpecs.get(container); + if (containerFlows != null) { + notify = false; + for (ContainerFlow cFlow : containerFlows) { + if (cFlow.allowsMatch(packetMatch)) { + notify = true; + break; + } + } + if (notify) { + IPluginOutDataPacketService s = this.pluginOutDataPacketServices.get(container); + if (s != null) { + s.receiveDataPacket(dataPacket); + if (logger.isTraceEnabled()) { + logger.trace( + "Dispatched to apps a frame of size: {}" + " on container: {}: {}", + new Object[] { ofPacket.getPacketData().length, container, + HexEncode.bytesToHexString(dataPacket.getPacketData()) }); + } + } + dispatched_to_container = true; } } } } - + if (!dispatched_to_container) { + // Now dispatch the packet toward SAL for default container + IPluginOutDataPacketService defaultOutService = this.pluginOutDataPacketServices + .get(GlobalConstants.DEFAULT.toString()); + if (defaultOutService != null) { + defaultOutService.receiveDataPacket(dataPacket); + if (logger.isTraceEnabled()) { + logger.trace("Dispatched to apps a frame of size: {} on " + "container: {}: {}", + new Object[] { ofPacket.getPacketData().length, + GlobalConstants.DEFAULT.toString(), + HexEncode.bytesToHexString(dataPacket.getPacketData()) }); + } + } + } // This is supposed to be the catch all for all the // DataPacket hence we will assume it has been handled return; } catch (ConstructionException cex) { + } catch (PacketException e) { + logger.debug("Failed to deserialize raw packet: ", e.getMessage()); } - // If we reach this point something went wrong. return; } else { diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ARP.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ARP.java index 8fc0d625eb..21c17b366c 100644 --- a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ARP.java +++ b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ARP.java @@ -1,6 +1,6 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -258,18 +258,23 @@ public class ARP extends Packet { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (!super.equals(obj)) + } + if (!super.equals(obj)) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } ARP other = (ARP) obj; if (fieldValues == null) { - if (other.fieldValues != null) + if (other.fieldValues != null) { return false; - } else if (!fieldValues.equals(other.fieldValues)) + } + } else if (!fieldValues.equals(other.fieldValues)) { return false; + } return true; } } diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Ethernet.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Ethernet.java index d0068564a9..235e71a760 100644 --- a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Ethernet.java +++ b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Ethernet.java @@ -15,6 +15,8 @@ import java.util.Map; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; +import org.opendaylight.controller.sal.match.Match; +import org.opendaylight.controller.sal.match.MatchType; import org.opendaylight.controller.sal.utils.EtherTypes; import org.opendaylight.controller.sal.utils.NetUtils; @@ -139,4 +141,10 @@ public class Ethernet extends Packet { return this; } + @Override + public void populateMatch(Match match) { + match.setField(MatchType.DL_SRC, this.getSourceMACAddress()); + match.setField(MatchType.DL_DST, this.getDestinationMACAddress()); + match.setField(MatchType.DL_TYPE, this.getEtherType()); + } } diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IEEE8021Q.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IEEE8021Q.java index 39c7d386bc..9825d0eefb 100644 --- a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IEEE8021Q.java +++ b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IEEE8021Q.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -13,6 +13,8 @@ import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; +import org.opendaylight.controller.sal.match.Match; +import org.opendaylight.controller.sal.match.MatchType; /** * Class that represents the IEEE 802.1Q objects @@ -148,4 +150,10 @@ public class IEEE8021Q extends Packet { return this; } + @Override + public void populateMatch(Match match) { + match.setField(MatchType.DL_VLAN, this.getVid()); + match.setField(MatchType.DL_VLAN_PR, this.getPcp()); + match.setField(MatchType.DL_TYPE, this.getEtherType()); + } } diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPv4.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPv4.java index 559acd633a..3363f423d6 100644 --- a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPv4.java +++ b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPv4.java @@ -1,6 +1,6 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -20,6 +20,8 @@ import java.util.Random; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; +import org.opendaylight.controller.sal.match.Match; +import org.opendaylight.controller.sal.match.MatchType; import org.opendaylight.controller.sal.utils.IPProtocols; import org.opendaylight.controller.sal.utils.NetUtils; import org.slf4j.Logger; @@ -577,4 +579,12 @@ public class IPv4 extends Packet { corrupted = true; } } + + @Override + public void populateMatch(Match match) { + match.setField(MatchType.NW_SRC, NetUtils.getInetAddress(this.getSourceAddress())); + match.setField(MatchType.NW_DST, NetUtils.getInetAddress(this.getDestinationAddress())); + match.setField(MatchType.NW_PROTO, this.getProtocol()); + match.setField(MatchType.NW_TOS, this.getDiffServ()); + } } diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDP.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDP.java index 6f5cf04a52..9b5dc082bb 100644 --- a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDP.java +++ b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDP.java @@ -12,6 +12,7 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; + import org.opendaylight.controller.sal.utils.HexEncode; import org.opendaylight.controller.sal.utils.NetUtils; diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDPTLV.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDPTLV.java index efb938e37f..35244ea697 100644 --- a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDPTLV.java +++ b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDPTLV.java @@ -151,18 +151,23 @@ public class LLDPTLV extends Packet { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (!super.equals(obj)) + } + if (!super.equals(obj)) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } LLDPTLV other = (LLDPTLV) obj; if (fieldValues == null) { - if (other.fieldValues != null) + if (other.fieldValues != null) { return false; - } else if (!fieldValues.equals(other.fieldValues)) + } + } else if (!fieldValues.equals(other.fieldValues)) { return false; + } return true; } diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Packet.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Packet.java index 58b5d3914a..789aa12653 100644 --- a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Packet.java +++ b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Packet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -13,6 +13,7 @@ import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang3.tuple.Pair; +import org.opendaylight.controller.sal.match.Match; import org.opendaylight.controller.sal.utils.HexEncode; import org.opendaylight.controller.sal.utils.NetUtils; import org.slf4j.Logger; @@ -364,4 +365,31 @@ public abstract class Packet { return true; } + /** + * Adds to the passed Match this packet's header fields + * + * @param match + * The Match object to populate + */ + public void populateMatch(Match match) { + // To be overridden by derived packet classes which have well known + // header fields so that Packet.getMatch would return desired result + } + + /** + * Returns the Match object containing this packet and its payload + * encapsulated packets' header fields + * + * @return The Match containing the header fields of this packet and of its + * payload encapsulated packets + */ + public Match getMatch() { + Match match = new Match(); + Packet packet = this; + while (packet != null) { + packet.populateMatch(match); + packet = packet.getPayload(); + } + return match; + } } diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/TCP.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/TCP.java index 8253ac46d3..d27494599c 100644 --- a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/TCP.java +++ b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/TCP.java @@ -1,6 +1,6 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -15,6 +15,8 @@ import java.util.Map; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; +import org.opendaylight.controller.sal.match.Match; +import org.opendaylight.controller.sal.match.MatchType; /** * Class that represents the TCP segment objects @@ -238,4 +240,9 @@ public class TCP extends Packet { return (BitBufferHelper.getShort(fieldValues.get(CHECKSUM))); } + @Override + public void populateMatch(Match match) { + match.setField(MatchType.TP_SRC, this.getSourcePort()); + match.setField(MatchType.TP_DST, this.getDestinationPort()); + } } diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/UDP.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/UDP.java index f82ed8fcae..069a277f89 100644 --- a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/UDP.java +++ b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/UDP.java @@ -1,6 +1,6 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -15,6 +15,8 @@ import java.util.Map; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; +import org.opendaylight.controller.sal.match.Match; +import org.opendaylight.controller.sal.match.MatchType; /** * Class that represents the UDP datagram objects @@ -156,4 +158,10 @@ public class UDP extends Packet { fieldValues.put(CHECKSUM, checksum); return this; } + + @Override + public void populateMatch(Match match) { + match.setField(MatchType.TP_SRC, this.getSourcePort()); + match.setField(MatchType.TP_DST, this.getDestinationPort()); + } } diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ARPTest.java b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ARPTest.java index a3ebd7ee0d..10bd535eb2 100644 --- a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ARPTest.java +++ b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ARPTest.java @@ -1,6 +1,6 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/EthernetTest.java b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/EthernetTest.java index 2494eb6b2d..494dd2abf2 100644 --- a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/EthernetTest.java +++ b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/EthernetTest.java @@ -1,6 +1,6 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -9,9 +9,14 @@ package org.opendaylight.controller.sal.packet; +import java.util.Arrays; + import junit.framework.Assert; import org.junit.Test; +import org.opendaylight.controller.sal.match.Match; +import org.opendaylight.controller.sal.match.MatchType; +import org.opendaylight.controller.sal.utils.EtherTypes; public class EthernetTest { @@ -95,4 +100,22 @@ public class EthernetTest { } + @Test + public void testGetMatch() throws Exception { + Ethernet eth = new Ethernet(); + byte smac[] = { (byte) 0xf0, (byte) 0xde, (byte) 0xf1, (byte) 0x71, (byte) 0x72, (byte) 0x8d }; + byte dmac[] = { (byte) 0xde, (byte) 0x28, (byte) 0xdb, (byte) 0xb3, (byte) 0x7c, (byte) 0xf8 }; + short ethType = EtherTypes.IPv4.shortValue(); + eth.setDestinationMACAddress(dmac); + eth.setSourceMACAddress(smac); + eth.setEtherType(ethType); + + Match match = eth.getMatch(); + + Assert.assertTrue(Arrays.equals(smac, (byte[]) match.getField(MatchType.DL_SRC).getValue())); + Assert.assertTrue(Arrays.equals(dmac, (byte[]) match.getField(MatchType.DL_DST).getValue())); + Assert.assertEquals(ethType, (short) match.getField(MatchType.DL_TYPE).getValue()); + + } + } diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IEEE8021QTest.java b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IEEE8021QTest.java index a4c6c1fc4b..2443b491c7 100644 --- a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IEEE8021QTest.java +++ b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IEEE8021QTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -9,7 +9,11 @@ package org.opendaylight.controller.sal.packet; import junit.framework.Assert; + import org.junit.Test; +import org.opendaylight.controller.sal.match.Match; +import org.opendaylight.controller.sal.match.MatchType; +import org.opendaylight.controller.sal.utils.EtherTypes; import org.opendaylight.controller.sal.utils.NetUtils; public class IEEE8021QTest { @@ -212,4 +216,21 @@ public class IEEE8021QTest { Assert.assertTrue(data[44] == (byte) 0x09); Assert.assertTrue(data[45] == (byte) 0xFE); } + + @Test + public void testGetMatchFullPacket() throws Exception { + IEEE8021Q dot1q = new IEEE8021Q(); + byte priority = 4; + short vlanId = 59; + short ethType = EtherTypes.IPv4.shortValue(); + dot1q.setPcp(priority); + dot1q.setVid(vlanId); + dot1q.setEtherType(ethType); + + Match match = dot1q.getMatch(); + + Assert.assertEquals(priority, (byte) match.getField(MatchType.DL_VLAN_PR).getValue()); + Assert.assertEquals(vlanId, (short) match.getField(MatchType.DL_VLAN).getValue()); + Assert.assertEquals(ethType, (short) match.getField(MatchType.DL_TYPE).getValue()); + } } diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IPv4Test.java b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IPv4Test.java index 5afcd8be7d..f5298711b6 100644 --- a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IPv4Test.java +++ b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IPv4Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -15,6 +15,8 @@ import java.util.Arrays; import junit.framework.Assert; import org.junit.Test; +import org.opendaylight.controller.sal.match.Match; +import org.opendaylight.controller.sal.match.MatchType; import org.opendaylight.controller.sal.utils.EtherTypes; import org.opendaylight.controller.sal.utils.IPProtocols; import org.opendaylight.controller.sal.utils.NetUtils; @@ -452,4 +454,31 @@ public class IPv4Test { Assert.assertFalse(decIcmp.isCorrupted()); Assert.assertTrue(Arrays.equals(icmpRawPayload, decIcmp.getRawPayload())); } + + @Test + public void testGetMatch() throws Exception { + IPv4 ip = new IPv4(); + InetAddress sourceAddress = InetAddress.getByName("172.168.190.15"); + InetAddress destintationAddress = InetAddress.getByName("23.128.0.11"); + byte protocol = IPProtocols.TCP.byteValue(); + byte tos = 7; + ip.setVersion((byte) 4); + ip.setIdentification((short) 5); + ip.setDiffServ(tos); + ip.setECN((byte) 0); + ip.setTotalLength((short) 84); + ip.setFlags((byte) 2); + ip.setFragmentOffset((short) 0); + ip.setTtl((byte) 64); + ip.setProtocol(protocol); + ip.setDestinationAddress(destintationAddress); + ip.setSourceAddress(sourceAddress); + + Match match = ip.getMatch(); + + Assert.assertEquals(sourceAddress, match.getField(MatchType.NW_SRC).getValue()); + Assert.assertEquals(destintationAddress, match.getField(MatchType.NW_DST).getValue()); + Assert.assertEquals(protocol, (byte) match.getField(MatchType.NW_PROTO).getValue()); + Assert.assertEquals(tos, (byte) match.getField(MatchType.NW_TOS).getValue()); + } } diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/PacketTest.java b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/PacketTest.java index 8f3b283b2e..95eff32ef1 100644 --- a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/PacketTest.java +++ b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/PacketTest.java @@ -1,6 +1,6 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -9,11 +9,17 @@ package org.opendaylight.controller.sal.packet; +import java.net.InetAddress; +import java.util.Arrays; import java.util.Map; import junit.framework.Assert; import org.junit.Test; +import org.opendaylight.controller.sal.match.Match; +import org.opendaylight.controller.sal.match.MatchType; +import org.opendaylight.controller.sal.utils.EtherTypes; +import org.opendaylight.controller.sal.utils.IPProtocols; public class PacketTest { @@ -120,9 +126,9 @@ public class PacketTest { eth.setSourceMACAddress(sMAC); eth.setEtherType(etherType); - dMACdata = (byte[]) fCValues.get("DestinationMACAddress"); - sMACdata = (byte[]) fCValues.get("SourceMACAddress"); - etherTypedata = (byte[]) fCValues.get("EtherType"); + dMACdata = fCValues.get("DestinationMACAddress"); + sMACdata = fCValues.get("SourceMACAddress"); + etherTypedata = fCValues.get("EtherType"); Assert.assertTrue(dMACdata[0] == 10); Assert.assertTrue(dMACdata[1] == 12); @@ -160,4 +166,62 @@ public class PacketTest { Assert.assertTrue(data[13] == 6); } + + @Test + public void testGetMatch() throws Exception { + TCP tcp = new TCP(); + short sport = (short) 11093; + short dport = (short) 23; + tcp.setSourcePort(sport); + tcp.setDestinationPort(dport); + + IPv4 ip = new IPv4(); + InetAddress sourceAddress = InetAddress.getByName("192.168.100.100"); + InetAddress destintationAddress = InetAddress.getByName("192.168.100.101"); + byte protocol = IPProtocols.TCP.byteValue(); + byte tos = 5; + ip.setVersion((byte) 4); + ip.setIdentification((short) 5); + ip.setDiffServ(tos); + ip.setECN((byte) 0); + ip.setTotalLength((short) 84); + ip.setFlags((byte) 2); + ip.setFragmentOffset((short) 0); + ip.setTtl((byte) 64); + ip.setProtocol(protocol); + ip.setDestinationAddress(destintationAddress); + ip.setSourceAddress(sourceAddress); + ip.setPayload(tcp); + + IEEE8021Q dot1q = new IEEE8021Q(); + byte priority = 4; + short vlanId = 59; + short ethType = EtherTypes.IPv4.shortValue(); + dot1q.setPcp(priority); + dot1q.setVid(vlanId); + dot1q.setEtherType(ethType); + dot1q.setPayload(ip); + + Ethernet eth = new Ethernet(); + byte smac[] = { (byte) 0xf0, (byte) 0xde, (byte) 0xf1, (byte) 0x71, (byte) 0x72, (byte) 0x8d }; + byte dmac[] = { (byte) 0xde, (byte) 0x28, (byte) 0xdb, (byte) 0xb3, (byte) 0x7c, (byte) 0xf8 }; + eth.setDestinationMACAddress(dmac); + eth.setSourceMACAddress(smac); + eth.setEtherType(EtherTypes.VLANTAGGED.shortValue()); + eth.setPayload(dot1q); + + Match match = eth.getMatch(); + + Assert.assertTrue(Arrays.equals(smac, (byte[]) match.getField(MatchType.DL_SRC).getValue())); + Assert.assertTrue(Arrays.equals(dmac, (byte[]) match.getField(MatchType.DL_DST).getValue())); + Assert.assertEquals(priority, (byte) match.getField(MatchType.DL_VLAN_PR).getValue()); + Assert.assertEquals(vlanId, (short) match.getField(MatchType.DL_VLAN).getValue()); + Assert.assertEquals(ethType, (short) match.getField(MatchType.DL_TYPE).getValue()); + Assert.assertEquals(sourceAddress, match.getField(MatchType.NW_SRC).getValue()); + Assert.assertEquals(destintationAddress, match.getField(MatchType.NW_DST).getValue()); + Assert.assertEquals(protocol, (byte) match.getField(MatchType.NW_PROTO).getValue()); + Assert.assertEquals(tos, (byte) match.getField(MatchType.NW_TOS).getValue()); + Assert.assertEquals(sport, (short) match.getField(MatchType.TP_SRC).getValue()); + Assert.assertEquals(dport, (short) match.getField(MatchType.TP_DST).getValue()); + } } diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/TCPTest.java b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/TCPTest.java index 3e18aedfdb..e56f41e5c1 100644 --- a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/TCPTest.java +++ b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/TCPTest.java @@ -1,6 +1,6 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -12,6 +12,8 @@ package org.opendaylight.controller.sal.packet; import junit.framework.Assert; import org.junit.Test; +import org.opendaylight.controller.sal.match.Match; +import org.opendaylight.controller.sal.match.MatchType; public class TCPTest { @@ -113,4 +115,18 @@ public class TCPTest { short checksum = tcp.getChecksum(); Assert.assertTrue(checksum == 200); } + + @Test + public void testGetMatch() throws Exception { + TCP tcp = new TCP(); + short sport = (short) 52012; + short dport = (short) 40345; + tcp.setSourcePort(sport); + tcp.setDestinationPort(dport); + + Match match = tcp.getMatch(); + + Assert.assertEquals(sport, (short) match.getField(MatchType.TP_SRC).getValue()); + Assert.assertEquals(dport, (short) match.getField(MatchType.TP_DST).getValue()); + } } diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/UDPTest.java b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/UDPTest.java index 8d5be849a0..a3a597a82d 100644 --- a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/UDPTest.java +++ b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/UDPTest.java @@ -1,6 +1,6 @@ /* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, @@ -12,6 +12,8 @@ package org.opendaylight.controller.sal.packet; import junit.framework.Assert; import org.junit.Test; +import org.opendaylight.controller.sal.match.Match; +import org.opendaylight.controller.sal.match.MatchType; public class UDPTest { @@ -95,4 +97,19 @@ public class UDPTest { } + @Test + public void testGetMatch() throws Exception { + UDP udp = new UDP(); + short sport = (short) 33000; + short dport = (short) 843; + udp.setSourcePort(sport); + udp.setDestinationPort(dport); + + Match match = udp.getMatch(); + + Assert.assertEquals(sport, (short) match.getField(MatchType.TP_SRC).getValue()); + Assert.assertEquals(dport, (short) match.getField(MatchType.TP_DST).getValue()); + + } + }